Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rcamera is autogenerated from api definition #157

Merged
merged 1 commit into from
Nov 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions manual/config_guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,18 @@ DrawLineStrip/points
DrawTriangleFan/points
```

#### HiddenRefParameters

Hides pointer semantics by using the `.byref` pragma.

```ini
[HiddenRefParameters]
GetCameraForward/camera
GetCameraUp/camera
GetCameraRight/camera
GetCameraViewMatrix/camera
```

#### TypeReplacements

Allows manual type conversion in cases where C types don’t map well to Nim types:
Expand Down
4 changes: 1 addition & 3 deletions src/raylib.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2739,9 +2739,7 @@ proc loadFontFromMemory*(fileType: string; fileData: openArray[uint8]; fontSize:

proc loadFontFromData*(chars: sink RArray[GlyphInfo]; baseSize, padding: int32, packMethod: int32): Font =
## Load font using chars info
result.baseSize = baseSize
result.glyphCount = chars.len.int32
result.glyphs = chars.data
result = Font(baseSize: baseSize, glyphCount: chars.len.int32, glyphs: chars.data)
wasMoved(chars)
let atlas = genImageFontAtlasImpl(result.glyphs, addr result.recs, result.glyphCount, baseSize,
padding, packMethod)
Expand Down
186 changes: 14 additions & 172 deletions src/rcamera.nim
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
from raylib import CameraMode, CameraProjection, Vector2, Vector3, Matrix, Camera3D, Camera
from std/math import degToRad
import raymath

# -----------------------------------------------------------------------------------------
# Defines and Macros
# -----------------------------------------------------------------------------------------

const
CameraMoveSpeed* = 5.4'f32 # Units per second
Expand All @@ -20,170 +14,18 @@ const
CameraCullDistanceNear* = 0.01
CameraCullDistanceFar* = 1000.0

# -----------------------------------------------------------------------------------------
# Module Functions Definition
# -----------------------------------------------------------------------------------------

func getCameraForward*(camera: Camera): Vector3 =
## Returns the camera's forward vector (normalized)
normalize(camera.target - camera.position)

func getCameraUp*(camera: Camera): Vector3 =
## Returns the camera's up vector (normalized)
## Note: The up vector might not be perpendicular to the forward vector
normalize(camera.up)

func getCameraRight*(camera: Camera): Vector3 =
## Returns the camera's right vector (normalized)
let forward = getCameraForward(camera)
let up = getCameraUp(camera)
normalize(crossProduct(forward, up))

func moveForward*(camera: var Camera, distance: float32, moveInWorldPlane: bool) =
## Moves the camera in its forward direction
var forward = getCameraForward(camera)

if moveInWorldPlane:
# Project vector onto world plane
forward.y = 0
forward = normalize(forward)

# Scale by distance
forward *= distance

# Move position and target
camera.position += forward
camera.target += forward

func moveUp*(camera: var Camera, distance: float32) =
## Moves the camera in its up direction
var up = getCameraUp(camera)

# Scale by distance
up *= distance

# Move position and target
camera.position += up
camera.target += up

func moveRight*(camera: var Camera, distance: float32, moveInWorldPlane: bool) =
## Moves the camera target in its current right direction
var right = getCameraRight(camera)

if moveInWorldPlane:
# Project vector onto world plane
right.y = 0
right = normalize(right)

# Scale by distance
right *= distance

# Move position and target
camera.position += right
camera.target += right

func moveToTarget*(camera: var Camera, delta: float32) =
## Moves the camera position closer/farther to/from the camera target
var distance = distance(camera.position, camera.target)

# Apply delta
distance += delta

# Distance must be greater than 0
if distance <= 0: distance = 0.001'f32

# Set new distance by moving the position along the forward vector
let forward = getCameraForward(camera)
camera.position = camera.target + (forward * -distance)

func yaw*(camera: var Camera, angle: float32, rotateAroundTarget: bool) =
## Rotates the camera around its up vector
## Yaw is "looking left and right"
## If rotateAroundTarget is false, the camera rotates around its position
## Note: angle must be provided in radians
# Rotation axis
let up = getCameraUp(camera)

# View vector
var targetPosition = camera.target - camera.position

# Rotate view vector around up axis
targetPosition = rotateByAxisAngle(targetPosition, up, angle)

if rotateAroundTarget:
# Move position relative to target
camera.position = camera.target - targetPosition
else:
# Move target relative to position
camera.target = camera.position + targetPosition

func pitch*(camera: var Camera, angle: float32, lockView, rotateAroundTarget, rotateUp: bool) =
## Rotates the camera around its right vector, pitch is "looking up and down"
## - lockView prevents camera overrotation (aka "somersaults")
## - rotateAroundTarget defines if rotation is around target or around its position
## - rotateUp rotates the up direction as well (typically only useful in CAMERA_FREE)
## NOTE: angle must be provided in radians
# Up direction
var angle = angle
let up = getCameraUp(camera)

# View vector
var targetPosition = camera.target - camera.position

if lockView:
# In these camera modes we clamp the Pitch angle
# to allow only viewing straight up or down.

# Clamp view up
var maxAngleUp = angle(up, targetPosition)
maxAngleUp -= 0.001'f32 # avoid numerical errors
if angle > maxAngleUp: angle = maxAngleUp

# Clamp view down
var maxAngleDown = angle(-up, targetPosition)
maxAngleDown *= -1.0'f32 # downwards angle is negative
maxAngleDown += 0.001'f32 # avoid numerical errors
if angle < maxAngleDown: angle = maxAngleDown

# Rotation axis
let right = getCameraRight(camera)

# Rotate view vector around right axis
targetPosition = rotateByAxisAngle(targetPosition, right, angle)

if rotateAroundTarget:
# Move position relative to target
camera.position = camera.target - targetPosition
else:
# Move target relative to position
camera.target = camera.position + targetPosition

if rotateUp:
# Rotate up direction around right axis
camera.up = rotateByAxisAngle(camera.up, right, angle)

func roll*(camera: var Camera, angle: float32) =
## Rotates the camera around its forward vector
## Roll is "turning your head sideways to the left or right"
## Note: angle must be provided in radians
# Rotation axis
let forward = getCameraForward(camera)

# Rotate up direction around forward axis
camera.up = rotateByAxisAngle(camera.up, forward, angle)

func getCameraViewMatrix*(camera: Camera): Matrix =
## Returns the camera view matrix
lookAt(camera.position, camera.target, camera.up)
{.push callconv: cdecl, header: "rcamera.h".}
func getCameraForward*(camera {.byref.}: Camera): Vector3 {.importc: "GetCameraForward".}
func getCameraUp*(camera {.byref.}: Camera): Vector3 {.importc: "GetCameraUp".}
func getCameraRight*(camera {.byref.}: Camera): Vector3 {.importc: "GetCameraRight".}
func moveForward*(camera: var Camera, distance: float32, moveInWorldPlane: bool) {.importc: "CameraMoveForward".}
func moveUp*(camera: var Camera, distance: float32) {.importc: "CameraMoveUp".}
func moveRight*(camera: var Camera, distance: float32, moveInWorldPlane: bool) {.importc: "CameraMoveRight".}
func moveToTarget*(camera: var Camera, delta: float32) {.importc: "CameraMoveToTarget".}
func yaw*(camera: var Camera, angle: float32, rotateAroundTarget: bool) {.importc: "CameraYaw".}
func pitch*(camera: var Camera, angle: float32, lockView: bool, rotateAroundTarget: bool, rotateUp: bool) {.importc: "CameraPitch".}
func roll*(camera: var Camera, angle: float32) {.importc: "CameraRoll".}
func getCameraViewMatrix*(camera {.byref.}: Camera): Matrix {.importc: "GetCameraViewMatrix".}
func getCameraProjectionMatrix*(camera {.byref.}: Camera, aspect: float32): Matrix {.importc: "GetCameraProjectionMatrix".}
{.pop.}

func getCameraProjectionMatrix*(camera: Camera, aspect: float32): Matrix =
# Returns the camera projection matrix
case camera.projection
of Perspective:
perspective(degToRad(camera.fovy), aspect, CameraCullDistanceNear, CameraCullDistanceFar)
of Orthographic:
let top = camera.fovy / 2.0
let right = top * aspect
ortho(-right, right, -top, top, CameraCullDistanceNear, CameraCullDistanceFar)
else:
identity(Matrix)
2 changes: 1 addition & 1 deletion tests/basic_window.nim
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
#
# ****************************************************************************************

import raylib, rlgl, raymath, rmem, reasings
import raylib, rlgl, raymath, rmem, reasings, rcamera

# ----------------------------------------------------------------------------------------
# Global Variables Definition
Expand Down
2 changes: 1 addition & 1 deletion tests/basic_window_web.nim
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
#
# ****************************************************************************************

import raylib, rlgl, raymath, rmem, reasings
import raylib, rlgl, raymath, rmem, reasings, rcamera

# ----------------------------------------------------------------------------------------
# Global Variables Definition
Expand Down
4 changes: 2 additions & 2 deletions tools/wrapper/api/raylib.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
{
"name": "RAYLIB_VERSION_MINOR",
"type": "INT",
"value": 5,
"value": 6,
"description": ""
},
{
Expand All @@ -27,7 +27,7 @@
{
"name": "RAYLIB_VERSION",
"type": "STRING",
"value": "5.5",
"value": "5.6-dev",
"description": ""
},
{
Expand Down
6 changes: 5 additions & 1 deletion tools/wrapper/builder.nim
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ proc generateProc*(b: var Builder, fnc: FunctionInfo) =
if i > 0:
b.addRaw ", "
b.addIdent param.name
if isPrivate notin fnc.flags and isHiddenRefParam in param.flags:
b.addRaw " {.byref.}"
b.addRaw ": "
b.addRaw param.`type`
b.addRaw ")"
Expand All @@ -165,10 +167,12 @@ proc generateWrappedProc*(b: var Builder, fnc: FunctionInfo) =
if i > 0:
b.addRaw ", "
b.addIdent param.name
if isHiddenRefParam in param.flags:
b.addRaw " {.byref.}"
b.addRaw ": "
if isString in param.flags:
b.addRaw "string"
elif {isOpenArray, isVarParam} * param.flags != {}:
elif {isOpenArray, isVarParam, isHiddenRefParam} * param.flags != {}:
b.addRaw param.dirty # stores native nim type
else:
b.addRaw param.`type`
Expand Down
3 changes: 3 additions & 0 deletions tools/wrapper/config.nim
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ type
privateSymbols*: HashSet[SymbolPair]
ignoredSymbols*: HashSet[SymbolPair]
openArrayParameters*: HashSet[SymbolPair]
hiddenRefParameters*: HashSet[SymbolPair]
discardReturn*: HashSet[string]
boolReturn*: HashSet[string]
wrappedFuncs*: HashSet[string]
Expand Down Expand Up @@ -62,6 +63,8 @@ proc processKeyWithoutValue(config: var ConfigData; section: string, key: string
config.ignoredSymbols.incl(sp)
of "OpenArrayParameters":
config.openArrayParameters.incl(sp)
of "HiddenRefParameters":
config.hiddenRefParameters.incl(sp)
of "DiscardReturn":
config.discardReturn.incl(key)
of "BoolReturn":
Expand Down
12 changes: 9 additions & 3 deletions tools/wrapper/config/rcamera.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ cHeader = rcamera.h

[ Snippets ]

moduleHeader = """
from raylib import CameraMode, CameraProjection, Vector2, Vector3, Matrix, Camera3D, Camera
"""
moduleHeader = snippets/rcamera_header.nim

[ IgnoredSymbols ]

Expand All @@ -23,6 +21,14 @@ Camera

Camera

[ HiddenRefParameters ]

GetCameraForward/camera
GetCameraUp/camera
GetCameraRight/camera
GetCameraViewMatrix/camera
GetCameraProjectionMatrix/camera

[ NoSideEffectsFuncs ]

GetCameraForward
Expand Down
6 changes: 4 additions & 2 deletions tools/wrapper/ctypes.nim
Original file line number Diff line number Diff line change
Expand Up @@ -65,16 +65,17 @@ type
ptOut
ptArray
ptOpenArray
ptHidden

proc convertPointerType(s: sink string, pointerType: PointerType): string =
result = s
if result.contains('*'):
let pointerDepth = result.count('*')
result = result.replace(" *", "")
result = result.replace("*", "")
for i in 1..pointerDepth - ord(pointerType in {ptVar, ptOut, ptOpenArray}):
for i in 1..pointerDepth - ord(pointerType in {ptVar, ptOut, ptOpenArray, ptHidden}):
case pointerType:
of ptPtr, ptVar, ptOut, ptOpenArray:
of ptPtr, ptVar, ptOut, ptOpenArray, ptHidden:
result = "ptr " & result
of ptArray:
result = "ptr UncheckedArray[" & result & "]"
Expand Down Expand Up @@ -119,6 +120,7 @@ proc convertType*(s: string; prefix = ""; pointerType = ptPtr): string =
when isMainModule:
import std/assertions

assert convertType("Camera *", pointerType = ptHidden) == "Camera"
assert convertType("rlDrawCall", "rl") == "DrawCall"
assert convertType("BorderlessWindowed", prefix = "rl") == "BorderlessWindowed"
assert convertType("int[RL_MAX_GAMEPADS]", "RL_") == "array[MaxGamepads, int32]"
Expand Down
9 changes: 9 additions & 0 deletions tools/wrapper/processor.nim
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ proc checkCstringType(fnc: FunctionInfo, kind: string, config: ConfigData): bool
proc isOpenArrayParameter(x, y: string, config: ConfigData): bool =
(x, y) in config.openArrayParameters

proc isHiddenRefParameter(x, y: string, config: ConfigData): bool =
(x, y) in config.hiddenRefParameters

proc isVarargsParam(param: ParamInfo): bool =
param.name == "args" and param.`type` == "..."

Expand Down Expand Up @@ -194,8 +197,11 @@ proc processParameters(fnc: var FunctionInfo, config: ConfigData) =
for i, param in enumerate(fnc.params.mitems):
if isArray(fnc.name, param.name, config):
param.flags.incl isPtArray
if isHiddenRefParameter(fnc.name, param.name, config):
param.flags.incl isHiddenRefParam
let pointerType =
if isPtArray in param.flags: ptArray
elif isHiddenRefParam in param.flags: ptHidden
elif isOutParameter(fnc.name, param.name, config): ptOut
elif isPrivate notin fnc.flags: ptVar
else: ptPtr
Expand All @@ -213,6 +219,8 @@ proc processParameters(fnc: var FunctionInfo, config: ConfigData) =
if paramType.startsWith("var "):
param.flags.incl isVarParam
param.dirty = paramType
if isHiddenRefParam in param.flags:
param.dirty = paramType

proc processReturnType(fnc: var FunctionInfo, config: ConfigData) =
if fnc.returnType != "void":
Expand All @@ -234,6 +242,7 @@ proc updateParameterTypes(fnc: var FunctionInfo, config: ConfigData) =
let pointerType =
if isPtArray in param.flags: ptArray
elif isOutParameter(fnc.name, param.name, config): ptOut
elif isHiddenRefParam in param.flags: (if isPrivate in fnc.flags: ptPtr else: ptHidden)
elif isPrivate notin fnc.flags: ptVar
else: ptPtr
updateType(param.`type`, fnc.name, param.name, pointerType, config)
Expand Down
Loading