From 63c9cd8bf3aca1409449a8f6d0136cbfcc0b5b08 Mon Sep 17 00:00:00 2001 From: BrownNPC Date: Tue, 27 Jan 2026 06:36:34 +0500 Subject: [PATCH 01/12] v2 --- raylib/raylib.go | 159 +- raylib/raylib_wasm.go | 122 -- raylib/rcore_wasm.go | 3951 ----------------------------------------- 3 files changed, 92 insertions(+), 4140 deletions(-) delete mode 100644 raylib/raylib_wasm.go delete mode 100644 raylib/rcore_wasm.go diff --git a/raylib/raylib.go b/raylib/raylib.go index 3aff8b1..92a7d3f 100644 --- a/raylib/raylib.go +++ b/raylib/raylib.go @@ -11,10 +11,15 @@ package rl import ( "image/color" "io" - - wasm "github.com/BrownNPC/wasm-ffi-go" + "io/fs" + "runtime" + "unsafe" ) +func init() { + // Make sure the main goroutine is bound to the main thread. + runtime.LockOSThread() +} // Wave type, defines audio wave data type Wave struct { @@ -27,15 +32,15 @@ type Wave struct { // Number of channels (1-mono, 2-stereo) Channels uint32 // Buffer data pointer - Data wasm.Pointer + Data unsafe.Pointer } -// // NewWave - Returns new Wave -// func NewWave(sampleCount, sampleRate, sampleSize, channels uint32, data []byte) Wave { -// d := wasm.Pointer(&data[0]) +// NewWave - Returns new Wave +func NewWave(sampleCount, sampleRate, sampleSize, channels uint32, data []byte) Wave { + d := unsafe.Pointer(&data[0]) -// return Wave{sampleCount, sampleRate, sampleSize, channels, d} -// } + return Wave{sampleCount, sampleRate, sampleSize, channels, d} +} // AudioCallback function. type AudioCallback func(data []float32, frames int) @@ -54,7 +59,7 @@ type Music struct { FrameCount uint32 Looping bool CtxType int32 - CtxData wasm.Pointer + CtxData unsafe.Pointer } // AudioStream type @@ -178,12 +183,12 @@ type AutomationEventList struct { Events *AutomationEvent } -// func (a *AutomationEventList) GetEvents() []AutomationEvent { -// return wasm.Slice(a.Events, a.Count) -// } +func (a *AutomationEventList) GetEvents() []AutomationEvent { + return unsafe.Slice(a.Events, a.Count) +} // CameraMode type -type CameraMode = int32 +type CameraMode int32 // Camera system modes const ( @@ -195,7 +200,7 @@ const ( ) // CameraProjection type -type CameraProjection = int32 +type CameraProjection int32 // Camera projection modes const ( @@ -369,7 +374,7 @@ const ( MouseMiddleButton = MouseButtonMiddle ) -type MouseButton = int32 +type MouseButton int32 // Mouse Buttons const ( @@ -662,14 +667,34 @@ func NewBoundingBox(min, max Vector3) BoundingBox { return BoundingBox{min, max} } -// Asset file -type Asset interface { +// Asset implements fs.FS interfaces +type Asset struct { + root string + fsys fs.FS +} + +// NewAsset - creates a new Asset filesystem +// For Android: root should be empty or a directory path within assets +// For Desktop: root should be the filesystem path to assets +func NewAsset(root string) *Asset { + return &Asset{root: root} +} + +// NewAssetFromFS - creates a new Asset filesystem from a fs.FS +// The root parameter specifies a subdirectory within the embedded filesystem (can be empty for root) +func NewAssetFromFS(fsys fs.FS, root string) *Asset { + return &Asset{root: root, fsys: fsys} +} + +// AssetFile represents an opened asset file +type AssetFile interface { io.ReadSeeker io.Closer + Stat() (fs.FileInfo, error) } // Gestures type -type Gestures = int32 +type Gestures int32 // Gestures types // NOTE: It could be used as flags to enable only some gestures @@ -721,7 +746,7 @@ const ( ) // ShaderUniformDataType type -type ShaderUniformDataType = int32 +type ShaderUniformDataType int32 // ShaderUniformDataType enumeration const ( @@ -828,10 +853,10 @@ type Material struct { Params [4]float32 } -// // GetMap - Get pointer to MaterialMap by map type -// func (mt Material) GetMap(index int32) *MaterialMap { -// return (*MaterialMap)(wasm.Pointer(uintptr(wasm.Pointer(mt.Maps)) + uintptr(index)*wasm.Sizeof(MaterialMap{}))) -// } +// GetMap - Get pointer to MaterialMap by map type +func (mt Material) GetMap(index int32) *MaterialMap { + return (*MaterialMap)(unsafe.Pointer(uintptr(unsafe.Pointer(mt.Maps)) + uintptr(index)*unsafe.Sizeof(MaterialMap{}))) +} // MaterialMap type type MaterialMap struct { @@ -873,25 +898,25 @@ type Model struct { BindPose *Transform } -// // GetMeshes returns the meshes of a model as go slice -// func (m Model) GetMeshes() []Mesh { -// return wasm.Slice(m.Meshes, m.MeshCount) -// } +// GetMeshes returns the meshes of a model as go slice +func (m Model) GetMeshes() []Mesh { + return unsafe.Slice(m.Meshes, m.MeshCount) +} -// // GetMaterials returns the materials of a model as go slice -// func (m Model) GetMaterials() []Material { -// return wasm.Slice(m.Materials, m.MaterialCount) -// } +// GetMaterials returns the materials of a model as go slice +func (m Model) GetMaterials() []Material { + return unsafe.Slice(m.Materials, m.MaterialCount) +} -// // GetBones returns the bones information (skeleton) of a model as go slice -// func (m Model) GetBones() []BoneInfo { -// return wasm.Slice(m.Bones, m.BoneCount) -// } +// GetBones returns the bones information (skeleton) of a model as go slice +func (m Model) GetBones() []BoneInfo { + return unsafe.Slice(m.Bones, m.BoneCount) +} -// // GetBindPose returns the bones base transformation of a model as go slice -// func (m Model) GetBindPose() []Transform { -// return wasm.Slice(m.BindPose, m.BoneCount) -// } +// GetBindPose returns the bones base transformation of a model as go slice +func (m Model) GetBindPose() []Transform { + return unsafe.Slice(m.BindPose, m.BoneCount) +} // BoneInfo type type BoneInfo struct { @@ -928,16 +953,16 @@ type ModelAnimation struct { Name [32]uint8 } -// // GetBones returns the bones information (skeleton) of a ModelAnimation as go slice -// func (m ModelAnimation) GetBones() []BoneInfo { -// return wasm.Slice(m.Bones, m.BoneCount) -// } +// GetBones returns the bones information (skeleton) of a ModelAnimation as go slice +func (m ModelAnimation) GetBones() []BoneInfo { + return unsafe.Slice(m.Bones, m.BoneCount) +} -// // GetFramePose returns the Transform for a specific bone at a specific frame -// func (m ModelAnimation) GetFramePose(frame, bone int) Transform { -// framePoses := wasm.Slice(m.FramePoses, m.FrameCount) -// return wasm.Slice(framePoses[frame], m.BoneCount)[bone] -// } +// GetFramePose returns the Transform for a specific bone at a specific frame +func (m ModelAnimation) GetFramePose(frame, bone int) Transform { + framePoses := unsafe.Slice(m.FramePoses, m.FrameCount) + return unsafe.Slice(framePoses[frame], m.BoneCount)[bone] +} // GetName returns the ModelAnimation's name as go string func (m ModelAnimation) GetName() string { @@ -964,7 +989,7 @@ func NewRayCollision(hit bool, distance float32, point, normal Vector3) RayColli } // BlendMode type -type BlendMode = int32 +type BlendMode int32 // Color blending modes (pre-defined) const ( @@ -991,15 +1016,15 @@ func NewShader(id uint32, locs *int32) Shader { return Shader{id, locs} } -// // GetLocation - Get shader value's location -// func (sh Shader) GetLocation(index int32) int32 { -// return *(*int32)(wasm.Pointer(uintptr(wasm.Pointer(sh.Locs)) + uintptr(index*4))) -// } +// GetLocation - Get shader value's location +func (sh Shader) GetLocation(index int32) int32 { + return *(*int32)(unsafe.Pointer(uintptr(unsafe.Pointer(sh.Locs)) + uintptr(index*4))) +} -// // UpdateLocation - Update shader value's location -// func (sh Shader) UpdateLocation(index int32, loc int32) { -// *(*int32)(wasm.Pointer(uintptr(wasm.Pointer(sh.Locs)) + uintptr(index*4))) = loc -// } +// UpdateLocation - Update shader value's location +func (sh Shader) UpdateLocation(index int32, loc int32) { + *(*int32)(unsafe.Pointer(uintptr(unsafe.Pointer(sh.Locs)) + uintptr(index*4))) = loc +} // GlyphInfo - Font character info type GlyphInfo struct { @@ -1094,7 +1119,7 @@ const ( ) // TextureFilterMode - Texture filter mode -type TextureFilterMode = int32 +type TextureFilterMode int32 // Texture parameters: filter mode // NOTE 1: Filtering considers mipmaps if available in the texture @@ -1115,7 +1140,7 @@ const ( ) // TextureWrapMode - Texture wrap mode -type TextureWrapMode = int32 +type TextureWrapMode int32 // Texture parameters: wrap mode const ( @@ -1138,7 +1163,7 @@ const ( // NOTE: Data stored in CPU memory (RAM) type Image struct { // Image raw Data - Data wasm.Pointer + Data unsafe.Pointer // Image base width Width int32 // Image base height @@ -1149,12 +1174,12 @@ type Image struct { Format PixelFormat } -// // NewImage - Returns new Image -// func NewImage(data []byte, width, height, mipmaps int32, format PixelFormat) *Image { -// d := wasm.Pointer(&data[0]) +// NewImage - Returns new Image +func NewImage(data []byte, width, height, mipmaps int32, format PixelFormat) *Image { + d := unsafe.Pointer(&data[0]) -// return &Image{d, width, height, mipmaps, format} -// } + return &Image{d, width, height, mipmaps, format} +} // Texture2D type, bpp always RGBA (32bit) // NOTE: Data stored in GPU memory @@ -1195,7 +1220,7 @@ func NewRenderTexture2D(id uint32, texture, depth Texture2D) RenderTexture2D { type TraceLogCallbackFun func(int, string) // TraceLogLevel parameter of trace log message -type TraceLogLevel = int +type TraceLogLevel int // Trace log level // NOTE: Organized by priority level @@ -1219,7 +1244,7 @@ const ( ) // N-patch layout -type NPatchLayout = int32 +type NPatchLayout int32 const ( NPatchNinePatch NPatchLayout = iota // Npatch layout: 3x3 tiles diff --git a/raylib/raylib_wasm.go b/raylib/raylib_wasm.go deleted file mode 100644 index 096031f..0000000 --- a/raylib/raylib_wasm.go +++ /dev/null @@ -1,122 +0,0 @@ -//go:build js && wasm - -package rl - -// some functions need to be defined manually - -import ( - "image" - "image/color" - "io/fs" - "syscall/js" - - "github.com/BrownNPC/wasm-ffi-go" -) - -// DEPRECATED: use SetMain instead. -var SetMainLoop = SetMain - -// Use this instead of a for loop on web platform -func SetMain(UpdateAndDrawFrame func()) { - wasm.SetMainLoop(UpdateAndDrawFrame) - <-make(chan struct{}, 0) -} - -// Copy embed.FS to wasm memory. This must be called before loading assets -// pass it an embed.FS -func AddFileSystem(efs fs.FS) { - wasm.AddFileSystem(efs) -} - -// UNSUPPORTED: USE SetMainLoop -func WindowShouldClose() bool { - wasm.Panic("WindowShouldClose is unsupported on the web, use SetMainLoop") - return true -} - -var setTraceLogCallback = wasm.Proc("SetTraceLogCallback") - -// SetTraceLogCallback - Set custom trace log -func SetTraceLogCallback(fn TraceLogCallbackFun) { - _, fl := setTraceLogCallback.Call(js.FuncOf(func(this js.Value, args []js.Value) any { - fn(args[0].Int(), args[1].String()) - return nil - })) - wasm.Free(fl...) -} - -var initWindow = wasm.Proc("InitWindow") - -// InitWindow - Initialize window and OpenGL context -func InitWindow(width int32, height int32, title string) { - if width == 0 { - width = int32(js.Global().Get("innerWidth").Int()) - } - if height == 0 { - height = int32(js.Global().Get("innerHeight").Int()) - } - _, fl := initWindow.Call(width, height, title) - wasm.Free(fl...) -} - -var loadFontEx = wasm.Func[Font]("LoadFontEx") - -// LoadFontEx - Load font from file with extended parameters, use NULL for codepoints and 0 for codepointCount to load the default character setFont -func LoadFontEx(fileName string, fontSize int32, codepoints []rune, runesNumber ...int32) Font { - codepointCount := int32(len(codepoints)) - if len(runesNumber) > 0 { - codepointCount = int32(runesNumber[0]) - } - - // Handle empty codepoints slice by passing nil - var codepointsToPass any = codepoints - if len(codepoints) == 0 { - codepointsToPass = nil - } - - ret, fl := loadFontEx.Call(fileName, fontSize, codepointsToPass, codepointCount) - v := wasm.ReadStruct[Font](ret) - wasm.Free(fl...) - return v -} - -// NewImageFromImage - Returns new Image from Go image.Image - -// NewImageFromImage - Returns new Image from Go image.Image -func NewImageFromImage(img image.Image) *Image { - size := img.Bounds().Size() - - ret := GenImageColor(size.X, size.Y, White) - - for y := range size.Y { - for x := range size.X { - col := img.At(x, y) - r, g, b, a := col.RGBA() - rcolor := NewColor(uint8(r>>8), uint8(g>>8), uint8(b>>8), uint8(a>>8)) - ImageDrawPixel(ret, int32(x), int32(y), rcolor) - } - } - return ret -} - -// GenImageColor - Generate image: plain color -func GenImageColor(width int, height int, col color.RGBA) *Image { - ret, fl := genImageColor.Call(width, height, wasm.Struct(col)) - v := wasm.ReadStruct[Image](ret) - wasm.Free(fl...) - return &v -} - -// LoadTextureFromImage - Load texture from image data -func LoadTextureFromImage(image *Image) Texture2D { - ret, fl := loadTextureFromImage.Call(wasm.Struct(*image)) - v := wasm.ReadStruct[Texture2D](ret) - wasm.Free(fl...) - return v -} - -// ImageDrawPixel - Draw pixel within an image -func ImageDrawPixel(dst *Image, posX int32, posY int32, col color.RGBA) { - _, fl := imageDrawPixel.Call(wasm.Struct(*dst), posX, posY, wasm.Struct(col)) - wasm.Free(fl...) -} diff --git a/raylib/rcore_wasm.go b/raylib/rcore_wasm.go deleted file mode 100644 index 71b447e..0000000 --- a/raylib/rcore_wasm.go +++ /dev/null @@ -1,3951 +0,0 @@ -package rl - -import ( - "image" - "image/color" - "unsafe" - - wasm "github.com/BrownNPC/wasm-ffi-go" -) - -var closeWindow = wasm.Proc("CloseWindow") -var isWindowReady = wasm.Func[bool]("IsWindowReady") -var isWindowFullscreen = wasm.Func[bool]("IsWindowFullscreen") -var isWindowResized = wasm.Func[bool]("IsWindowResized") -var isWindowState = wasm.Func[bool]("IsWindowState") -var clearWindowState = wasm.Proc("ClearWindowState") -var setWindowIcon = wasm.Proc("SetWindowIcon") -var setWindowIcons = wasm.Proc("SetWindowIcons") -var setWindowTitle = wasm.Proc("SetWindowTitle") -var setWindowMonitor = wasm.Proc("SetWindowMonitor") -var setWindowMinSize = wasm.Proc("SetWindowMinSize") -var setWindowMaxSize = wasm.Proc("SetWindowMaxSize") -var setWindowSize = wasm.Proc("SetWindowSize") -var getWindowHandle = wasm.Func[unsafe.Pointer]("GetWindowHandle") -var getScreenWidth = wasm.Func[int]("GetScreenWidth") -var getScreenHeight = wasm.Func[int]("GetScreenHeight") -var getRenderWidth = wasm.Func[int]("GetRenderWidth") -var getRenderHeight = wasm.Func[int]("GetRenderHeight") -var getMonitorCount = wasm.Func[int]("GetMonitorCount") -var getCurrentMonitor = wasm.Func[int]("GetCurrentMonitor") -var getMonitorPosition = wasm.Func[Vector2]("GetMonitorPosition") -var getMonitorWidth = wasm.Func[int]("GetMonitorWidth") -var getMonitorHeight = wasm.Func[int]("GetMonitorHeight") -var getMonitorPhysicalWidth = wasm.Func[int]("GetMonitorPhysicalWidth") -var getMonitorPhysicalHeight = wasm.Func[int]("GetMonitorPhysicalHeight") -var getMonitorRefreshRate = wasm.Func[int]("GetMonitorRefreshRate") -var getWindowPosition = wasm.Func[Vector2]("GetWindowPosition") -var getWindowScaleDPI = wasm.Func[Vector2]("GetWindowScaleDPI") -var getMonitorName = wasm.Func[string]("GetMonitorName") -var setClipboardText = wasm.Proc("SetClipboardText") -var getClipboardText = wasm.Func[string]("GetClipboardText") -var getClipboardImage = wasm.Func[Image]("GetClipboardImage") -var enableEventWaiting = wasm.Proc("EnableEventWaiting") -var disableEventWaiting = wasm.Proc("DisableEventWaiting") -var showCursor = wasm.Proc("ShowCursor") -var hideCursor = wasm.Proc("HideCursor") -var isCursorHidden = wasm.Func[bool]("IsCursorHidden") -var enableCursor = wasm.Proc("EnableCursor") -var disableCursor = wasm.Proc("DisableCursor") -var isCursorOnScreen = wasm.Func[bool]("IsCursorOnScreen") -var clearBackground = wasm.Proc("ClearBackground") -var beginDrawing = wasm.Proc("BeginDrawing") -var endDrawing = wasm.Proc("EndDrawing") -var beginMode2D = wasm.Proc("BeginMode2D") -var endMode2D = wasm.Proc("EndMode2D") -var beginMode3D = wasm.Proc("BeginMode3D") -var endMode3D = wasm.Proc("EndMode3D") -var beginTextureMode = wasm.Proc("BeginTextureMode") -var endTextureMode = wasm.Proc("EndTextureMode") -var beginShaderMode = wasm.Proc("BeginShaderMode") -var endShaderMode = wasm.Proc("EndShaderMode") -var beginBlendMode = wasm.Proc("BeginBlendMode") -var endBlendMode = wasm.Proc("EndBlendMode") -var beginScissorMode = wasm.Proc("BeginScissorMode") -var endScissorMode = wasm.Proc("EndScissorMode") -var beginVrStereoMode = wasm.Proc("BeginVrStereoMode") -var endVrStereoMode = wasm.Proc("EndVrStereoMode") -var loadVrStereoConfig = wasm.Func[VrStereoConfig]("LoadVrStereoConfig") -var unloadVrStereoConfig = wasm.Proc("UnloadVrStereoConfig") -var loadShader = wasm.Func[Shader]("LoadShader") -var loadShaderFromMemory = wasm.Func[Shader]("LoadShaderFromMemory") -var isShaderValid = wasm.Func[bool]("IsShaderValid") -var getShaderLocation = wasm.Func[int32]("GetShaderLocation") -var getShaderLocationAttrib = wasm.Func[int32]("GetShaderLocationAttrib") -var setShaderValue = wasm.Proc("SetShaderValue") -var setShaderValueV = wasm.Proc("SetShaderValueV") -var setShaderValueMatrix = wasm.Proc("SetShaderValueMatrix") -var setShaderValueTexture = wasm.Proc("SetShaderValueTexture") -var unloadShader = wasm.Proc("UnloadShader") -var getMouseRay = wasm.Func[Ray]("GetMouseRay") -var getScreenToWorldRay = wasm.Func[Ray]("GetScreenToWorldRay") -var getScreenToWorldRayEx = wasm.Func[Ray]("GetScreenToWorldRayEx") -var getCameraMatrix = wasm.Func[Matrix]("GetCameraMatrix") -var getCameraMatrix2D = wasm.Func[Matrix]("GetCameraMatrix2D") -var getWorldToScreen = wasm.Func[Vector2]("GetWorldToScreen") -var getScreenToWorld2D = wasm.Func[Vector2]("GetScreenToWorld2D") -var getWorldToScreenEx = wasm.Func[Vector2]("GetWorldToScreenEx") -var getWorldToScreen2D = wasm.Func[Vector2]("GetWorldToScreen2D") -var setTargetFPS = wasm.Proc("SetTargetFPS") -var getFrameTime = wasm.Func[float32]("GetFrameTime") -var getTime = wasm.Func[float64]("GetTime") -var getFPS = wasm.Func[int32]("GetFPS") -var swapScreenBuffer = wasm.Proc("SwapScreenBuffer") -var pollInputEvents = wasm.Proc("PollInputEvents") -var waitTime = wasm.Proc("WaitTime") -var setRandomSeed = wasm.Proc("SetRandomSeed") -var getRandomValue = wasm.Func[int32]("GetRandomValue") -var loadRandomSequence = wasm.Func[[]int32]("LoadRandomSequence") -var unloadRandomSequence = wasm.Proc("UnloadRandomSequence") -var takeScreenshot = wasm.Proc("TakeScreenshot") -var setConfigFlags = wasm.Proc("SetConfigFlags") -var openURL = wasm.Proc("OpenURL") -var traceLog = wasm.Proc("TraceLog") -var setTraceLogLevel = wasm.Proc("SetTraceLogLevel") -var memAlloc = wasm.Func[unsafe.Pointer]("MemAlloc") -var memRealloc = wasm.Func[unsafe.Pointer]("MemRealloc") -var memFree = wasm.Proc("MemFree") -var isFileDropped = wasm.Func[bool]("IsFileDropped") -var loadDroppedFiles = wasm.Func[[]string]("LoadDroppedFiles") -var unloadDroppedFiles = wasm.Proc("UnloadDroppedFiles") -var loadAutomationEventList = wasm.Func[AutomationEventList]("LoadAutomationEventList") -var unloadAutomationEventList = wasm.Proc("UnloadAutomationEventList") -var exportAutomationEventList = wasm.Func[bool]("ExportAutomationEventList") -var setAutomationEventList = wasm.Proc("SetAutomationEventList") -var setAutomationEventBaseFrame = wasm.Proc("SetAutomationEventBaseFrame") -var startAutomationEventRecording = wasm.Proc("StartAutomationEventRecording") -var stopAutomationEventRecording = wasm.Proc("StopAutomationEventRecording") -var playAutomationEvent = wasm.Proc("PlayAutomationEvent") -var isKeyPressed = wasm.Func[bool]("IsKeyPressed") -var isKeyPressedRepeat = wasm.Func[bool]("IsKeyPressedRepeat") -var isKeyDown = wasm.Func[bool]("IsKeyDown") -var isKeyReleased = wasm.Func[bool]("IsKeyReleased") -var isKeyUp = wasm.Func[bool]("IsKeyUp") -var getKeyPressed = wasm.Func[int32]("GetKeyPressed") -var getCharPressed = wasm.Func[int32]("GetCharPressed") -var setExitKey = wasm.Proc("SetExitKey") -var isGamepadAvailable = wasm.Func[bool]("IsGamepadAvailable") -var getGamepadName = wasm.Func[string]("GetGamepadName") -var isGamepadButtonPressed = wasm.Func[bool]("IsGamepadButtonPressed") -var isGamepadButtonDown = wasm.Func[bool]("IsGamepadButtonDown") -var isGamepadButtonReleased = wasm.Func[bool]("IsGamepadButtonReleased") -var isGamepadButtonUp = wasm.Func[bool]("IsGamepadButtonUp") -var getGamepadButtonPressed = wasm.Func[int32]("GetGamepadButtonPressed") -var getGamepadAxisCount = wasm.Func[int32]("GetGamepadAxisCount") -var getGamepadAxisMovement = wasm.Func[float32]("GetGamepadAxisMovement") -var setGamepadMappings = wasm.Func[int32]("SetGamepadMappings") -var setGamepadVibration = wasm.Proc("SetGamepadVibration") -var isMouseButtonPressed = wasm.Func[bool]("IsMouseButtonPressed") -var isMouseButtonDown = wasm.Func[bool]("IsMouseButtonDown") -var isMouseButtonReleased = wasm.Func[bool]("IsMouseButtonReleased") -var isMouseButtonUp = wasm.Func[bool]("IsMouseButtonUp") -var getMouseX = wasm.Func[int32]("GetMouseX") -var getMouseY = wasm.Func[int32]("GetMouseY") -var getMousePosition = wasm.Func[Vector2]("GetMousePosition") -var getMouseDelta = wasm.Func[Vector2]("GetMouseDelta") -var setMousePosition = wasm.Proc("SetMousePosition") -var setMouseOffset = wasm.Proc("SetMouseOffset") -var setMouseScale = wasm.Proc("SetMouseScale") -var getMouseWheelMove = wasm.Func[float32]("GetMouseWheelMove") -var getMouseWheelMoveV = wasm.Func[Vector2]("GetMouseWheelMoveV") -var setMouseCursor = wasm.Proc("SetMouseCursor") -var getTouchX = wasm.Func[int32]("GetTouchX") -var getTouchY = wasm.Func[int32]("GetTouchY") -var getTouchPosition = wasm.Func[Vector2]("GetTouchPosition") -var getTouchPointId = wasm.Func[int32]("GetTouchPointId") -var getTouchPointCount = wasm.Func[int32]("GetTouchPointCount") -var setGesturesEnabled = wasm.Proc("SetGesturesEnabled") -var isGestureDetected = wasm.Func[bool]("IsGestureDetected") -var getGestureDetected = wasm.Func[Gestures]("GetGestureDetected") -var getGestureHoldDuration = wasm.Func[float32]("GetGestureHoldDuration") -var getGestureDragVector = wasm.Func[Vector2]("GetGestureDragVector") -var getGestureDragAngle = wasm.Func[float32]("GetGestureDragAngle") -var getGesturePinchVector = wasm.Func[Vector2]("GetGesturePinchVector") -var getGesturePinchAngle = wasm.Func[float32]("GetGesturePinchAngle") -var setShapesTexture = wasm.Proc("SetShapesTexture") -var getShapesTexture = wasm.Func[Texture2D]("GetShapesTexture") -var getShapesTextureRectangle = wasm.Func[Rectangle]("GetShapesTextureRectangle") -var drawPixel = wasm.Proc("DrawPixel") -var drawPixelV = wasm.Proc("DrawPixelV") -var drawLine = wasm.Proc("DrawLine") -var drawLineV = wasm.Proc("DrawLineV") -var drawLineEx = wasm.Proc("DrawLineEx") -var drawLineStrip = wasm.Proc("DrawLineStrip") -var drawLineBezier = wasm.Proc("DrawLineBezier") -var drawCircle = wasm.Proc("DrawCircle") -var drawCircleSector = wasm.Proc("DrawCircleSector") -var drawCircleSectorLines = wasm.Proc("DrawCircleSectorLines") -var drawCircleGradient = wasm.Proc("DrawCircleGradient") -var drawCircleV = wasm.Proc("DrawCircleV") -var drawCircleLines = wasm.Proc("DrawCircleLines") -var drawCircleLinesV = wasm.Proc("DrawCircleLinesV") -var drawEllipse = wasm.Proc("DrawEllipse") -var drawEllipseLines = wasm.Proc("DrawEllipseLines") -var drawRing = wasm.Proc("DrawRing") -var drawRingLines = wasm.Proc("DrawRingLines") -var drawRectangle = wasm.Proc("DrawRectangle") -var drawRectangleV = wasm.Proc("DrawRectangleV") -var drawRectangleRec = wasm.Proc("DrawRectangleRec") -var drawRectanglePro = wasm.Proc("DrawRectanglePro") -var drawRectangleGradientV = wasm.Proc("DrawRectangleGradientV") -var drawRectangleGradientH = wasm.Proc("DrawRectangleGradientH") -var drawRectangleGradientEx = wasm.Proc("DrawRectangleGradientEx") -var drawRectangleLines = wasm.Proc("DrawRectangleLines") -var drawRectangleLinesEx = wasm.Proc("DrawRectangleLinesEx") -var drawRectangleRounded = wasm.Proc("DrawRectangleRounded") -var drawRectangleRoundedLines = wasm.Proc("DrawRectangleRoundedLines") -var drawRectangleRoundedLinesEx = wasm.Proc("DrawRectangleRoundedLinesEx") -var drawTriangle = wasm.Proc("DrawTriangle") -var drawTriangleLines = wasm.Proc("DrawTriangleLines") -var drawTriangleFan = wasm.Proc("DrawTriangleFan") -var drawTriangleStrip = wasm.Proc("DrawTriangleStrip") -var drawPoly = wasm.Proc("DrawPoly") -var drawPolyLines = wasm.Proc("DrawPolyLines") -var drawPolyLinesEx = wasm.Proc("DrawPolyLinesEx") -var drawSplineLinear = wasm.Proc("DrawSplineLinear") -var drawSplineBasis = wasm.Proc("DrawSplineBasis") -var drawSplineCatmullRom = wasm.Proc("DrawSplineCatmullRom") -var drawSplineBezierQuadratic = wasm.Proc("DrawSplineBezierQuadratic") -var drawSplineBezierCubic = wasm.Proc("DrawSplineBezierCubic") -var drawSplineSegmentLinear = wasm.Proc("DrawSplineSegmentLinear") -var drawSplineSegmentBasis = wasm.Proc("DrawSplineSegmentBasis") -var drawSplineSegmentCatmullRom = wasm.Proc("DrawSplineSegmentCatmullRom") -var drawSplineSegmentBezierQuadratic = wasm.Proc("DrawSplineSegmentBezierQuadratic") -var drawSplineSegmentBezierCubic = wasm.Proc("DrawSplineSegmentBezierCubic") -var getSplinePointLinear = wasm.Func[Vector2]("GetSplinePointLinear") -var getSplinePointBasis = wasm.Func[Vector2]("GetSplinePointBasis") -var getSplinePointCatmullRom = wasm.Func[Vector2]("GetSplinePointCatmullRom") -var getSplinePointBezierQuad = wasm.Func[Vector2]("GetSplinePointBezierQuad") -var getSplinePointBezierCubic = wasm.Func[Vector2]("GetSplinePointBezierCubic") -var checkCollisionRecs = wasm.Func[bool]("CheckCollisionRecs") -var checkCollisionCircles = wasm.Func[bool]("CheckCollisionCircles") -var checkCollisionCircleRec = wasm.Func[bool]("CheckCollisionCircleRec") -var checkCollisionCircleLine = wasm.Func[bool]("CheckCollisionCircleLine") -var checkCollisionPointRec = wasm.Func[bool]("CheckCollisionPointRec") -var checkCollisionPointCircle = wasm.Func[bool]("CheckCollisionPointCircle") -var checkCollisionPointTriangle = wasm.Func[bool]("CheckCollisionPointTriangle") -var checkCollisionPointPoly = wasm.Func[bool]("CheckCollisionPointPoly") -var checkCollisionLines = wasm.Func[bool]("CheckCollisionLines") -var checkCollisionPointLine = wasm.Func[bool]("CheckCollisionPointLine") -var getCollisionRec = wasm.Func[Rectangle]("GetCollisionRec") -var loadImage = wasm.Func[*Image]("LoadImage") -var loadImageRaw = wasm.Func[*Image]("LoadImageRaw") -var loadImageAnim = wasm.Func[*Image]("LoadImageAnim") -var loadImageAnimFromMemory = wasm.Func[*Image]("LoadImageAnimFromMemory") -var loadImageFromMemory = wasm.Func[*Image]("LoadImageFromMemory") -var loadImageFromTexture = wasm.Func[*Image]("LoadImageFromTexture") -var loadImageFromScreen = wasm.Func[*Image]("LoadImageFromScreen") -var isImageValid = wasm.Func[bool]("IsImageValid") -var unloadImage = wasm.Proc("UnloadImage") -var exportImage = wasm.Func[bool]("ExportImage") -var exportImageToMemory = wasm.Func[[]byte]("ExportImageToMemory") -var genImageColor = wasm.Func[*Image]("GenImageColor") -var genImageGradientLinear = wasm.Func[*Image]("GenImageGradientLinear") -var genImageGradientRadial = wasm.Func[*Image]("GenImageGradientRadial") -var genImageGradientSquare = wasm.Func[*Image]("GenImageGradientSquare") -var genImageChecked = wasm.Func[*Image]("GenImageChecked") -var genImageWhiteNoise = wasm.Func[*Image]("GenImageWhiteNoise") -var genImagePerlinNoise = wasm.Func[*Image]("GenImagePerlinNoise") -var genImageCellular = wasm.Func[*Image]("GenImageCellular") -var genImageText = wasm.Func[Image]("GenImageText") -var imageCopy = wasm.Func[*Image]("ImageCopy") -var imageFromImage = wasm.Func[Image]("ImageFromImage") -var imageFromChannel = wasm.Func[Image]("ImageFromChannel") -var imageText = wasm.Func[Image]("ImageText") -var imageTextEx = wasm.Func[Image]("ImageTextEx") -var imageFormat = wasm.Proc("ImageFormat") -var imageToPOT = wasm.Proc("ImageToPOT") -var imageCrop = wasm.Proc("ImageCrop") -var imageAlphaCrop = wasm.Proc("ImageAlphaCrop") -var imageAlphaClear = wasm.Proc("ImageAlphaClear") -var imageAlphaMask = wasm.Proc("ImageAlphaMask") -var imageAlphaPremultiply = wasm.Proc("ImageAlphaPremultiply") -var imageBlurGaussian = wasm.Proc("ImageBlurGaussian") -var imageKernelConvolution = wasm.Proc("ImageKernelConvolution") -var imageResize = wasm.Proc("ImageResize") -var imageResizeNN = wasm.Proc("ImageResizeNN") -var imageResizeCanvas = wasm.Proc("ImageResizeCanvas") -var imageMipmaps = wasm.Proc("ImageMipmaps") -var imageDither = wasm.Proc("ImageDither") -var imageFlipVertical = wasm.Proc("ImageFlipVertical") -var imageFlipHorizontal = wasm.Proc("ImageFlipHorizontal") -var imageRotate = wasm.Proc("ImageRotate") -var imageRotateCW = wasm.Proc("ImageRotateCW") -var imageRotateCCW = wasm.Proc("ImageRotateCCW") -var imageColorTint = wasm.Proc("ImageColorTint") -var imageColorInvert = wasm.Proc("ImageColorInvert") -var imageColorGrayscale = wasm.Proc("ImageColorGrayscale") -var imageColorContrast = wasm.Proc("ImageColorContrast") -var imageColorBrightness = wasm.Proc("ImageColorBrightness") -var imageColorReplace = wasm.Proc("ImageColorReplace") -var loadImageColors = wasm.Func[[]color.RGBA]("LoadImageColors") -var loadImagePalette = wasm.Func[[]color.RGBA]("LoadImagePalette") -var unloadImageColors = wasm.Proc("UnloadImageColors") -var unloadImagePalette = wasm.Proc("UnloadImagePalette") -var getImageAlphaBorder = wasm.Func[Rectangle]("GetImageAlphaBorder") -var getImageColor = wasm.Func[color.RGBA]("GetImageColor") -var imageClearBackground = wasm.Proc("ImageClearBackground") -var imageDrawPixel = wasm.Proc("ImageDrawPixel") -var imageDrawPixelV = wasm.Proc("ImageDrawPixelV") -var imageDrawLine = wasm.Proc("ImageDrawLine") -var imageDrawLineV = wasm.Proc("ImageDrawLineV") -var imageDrawLineEx = wasm.Proc("ImageDrawLineEx") -var imageDrawCircle = wasm.Proc("ImageDrawCircle") -var imageDrawCircleV = wasm.Proc("ImageDrawCircleV") -var imageDrawCircleLines = wasm.Proc("ImageDrawCircleLines") -var imageDrawCircleLinesV = wasm.Proc("ImageDrawCircleLinesV") -var imageDrawRectangle = wasm.Proc("ImageDrawRectangle") -var imageDrawRectangleV = wasm.Proc("ImageDrawRectangleV") -var imageDrawRectangleRec = wasm.Proc("ImageDrawRectangleRec") -var imageDrawRectangleLines = wasm.Proc("ImageDrawRectangleLines") -var imageDrawTriangle = wasm.Proc("ImageDrawTriangle") -var imageDrawTriangleEx = wasm.Proc("ImageDrawTriangleEx") -var imageDrawTriangleLines = wasm.Proc("ImageDrawTriangleLines") -var imageDrawTriangleFan = wasm.Proc("ImageDrawTriangleFan") -var imageDrawTriangleStrip = wasm.Proc("ImageDrawTriangleStrip") -var imageDraw = wasm.Proc("ImageDraw") -var imageDrawText = wasm.Proc("ImageDrawText") -var imageDrawTextEx = wasm.Proc("ImageDrawTextEx") -var loadTexture = wasm.Func[Texture2D]("LoadTexture") -var loadTextureFromImage = wasm.Func[Texture2D]("LoadTextureFromImage") -var loadTextureCubemap = wasm.Func[Texture2D]("LoadTextureCubemap") -var loadRenderTexture = wasm.Func[RenderTexture2D]("LoadRenderTexture") -var isTextureValid = wasm.Func[bool]("IsTextureValid") -var unloadTexture = wasm.Proc("UnloadTexture") -var isRenderTextureValid = wasm.Func[bool]("IsRenderTextureValid") -var unloadRenderTexture = wasm.Proc("UnloadRenderTexture") -var updateTexture = wasm.Proc("UpdateTexture") -var updateTextureRec = wasm.Proc("UpdateTextureRec") -var genTextureMipmaps = wasm.Proc("GenTextureMipmaps") -var setTextureFilter = wasm.Proc("SetTextureFilter") -var setTextureWrap = wasm.Proc("SetTextureWrap") -var drawTexture = wasm.Proc("DrawTexture") -var drawTextureV = wasm.Proc("DrawTextureV") -var drawTextureEx = wasm.Proc("DrawTextureEx") -var drawTextureRec = wasm.Proc("DrawTextureRec") -var drawTexturePro = wasm.Proc("DrawTexturePro") -var drawTextureNPatch = wasm.Proc("DrawTextureNPatch") -var fade = wasm.Func[color.RGBA]("Fade") -var colorToInt = wasm.Func[int32]("ColorToInt") -var colorNormalize = wasm.Func[Vector4]("ColorNormalize") -var colorFromNormalized = wasm.Func[color.RGBA]("ColorFromNormalized") -var colorToHSV = wasm.Func[Vector3]("ColorToHSV") -var colorFromHSV = wasm.Func[color.RGBA]("ColorFromHSV") -var colorTint = wasm.Func[color.RGBA]("ColorTint") -var colorBrightness = wasm.Func[color.RGBA]("ColorBrightness") -var colorContrast = wasm.Func[color.RGBA]("ColorContrast") -var colorAlpha = wasm.Func[color.RGBA]("ColorAlpha") -var colorAlphaBlend = wasm.Func[color.RGBA]("ColorAlphaBlend") -var colorLerp = wasm.Func[color.RGBA]("ColorLerp") -var getColor = wasm.Func[color.RGBA]("GetColor") -var getPixelColor = wasm.Func[color.RGBA]("GetPixelColor") -var setPixelColor = wasm.Proc("SetPixelColor") -var getPixelDataSize = wasm.Func[int32]("GetPixelDataSize") -var getFontDefault = wasm.Func[Font]("GetFontDefault") -var loadFont = wasm.Func[Font]("LoadFont") -var loadFontFromImage = wasm.Func[Font]("LoadFontFromImage") -var loadFontFromMemory = wasm.Func[Font]("LoadFontFromMemory") -var isFontValid = wasm.Func[bool]("IsFontValid") -var loadFontData = wasm.Func[[]GlyphInfo]("LoadFontData") -var genImageFontAtlas = wasm.Func[Image]("GenImageFontAtlas") -var unloadFontData = wasm.Proc("UnloadFontData") -var unloadFont = wasm.Proc("UnloadFont") -var drawFPS = wasm.Proc("DrawFPS") -var drawText = wasm.Proc("DrawText") -var drawTextEx = wasm.Proc("DrawTextEx") -var drawTextPro = wasm.Proc("DrawTextPro") -var drawTextCodepoint = wasm.Proc("DrawTextCodepoint") -var drawTextCodepoints = wasm.Proc("DrawTextCodepoints") -var setTextLineSpacing = wasm.Proc("SetTextLineSpacing") -var measureText = wasm.Func[int32]("MeasureText") -var measureTextEx = wasm.Func[Vector2]("MeasureTextEx") -var getGlyphIndex = wasm.Func[int32]("GetGlyphIndex") -var getGlyphInfo = wasm.Func[GlyphInfo]("GetGlyphInfo") -var getGlyphAtlasRec = wasm.Func[Rectangle]("GetGlyphAtlasRec") -var drawLine3D = wasm.Proc("DrawLine3D") -var drawPoint3D = wasm.Proc("DrawPoint3D") -var drawCircle3D = wasm.Proc("DrawCircle3D") -var drawTriangle3D = wasm.Proc("DrawTriangle3D") -var drawTriangleStrip3D = wasm.Proc("DrawTriangleStrip3D") -var drawCube = wasm.Proc("DrawCube") -var drawCubeV = wasm.Proc("DrawCubeV") -var drawCubeWires = wasm.Proc("DrawCubeWires") -var drawCubeWiresV = wasm.Proc("DrawCubeWiresV") -var drawSphere = wasm.Proc("DrawSphere") -var drawSphereEx = wasm.Proc("DrawSphereEx") -var drawSphereWires = wasm.Proc("DrawSphereWires") -var drawCylinder = wasm.Proc("DrawCylinder") -var drawCylinderEx = wasm.Proc("DrawCylinderEx") -var drawCylinderWires = wasm.Proc("DrawCylinderWires") -var drawCylinderWiresEx = wasm.Proc("DrawCylinderWiresEx") -var drawCapsule = wasm.Proc("DrawCapsule") -var drawCapsuleWires = wasm.Proc("DrawCapsuleWires") -var drawPlane = wasm.Proc("DrawPlane") -var drawRay = wasm.Proc("DrawRay") -var drawGrid = wasm.Proc("DrawGrid") -var loadModel = wasm.Func[Model]("LoadModel") -var loadModelFromMesh = wasm.Func[Model]("LoadModelFromMesh") -var isModelValid = wasm.Func[bool]("IsModelValid") -var unloadModel = wasm.Proc("UnloadModel") -var getModelBoundingBox = wasm.Func[BoundingBox]("GetModelBoundingBox") -var drawModel = wasm.Proc("DrawModel") -var drawModelEx = wasm.Proc("DrawModelEx") -var drawModelWires = wasm.Proc("DrawModelWires") -var drawModelWiresEx = wasm.Proc("DrawModelWiresEx") -var drawModelPoints = wasm.Proc("DrawModelPoints") -var drawModelPointsEx = wasm.Proc("DrawModelPointsEx") -var drawBoundingBox = wasm.Proc("DrawBoundingBox") -var drawBillboard = wasm.Proc("DrawBillboard") -var drawBillboardRec = wasm.Proc("DrawBillboardRec") -var drawBillboardPro = wasm.Proc("DrawBillboardPro") -var uploadMesh = wasm.Proc("UploadMesh") -var updateMeshBuffer = wasm.Proc("UpdateMeshBuffer") -var unloadMesh = wasm.Proc("UnloadMesh") -var drawMesh = wasm.Proc("DrawMesh") -var drawMeshInstanced = wasm.Proc("DrawMeshInstanced") -var exportMesh = wasm.Func[bool]("ExportMesh") -var getMeshBoundingBox = wasm.Func[BoundingBox]("GetMeshBoundingBox") -var genMeshTangents = wasm.Proc("GenMeshTangents") -var genMeshPoly = wasm.Func[Mesh]("GenMeshPoly") -var genMeshPlane = wasm.Func[Mesh]("GenMeshPlane") -var genMeshCube = wasm.Func[Mesh]("GenMeshCube") -var genMeshSphere = wasm.Func[Mesh]("GenMeshSphere") -var genMeshHemiSphere = wasm.Func[Mesh]("GenMeshHemiSphere") -var genMeshCylinder = wasm.Func[Mesh]("GenMeshCylinder") -var genMeshCone = wasm.Func[Mesh]("GenMeshCone") -var genMeshTorus = wasm.Func[Mesh]("GenMeshTorus") -var genMeshKnot = wasm.Func[Mesh]("GenMeshKnot") -var genMeshHeightmap = wasm.Func[Mesh]("GenMeshHeightmap") -var genMeshCubicmap = wasm.Func[Mesh]("GenMeshCubicmap") -var loadMaterials = wasm.Func[[]Material]("LoadMaterials") -var loadMaterialDefault = wasm.Func[Material]("LoadMaterialDefault") -var isMaterialValid = wasm.Func[bool]("IsMaterialValid") -var unloadMaterial = wasm.Proc("UnloadMaterial") -var setMaterialTexture = wasm.Proc("SetMaterialTexture") -var setModelMeshMaterial = wasm.Proc("SetModelMeshMaterial") -var loadModelAnimations = wasm.Func[[]ModelAnimation]("LoadModelAnimations") -var updateModelAnimation = wasm.Proc("UpdateModelAnimation") -var updateModelAnimationBones = wasm.Proc("UpdateModelAnimationBones") -var unloadModelAnimation = wasm.Proc("UnloadModelAnimation") -var unloadModelAnimations = wasm.Proc("UnloadModelAnimations") -var isModelAnimationValid = wasm.Func[bool]("IsModelAnimationValid") -var checkCollisionSpheres = wasm.Func[bool]("CheckCollisionSpheres") -var checkCollisionBoxes = wasm.Func[bool]("CheckCollisionBoxes") -var checkCollisionBoxSphere = wasm.Func[bool]("CheckCollisionBoxSphere") -var getRayCollisionSphere = wasm.Func[RayCollision]("GetRayCollisionSphere") -var getRayCollisionBox = wasm.Func[RayCollision]("GetRayCollisionBox") -var getRayCollisionMesh = wasm.Func[RayCollision]("GetRayCollisionMesh") -var getRayCollisionTriangle = wasm.Func[RayCollision]("GetRayCollisionTriangle") -var getRayCollisionQuad = wasm.Func[RayCollision]("GetRayCollisionQuad") -var initAudioDevice = wasm.Proc("InitAudioDevice") -var closeAudioDevice = wasm.Proc("CloseAudioDevice") -var isAudioDeviceReady = wasm.Func[bool]("IsAudioDeviceReady") -var setMasterVolume = wasm.Proc("SetMasterVolume") -var getMasterVolume = wasm.Func[float32]("GetMasterVolume") -var loadWave = wasm.Func[Wave]("LoadWave") -var loadWaveFromMemory = wasm.Func[Wave]("LoadWaveFromMemory") -var isWaveValid = wasm.Func[bool]("IsWaveValid") -var loadSound = wasm.Func[Sound]("LoadSound") -var loadSoundFromWave = wasm.Func[Sound]("LoadSoundFromWave") -var loadSoundAlias = wasm.Func[Sound]("LoadSoundAlias") -var isSoundValid = wasm.Func[bool]("IsSoundValid") -var updateSound = wasm.Proc("UpdateSound") -var unloadWave = wasm.Proc("UnloadWave") -var unloadSound = wasm.Proc("UnloadSound") -var unloadSoundAlias = wasm.Proc("UnloadSoundAlias") -var exportWave = wasm.Func[bool]("ExportWave") -var playSound = wasm.Proc("PlaySound") -var stopSound = wasm.Proc("StopSound") -var pauseSound = wasm.Proc("PauseSound") -var resumeSound = wasm.Proc("ResumeSound") -var isSoundPlaying = wasm.Func[bool]("IsSoundPlaying") -var setSoundVolume = wasm.Proc("SetSoundVolume") -var setSoundPitch = wasm.Proc("SetSoundPitch") -var setSoundPan = wasm.Proc("SetSoundPan") -var waveCopy = wasm.Func[Wave]("WaveCopy") -var waveCrop = wasm.Proc("WaveCrop") -var waveFormat = wasm.Proc("WaveFormat") -var loadWaveSamples = wasm.Func[[]float32]("LoadWaveSamples") -var unloadWaveSamples = wasm.Proc("UnloadWaveSamples") -var loadMusicStream = wasm.Func[Music]("LoadMusicStream") -var loadMusicStreamFromMemory = wasm.Func[Music]("LoadMusicStreamFromMemory") -var isMusicValid = wasm.Func[bool]("IsMusicValid") -var unloadMusicStream = wasm.Proc("UnloadMusicStream") -var playMusicStream = wasm.Proc("PlayMusicStream") -var isMusicStreamPlaying = wasm.Func[bool]("IsMusicStreamPlaying") -var updateMusicStream = wasm.Proc("UpdateMusicStream") -var stopMusicStream = wasm.Proc("StopMusicStream") -var pauseMusicStream = wasm.Proc("PauseMusicStream") -var resumeMusicStream = wasm.Proc("ResumeMusicStream") -var seekMusicStream = wasm.Proc("SeekMusicStream") -var setMusicVolume = wasm.Proc("SetMusicVolume") -var setMusicPitch = wasm.Proc("SetMusicPitch") -var setMusicPan = wasm.Proc("SetMusicPan") -var getMusicTimeLength = wasm.Func[float32]("GetMusicTimeLength") -var getMusicTimePlayed = wasm.Func[float32]("GetMusicTimePlayed") -var loadAudioStream = wasm.Func[AudioStream]("LoadAudioStream") -var isAudioStreamValid = wasm.Func[bool]("IsAudioStreamValid") -var unloadAudioStream = wasm.Proc("UnloadAudioStream") -var updateAudioStream = wasm.Proc("UpdateAudioStream") -var isAudioStreamProcessed = wasm.Func[bool]("IsAudioStreamProcessed") -var playAudioStream = wasm.Proc("PlayAudioStream") -var pauseAudioStream = wasm.Proc("PauseAudioStream") -var resumeAudioStream = wasm.Proc("ResumeAudioStream") -var isAudioStreamPlaying = wasm.Func[bool]("IsAudioStreamPlaying") -var stopAudioStream = wasm.Proc("StopAudioStream") -var setAudioStreamVolume = wasm.Proc("SetAudioStreamVolume") -var setAudioStreamPitch = wasm.Proc("SetAudioStreamPitch") -var setAudioStreamPan = wasm.Proc("SetAudioStreamPan") -var setAudioStreamBufferSizeDefault = wasm.Proc("SetAudioStreamBufferSizeDefault") -var setAudioStreamCallback = wasm.Proc("SetAudioStreamCallback") -var attachAudioStreamProcessor = wasm.Proc("AttachAudioStreamProcessor") -var detachAudioStreamProcessor = wasm.Proc("DetachAudioStreamProcessor") -var attachAudioMixedProcessor = wasm.Proc("AttachAudioMixedProcessor") -var detachAudioMixedProcessor = wasm.Proc("DetachAudioMixedProcessor") -var setCallbackFunc = wasm.Proc("SetCallbackFunc") -var newImageFromImage = wasm.Func[*Image]("NewImageFromImage") -var toImage = wasm.Func[image.Image]("ToImage") -var openAsset = wasm.Func[Asset]("OpenAsset") -var homeDir = wasm.Func[string]("HomeDir") - -// CloseWindow - Close window and unload OpenGL context -func CloseWindow() { - _, fl := closeWindow.Call() - wasm.Free(fl...) -} - -// IsWindowReady - Check if window has been initialized successfully -func IsWindowReady() bool { - ret, fl := isWindowReady.Call() - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// IsWindowFullscreen - Check if window is currently fullscreen -func IsWindowFullscreen() bool { - ret, fl := isWindowFullscreen.Call() - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// IsWindowHidden - Check if window is currently hidden (only PLATFORM_DESKTOP) -func IsWindowHidden() bool { - var zero bool - return zero -} - -// IsWindowMinimized - Check if window is currently minimized (only PLATFORM_DESKTOP) -func IsWindowMinimized() bool { - var zero bool - return zero -} - -// IsWindowMaximized - Check if window is currently maximized (only PLATFORM_DESKTOP) -func IsWindowMaximized() bool { - var zero bool - return zero -} - -// IsWindowFocused - Check if window is currently focused (only PLATFORM_DESKTOP) -func IsWindowFocused() bool { - var zero bool - return zero -} - -// IsWindowResized - Check if window has been resized last frame -func IsWindowResized() bool { - ret, fl := isWindowResized.Call() - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// IsWindowState - Check if one specific window flag is enabled -func IsWindowState(flag uint32) bool { - ret, fl := isWindowState.Call(flag) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// SetWindowState - Set window configuration state using flags (only PLATFORM_DESKTOP) -func SetWindowState(flags uint32) { -} - -// ClearWindowState - Clear window configuration state flags -func ClearWindowState(flags uint32) { - _, fl := clearWindowState.Call(flags) - wasm.Free(fl...) -} - -// ToggleFullscreen - Toggle window state: fullscreen/windowed (only PLATFORM_DESKTOP) -func ToggleFullscreen() { -} - -// ToggleBorderlessWindowed - Toggle window state: borderless windowed (only PLATFORM_DESKTOP) -func ToggleBorderlessWindowed() { -} - -// MaximizeWindow - Set window state: maximized, if resizable (only PLATFORM_DESKTOP) -func MaximizeWindow() { -} - -// MinimizeWindow - Set window state: minimized, if resizable (only PLATFORM_DESKTOP) -func MinimizeWindow() { -} - -// RestoreWindow - Set window state: not minimized/maximized (only PLATFORM_DESKTOP) -func RestoreWindow() { -} - -// SetWindowIcon - Set icon for window (single image, RGBA 32bit, only PLATFORM_DESKTOP) -func SetWindowIcon(image Image) { - _, fl := setWindowIcon.Call(wasm.Struct(image)) - wasm.Free(fl...) -} - -// SetWindowIcons - Set icon for window (multiple images, RGBA 32bit, only PLATFORM_DESKTOP) -func SetWindowIcons(images []Image, count int32) { - _, fl := setWindowIcons.Call(images, count) - wasm.Free(fl...) -} - -// SetWindowTitle - Set title for window (only PLATFORM_DESKTOP and PLATFORM_WEB) -func SetWindowTitle(title string) { - _, fl := setWindowTitle.Call(title) - wasm.Free(fl...) -} - -// SetWindowPosition - Set window position on screen (only PLATFORM_DESKTOP) -func SetWindowPosition(x int, y int) { -} - -// SetWindowMonitor - Set monitor for the current window -func SetWindowMonitor(monitor int) { - _, fl := setWindowMonitor.Call(monitor) - wasm.Free(fl...) -} - -// SetWindowMinSize - Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) -func SetWindowMinSize(width int, height int) { - _, fl := setWindowMinSize.Call(width, height) - wasm.Free(fl...) -} - -// SetWindowMaxSize - Set window maximum dimensions (for FLAG_WINDOW_RESIZABLE) -func SetWindowMaxSize(width int, height int) { - _, fl := setWindowMaxSize.Call(width, height) - wasm.Free(fl...) -} - -// SetWindowSize - Set window dimensions -func SetWindowSize(width int, height int) { - _, fl := setWindowSize.Call(width, height) - wasm.Free(fl...) -} - -// SetWindowOpacity - Set window opacity [0.0f..1.0f] (only PLATFORM_DESKTOP) -func SetWindowOpacity(opacity float32) { -} - -// SetWindowFocused - Set window focused (only PLATFORM_DESKTOP) -func SetWindowFocused() { -} - -// GetWindowHandle - Get native window handle -func GetWindowHandle() unsafe.Pointer { - var zero unsafe.Pointer - return zero -} - -// GetScreenWidth - Get current screen width -func GetScreenWidth() int { - ret, fl := getScreenWidth.Call() - v := wasm.Numeric[int](ret) - wasm.Free(fl...) - return v -} - -// GetScreenHeight - Get current screen height -func GetScreenHeight() int { - ret, fl := getScreenHeight.Call() - v := wasm.Numeric[int](ret) - wasm.Free(fl...) - return v -} - -// GetRenderWidth - Get current render width (it considers HiDPI) -func GetRenderWidth() int { - ret, fl := getRenderWidth.Call() - v := wasm.Numeric[int](ret) - wasm.Free(fl...) - return v -} - -// GetRenderHeight - Get current render height (it considers HiDPI) -func GetRenderHeight() int { - ret, fl := getRenderHeight.Call() - v := wasm.Numeric[int](ret) - wasm.Free(fl...) - return v -} - -// GetMonitorCount - Get number of connected monitors -func GetMonitorCount() int { - ret, fl := getMonitorCount.Call() - v := wasm.Numeric[int](ret) - wasm.Free(fl...) - return v -} - -// GetCurrentMonitor - Get current monitor where window is placed -func GetCurrentMonitor() int { - ret, fl := getCurrentMonitor.Call() - v := wasm.Numeric[int](ret) - wasm.Free(fl...) - return v -} - -// GetMonitorPosition - Get specified monitor position -func GetMonitorPosition(monitor int) Vector2 { - ret, fl := getMonitorPosition.Call(monitor) - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetMonitorWidth - Get specified monitor width (current video mode used by monitor) -func GetMonitorWidth(monitor int) int { - ret, fl := getMonitorWidth.Call(monitor) - v := wasm.Numeric[int](ret) - wasm.Free(fl...) - return v -} - -// GetMonitorHeight - Get specified monitor height (current video mode used by monitor) -func GetMonitorHeight(monitor int) int { - ret, fl := getMonitorHeight.Call(monitor) - v := wasm.Numeric[int](ret) - wasm.Free(fl...) - return v -} - -// GetMonitorPhysicalWidth - Get specified monitor physical width in millimetres -func GetMonitorPhysicalWidth(monitor int) int { - ret, fl := getMonitorPhysicalWidth.Call(monitor) - v := wasm.Numeric[int](ret) - wasm.Free(fl...) - return v -} - -// GetMonitorPhysicalHeight - Get specified monitor physical height in millimetres -func GetMonitorPhysicalHeight(monitor int) int { - ret, fl := getMonitorPhysicalHeight.Call(monitor) - v := wasm.Numeric[int](ret) - wasm.Free(fl...) - return v -} - -// GetMonitorRefreshRate - Get specified monitor refresh rate -func GetMonitorRefreshRate(monitor int) int { - ret, fl := getMonitorRefreshRate.Call(monitor) - v := wasm.Numeric[int](ret) - wasm.Free(fl...) - return v -} - -// GetWindowPosition - Get window position XY on monitor -func GetWindowPosition() Vector2 { - ret, fl := getWindowPosition.Call() - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetWindowScaleDPI - Get window scale DPI factor -func GetWindowScaleDPI() Vector2 { - ret, fl := getWindowScaleDPI.Call() - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetMonitorName - Get the human-readable, UTF-8 encoded name of the specified monitor -func GetMonitorName(monitor int) string { - ret, fl := getMonitorName.Call(monitor) - v := wasm.Numeric[string](ret) - wasm.Free(fl...) - return v -} - -// SetClipboardText - Set clipboard text content -func SetClipboardText(text string) { - _, fl := setClipboardText.Call(text) - wasm.Free(fl...) -} - -// GetClipboardText - Get clipboard text content -func GetClipboardText() string { - ret, fl := getClipboardText.Call() - v := wasm.Numeric[string](ret) - wasm.Free(fl...) - return v -} - -// GetClipboardImage - Get clipboard image content -// -// Only works with SDL3 backend or Windows with RGFW/GLFW -func GetClipboardImage() Image { - ret, fl := getClipboardImage.Call() - v := wasm.ReadStruct[Image](ret) - wasm.Free(fl...) - return v -} - -// EnableEventWaiting - Enable waiting for events on EndDrawing(), no automatic event polling -func EnableEventWaiting() { - _, fl := enableEventWaiting.Call() - wasm.Free(fl...) -} - -// DisableEventWaiting - Disable waiting for events on EndDrawing(), automatic events polling -func DisableEventWaiting() { - _, fl := disableEventWaiting.Call() - wasm.Free(fl...) -} - -// ShowCursor - Shows cursor -func ShowCursor() { - _, fl := showCursor.Call() - wasm.Free(fl...) -} - -// HideCursor - Hides cursor -func HideCursor() { - _, fl := hideCursor.Call() - wasm.Free(fl...) -} - -// IsCursorHidden - Check if cursor is not visible -func IsCursorHidden() bool { - ret, fl := isCursorHidden.Call() - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// EnableCursor - Enables cursor (unlock cursor) -func EnableCursor() { - _, fl := enableCursor.Call() - wasm.Free(fl...) -} - -// DisableCursor - Disables cursor (lock cursor) -func DisableCursor() { - _, fl := disableCursor.Call() - wasm.Free(fl...) -} - -// IsCursorOnScreen - Check if cursor is on the screen -func IsCursorOnScreen() bool { - ret, fl := isCursorOnScreen.Call() - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// ClearBackground - Set background color (framebuffer clear color) -func ClearBackground(col color.RGBA) { - _, fl := clearBackground.Call(wasm.Struct(col)) - wasm.Free(fl...) -} - -// BeginDrawing - Setup canvas (framebuffer) to start drawing -func BeginDrawing() { - _, fl := beginDrawing.Call() - wasm.Free(fl...) -} - -// EndDrawing - End canvas drawing and swap buffers (double buffering) -func EndDrawing() { - _, fl := endDrawing.Call() - wasm.Free(fl...) -} - -// BeginMode2D - Begin 2D mode with custom camera (2D) -func BeginMode2D(camera Camera2D) { - _, fl := beginMode2D.Call(wasm.Struct(camera)) - wasm.Free(fl...) -} - -// EndMode2D - Ends 2D mode with custom camera -func EndMode2D() { - _, fl := endMode2D.Call() - wasm.Free(fl...) -} - -// BeginMode3D - Begin 3D mode with custom camera (3D) -func BeginMode3D(camera Camera3D) { - _, fl := beginMode3D.Call(wasm.Struct(camera)) - wasm.Free(fl...) -} - -// EndMode3D - Ends 3D mode and returns to default 2D orthographic mode -func EndMode3D() { - _, fl := endMode3D.Call() - wasm.Free(fl...) -} - -// BeginTextureMode - Begin drawing to render texture -func BeginTextureMode(target RenderTexture2D) { - _, fl := beginTextureMode.Call(wasm.Struct(target)) - wasm.Free(fl...) -} - -// EndTextureMode - Ends drawing to render texture -func EndTextureMode() { - _, fl := endTextureMode.Call() - wasm.Free(fl...) -} - -// BeginShaderMode - Begin custom shader drawing -func BeginShaderMode(shader Shader) { - _, fl := beginShaderMode.Call(wasm.Struct(shader)) - wasm.Free(fl...) -} - -// EndShaderMode - End custom shader drawing (use default shader) -func EndShaderMode() { - _, fl := endShaderMode.Call() - wasm.Free(fl...) -} - -// BeginBlendMode - Begin blending mode (alpha, additive, multiplied, subtract, custom) -func BeginBlendMode(mode BlendMode) { - _, fl := beginBlendMode.Call(mode) - wasm.Free(fl...) -} - -// EndBlendMode - End blending mode (reset to default: alpha blending) -func EndBlendMode() { - _, fl := endBlendMode.Call() - wasm.Free(fl...) -} - -// BeginScissorMode - Begin scissor mode (define screen area for following drawing) -func BeginScissorMode(x int32, y int32, width int32, height int32) { - _, fl := beginScissorMode.Call(x, y, width, height) - wasm.Free(fl...) -} - -// EndScissorMode - End scissor mode -func EndScissorMode() { - _, fl := endScissorMode.Call() - wasm.Free(fl...) -} - -// BeginVrStereoMode - Begin stereo rendering (requires VR simulator) -func BeginVrStereoMode(config VrStereoConfig) { - _, fl := beginVrStereoMode.Call(wasm.Struct(config)) - wasm.Free(fl...) -} - -// EndVrStereoMode - End stereo rendering (requires VR simulator) -func EndVrStereoMode() { - _, fl := endVrStereoMode.Call() - wasm.Free(fl...) -} - -// LoadVrStereoConfig - Load VR stereo config for VR simulator device parameters -func LoadVrStereoConfig(device VrDeviceInfo) VrStereoConfig { - ret, fl := loadVrStereoConfig.Call(wasm.Struct(device)) - v := wasm.ReadStruct[VrStereoConfig](ret) - wasm.Free(fl...) - return v -} - -// UnloadVrStereoConfig - Unload VR stereo config -func UnloadVrStereoConfig(config VrStereoConfig) { - _, fl := unloadVrStereoConfig.Call(wasm.Struct(config)) - wasm.Free(fl...) -} - -// LoadShader - Load shader from files and bind default locations -func LoadShader(vsFileName string, fsFileName string) Shader { - ret, fl := loadShader.Call(vsFileName, fsFileName) - v := wasm.ReadStruct[Shader](ret) - wasm.Free(fl...) - return v -} - -// LoadShaderFromMemory - Load shader from code strings and bind default locations -func LoadShaderFromMemory(vsCode string, fsCode string) Shader { - ret, fl := loadShaderFromMemory.Call(vsCode, fsCode) - v := wasm.ReadStruct[Shader](ret) - wasm.Free(fl...) - return v -} - -// IsShaderValid - Check if a shader is valid (loaded on GPU) -func IsShaderValid(shader Shader) bool { - ret, fl := isShaderValid.Call(wasm.Struct(shader)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// GetShaderLocation - Get shader uniform location -func GetShaderLocation(shader Shader, uniformName string) int32 { - ret, fl := getShaderLocation.Call(wasm.Struct(shader), uniformName) - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// GetShaderLocationAttrib - Get shader attribute location -func GetShaderLocationAttrib(shader Shader, attribName string) int32 { - ret, fl := getShaderLocationAttrib.Call(wasm.Struct(shader), attribName) - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// SetShaderValue - Set shader uniform value -func SetShaderValue(shader Shader, locIndex int32, value []float32, uniformType ShaderUniformDataType) { - _, fl := setShaderValue.Call(wasm.Struct(shader), locIndex, value, uniformType) - wasm.Free(fl...) -} - -// SetShaderValueV - Set shader uniform value vector -func SetShaderValueV(shader Shader, locIndex int32, value []float32, uniformType ShaderUniformDataType, count int32) { - _, fl := setShaderValueV.Call(wasm.Struct(shader), locIndex, value, uniformType, count) - wasm.Free(fl...) -} - -// SetShaderValueMatrix - Set shader uniform value (matrix 4x4) -func SetShaderValueMatrix(shader Shader, locIndex int32, mat Matrix) { - _, fl := setShaderValueMatrix.Call(wasm.Struct(shader), locIndex, wasm.Struct(mat)) - wasm.Free(fl...) -} - -// SetShaderValueTexture - Set shader uniform value for texture (sampler2d) -func SetShaderValueTexture(shader Shader, locIndex int32, texture Texture2D) { - _, fl := setShaderValueTexture.Call(wasm.Struct(shader), locIndex, wasm.Struct(texture)) - wasm.Free(fl...) -} - -// UnloadShader - Unload shader from GPU memory (VRAM) -func UnloadShader(shader Shader) { - _, fl := unloadShader.Call(wasm.Struct(shader)) - wasm.Free(fl...) -} - -// GetMouseRay - Get a ray trace from mouse position -// -// Deprecated: Use [GetScreenToWorldRay] instead. -func GetMouseRay(mousePosition Vector2, camera Camera) Ray { - ret, fl := getMouseRay.Call(wasm.Struct(mousePosition), camera) - v := wasm.ReadStruct[Ray](ret) - wasm.Free(fl...) - return v -} - -// GetScreenToWorldRay - Get a ray trace from screen position (i.e mouse) -func GetScreenToWorldRay(position Vector2, camera Camera) Ray { - ret, fl := getScreenToWorldRay.Call(wasm.Struct(position), camera) - v := wasm.ReadStruct[Ray](ret) - wasm.Free(fl...) - return v -} - -// GetScreenToWorldRayEx - Get a ray trace from screen position (i.e mouse) in a viewport -func GetScreenToWorldRayEx(position Vector2, camera Camera, width int32, height int32) Ray { - ret, fl := getScreenToWorldRayEx.Call(wasm.Struct(position), camera, width, height) - v := wasm.ReadStruct[Ray](ret) - wasm.Free(fl...) - return v -} - -// GetCameraMatrix - Get camera transform matrix (view matrix) -func GetCameraMatrix(camera Camera) Matrix { - ret, fl := getCameraMatrix.Call(camera) - v := wasm.ReadStruct[Matrix](ret) - wasm.Free(fl...) - return v -} - -// GetCameraMatrix2D - Get camera 2d transform matrix -func GetCameraMatrix2D(camera Camera2D) Matrix { - ret, fl := getCameraMatrix2D.Call(wasm.Struct(camera)) - v := wasm.ReadStruct[Matrix](ret) - wasm.Free(fl...) - return v -} - -// GetWorldToScreen - Get the screen space position for a 3d world space position -func GetWorldToScreen(position Vector3, camera Camera) Vector2 { - ret, fl := getWorldToScreen.Call(wasm.Struct(position), camera) - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetScreenToWorld2D - Get the world space position for a 2d camera screen space position -func GetScreenToWorld2D(position Vector2, camera Camera2D) Vector2 { - ret, fl := getScreenToWorld2D.Call(wasm.Struct(position), wasm.Struct(camera)) - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetWorldToScreenEx - Get size position for a 3d world space position -func GetWorldToScreenEx(position Vector3, camera Camera, width int32, height int32) Vector2 { - ret, fl := getWorldToScreenEx.Call(wasm.Struct(position), camera, width, height) - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetWorldToScreen2D - Get the screen space position for a 2d camera world space position -func GetWorldToScreen2D(position Vector2, camera Camera2D) Vector2 { - ret, fl := getWorldToScreen2D.Call(wasm.Struct(position), wasm.Struct(camera)) - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// SetTargetFPS - Set target FPS (maximum) -func SetTargetFPS(fps int32) { - _, fl := setTargetFPS.Call(fps) - wasm.Free(fl...) -} - -// GetFrameTime - Get time in seconds for last frame drawn (delta time) -func GetFrameTime() float32 { - ret, fl := getFrameTime.Call() - v := wasm.Numeric[float32](ret) - wasm.Free(fl...) - return v -} - -// GetTime - Get elapsed time in seconds since InitWindow() -func GetTime() float64 { - ret, fl := getTime.Call() - v := wasm.Numeric[float64](ret) - wasm.Free(fl...) - return v -} - -// GetFPS - Get current FPS -func GetFPS() int32 { - ret, fl := getFPS.Call() - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// SwapScreenBuffer - Swap back buffer with front buffer (screen drawing) -func SwapScreenBuffer() { - _, fl := swapScreenBuffer.Call() - wasm.Free(fl...) -} - -// PollInputEvents - Register all input events -func PollInputEvents() { - _, fl := pollInputEvents.Call() - wasm.Free(fl...) -} - -// WaitTime - Wait for some time (halt program execution) -func WaitTime(seconds float64) { - _, fl := waitTime.Call(seconds) - wasm.Free(fl...) -} - -// SetRandomSeed - Set the seed for the random number generator -// -// Note: You can use go's math/rand package instead -func SetRandomSeed(seed uint32) { - _, fl := setRandomSeed.Call(seed) - wasm.Free(fl...) -} - -// GetRandomValue - Get a random value between min and max (both included) -// -// Note: You can use go's math/rand package instead -func GetRandomValue(minimum int32, maximum int32) int32 { - ret, fl := getRandomValue.Call(minimum, maximum) - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// LoadRandomSequence - Load random values sequence, no values repeated -// -// Note: Use UnloadRandomSequence if you don't need the sequence any more. You can use go's math/rand.Perm function instead. -func LoadRandomSequence(count uint32, minimum int32, maximum int32) []int32 { - var zero []int32 - return zero -} - -// UnloadRandomSequence - Unload random values sequence -func UnloadRandomSequence(sequence []int32) { - _, fl := unloadRandomSequence.Call(sequence) - wasm.Free(fl...) -} - -// TakeScreenshot - Takes a screenshot of current screen (filename extension defines format) -func TakeScreenshot(fileName string) { - _, fl := takeScreenshot.Call(fileName) - wasm.Free(fl...) -} - -// SetConfigFlags - Setup init configuration flags (view FLAGS) -func SetConfigFlags(flags uint32) { - _, fl := setConfigFlags.Call(flags) - wasm.Free(fl...) -} - -// OpenURL - Open URL with default system browser (if available) -func OpenURL(url string) { - _, fl := openURL.Call(url) - wasm.Free(fl...) -} - -// TraceLog - Show trace log messages (LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR...) -func TraceLog(logLevel TraceLogLevel, text string, args ...any) { - _, fl := traceLog.Call(logLevel, text, args) - wasm.Free(fl...) -} - -// SetTraceLogLevel - Set the current threshold (minimum) log level -func SetTraceLogLevel(logLevel TraceLogLevel) { - _, fl := setTraceLogLevel.Call(logLevel) - wasm.Free(fl...) -} - -// MemAlloc - Internal memory allocator -func MemAlloc(size uint32) unsafe.Pointer { - var zero unsafe.Pointer - return zero -} - -// MemRealloc - Internal memory reallocator -func MemRealloc(ptr unsafe.Pointer, size uint32) unsafe.Pointer { - var zero unsafe.Pointer - return zero -} - -// MemFree - Internal memory free -func MemFree(ptr unsafe.Pointer) { - _, fl := memFree.Call(ptr) - wasm.Free(fl...) -} - -// IsFileDropped - Check if a file has been dropped into window -func IsFileDropped() bool { - ret, fl := isFileDropped.Call() - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// LoadDroppedFiles - Load dropped filepaths -func LoadDroppedFiles() []string { - var zero []string - return zero -} - -// UnloadDroppedFiles - Unload dropped filepaths -func UnloadDroppedFiles() { - _, fl := unloadDroppedFiles.Call() - wasm.Free(fl...) -} - -// LoadAutomationEventList - Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS -func LoadAutomationEventList(fileName string) AutomationEventList { - ret, fl := loadAutomationEventList.Call(fileName) - v := wasm.ReadStruct[AutomationEventList](ret) - wasm.Free(fl...) - return v -} - -// UnloadAutomationEventList - Unload automation events list from file -func UnloadAutomationEventList(list *AutomationEventList) { - _, fl := unloadAutomationEventList.Call(list) - wasm.Free(fl...) -} - -// ExportAutomationEventList - Export automation events list as text file -func ExportAutomationEventList(list AutomationEventList, fileName string) bool { - ret, fl := exportAutomationEventList.Call(wasm.Struct(list), fileName) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// SetAutomationEventList - Set automation event list to record to -func SetAutomationEventList(list *AutomationEventList) { - _, fl := setAutomationEventList.Call(list) - wasm.Free(fl...) -} - -// SetAutomationEventBaseFrame - Set automation event internal base frame to start recording -func SetAutomationEventBaseFrame(frame int) { - _, fl := setAutomationEventBaseFrame.Call(frame) - wasm.Free(fl...) -} - -// StartAutomationEventRecording - Start recording automation events (AutomationEventList must be set) -func StartAutomationEventRecording() { - _, fl := startAutomationEventRecording.Call() - wasm.Free(fl...) -} - -// StopAutomationEventRecording - Stop recording automation events -func StopAutomationEventRecording() { - _, fl := stopAutomationEventRecording.Call() - wasm.Free(fl...) -} - -// PlayAutomationEvent - Play a recorded automation event -func PlayAutomationEvent(event AutomationEvent) { - _, fl := playAutomationEvent.Call(wasm.Struct(event)) - wasm.Free(fl...) -} - -// IsKeyPressed - Check if a key has been pressed once -func IsKeyPressed(key int32) bool { - ret, fl := isKeyPressed.Call(key) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// IsKeyPressedRepeat - Check if a key has been pressed again (Only PLATFORM_DESKTOP) -func IsKeyPressedRepeat(key int32) bool { - ret, fl := isKeyPressedRepeat.Call(key) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// IsKeyDown - Check if a key is being pressed -func IsKeyDown(key int32) bool { - ret, fl := isKeyDown.Call(key) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// IsKeyReleased - Check if a key has been released once -func IsKeyReleased(key int32) bool { - ret, fl := isKeyReleased.Call(key) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// IsKeyUp - Check if a key is NOT being pressed -func IsKeyUp(key int32) bool { - ret, fl := isKeyUp.Call(key) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// GetKeyPressed - Get key pressed (keycode), call it multiple times for keys queued, returns 0 when the queue is empty -func GetKeyPressed() int32 { - ret, fl := getKeyPressed.Call() - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// GetCharPressed - Get char pressed (unicode), call it multiple times for chars queued, returns 0 when the queue is empty -func GetCharPressed() int32 { - ret, fl := getCharPressed.Call() - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// SetExitKey - Set a custom key to exit program (default is ESC) -func SetExitKey(key int32) { - _, fl := setExitKey.Call(key) - wasm.Free(fl...) -} - -// IsGamepadAvailable - Check if a gamepad is available -func IsGamepadAvailable(gamepad int32) bool { - ret, fl := isGamepadAvailable.Call(gamepad) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// GetGamepadName - Get gamepad internal name id -func GetGamepadName(gamepad int32) string { - ret, fl := getGamepadName.Call(gamepad) - v := wasm.Numeric[string](ret) - wasm.Free(fl...) - return v -} - -// IsGamepadButtonPressed - Check if a gamepad button has been pressed once -func IsGamepadButtonPressed(gamepad int32, button int32) bool { - ret, fl := isGamepadButtonPressed.Call(gamepad, button) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// IsGamepadButtonDown - Check if a gamepad button is being pressed -func IsGamepadButtonDown(gamepad int32, button int32) bool { - ret, fl := isGamepadButtonDown.Call(gamepad, button) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// IsGamepadButtonReleased - Check if a gamepad button has been released once -func IsGamepadButtonReleased(gamepad int32, button int32) bool { - ret, fl := isGamepadButtonReleased.Call(gamepad, button) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// IsGamepadButtonUp - Check if a gamepad button is NOT being pressed -func IsGamepadButtonUp(gamepad int32, button int32) bool { - ret, fl := isGamepadButtonUp.Call(gamepad, button) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// GetGamepadButtonPressed - Get the last gamepad button pressed -func GetGamepadButtonPressed() int32 { - ret, fl := getGamepadButtonPressed.Call() - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// GetGamepadAxisCount - Get gamepad axis count for a gamepad -func GetGamepadAxisCount(gamepad int32) int32 { - ret, fl := getGamepadAxisCount.Call(gamepad) - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// GetGamepadAxisMovement - Get axis movement value for a gamepad axis -func GetGamepadAxisMovement(gamepad int32, axis int32) float32 { - ret, fl := getGamepadAxisMovement.Call(gamepad, axis) - v := wasm.Numeric[float32](ret) - wasm.Free(fl...) - return v -} - -// SetGamepadMappings - Set internal gamepad mappings (SDL_GameControllerDB) -func SetGamepadMappings(mappings string) int32 { - ret, fl := setGamepadMappings.Call(mappings) - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// SetGamepadVibration - Set gamepad vibration for both motors (duration in seconds) -func SetGamepadVibration(gamepad int32, leftMotor float32, rightMotor float32, duration float32) { - _, fl := setGamepadVibration.Call(gamepad, leftMotor, rightMotor, duration) - wasm.Free(fl...) -} - -// IsMouseButtonPressed - Check if a mouse button has been pressed once -func IsMouseButtonPressed(button MouseButton) bool { - ret, fl := isMouseButtonPressed.Call(button) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// IsMouseButtonDown - Check if a mouse button is being pressed -func IsMouseButtonDown(button MouseButton) bool { - ret, fl := isMouseButtonDown.Call(button) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// IsMouseButtonReleased - Check if a mouse button has been released once -func IsMouseButtonReleased(button MouseButton) bool { - ret, fl := isMouseButtonReleased.Call(button) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// IsMouseButtonUp - Check if a mouse button is NOT being pressed -func IsMouseButtonUp(button MouseButton) bool { - ret, fl := isMouseButtonUp.Call(button) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// GetMouseX - Get mouse position X -func GetMouseX() int32 { - ret, fl := getMouseX.Call() - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// GetMouseY - Get mouse position Y -func GetMouseY() int32 { - ret, fl := getMouseY.Call() - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// GetMousePosition - Get mouse position XY -func GetMousePosition() Vector2 { - ret, fl := getMousePosition.Call() - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetMouseDelta - Get mouse delta between frames -func GetMouseDelta() Vector2 { - ret, fl := getMouseDelta.Call() - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// SetMousePosition - Set mouse position XY -func SetMousePosition(x int32, y int32) { - _, fl := setMousePosition.Call(x, y) - wasm.Free(fl...) -} - -// SetMouseOffset - Set mouse offset -func SetMouseOffset(offsetX int32, offsetY int32) { - _, fl := setMouseOffset.Call(offsetX, offsetY) - wasm.Free(fl...) -} - -// SetMouseScale - Set mouse scaling -func SetMouseScale(scaleX float32, scaleY float32) { - _, fl := setMouseScale.Call(scaleX, scaleY) - wasm.Free(fl...) -} - -// GetMouseWheelMove - Get mouse wheel movement for X or Y, whichever is larger -func GetMouseWheelMove() float32 { - ret, fl := getMouseWheelMove.Call() - v := wasm.Numeric[float32](ret) - wasm.Free(fl...) - return v -} - -// GetMouseWheelMoveV - Get mouse wheel movement for both X and Y -func GetMouseWheelMoveV() Vector2 { - ret, fl := getMouseWheelMoveV.Call() - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// SetMouseCursor - Set mouse cursor -func SetMouseCursor(cursor int32) { - _, fl := setMouseCursor.Call(cursor) - wasm.Free(fl...) -} - -// GetTouchX - Get touch position X for touch point 0 (relative to screen size) -func GetTouchX() int32 { - ret, fl := getTouchX.Call() - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// GetTouchY - Get touch position Y for touch point 0 (relative to screen size) -func GetTouchY() int32 { - ret, fl := getTouchY.Call() - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// GetTouchPosition - Get touch position XY for a touch point index (relative to screen size) -func GetTouchPosition(index int32) Vector2 { - ret, fl := getTouchPosition.Call(index) - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetTouchPointId - Get touch point identifier for given index -func GetTouchPointId(index int32) int32 { - ret, fl := getTouchPointId.Call(index) - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// GetTouchPointCount - Get number of touch points -func GetTouchPointCount() int32 { - ret, fl := getTouchPointCount.Call() - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// SetGesturesEnabled - Enable a set of gestures using flags -func SetGesturesEnabled(flags uint32) { - _, fl := setGesturesEnabled.Call(flags) - wasm.Free(fl...) -} - -// IsGestureDetected - Check if a gesture have been detected -func IsGestureDetected(gesture Gestures) bool { - ret, fl := isGestureDetected.Call(gesture) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// GetGestureDetected - Get latest detected gesture -func GetGestureDetected() Gestures { - ret, fl := getGestureDetected.Call() - v := wasm.Numeric[Gestures](ret) - wasm.Free(fl...) - return v -} - -// GetGestureHoldDuration - Get gesture hold time in milliseconds -func GetGestureHoldDuration() float32 { - ret, fl := getGestureHoldDuration.Call() - v := wasm.Numeric[float32](ret) - wasm.Free(fl...) - return v -} - -// GetGestureDragVector - Get gesture drag vector -func GetGestureDragVector() Vector2 { - ret, fl := getGestureDragVector.Call() - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetGestureDragAngle - Get gesture drag angle -func GetGestureDragAngle() float32 { - ret, fl := getGestureDragAngle.Call() - v := wasm.Numeric[float32](ret) - wasm.Free(fl...) - return v -} - -// GetGesturePinchVector - Get gesture pinch delta -func GetGesturePinchVector() Vector2 { - ret, fl := getGesturePinchVector.Call() - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetGesturePinchAngle - Get gesture pinch angle -func GetGesturePinchAngle() float32 { - ret, fl := getGesturePinchAngle.Call() - v := wasm.Numeric[float32](ret) - wasm.Free(fl...) - return v -} - -// SetShapesTexture - Set texture and rectangle to be used on shapes drawing -func SetShapesTexture(texture Texture2D, source Rectangle) { - _, fl := setShapesTexture.Call(wasm.Struct(texture), wasm.Struct(source)) - wasm.Free(fl...) -} - -// GetShapesTexture - Get texture that is used for shapes drawing -func GetShapesTexture() Texture2D { - ret, fl := getShapesTexture.Call() - v := wasm.ReadStruct[Texture2D](ret) - wasm.Free(fl...) - return v -} - -// GetShapesTextureRectangle - Get texture source rectangle that is used for shapes drawing -func GetShapesTextureRectangle() Rectangle { - ret, fl := getShapesTextureRectangle.Call() - v := wasm.ReadStruct[Rectangle](ret) - wasm.Free(fl...) - return v -} - -// DrawPixel - Draw a pixel -func DrawPixel(posX int32, posY int32, col color.RGBA) { - _, fl := drawPixel.Call(posX, posY, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawPixelV - Draw a pixel (Vector version) -func DrawPixelV(position Vector2, col color.RGBA) { - _, fl := drawPixelV.Call(wasm.Struct(position), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawLine - Draw a line -func DrawLine(startPosX int32, startPosY int32, endPosX int32, endPosY int32, col color.RGBA) { - _, fl := drawLine.Call(startPosX, startPosY, endPosX, endPosY, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawLineV - Draw a line (using gl lines) -func DrawLineV(startPos Vector2, endPos Vector2, col color.RGBA) { - _, fl := drawLineV.Call(wasm.Struct(startPos), wasm.Struct(endPos), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawLineEx - Draw a line (using triangles/quads) -func DrawLineEx(startPos Vector2, endPos Vector2, thick float32, col color.RGBA) { - _, fl := drawLineEx.Call(wasm.Struct(startPos), wasm.Struct(endPos), thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawLineStrip - Draw lines sequence (using gl lines) -func DrawLineStrip(points []Vector2, col color.RGBA) { - _, fl := drawLineStrip.Call(points, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawLineBezier - Draw line segment cubic-bezier in-out interpolation -func DrawLineBezier(startPos Vector2, endPos Vector2, thick float32, col color.RGBA) { - _, fl := drawLineBezier.Call(wasm.Struct(startPos), wasm.Struct(endPos), thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCircle - Draw a color-filled circle -func DrawCircle(centerX int32, centerY int32, radius float32, col color.RGBA) { - _, fl := drawCircle.Call(centerX, centerY, radius, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCircleSector - Draw a piece of a circle -func DrawCircleSector(center Vector2, radius float32, startAngle float32, endAngle float32, segments int32, col color.RGBA) { - _, fl := drawCircleSector.Call(wasm.Struct(center), radius, startAngle, endAngle, segments, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCircleSectorLines - Draw circle sector outline -func DrawCircleSectorLines(center Vector2, radius float32, startAngle float32, endAngle float32, segments int32, col color.RGBA) { - _, fl := drawCircleSectorLines.Call(wasm.Struct(center), radius, startAngle, endAngle, segments, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCircleGradient - Draw a gradient-filled circle -func DrawCircleGradient(centerX int32, centerY int32, radius float32, inner color.RGBA, outer color.RGBA) { - _, fl := drawCircleGradient.Call(centerX, centerY, radius, wasm.Struct(inner), wasm.Struct(outer)) - wasm.Free(fl...) -} - -// DrawCircleV - Draw a color-filled circle (Vector version) -func DrawCircleV(center Vector2, radius float32, col color.RGBA) { - _, fl := drawCircleV.Call(wasm.Struct(center), radius, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCircleLines - Draw circle outline -func DrawCircleLines(centerX int32, centerY int32, radius float32, col color.RGBA) { - _, fl := drawCircleLines.Call(centerX, centerY, radius, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCircleLinesV - Draw circle outline (Vector version) -func DrawCircleLinesV(center Vector2, radius float32, col color.RGBA) { - _, fl := drawCircleLinesV.Call(wasm.Struct(center), radius, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawEllipse - Draw ellipse -func DrawEllipse(centerX int32, centerY int32, radiusH float32, radiusV float32, col color.RGBA) { - _, fl := drawEllipse.Call(centerX, centerY, radiusH, radiusV, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawEllipseLines - Draw ellipse outline -func DrawEllipseLines(centerX int32, centerY int32, radiusH float32, radiusV float32, col color.RGBA) { - _, fl := drawEllipseLines.Call(centerX, centerY, radiusH, radiusV, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawRing - Draw ring -func DrawRing(center Vector2, innerRadius float32, outerRadius float32, startAngle float32, endAngle float32, segments int32, col color.RGBA) { - _, fl := drawRing.Call(wasm.Struct(center), innerRadius, outerRadius, startAngle, endAngle, segments, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawRingLines - Draw ring outline -func DrawRingLines(center Vector2, innerRadius float32, outerRadius float32, startAngle float32, endAngle float32, segments int32, col color.RGBA) { - _, fl := drawRingLines.Call(wasm.Struct(center), innerRadius, outerRadius, startAngle, endAngle, segments, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawRectangle - Draw a color-filled rectangle -func DrawRectangle(posX int32, posY int32, width int32, height int32, col color.RGBA) { - _, fl := drawRectangle.Call(posX, posY, width, height, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawRectangleV - Draw a color-filled rectangle (Vector version) -func DrawRectangleV(position Vector2, size Vector2, col color.RGBA) { - _, fl := drawRectangleV.Call(wasm.Struct(position), wasm.Struct(size), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawRectangleRec - Draw a color-filled rectangle -func DrawRectangleRec(rec Rectangle, col color.RGBA) { - _, fl := drawRectangleRec.Call(wasm.Struct(rec), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawRectanglePro - Draw a color-filled rectangle with pro parameters -func DrawRectanglePro(rec Rectangle, origin Vector2, rotation float32, col color.RGBA) { - _, fl := drawRectanglePro.Call(wasm.Struct(rec), wasm.Struct(origin), rotation, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawRectangleGradientV - Draw a vertical-gradient-filled rectangle -func DrawRectangleGradientV(posX int32, posY int32, width int32, height int32, top color.RGBA, bottom color.RGBA) { - _, fl := drawRectangleGradientV.Call(posX, posY, width, height, wasm.Struct(top), wasm.Struct(bottom)) - wasm.Free(fl...) -} - -// DrawRectangleGradientH - Draw a horizontal-gradient-filled rectangle -func DrawRectangleGradientH(posX int32, posY int32, width int32, height int32, left color.RGBA, right color.RGBA) { - _, fl := drawRectangleGradientH.Call(posX, posY, width, height, wasm.Struct(left), wasm.Struct(right)) - wasm.Free(fl...) -} - -// DrawRectangleGradientEx - Draw a gradient-filled rectangle with custom vertex colors -func DrawRectangleGradientEx(rec Rectangle, topLeft color.RGBA, bottomLeft color.RGBA, topRight color.RGBA, bottomRight color.RGBA) { - _, fl := drawRectangleGradientEx.Call(wasm.Struct(rec), wasm.Struct(topLeft), wasm.Struct(bottomLeft), wasm.Struct(topRight), wasm.Struct(bottomRight)) - wasm.Free(fl...) -} - -// DrawRectangleLines - Draw rectangle outline -func DrawRectangleLines(posX int32, posY int32, width int32, height int32, col color.RGBA) { - _, fl := drawRectangleLines.Call(posX, posY, width, height, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawRectangleLinesEx - Draw rectangle outline with extended parameters -func DrawRectangleLinesEx(rec Rectangle, lineThick float32, col color.RGBA) { - _, fl := drawRectangleLinesEx.Call(wasm.Struct(rec), lineThick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawRectangleRounded - Draw rectangle with rounded edges -func DrawRectangleRounded(rec Rectangle, roundness float32, segments int32, col color.RGBA) { - _, fl := drawRectangleRounded.Call(wasm.Struct(rec), roundness, segments, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawRectangleRoundedLines - Draw rectangle lines with rounded edges -func DrawRectangleRoundedLines(rec Rectangle, roundness float32, segments int32, col color.RGBA) { - _, fl := drawRectangleRoundedLines.Call(wasm.Struct(rec), roundness, segments, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawRectangleRoundedLinesEx - Draw rectangle with rounded edges outline -func DrawRectangleRoundedLinesEx(rec Rectangle, roundness float32, segments int32, lineThick float32, col color.RGBA) { - _, fl := drawRectangleRoundedLinesEx.Call(wasm.Struct(rec), roundness, segments, lineThick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawTriangle - Draw a color-filled triangle (vertex in counter-clockwise order!) -func DrawTriangle(v1 Vector2, v2 Vector2, v3 Vector2, col color.RGBA) { - _, fl := drawTriangle.Call(wasm.Struct(v1), wasm.Struct(v2), wasm.Struct(v3), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawTriangleLines - Draw triangle outline (vertex in counter-clockwise order!) -func DrawTriangleLines(v1 Vector2, v2 Vector2, v3 Vector2, col color.RGBA) { - _, fl := drawTriangleLines.Call(wasm.Struct(v1), wasm.Struct(v2), wasm.Struct(v3), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawTriangleFan - Draw a triangle fan defined by points (first vertex is the center) -func DrawTriangleFan(points []Vector2, col color.RGBA) { - _, fl := drawTriangleFan.Call(points, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawTriangleStrip - Draw a triangle strip defined by points -func DrawTriangleStrip(points []Vector2, col color.RGBA) { - _, fl := drawTriangleStrip.Call(points, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawPoly - Draw a regular polygon (Vector version) -func DrawPoly(center Vector2, sides int32, radius float32, rotation float32, col color.RGBA) { - _, fl := drawPoly.Call(wasm.Struct(center), sides, radius, rotation, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawPolyLines - Draw a polygon outline of n sides -func DrawPolyLines(center Vector2, sides int32, radius float32, rotation float32, col color.RGBA) { - _, fl := drawPolyLines.Call(wasm.Struct(center), sides, radius, rotation, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawPolyLinesEx - Draw a polygon outline of n sides with extended parameters -func DrawPolyLinesEx(center Vector2, sides int32, radius float32, rotation float32, lineThick float32, col color.RGBA) { - _, fl := drawPolyLinesEx.Call(wasm.Struct(center), sides, radius, rotation, lineThick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawSplineLinear - Draw spline: Linear, minimum 2 points -func DrawSplineLinear(points []Vector2, thick float32, col color.RGBA) { - _, fl := drawSplineLinear.Call(points, thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawSplineBasis - Draw spline: B-Spline, minimum 4 points -func DrawSplineBasis(points []Vector2, thick float32, col color.RGBA) { - _, fl := drawSplineBasis.Call(points, thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawSplineCatmullRom - Draw spline: Catmull-Rom, minimum 4 points -func DrawSplineCatmullRom(points []Vector2, thick float32, col color.RGBA) { - _, fl := drawSplineCatmullRom.Call(points, thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawSplineBezierQuadratic - Draw spline: Quadratic Bezier, minimum 3 points (1 control point): [p1, c2, p3, c4...] -func DrawSplineBezierQuadratic(points []Vector2, thick float32, col color.RGBA) { - _, fl := drawSplineBezierQuadratic.Call(points, thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawSplineBezierCubic - Draw spline: Cubic Bezier, minimum 4 points (2 control points): [p1, c2, c3, p4, c5, c6...] -func DrawSplineBezierCubic(points []Vector2, thick float32, col color.RGBA) { - _, fl := drawSplineBezierCubic.Call(points, thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawSplineSegmentLinear - Draw spline segment: Linear, 2 points -func DrawSplineSegmentLinear(p1 Vector2, p2 Vector2, thick float32, col color.RGBA) { - _, fl := drawSplineSegmentLinear.Call(wasm.Struct(p1), wasm.Struct(p2), thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawSplineSegmentBasis - Draw spline segment: B-Spline, 4 points -func DrawSplineSegmentBasis(p1 Vector2, p2 Vector2, p3 Vector2, p4 Vector2, thick float32, col color.RGBA) { - _, fl := drawSplineSegmentBasis.Call(wasm.Struct(p1), wasm.Struct(p2), wasm.Struct(p3), wasm.Struct(p4), thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawSplineSegmentCatmullRom - Draw spline segment: Catmull-Rom, 4 points -func DrawSplineSegmentCatmullRom(p1 Vector2, p2 Vector2, p3 Vector2, p4 Vector2, thick float32, col color.RGBA) { - _, fl := drawSplineSegmentCatmullRom.Call(wasm.Struct(p1), wasm.Struct(p2), wasm.Struct(p3), wasm.Struct(p4), thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawSplineSegmentBezierQuadratic - Draw spline segment: Quadratic Bezier, 2 points, 1 control point -func DrawSplineSegmentBezierQuadratic(p1 Vector2, c2 Vector2, p3 Vector2, thick float32, col color.RGBA) { - _, fl := drawSplineSegmentBezierQuadratic.Call(wasm.Struct(p1), wasm.Struct(c2), wasm.Struct(p3), thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawSplineSegmentBezierCubic - Draw spline segment: Cubic Bezier, 2 points, 2 control points -func DrawSplineSegmentBezierCubic(p1 Vector2, c2 Vector2, c3 Vector2, p4 Vector2, thick float32, col color.RGBA) { - _, fl := drawSplineSegmentBezierCubic.Call(wasm.Struct(p1), wasm.Struct(c2), wasm.Struct(c3), wasm.Struct(p4), thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// GetSplinePointLinear - Get (evaluate) spline point: Linear -func GetSplinePointLinear(startPos Vector2, endPos Vector2, t float32) Vector2 { - ret, fl := getSplinePointLinear.Call(wasm.Struct(startPos), wasm.Struct(endPos), t) - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetSplinePointBasis - Get (evaluate) spline point: B-Spline -func GetSplinePointBasis(p1 Vector2, p2 Vector2, p3 Vector2, p4 Vector2, t float32) Vector2 { - ret, fl := getSplinePointBasis.Call(wasm.Struct(p1), wasm.Struct(p2), wasm.Struct(p3), wasm.Struct(p4), t) - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetSplinePointCatmullRom - Get (evaluate) spline point: Catmull-Rom -func GetSplinePointCatmullRom(p1 Vector2, p2 Vector2, p3 Vector2, p4 Vector2, t float32) Vector2 { - ret, fl := getSplinePointCatmullRom.Call(wasm.Struct(p1), wasm.Struct(p2), wasm.Struct(p3), wasm.Struct(p4), t) - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetSplinePointBezierQuad - Get (evaluate) spline point: Quadratic Bezier -func GetSplinePointBezierQuad(p1 Vector2, c2 Vector2, p3 Vector2, t float32) Vector2 { - ret, fl := getSplinePointBezierQuad.Call(wasm.Struct(p1), wasm.Struct(c2), wasm.Struct(p3), t) - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetSplinePointBezierCubic - Get (evaluate) spline point: Cubic Bezier -func GetSplinePointBezierCubic(p1 Vector2, c2 Vector2, c3 Vector2, p4 Vector2, t float32) Vector2 { - ret, fl := getSplinePointBezierCubic.Call(wasm.Struct(p1), wasm.Struct(c2), wasm.Struct(c3), wasm.Struct(p4), t) - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// CheckCollisionRecs - Check collision between two rectangles -func CheckCollisionRecs(rec1 Rectangle, rec2 Rectangle) bool { - ret, fl := checkCollisionRecs.Call(wasm.Struct(rec1), wasm.Struct(rec2)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// CheckCollisionCircles - Check collision between two circles -func CheckCollisionCircles(center1 Vector2, radius1 float32, center2 Vector2, radius2 float32) bool { - ret, fl := checkCollisionCircles.Call(wasm.Struct(center1), radius1, wasm.Struct(center2), radius2) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// CheckCollisionCircleRec - Check collision between circle and rectangle -func CheckCollisionCircleRec(center Vector2, radius float32, rec Rectangle) bool { - ret, fl := checkCollisionCircleRec.Call(wasm.Struct(center), radius, wasm.Struct(rec)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// CheckCollisionCircleLine - Check if circle collides with a line created betweeen two points [p1] and [p2] -func CheckCollisionCircleLine(center Vector2, radius float32, p1 Vector2, p2 Vector2) bool { - ret, fl := checkCollisionCircleLine.Call(wasm.Struct(center), radius, wasm.Struct(p1), wasm.Struct(p2)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// CheckCollisionPointRec - Check if point is inside rectangle -func CheckCollisionPointRec(point Vector2, rec Rectangle) bool { - ret, fl := checkCollisionPointRec.Call(wasm.Struct(point), wasm.Struct(rec)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// CheckCollisionPointCircle - Check if point is inside circle -func CheckCollisionPointCircle(point Vector2, center Vector2, radius float32) bool { - ret, fl := checkCollisionPointCircle.Call(wasm.Struct(point), wasm.Struct(center), radius) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// CheckCollisionPointTriangle - Check if point is inside a triangle -func CheckCollisionPointTriangle(point Vector2, p1 Vector2, p2 Vector2, p3 Vector2) bool { - ret, fl := checkCollisionPointTriangle.Call(wasm.Struct(point), wasm.Struct(p1), wasm.Struct(p2), wasm.Struct(p3)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// CheckCollisionPointPoly - Check if point is within a polygon described by array of vertices -func CheckCollisionPointPoly(point Vector2, points []Vector2) bool { - ret, fl := checkCollisionPointPoly.Call(wasm.Struct(point), points) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// CheckCollisionLines - Check the collision between two lines defined by two points each, returns collision point by reference -func CheckCollisionLines(startPos1 Vector2, endPos1 Vector2, startPos2 Vector2, endPos2 Vector2, collisionPoint *Vector2) bool { - _collisionPoint := wasm.Struct(*collisionPoint) - ret, fl := checkCollisionLines.Call(wasm.Struct(startPos1), wasm.Struct(endPos1), wasm.Struct(startPos2), wasm.Struct(endPos2), _collisionPoint) - v := wasm.Boolean(ret) - *collisionPoint = wasm.BytesToStruct[Vector2](wasm.ReadFromWASM(_collisionPoint.Mem, _collisionPoint.Size)) - wasm.Free(fl...) - return v -} - -// CheckCollisionPointLine - Check if point belongs to line created between two points [p1] and [p2] with defined margin in pixels [threshold] -func CheckCollisionPointLine(point Vector2, p1 Vector2, p2 Vector2, threshold int32) bool { - ret, fl := checkCollisionPointLine.Call(wasm.Struct(point), wasm.Struct(p1), wasm.Struct(p2), threshold) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// GetCollisionRec - Get collision rectangle for two rectangles collision -func GetCollisionRec(rec1 Rectangle, rec2 Rectangle) Rectangle { - ret, fl := getCollisionRec.Call(wasm.Struct(rec1), wasm.Struct(rec2)) - v := wasm.ReadStruct[Rectangle](ret) - wasm.Free(fl...) - return v -} - -// LoadImage - Load image from file into CPU memory (RAM) -func LoadImage(fileName string) *Image { - var zero *Image - return zero -} - -// LoadImageRaw - Load image from RAW file data -func LoadImageRaw(fileName string, width int32, height int32, format PixelFormat, headerSize int32) *Image { - var zero *Image - return zero -} - -// LoadImageAnim - Load image sequence from file (frames appended to image.data) -func LoadImageAnim(fileName string, frames *int32) *Image { - var zero *Image - return zero -} - -// LoadImageAnimFromMemory - Load image sequence from memory buffer -func LoadImageAnimFromMemory(fileType string, fileData []byte, dataSize int32, frames *int32) *Image { - var zero *Image - return zero -} - -// LoadImageFromMemory - Load image from memory buffer, fileType refers to extension: i.e. '.png' -func LoadImageFromMemory(fileType string, fileData []byte, dataSize int32) *Image { - var zero *Image - return zero -} - -// LoadImageFromTexture - Load image from GPU texture data -func LoadImageFromTexture(texture Texture2D) *Image { - var zero *Image - return zero -} - -// LoadImageFromScreen - Load image from screen buffer and (screenshot) -func LoadImageFromScreen() *Image { - var zero *Image - return zero -} - -// IsImageValid - Check if an image is valid (data and parameters) -func IsImageValid(image *Image) bool { - ret, fl := isImageValid.Call(image) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// UnloadImage - Unload image from CPU memory (RAM) -func UnloadImage(image *Image) { - _, fl := unloadImage.Call(image) - wasm.Free(fl...) -} - -// ExportImage - Export image data to file, returns true on success -func ExportImage(image Image, fileName string) bool { - ret, fl := exportImage.Call(wasm.Struct(image), fileName) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// ExportImageToMemory - Export image to memory buffer -func ExportImageToMemory(image Image, fileType string) []byte { - var zero []byte - return zero -} - - -// GenImageGradientLinear - Generate image: linear gradient, direction in degrees [0..360], 0=Vertical gradient -func GenImageGradientLinear(width int, height int, direction int, start color.RGBA, end color.RGBA) *Image { - var zero *Image - return zero -} - -// GenImageGradientRadial - Generate image: radial gradient -func GenImageGradientRadial(width int, height int, density float32, inner color.RGBA, outer color.RGBA) *Image { - var zero *Image - return zero -} - -// GenImageGradientSquare - Generate image: square gradient -func GenImageGradientSquare(width int, height int, density float32, inner color.RGBA, outer color.RGBA) *Image { - var zero *Image - return zero -} - -// GenImageChecked - Generate image: checked -func GenImageChecked(width int, height int, checksX int, checksY int, col1 color.RGBA, col2 color.RGBA) *Image { - var zero *Image - return zero -} - -// GenImageWhiteNoise - Generate image: white noise -func GenImageWhiteNoise(width int, height int, factor float32) *Image { - var zero *Image - return zero -} - -// GenImagePerlinNoise - Generate image: perlin noise -func GenImagePerlinNoise(width int, height int, offsetX int32, offsetY int32, scale float32) *Image { - var zero *Image - return zero -} - -// GenImageCellular - Generate image: cellular algorithm, bigger tileSize means bigger cells -func GenImageCellular(width int, height int, tileSize int) *Image { - var zero *Image - return zero -} - -// GenImageText - Generate image: grayscale image from text data -func GenImageText(width int, height int, text string) Image { - ret, fl := genImageText.Call(width, height, text) - v := wasm.ReadStruct[Image](ret) - wasm.Free(fl...) - return v -} - -// ImageCopy - Create an image duplicate (useful for transformations) -func ImageCopy(image *Image) *Image { - var zero *Image - return zero -} - -// ImageFromImage - Create an image from another image piece -func ImageFromImage(image Image, rec Rectangle) Image { - ret, fl := imageFromImage.Call(wasm.Struct(image), wasm.Struct(rec)) - v := wasm.ReadStruct[Image](ret) - wasm.Free(fl...) - return v -} - -// ImageFromChannel - Create an image from a selected channel of another image (GRAYSCALE) -func ImageFromChannel(image Image, selectedChannel int32) Image { - ret, fl := imageFromChannel.Call(wasm.Struct(image), selectedChannel) - v := wasm.ReadStruct[Image](ret) - wasm.Free(fl...) - return v -} - -// ImageText - Create an image from text (default font) -func ImageText(text string, fontSize int32, col color.RGBA) Image { - ret, fl := imageText.Call(text, fontSize, wasm.Struct(col)) - v := wasm.ReadStruct[Image](ret) - wasm.Free(fl...) - return v -} - -// ImageTextEx - Create an image from text (custom sprite font) -func ImageTextEx(font Font, text string, fontSize float32, spacing float32, tint color.RGBA) Image { - ret, fl := imageTextEx.Call(wasm.Struct(font), text, fontSize, spacing, wasm.Struct(tint)) - v := wasm.ReadStruct[Image](ret) - wasm.Free(fl...) - return v -} - -// ImageFormat - Convert image data to desired format -func ImageFormat(image *Image, newFormat PixelFormat) { - _, fl := imageFormat.Call(image, newFormat) - wasm.Free(fl...) -} - -// ImageToPOT - Convert image to POT (power-of-two) -func ImageToPOT(image *Image, fill color.RGBA) { - _, fl := imageToPOT.Call(image, wasm.Struct(fill)) - wasm.Free(fl...) -} - -// ImageCrop - Crop an image to a defined rectangle -func ImageCrop(image *Image, crop Rectangle) { - _, fl := imageCrop.Call(image, wasm.Struct(crop)) - wasm.Free(fl...) -} - -// ImageAlphaCrop - Crop image depending on alpha value -func ImageAlphaCrop(image *Image, threshold float32) { - _, fl := imageAlphaCrop.Call(image, threshold) - wasm.Free(fl...) -} - -// ImageAlphaClear - Clear alpha channel to desired color -func ImageAlphaClear(image *Image, col color.RGBA, threshold float32) { - _, fl := imageAlphaClear.Call(image, wasm.Struct(col), threshold) - wasm.Free(fl...) -} - -// ImageAlphaMask - Apply alpha mask to image -func ImageAlphaMask(image *Image, alphaMask *Image) { - _, fl := imageAlphaMask.Call(image, alphaMask) - wasm.Free(fl...) -} - -// ImageAlphaPremultiply - Premultiply alpha channel -func ImageAlphaPremultiply(image *Image) { - _, fl := imageAlphaPremultiply.Call(image) - wasm.Free(fl...) -} - -// ImageBlurGaussian - Apply Gaussian blur using a box blur approximation -func ImageBlurGaussian(image *Image, blurSize int32) { - _, fl := imageBlurGaussian.Call(image, blurSize) - wasm.Free(fl...) -} - -// ImageKernelConvolution - Apply custom square convolution kernel to image -func ImageKernelConvolution(image *Image, kernel []float32) { - _, fl := imageKernelConvolution.Call(image, kernel) - wasm.Free(fl...) -} - -// ImageResize - Resize image (Bicubic scaling algorithm) -func ImageResize(image *Image, newWidth int32, newHeight int32) { - _, fl := imageResize.Call(image, newWidth, newHeight) - wasm.Free(fl...) -} - -// ImageResizeNN - Resize image (Nearest-Neighbor scaling algorithm) -func ImageResizeNN(image *Image, newWidth int32, newHeight int32) { - _, fl := imageResizeNN.Call(image, newWidth, newHeight) - wasm.Free(fl...) -} - -// ImageResizeCanvas - Resize canvas and fill with color -func ImageResizeCanvas(image *Image, newWidth int32, newHeight int32, offsetX int32, offsetY int32, fill color.RGBA) { - _, fl := imageResizeCanvas.Call(image, newWidth, newHeight, offsetX, offsetY, wasm.Struct(fill)) - wasm.Free(fl...) -} - -// ImageMipmaps - Compute all mipmap levels for a provided image -func ImageMipmaps(image *Image) { - _, fl := imageMipmaps.Call(image) - wasm.Free(fl...) -} - -// ImageDither - Dither image data to 16bpp or lower (Floyd-Steinberg dithering) -func ImageDither(image *Image, rBpp int32, gBpp int32, bBpp int32, aBpp int32) { - _, fl := imageDither.Call(image, rBpp, gBpp, bBpp, aBpp) - wasm.Free(fl...) -} - -// ImageFlipVertical - Flip image vertically -func ImageFlipVertical(image *Image) { - _, fl := imageFlipVertical.Call(image) - wasm.Free(fl...) -} - -// ImageFlipHorizontal - Flip image horizontally -func ImageFlipHorizontal(image *Image) { - _, fl := imageFlipHorizontal.Call(image) - wasm.Free(fl...) -} - -// ImageRotate - Rotate image by input angle in degrees (-359 to 359) -func ImageRotate(image *Image, degrees int32) { - _, fl := imageRotate.Call(image, degrees) - wasm.Free(fl...) -} - -// ImageRotateCW - Rotate image clockwise 90deg -func ImageRotateCW(image *Image) { - _, fl := imageRotateCW.Call(image) - wasm.Free(fl...) -} - -// ImageRotateCCW - Rotate image counter-clockwise 90deg -func ImageRotateCCW(image *Image) { - _, fl := imageRotateCCW.Call(image) - wasm.Free(fl...) -} - -// ImageColorTint - Modify image color: tint -func ImageColorTint(image *Image, col color.RGBA) { - _, fl := imageColorTint.Call(image, wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageColorInvert - Modify image color: invert -func ImageColorInvert(image *Image) { - _, fl := imageColorInvert.Call(image) - wasm.Free(fl...) -} - -// ImageColorGrayscale - Modify image color: grayscale -func ImageColorGrayscale(image *Image) { - _, fl := imageColorGrayscale.Call(image) - wasm.Free(fl...) -} - -// ImageColorContrast - Modify image color: contrast (-100 to 100) -func ImageColorContrast(image *Image, contrast float32) { - _, fl := imageColorContrast.Call(image, contrast) - wasm.Free(fl...) -} - -// ImageColorBrightness - Modify image color: brightness (-255 to 255) -func ImageColorBrightness(image *Image, brightness int32) { - _, fl := imageColorBrightness.Call(image, brightness) - wasm.Free(fl...) -} - -// ImageColorReplace - Modify image color: replace color -func ImageColorReplace(image *Image, col color.RGBA, replace color.RGBA) { - _, fl := imageColorReplace.Call(image, wasm.Struct(col), wasm.Struct(replace)) - wasm.Free(fl...) -} - -// LoadImageColors - Load color data from image as a Color array (RGBA - 32bit) -// -// NOTE: Memory allocated should be freed using UnloadImageColors() -func LoadImageColors(image *Image) []color.RGBA { - var zero []color.RGBA - return zero -} - -// LoadImagePalette - Load colors palette from image as a Color array (RGBA - 32bit) -// -// NOTE: Memory allocated should be freed using UnloadImagePalette() -func LoadImagePalette(image Image, maxPaletteSize int32) []color.RGBA { - var zero []color.RGBA - return zero -} - -// UnloadImageColors - Unload color data loaded with LoadImageColors() -func UnloadImageColors(colors []color.RGBA) { - _, fl := unloadImageColors.Call(colors) - wasm.Free(fl...) -} - -// UnloadImagePalette - Unload colors palette loaded with LoadImagePalette() -func UnloadImagePalette(colors []color.RGBA) { - _, fl := unloadImagePalette.Call(colors) - wasm.Free(fl...) -} - -// GetImageAlphaBorder - Get image alpha border rectangle -func GetImageAlphaBorder(image Image, threshold float32) Rectangle { - ret, fl := getImageAlphaBorder.Call(wasm.Struct(image), threshold) - v := wasm.ReadStruct[Rectangle](ret) - wasm.Free(fl...) - return v -} - -// GetImageColor - Get image pixel color at (x, y) position -func GetImageColor(image Image, x int32, y int32) color.RGBA { - ret, fl := getImageColor.Call(wasm.Struct(image), x, y) - v := wasm.ReadStruct[color.RGBA](ret) - wasm.Free(fl...) - return v -} - -// ImageClearBackground - Clear image background with given color -func ImageClearBackground(dst *Image, col color.RGBA) { - _, fl := imageClearBackground.Call(dst, wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawPixelV - Draw pixel within an image (Vector version) -func ImageDrawPixelV(dst *Image, position Vector2, col color.RGBA) { - _, fl := imageDrawPixelV.Call(dst, wasm.Struct(position), wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawLine - Draw line within an image -func ImageDrawLine(dst *Image, startPosX int32, startPosY int32, endPosX int32, endPosY int32, col color.RGBA) { - _, fl := imageDrawLine.Call(dst, startPosX, startPosY, endPosX, endPosY, wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawLineV - Draw line within an image (Vector version) -func ImageDrawLineV(dst *Image, start Vector2, end Vector2, col color.RGBA) { - _, fl := imageDrawLineV.Call(dst, wasm.Struct(start), wasm.Struct(end), wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawLineEx - Draw a line defining thickness within an image -func ImageDrawLineEx(dst *Image, start Vector2, end Vector2, thick int32, col color.RGBA) { - _, fl := imageDrawLineEx.Call(dst, wasm.Struct(start), wasm.Struct(end), thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawCircle - Draw a filled circle within an image -func ImageDrawCircle(dst *Image, centerX int32, centerY int32, radius int32, col color.RGBA) { - _, fl := imageDrawCircle.Call(dst, centerX, centerY, radius, wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawCircleV - Draw a filled circle within an image (Vector version) -func ImageDrawCircleV(dst *Image, center Vector2, radius int32, col color.RGBA) { - _, fl := imageDrawCircleV.Call(dst, wasm.Struct(center), radius, wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawCircleLines - Draw circle outline within an image -func ImageDrawCircleLines(dst *Image, centerX int32, centerY int32, radius int32, col color.RGBA) { - _, fl := imageDrawCircleLines.Call(dst, centerX, centerY, radius, wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawCircleLinesV - Draw circle outline within an image (Vector version) -func ImageDrawCircleLinesV(dst *Image, center Vector2, radius int32, col color.RGBA) { - _, fl := imageDrawCircleLinesV.Call(dst, wasm.Struct(center), radius, wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawRectangle - Draw rectangle within an image -func ImageDrawRectangle(dst *Image, posX int32, posY int32, width int32, height int32, col color.RGBA) { - _, fl := imageDrawRectangle.Call(dst, posX, posY, width, height, wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawRectangleV - Draw rectangle within an image (Vector version) -func ImageDrawRectangleV(dst *Image, position Vector2, size Vector2, col color.RGBA) { - _, fl := imageDrawRectangleV.Call(dst, wasm.Struct(position), wasm.Struct(size), wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawRectangleRec - Draw rectangle within an image -func ImageDrawRectangleRec(dst *Image, rec Rectangle, col color.RGBA) { - _, fl := imageDrawRectangleRec.Call(dst, wasm.Struct(rec), wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawRectangleLines - Draw rectangle lines within an image -func ImageDrawRectangleLines(dst *Image, rec Rectangle, thick int, col color.RGBA) { - _, fl := imageDrawRectangleLines.Call(dst, wasm.Struct(rec), thick, wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawTriangle - Draw triangle within an image -func ImageDrawTriangle(dst *Image, v1 Vector2, v2 Vector2, v3 Vector2, col color.RGBA) { - _, fl := imageDrawTriangle.Call(dst, wasm.Struct(v1), wasm.Struct(v2), wasm.Struct(v3), wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawTriangleEx - Draw triangle with interpolated colors within an image -func ImageDrawTriangleEx(dst *Image, v1 Vector2, v2 Vector2, v3 Vector2, c1 color.RGBA, c2 color.RGBA, c3 color.RGBA) { - _, fl := imageDrawTriangleEx.Call(dst, wasm.Struct(v1), wasm.Struct(v2), wasm.Struct(v3), wasm.Struct(c1), wasm.Struct(c2), wasm.Struct(c3)) - wasm.Free(fl...) -} - -// ImageDrawTriangleLines - Draw triangle outline within an image -func ImageDrawTriangleLines(dst *Image, v1 Vector2, v2 Vector2, v3 Vector2, col color.RGBA) { - _, fl := imageDrawTriangleLines.Call(dst, wasm.Struct(v1), wasm.Struct(v2), wasm.Struct(v3), wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawTriangleFan - Draw a triangle fan defined by points within an image (first vertex is the center) -func ImageDrawTriangleFan(dst *Image, points []Vector2, col color.RGBA) { - _, fl := imageDrawTriangleFan.Call(dst, points, wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawTriangleStrip - Draw a triangle strip defined by points within an image -func ImageDrawTriangleStrip(dst *Image, points []Vector2, col color.RGBA) { - _, fl := imageDrawTriangleStrip.Call(dst, points, wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDraw - Draw a source image within a destination image (tint applied to source) -func ImageDraw(dst *Image, src *Image, srcRec Rectangle, dstRec Rectangle, tint color.RGBA) { - _, fl := imageDraw.Call(dst, src, wasm.Struct(srcRec), wasm.Struct(dstRec), wasm.Struct(tint)) - wasm.Free(fl...) -} - -// ImageDrawText - Draw text (using default font) within an image (destination) -func ImageDrawText(dst *Image, posX int32, posY int32, text string, fontSize int32, col color.RGBA) { - _, fl := imageDrawText.Call(dst, posX, posY, text, fontSize, wasm.Struct(col)) - wasm.Free(fl...) -} - -// ImageDrawTextEx - Draw text (custom sprite font) within an image (destination) -func ImageDrawTextEx(dst *Image, position Vector2, font Font, text string, fontSize float32, spacing float32, tint color.RGBA) { - _, fl := imageDrawTextEx.Call(dst, wasm.Struct(position), wasm.Struct(font), text, fontSize, spacing, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// LoadTexture - Load texture from file into GPU memory (VRAM) -func LoadTexture(fileName string) Texture2D { - ret, fl := loadTexture.Call(fileName) - v := wasm.ReadStruct[Texture2D](ret) - wasm.Free(fl...) - return v -} - - -// LoadTextureCubemap - Load cubemap from image, multiple image cubemap layouts supported -func LoadTextureCubemap(image *Image, layout int32) Texture2D { - ret, fl := loadTextureCubemap.Call(image, layout) - v := wasm.ReadStruct[Texture2D](ret) - wasm.Free(fl...) - return v -} - -// LoadRenderTexture - Load texture for rendering (framebuffer) -func LoadRenderTexture(width int32, height int32) RenderTexture2D { - ret, fl := loadRenderTexture.Call(width, height) - v := wasm.ReadStruct[RenderTexture2D](ret) - wasm.Free(fl...) - return v -} - -// IsTextureValid - Check if a texture is valid (loaded in GPU) -func IsTextureValid(texture Texture2D) bool { - ret, fl := isTextureValid.Call(wasm.Struct(texture)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// UnloadTexture - Unload texture from GPU memory (VRAM) -func UnloadTexture(texture Texture2D) { - _, fl := unloadTexture.Call(wasm.Struct(texture)) - wasm.Free(fl...) -} - -// IsRenderTextureValid - Check if a render texture is valid (loaded in GPU) -func IsRenderTextureValid(target RenderTexture2D) bool { - ret, fl := isRenderTextureValid.Call(wasm.Struct(target)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// UnloadRenderTexture - Unload render texture from GPU memory (VRAM) -func UnloadRenderTexture(target RenderTexture2D) { - _, fl := unloadRenderTexture.Call(wasm.Struct(target)) - wasm.Free(fl...) -} - -// UpdateTexture - Update GPU texture with new data -func UpdateTexture(texture Texture2D, pixels []color.RGBA) { - _, fl := updateTexture.Call(wasm.Struct(texture), pixels) - wasm.Free(fl...) -} - -// UpdateTextureRec - Update GPU texture rectangle with new data -func UpdateTextureRec(texture Texture2D, rec Rectangle, pixels []color.RGBA) { - _, fl := updateTextureRec.Call(wasm.Struct(texture), wasm.Struct(rec), pixels) - wasm.Free(fl...) -} - -// GenTextureMipmaps - Generate GPU mipmaps for a texture -func GenTextureMipmaps(texture *Texture2D) { - _, fl := genTextureMipmaps.Call(texture) - wasm.Free(fl...) -} - -// SetTextureFilter - Set texture scaling filter mode -func SetTextureFilter(texture Texture2D, filter TextureFilterMode) { - _, fl := setTextureFilter.Call(wasm.Struct(texture), filter) - wasm.Free(fl...) -} - -// SetTextureWrap - Set texture wrapping mode -func SetTextureWrap(texture Texture2D, wrap TextureWrapMode) { - _, fl := setTextureWrap.Call(wasm.Struct(texture), wrap) - wasm.Free(fl...) -} - -// DrawTexture - Draw a Texture2D -func DrawTexture(texture Texture2D, posX int32, posY int32, tint color.RGBA) { - _, fl := drawTexture.Call(wasm.Struct(texture), posX, posY, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawTextureV - Draw a Texture2D with position defined as Vector2 -func DrawTextureV(texture Texture2D, position Vector2, tint color.RGBA) { - _, fl := drawTextureV.Call(wasm.Struct(texture), wasm.Struct(position), wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawTextureEx - Draw a Texture2D with extended parameters -func DrawTextureEx(texture Texture2D, position Vector2, rotation float32, scale float32, tint color.RGBA) { - _, fl := drawTextureEx.Call(wasm.Struct(texture), wasm.Struct(position), rotation, scale, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawTextureRec - Draw a part of a texture defined by a rectangle -func DrawTextureRec(texture Texture2D, source Rectangle, position Vector2, tint color.RGBA) { - _, fl := drawTextureRec.Call(wasm.Struct(texture), wasm.Struct(source), wasm.Struct(position), wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawTexturePro - Draw a part of a texture defined by a rectangle with 'pro' parameters -func DrawTexturePro(texture Texture2D, source Rectangle, dest Rectangle, origin Vector2, rotation float32, tint color.RGBA) { - _, fl := drawTexturePro.Call(wasm.Struct(texture), wasm.Struct(source), wasm.Struct(dest), wasm.Struct(origin), rotation, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawTextureNPatch - Draws a texture (or part of it) that stretches or shrinks nicely -func DrawTextureNPatch(texture Texture2D, nPatchInfo NPatchInfo, dest Rectangle, origin Vector2, rotation float32, tint color.RGBA) { - _, fl := drawTextureNPatch.Call(wasm.Struct(texture), wasm.Struct(nPatchInfo), wasm.Struct(dest), wasm.Struct(origin), rotation, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// Fade - Get color with alpha applied, alpha goes from 0.0f to 1.0f -func Fade(col color.RGBA, alpha float32) color.RGBA { - ret, fl := fade.Call(wasm.Struct(col), alpha) - v := wasm.ReadStruct[color.RGBA](ret) - wasm.Free(fl...) - return v -} - -// ColorToInt - Get hexadecimal value for a Color (0xRRGGBBAA) -func ColorToInt(col color.RGBA) int32 { - ret, fl := colorToInt.Call(wasm.Struct(col)) - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// ColorNormalize - Get Color normalized as float [0..1] -func ColorNormalize(col color.RGBA) Vector4 { - ret, fl := colorNormalize.Call(wasm.Struct(col)) - v := wasm.ReadStruct[Vector4](ret) - wasm.Free(fl...) - return v -} - -// ColorFromNormalized - Get Color from normalized values [0..1] -func ColorFromNormalized(normalized Vector4) color.RGBA { - ret, fl := colorFromNormalized.Call(wasm.Struct(normalized)) - v := wasm.ReadStruct[color.RGBA](ret) - wasm.Free(fl...) - return v -} - -// ColorToHSV - Get HSV values for a Color, hue [0..360], saturation/value [0..1] -func ColorToHSV(col color.RGBA) Vector3 { - ret, fl := colorToHSV.Call(wasm.Struct(col)) - v := wasm.ReadStruct[Vector3](ret) - wasm.Free(fl...) - return v -} - -// ColorFromHSV - Get a Color from HSV values, hue [0..360], saturation/value [0..1] -func ColorFromHSV(hue float32, saturation float32, value float32) color.RGBA { - ret, fl := colorFromHSV.Call(hue, saturation, value) - v := wasm.ReadStruct[color.RGBA](ret) - wasm.Free(fl...) - return v -} - -// ColorTint - Get color multiplied with another color -func ColorTint(col color.RGBA, tint color.RGBA) color.RGBA { - ret, fl := colorTint.Call(wasm.Struct(col), wasm.Struct(tint)) - v := wasm.ReadStruct[color.RGBA](ret) - wasm.Free(fl...) - return v -} - -// ColorBrightness - Get color with brightness correction, brightness factor goes from -1.0f to 1.0f -func ColorBrightness(col color.RGBA, factor float32) color.RGBA { - ret, fl := colorBrightness.Call(wasm.Struct(col), factor) - v := wasm.ReadStruct[color.RGBA](ret) - wasm.Free(fl...) - return v -} - -// ColorContrast - Get color with contrast correction, contrast values between -1.0f and 1.0f -func ColorContrast(col color.RGBA, contrast float32) color.RGBA { - ret, fl := colorContrast.Call(wasm.Struct(col), contrast) - v := wasm.ReadStruct[color.RGBA](ret) - wasm.Free(fl...) - return v -} - -// ColorAlpha - Get color with alpha applied, alpha goes from 0.0f to 1.0f -func ColorAlpha(col color.RGBA, alpha float32) color.RGBA { - ret, fl := colorAlpha.Call(wasm.Struct(col), alpha) - v := wasm.ReadStruct[color.RGBA](ret) - wasm.Free(fl...) - return v -} - -// ColorAlphaBlend - Get src alpha-blended into dst color with tint -func ColorAlphaBlend(dst color.RGBA, src color.RGBA, tint color.RGBA) color.RGBA { - ret, fl := colorAlphaBlend.Call(wasm.Struct(dst), wasm.Struct(src), wasm.Struct(tint)) - v := wasm.ReadStruct[color.RGBA](ret) - wasm.Free(fl...) - return v -} - -// ColorLerp - Get color lerp interpolation between two colors, factor [0.0f..1.0f] -func ColorLerp(col1 color.RGBA, col2 color.RGBA, factor float32) color.RGBA { - ret, fl := colorLerp.Call(wasm.Struct(col1), wasm.Struct(col2), factor) - v := wasm.ReadStruct[color.RGBA](ret) - wasm.Free(fl...) - return v -} - -// GetColor - Get Color structure from hexadecimal value -func GetColor(hexValue uint) color.RGBA { - ret, fl := getColor.Call(hexValue) - v := wasm.ReadStruct[color.RGBA](ret) - wasm.Free(fl...) - return v -} - -// GetPixelColor - Get Color from a source pixel pointer of certain format -func GetPixelColor(srcPtr unsafe.Pointer, format int32) color.RGBA { - ret, fl := getPixelColor.Call(srcPtr, format) - v := wasm.ReadStruct[color.RGBA](ret) - wasm.Free(fl...) - return v -} - -// SetPixelColor - Set color formatted into destination pixel pointer -func SetPixelColor(dstPtr unsafe.Pointer, col color.RGBA, format int32) { - _, fl := setPixelColor.Call(dstPtr, wasm.Struct(col), format) - wasm.Free(fl...) -} - -// GetPixelDataSize - Get pixel data size in bytes for certain format -func GetPixelDataSize(width int32, height int32, format int32) int32 { - ret, fl := getPixelDataSize.Call(width, height, format) - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// GetFontDefault - Get the default Font -func GetFontDefault() Font { - ret, fl := getFontDefault.Call() - v := wasm.ReadStruct[Font](ret) - wasm.Free(fl...) - return v -} - -// LoadFont - Load font from file into GPU memory (VRAM) -func LoadFont(fileName string) Font { - ret, fl := loadFont.Call(fileName) - v := wasm.ReadStruct[Font](ret) - wasm.Free(fl...) - return v -} - -// LoadFontFromImage - Load font from Image (XNA style) -func LoadFontFromImage(image Image, key color.RGBA, firstChar rune) Font { - ret, fl := loadFontFromImage.Call(wasm.Struct(image), wasm.Struct(key), firstChar) - v := wasm.ReadStruct[Font](ret) - wasm.Free(fl...) - return v -} - -// LoadFontFromMemory - Load font from memory buffer, fileType refers to extension: i.e. '.ttf' -func LoadFontFromMemory(fileType string, fileData []byte, fontSize int32, codepoints []rune) Font { - ret, fl := loadFontFromMemory.Call(fileType, fileData, fontSize, codepoints) - v := wasm.ReadStruct[Font](ret) - wasm.Free(fl...) - return v -} - -// IsFontValid - Check if a font is valid (font data loaded, WARNING: GPU texture not checked) -func IsFontValid(font Font) bool { - ret, fl := isFontValid.Call(wasm.Struct(font)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// LoadFontData - Load font data for further use -func LoadFontData(fileData []byte, fontSize int32, codepoints []rune, codepointCount int32, typ int32) []GlyphInfo { - var zero []GlyphInfo - return zero -} - -// GenImageFontAtlas - Generate image font atlas using chars info -func GenImageFontAtlas(glyphs []GlyphInfo, glyphRecs []*Rectangle, fontSize int32, padding int32, packMethod int32) Image { - ret, fl := genImageFontAtlas.Call(glyphs, glyphRecs, fontSize, padding, packMethod) - v := wasm.ReadStruct[Image](ret) - wasm.Free(fl...) - return v -} - -// UnloadFontData - Unload font chars info data (RAM) -func UnloadFontData(glyphs []GlyphInfo) { - _, fl := unloadFontData.Call(glyphs) - wasm.Free(fl...) -} - -// UnloadFont - Unload font from GPU memory (VRAM) -func UnloadFont(font Font) { - _, fl := unloadFont.Call(wasm.Struct(font)) - wasm.Free(fl...) -} - -// DrawFPS - Draw current FPS -func DrawFPS(posX int32, posY int32) { - _, fl := drawFPS.Call(posX, posY) - wasm.Free(fl...) -} - -// DrawText - Draw text (using default font) -func DrawText(text string, posX int32, posY int32, fontSize int32, col color.RGBA) { - _, fl := drawText.Call(text, posX, posY, fontSize, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawTextEx - Draw text using font and additional parameters -func DrawTextEx(font Font, text string, position Vector2, fontSize float32, spacing float32, tint color.RGBA) { - _, fl := drawTextEx.Call(wasm.Struct(font), text, wasm.Struct(position), fontSize, spacing, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawTextPro - Draw text using Font and pro parameters (rotation) -func DrawTextPro(font Font, text string, position Vector2, origin Vector2, rotation float32, fontSize float32, spacing float32, tint color.RGBA) { - _, fl := drawTextPro.Call(wasm.Struct(font), text, wasm.Struct(position), wasm.Struct(origin), rotation, fontSize, spacing, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawTextCodepoint - Draw one character (codepoint) -func DrawTextCodepoint(font Font, codepoint rune, position Vector2, fontSize float32, tint color.RGBA) { - _, fl := drawTextCodepoint.Call(wasm.Struct(font), codepoint, wasm.Struct(position), fontSize, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawTextCodepoints - Draw multiple character (codepoint) -func DrawTextCodepoints(font Font, codepoints []rune, position Vector2, fontSize float32, spacing float32, tint color.RGBA) { - _, fl := drawTextCodepoints.Call(wasm.Struct(font), codepoints, wasm.Struct(position), fontSize, spacing, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// SetTextLineSpacing - Set vertical line spacing when drawing with line-breaks -func SetTextLineSpacing(spacing int) { - _, fl := setTextLineSpacing.Call(spacing) - wasm.Free(fl...) -} - -// MeasureText - Measure string width for default font -func MeasureText(text string, fontSize int32) int32 { - ret, fl := measureText.Call(text, fontSize) - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// MeasureTextEx - Measure string size for Font -func MeasureTextEx(font Font, text string, fontSize float32, spacing float32) Vector2 { - ret, fl := measureTextEx.Call(wasm.Struct(font), text, fontSize, spacing) - v := wasm.ReadStruct[Vector2](ret) - wasm.Free(fl...) - return v -} - -// GetGlyphIndex - Get glyph index position in font for a codepoint (unicode character), fallback to '?' if not found -func GetGlyphIndex(font Font, codepoint rune) int32 { - ret, fl := getGlyphIndex.Call(wasm.Struct(font), codepoint) - v := wasm.Numeric[int32](ret) - wasm.Free(fl...) - return v -} - -// GetGlyphInfo - Get glyph font info data for a codepoint (unicode character), fallback to '?' if not found -func GetGlyphInfo(font Font, codepoint rune) GlyphInfo { - ret, fl := getGlyphInfo.Call(wasm.Struct(font), codepoint) - v := wasm.ReadStruct[GlyphInfo](ret) - wasm.Free(fl...) - return v -} - -// GetGlyphAtlasRec - Get glyph rectangle in font atlas for a codepoint (unicode character), fallback to '?' if not found -func GetGlyphAtlasRec(font Font, codepoint rune) Rectangle { - ret, fl := getGlyphAtlasRec.Call(wasm.Struct(font), codepoint) - v := wasm.ReadStruct[Rectangle](ret) - wasm.Free(fl...) - return v -} - -// DrawLine3D - Draw a line in 3D world space -func DrawLine3D(startPos Vector3, endPos Vector3, col color.RGBA) { - _, fl := drawLine3D.Call(wasm.Struct(startPos), wasm.Struct(endPos), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawPoint3D - Draw a point in 3D space, actually a small line -func DrawPoint3D(position Vector3, col color.RGBA) { - _, fl := drawPoint3D.Call(wasm.Struct(position), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCircle3D - Draw a circle in 3D world space -func DrawCircle3D(center Vector3, radius float32, rotationAxis Vector3, rotationAngle float32, col color.RGBA) { - _, fl := drawCircle3D.Call(wasm.Struct(center), radius, wasm.Struct(rotationAxis), rotationAngle, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawTriangle3D - Draw a color-filled triangle (vertex in counter-clockwise order!) -func DrawTriangle3D(v1 Vector3, v2 Vector3, v3 Vector3, col color.RGBA) { - _, fl := drawTriangle3D.Call(wasm.Struct(v1), wasm.Struct(v2), wasm.Struct(v3), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawTriangleStrip3D - Draw a triangle strip defined by points -func DrawTriangleStrip3D(points []Vector3, col color.RGBA) { - _, fl := drawTriangleStrip3D.Call(points, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCube - Draw cube -func DrawCube(position Vector3, width float32, height float32, length float32, col color.RGBA) { - _, fl := drawCube.Call(wasm.Struct(position), width, height, length, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCubeV - Draw cube (Vector version) -func DrawCubeV(position Vector3, size Vector3, col color.RGBA) { - _, fl := drawCubeV.Call(wasm.Struct(position), wasm.Struct(size), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCubeWires - Draw cube wires -func DrawCubeWires(position Vector3, width float32, height float32, length float32, col color.RGBA) { - _, fl := drawCubeWires.Call(wasm.Struct(position), width, height, length, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCubeWiresV - Draw cube wires (Vector version) -func DrawCubeWiresV(position Vector3, size Vector3, col color.RGBA) { - _, fl := drawCubeWiresV.Call(wasm.Struct(position), wasm.Struct(size), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawSphere - Draw sphere -func DrawSphere(centerPos Vector3, radius float32, col color.RGBA) { - _, fl := drawSphere.Call(wasm.Struct(centerPos), radius, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawSphereEx - Draw sphere with extended parameters -func DrawSphereEx(centerPos Vector3, radius float32, rings int32, slices int32, col color.RGBA) { - _, fl := drawSphereEx.Call(wasm.Struct(centerPos), radius, rings, slices, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawSphereWires - Draw sphere wires -func DrawSphereWires(centerPos Vector3, radius float32, rings int32, slices int32, col color.RGBA) { - _, fl := drawSphereWires.Call(wasm.Struct(centerPos), radius, rings, slices, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCylinder - Draw a cylinder/cone -func DrawCylinder(position Vector3, radiusTop float32, radiusBottom float32, height float32, slices int32, col color.RGBA) { - _, fl := drawCylinder.Call(wasm.Struct(position), radiusTop, radiusBottom, height, slices, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCylinderEx - Draw a cylinder with base at startPos and top at endPos -func DrawCylinderEx(startPos Vector3, endPos Vector3, startRadius float32, endRadius float32, sides int32, col color.RGBA) { - _, fl := drawCylinderEx.Call(wasm.Struct(startPos), wasm.Struct(endPos), startRadius, endRadius, sides, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCylinderWires - Draw a cylinder/cone wires -func DrawCylinderWires(position Vector3, radiusTop float32, radiusBottom float32, height float32, slices int32, col color.RGBA) { - _, fl := drawCylinderWires.Call(wasm.Struct(position), radiusTop, radiusBottom, height, slices, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCylinderWiresEx - Draw a cylinder wires with base at startPos and top at endPos -func DrawCylinderWiresEx(startPos Vector3, endPos Vector3, startRadius float32, endRadius float32, sides int32, col color.RGBA) { - _, fl := drawCylinderWiresEx.Call(wasm.Struct(startPos), wasm.Struct(endPos), startRadius, endRadius, sides, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCapsule - Draw a capsule with the center of its sphere caps at startPos and endPos -func DrawCapsule(startPos Vector3, endPos Vector3, radius float32, slices int32, rings int32, col color.RGBA) { - _, fl := drawCapsule.Call(wasm.Struct(startPos), wasm.Struct(endPos), radius, slices, rings, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawCapsuleWires - Draw capsule wireframe with the center of its sphere caps at startPos and endPos -func DrawCapsuleWires(startPos Vector3, endPos Vector3, radius float32, slices int32, rings int32, col color.RGBA) { - _, fl := drawCapsuleWires.Call(wasm.Struct(startPos), wasm.Struct(endPos), radius, slices, rings, wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawPlane - Draw a plane XZ -func DrawPlane(centerPos Vector3, size Vector2, col color.RGBA) { - _, fl := drawPlane.Call(wasm.Struct(centerPos), wasm.Struct(size), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawRay - Draw a ray line -func DrawRay(ray Ray, col color.RGBA) { - _, fl := drawRay.Call(wasm.Struct(ray), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawGrid - Draw a grid (centered at (0, 0, 0)) -func DrawGrid(slices int32, spacing float32) { - _, fl := drawGrid.Call(slices, spacing) - wasm.Free(fl...) -} - -// LoadModel - Load model from files (meshes and materials) -func LoadModel(fileName string) Model { - ret, fl := loadModel.Call(fileName) - v := wasm.ReadStruct[Model](ret) - wasm.Free(fl...) - return v -} - -// LoadModelFromMesh - Load model from generated mesh (default material) -func LoadModelFromMesh(mesh Mesh) Model { - ret, fl := loadModelFromMesh.Call(wasm.Struct(mesh)) - v := wasm.ReadStruct[Model](ret) - wasm.Free(fl...) - return v -} - -// IsModelValid - Check if a model is valid (loaded in GPU, VAO/VBOs) -func IsModelValid(model Model) bool { - ret, fl := isModelValid.Call(wasm.Struct(model)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// UnloadModel - Unload model (including meshes) from memory (RAM and/or VRAM) -func UnloadModel(model Model) { - _, fl := unloadModel.Call(wasm.Struct(model)) - wasm.Free(fl...) -} - -// GetModelBoundingBox - Compute model bounding box limits (considers all meshes) -func GetModelBoundingBox(model Model) BoundingBox { - ret, fl := getModelBoundingBox.Call(wasm.Struct(model)) - v := wasm.ReadStruct[BoundingBox](ret) - wasm.Free(fl...) - return v -} - -// DrawModel - Draw a model (with texture if set) -func DrawModel(model Model, position Vector3, scale float32, tint color.RGBA) { - _, fl := drawModel.Call(wasm.Struct(model), wasm.Struct(position), scale, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawModelEx - Draw a model with extended parameters -func DrawModelEx(model Model, position Vector3, rotationAxis Vector3, rotationAngle float32, scale Vector3, tint color.RGBA) { - _, fl := drawModelEx.Call(wasm.Struct(model), wasm.Struct(position), wasm.Struct(rotationAxis), rotationAngle, wasm.Struct(scale), wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawModelWires - Draw a model wires (with texture if set) -func DrawModelWires(model Model, position Vector3, scale float32, tint color.RGBA) { - _, fl := drawModelWires.Call(wasm.Struct(model), wasm.Struct(position), scale, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawModelWiresEx - Draw a model wires (with texture if set) with extended parameters -func DrawModelWiresEx(model Model, position Vector3, rotationAxis Vector3, rotationAngle float32, scale Vector3, tint color.RGBA) { - _, fl := drawModelWiresEx.Call(wasm.Struct(model), wasm.Struct(position), wasm.Struct(rotationAxis), rotationAngle, wasm.Struct(scale), wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawModelPoints - Draw a model as points -func DrawModelPoints(model Model, position Vector3, scale float32, tint color.RGBA) { - _, fl := drawModelPoints.Call(wasm.Struct(model), wasm.Struct(position), scale, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawModelPointsEx - Draw a model as points with extended parameters -func DrawModelPointsEx(model Model, position Vector3, rotationAxis Vector3, rotationAngle float32, scale Vector3, tint color.RGBA) { - _, fl := drawModelPointsEx.Call(wasm.Struct(model), wasm.Struct(position), wasm.Struct(rotationAxis), rotationAngle, wasm.Struct(scale), wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawBoundingBox - Draw bounding box (wires) -func DrawBoundingBox(box BoundingBox, col color.RGBA) { - _, fl := drawBoundingBox.Call(wasm.Struct(box), wasm.Struct(col)) - wasm.Free(fl...) -} - -// DrawBillboard - Draw a billboard texture -func DrawBillboard(camera Camera, texture Texture2D, position Vector3, scale float32, tint color.RGBA) { - _, fl := drawBillboard.Call(camera, wasm.Struct(texture), wasm.Struct(position), scale, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawBillboardRec - Draw a billboard texture defined by source -func DrawBillboardRec(camera Camera, texture Texture2D, source Rectangle, position Vector3, size Vector2, tint color.RGBA) { - _, fl := drawBillboardRec.Call(camera, wasm.Struct(texture), wasm.Struct(source), wasm.Struct(position), wasm.Struct(size), wasm.Struct(tint)) - wasm.Free(fl...) -} - -// DrawBillboardPro - Draw a billboard texture defined by source and rotation -func DrawBillboardPro(camera Camera, texture Texture2D, source Rectangle, position Vector3, up Vector3, size Vector2, origin Vector2, rotation float32, tint color.RGBA) { - _, fl := drawBillboardPro.Call(camera, wasm.Struct(texture), wasm.Struct(source), wasm.Struct(position), wasm.Struct(up), wasm.Struct(size), wasm.Struct(origin), rotation, wasm.Struct(tint)) - wasm.Free(fl...) -} - -// UploadMesh - Upload mesh vertex data in GPU and provide VAO/VBO ids -func UploadMesh(mesh *Mesh, dynamic bool) { - _, fl := uploadMesh.Call(mesh, dynamic) - wasm.Free(fl...) -} - -// UpdateMeshBuffer - Update mesh vertex data in GPU for a specific buffer index -func UpdateMeshBuffer(mesh Mesh, index int32, data []byte, offset int) { - _, fl := updateMeshBuffer.Call(wasm.Struct(mesh), index, data, offset) - wasm.Free(fl...) -} - -// UnloadMesh - Unload mesh data from CPU and GPU -func UnloadMesh(mesh *Mesh) { - _, fl := unloadMesh.Call(mesh) - wasm.Free(fl...) -} - -// DrawMesh - Draw a 3d mesh with material and transform -func DrawMesh(mesh Mesh, material Material, transform Matrix) { - _, fl := drawMesh.Call(wasm.Struct(mesh), wasm.Struct(material), wasm.Struct(transform)) - wasm.Free(fl...) -} - -// DrawMeshInstanced - Draw multiple mesh instances with material and different transforms -func DrawMeshInstanced(mesh Mesh, material Material, transforms []Matrix, instances int32) { - _, fl := drawMeshInstanced.Call(wasm.Struct(mesh), wasm.Struct(material), transforms, instances) - wasm.Free(fl...) -} - -// ExportMesh - Export mesh data to file, returns true on success -func ExportMesh(mesh Mesh, fileName string) bool { - ret, fl := exportMesh.Call(wasm.Struct(mesh), fileName) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// GetMeshBoundingBox - Compute mesh bounding box limits -func GetMeshBoundingBox(mesh Mesh) BoundingBox { - ret, fl := getMeshBoundingBox.Call(wasm.Struct(mesh)) - v := wasm.ReadStruct[BoundingBox](ret) - wasm.Free(fl...) - return v -} - -// GenMeshTangents - Compute mesh tangents -func GenMeshTangents(mesh *Mesh) { - _, fl := genMeshTangents.Call(mesh) - wasm.Free(fl...) -} - -// GenMeshPoly - Generate polygonal mesh -func GenMeshPoly(sides int, radius float32) Mesh { - ret, fl := genMeshPoly.Call(sides, radius) - v := wasm.ReadStruct[Mesh](ret) - wasm.Free(fl...) - return v -} - -// GenMeshPlane - Generate plane mesh (with subdivisions) -func GenMeshPlane(width float32, length float32, resX int, resZ int) Mesh { - ret, fl := genMeshPlane.Call(width, length, resX, resZ) - v := wasm.ReadStruct[Mesh](ret) - wasm.Free(fl...) - return v -} - -// GenMeshCube - Generate cuboid mesh -func GenMeshCube(width float32, height float32, length float32) Mesh { - ret, fl := genMeshCube.Call(width, height, length) - v := wasm.ReadStruct[Mesh](ret) - wasm.Free(fl...) - return v -} - -// GenMeshSphere - Generate sphere mesh (standard sphere) -func GenMeshSphere(radius float32, rings int, slices int) Mesh { - ret, fl := genMeshSphere.Call(radius, rings, slices) - v := wasm.ReadStruct[Mesh](ret) - wasm.Free(fl...) - return v -} - -// GenMeshHemiSphere - Generate half-sphere mesh (no bottom cap) -func GenMeshHemiSphere(radius float32, rings int, slices int) Mesh { - ret, fl := genMeshHemiSphere.Call(radius, rings, slices) - v := wasm.ReadStruct[Mesh](ret) - wasm.Free(fl...) - return v -} - -// GenMeshCylinder - Generate cylinder mesh -func GenMeshCylinder(radius float32, height float32, slices int) Mesh { - ret, fl := genMeshCylinder.Call(radius, height, slices) - v := wasm.ReadStruct[Mesh](ret) - wasm.Free(fl...) - return v -} - -// GenMeshCone - Generate cone/pyramid mesh -func GenMeshCone(radius float32, height float32, slices int) Mesh { - ret, fl := genMeshCone.Call(radius, height, slices) - v := wasm.ReadStruct[Mesh](ret) - wasm.Free(fl...) - return v -} - -// GenMeshTorus - Generate torus mesh -func GenMeshTorus(radius float32, size float32, radSeg int, sides int) Mesh { - ret, fl := genMeshTorus.Call(radius, size, radSeg, sides) - v := wasm.ReadStruct[Mesh](ret) - wasm.Free(fl...) - return v -} - -// GenMeshKnot - Generate trefoil knot mesh -func GenMeshKnot(radius float32, size float32, radSeg int, sides int) Mesh { - ret, fl := genMeshKnot.Call(radius, size, radSeg, sides) - v := wasm.ReadStruct[Mesh](ret) - wasm.Free(fl...) - return v -} - -// GenMeshHeightmap - Generate heightmap mesh from image data -func GenMeshHeightmap(heightmap Image, size Vector3) Mesh { - ret, fl := genMeshHeightmap.Call(wasm.Struct(heightmap), wasm.Struct(size)) - v := wasm.ReadStruct[Mesh](ret) - wasm.Free(fl...) - return v -} - -// GenMeshCubicmap - Generate cubes-based map mesh from image data -func GenMeshCubicmap(cubicmap Image, cubeSize Vector3) Mesh { - ret, fl := genMeshCubicmap.Call(wasm.Struct(cubicmap), wasm.Struct(cubeSize)) - v := wasm.ReadStruct[Mesh](ret) - wasm.Free(fl...) - return v -} - -// LoadMaterials - Load materials from model file -func LoadMaterials(fileName string) []Material { - var zero []Material - return zero -} - -// LoadMaterialDefault - Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) -func LoadMaterialDefault() Material { - ret, fl := loadMaterialDefault.Call() - v := wasm.ReadStruct[Material](ret) - wasm.Free(fl...) - return v -} - -// IsMaterialValid - Check if a material is valid (shader assigned, map textures loaded in GPU) -func IsMaterialValid(material Material) bool { - ret, fl := isMaterialValid.Call(wasm.Struct(material)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// UnloadMaterial - Unload material from GPU memory (VRAM) -func UnloadMaterial(material Material) { - _, fl := unloadMaterial.Call(wasm.Struct(material)) - wasm.Free(fl...) -} - -// SetMaterialTexture - Set texture for a material map type (MATERIAL_MAP_DIFFUSE, MATERIAL_MAP_SPECULAR...) -func SetMaterialTexture(material *Material, mapType int32, texture Texture2D) { - _, fl := setMaterialTexture.Call(material, mapType, wasm.Struct(texture)) - wasm.Free(fl...) -} - -// SetModelMeshMaterial - Set material for a mesh -func SetModelMeshMaterial(model *Model, meshId int32, materialId int32) { - _, fl := setModelMeshMaterial.Call(model, meshId, materialId) - wasm.Free(fl...) -} - -// LoadModelAnimations - Load model animations from file -func LoadModelAnimations(fileName string) []ModelAnimation { - var zero []ModelAnimation - return zero -} - -// UpdateModelAnimation - Update model animation pose (CPU) -func UpdateModelAnimation(model Model, anim ModelAnimation, frame int32) { - _, fl := updateModelAnimation.Call(wasm.Struct(model), wasm.Struct(anim), frame) - wasm.Free(fl...) -} - -// UpdateModelAnimationBones - Update model animation mesh bone matrices (GPU skinning) -func UpdateModelAnimationBones(model Model, anim ModelAnimation, frame int32) { - _, fl := updateModelAnimationBones.Call(wasm.Struct(model), wasm.Struct(anim), frame) - wasm.Free(fl...) -} - -// UnloadModelAnimation - Unload animation data -func UnloadModelAnimation(anim ModelAnimation) { - _, fl := unloadModelAnimation.Call(wasm.Struct(anim)) - wasm.Free(fl...) -} - -// UnloadModelAnimations - Unload animation array data -func UnloadModelAnimations(animations []ModelAnimation) { - _, fl := unloadModelAnimations.Call(animations) - wasm.Free(fl...) -} - -// IsModelAnimationValid - Check model animation skeleton match -func IsModelAnimationValid(model Model, anim ModelAnimation) bool { - ret, fl := isModelAnimationValid.Call(wasm.Struct(model), wasm.Struct(anim)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// CheckCollisionSpheres - Check collision between two spheres -func CheckCollisionSpheres(center1 Vector3, radius1 float32, center2 Vector3, radius2 float32) bool { - ret, fl := checkCollisionSpheres.Call(wasm.Struct(center1), radius1, wasm.Struct(center2), radius2) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// CheckCollisionBoxes - Check collision between two bounding boxes -func CheckCollisionBoxes(box1 BoundingBox, box2 BoundingBox) bool { - ret, fl := checkCollisionBoxes.Call(wasm.Struct(box1), wasm.Struct(box2)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// CheckCollisionBoxSphere - Check collision between box and sphere -func CheckCollisionBoxSphere(box BoundingBox, center Vector3, radius float32) bool { - ret, fl := checkCollisionBoxSphere.Call(wasm.Struct(box), wasm.Struct(center), radius) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// GetRayCollisionSphere - Get collision info between ray and sphere -func GetRayCollisionSphere(ray Ray, center Vector3, radius float32) RayCollision { - ret, fl := getRayCollisionSphere.Call(wasm.Struct(ray), wasm.Struct(center), radius) - v := wasm.ReadStruct[RayCollision](ret) - wasm.Free(fl...) - return v -} - -// GetRayCollisionBox - Get collision info between ray and box -func GetRayCollisionBox(ray Ray, box BoundingBox) RayCollision { - ret, fl := getRayCollisionBox.Call(wasm.Struct(ray), wasm.Struct(box)) - v := wasm.ReadStruct[RayCollision](ret) - wasm.Free(fl...) - return v -} - -// GetRayCollisionMesh - Get collision info between ray and mesh -func GetRayCollisionMesh(ray Ray, mesh Mesh, transform Matrix) RayCollision { - ret, fl := getRayCollisionMesh.Call(wasm.Struct(ray), wasm.Struct(mesh), wasm.Struct(transform)) - v := wasm.ReadStruct[RayCollision](ret) - wasm.Free(fl...) - return v -} - -// GetRayCollisionTriangle - Get collision info between ray and triangle -func GetRayCollisionTriangle(ray Ray, p1 Vector3, p2 Vector3, p3 Vector3) RayCollision { - ret, fl := getRayCollisionTriangle.Call(wasm.Struct(ray), wasm.Struct(p1), wasm.Struct(p2), wasm.Struct(p3)) - v := wasm.ReadStruct[RayCollision](ret) - wasm.Free(fl...) - return v -} - -// GetRayCollisionQuad - Get collision info between ray and quad -func GetRayCollisionQuad(ray Ray, p1 Vector3, p2 Vector3, p3 Vector3, p4 Vector3) RayCollision { - ret, fl := getRayCollisionQuad.Call(wasm.Struct(ray), wasm.Struct(p1), wasm.Struct(p2), wasm.Struct(p3), wasm.Struct(p4)) - v := wasm.ReadStruct[RayCollision](ret) - wasm.Free(fl...) - return v -} - -// InitAudioDevice - Initialize audio device and context -func InitAudioDevice() { - _, fl := initAudioDevice.Call() - wasm.Free(fl...) -} - -// CloseAudioDevice - Close the audio device and context -func CloseAudioDevice() { - _, fl := closeAudioDevice.Call() - wasm.Free(fl...) -} - -// IsAudioDeviceReady - Check if audio device has been initialized successfully -func IsAudioDeviceReady() bool { - ret, fl := isAudioDeviceReady.Call() - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// SetMasterVolume - Set master volume (listener) -func SetMasterVolume(volume float32) { - _, fl := setMasterVolume.Call(volume) - wasm.Free(fl...) -} - -// GetMasterVolume - Get master volume (listener) -func GetMasterVolume() float32 { - ret, fl := getMasterVolume.Call() - v := wasm.Numeric[float32](ret) - wasm.Free(fl...) - return v -} - -// LoadWave - Load wave data from file -func LoadWave(fileName string) Wave { - ret, fl := loadWave.Call(fileName) - v := wasm.ReadStruct[Wave](ret) - wasm.Free(fl...) - return v -} - -// LoadWaveFromMemory - Load wave from memory buffer, fileType refers to extension: i.e. '.wav' -func LoadWaveFromMemory(fileType string, fileData []byte, dataSize int32) Wave { - ret, fl := loadWaveFromMemory.Call(fileType, fileData, dataSize) - v := wasm.ReadStruct[Wave](ret) - wasm.Free(fl...) - return v -} - -// IsWaveValid - Checks if wave data is valid (data loaded and parameters) -func IsWaveValid(wave Wave) bool { - ret, fl := isWaveValid.Call(wasm.Struct(wave)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// LoadSound - Load sound from file -func LoadSound(fileName string) Sound { - ret, fl := loadSound.Call(fileName) - v := wasm.ReadStruct[Sound](ret) - wasm.Free(fl...) - return v -} - -// LoadSoundFromWave - Load sound from wave data -func LoadSoundFromWave(wave Wave) Sound { - ret, fl := loadSoundFromWave.Call(wasm.Struct(wave)) - v := wasm.ReadStruct[Sound](ret) - wasm.Free(fl...) - return v -} - -// LoadSoundAlias - Create a new sound that shares the same sample data as the source sound, does not own the sound data -func LoadSoundAlias(source Sound) Sound { - ret, fl := loadSoundAlias.Call(wasm.Struct(source)) - v := wasm.ReadStruct[Sound](ret) - wasm.Free(fl...) - return v -} - -// IsSoundValid - Checks if a sound is valid (data loaded and buffers initialized) -func IsSoundValid(sound Sound) bool { - ret, fl := isSoundValid.Call(wasm.Struct(sound)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// UpdateSound - Update sound buffer with new data -func UpdateSound(sound Sound, data []byte, sampleCount int32) { - _, fl := updateSound.Call(wasm.Struct(sound), data, sampleCount) - wasm.Free(fl...) -} - -// UnloadWave - Unload wave data -func UnloadWave(wave Wave) { - _, fl := unloadWave.Call(wasm.Struct(wave)) - wasm.Free(fl...) -} - -// UnloadSound - Unload sound -func UnloadSound(sound Sound) { - _, fl := unloadSound.Call(wasm.Struct(sound)) - wasm.Free(fl...) -} - -// UnloadSoundAlias - Unload a sound alias (does not deallocate sample data) -func UnloadSoundAlias(alias Sound) { - _, fl := unloadSoundAlias.Call(wasm.Struct(alias)) - wasm.Free(fl...) -} - -// ExportWave - Export wave data to file, returns true on success -func ExportWave(wave Wave, fileName string) bool { - ret, fl := exportWave.Call(wasm.Struct(wave), fileName) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// PlaySound - Play a sound -func PlaySound(sound Sound) { - _, fl := playSound.Call(wasm.Struct(sound)) - wasm.Free(fl...) -} - -// StopSound - Stop playing a sound -func StopSound(sound Sound) { - _, fl := stopSound.Call(wasm.Struct(sound)) - wasm.Free(fl...) -} - -// PauseSound - Pause a sound -func PauseSound(sound Sound) { - _, fl := pauseSound.Call(wasm.Struct(sound)) - wasm.Free(fl...) -} - -// ResumeSound - Resume a paused sound -func ResumeSound(sound Sound) { - _, fl := resumeSound.Call(wasm.Struct(sound)) - wasm.Free(fl...) -} - -// IsSoundPlaying - Check if a sound is currently playing -func IsSoundPlaying(sound Sound) bool { - ret, fl := isSoundPlaying.Call(wasm.Struct(sound)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// SetSoundVolume - Set volume for a sound (1.0 is max level) -func SetSoundVolume(sound Sound, volume float32) { - _, fl := setSoundVolume.Call(wasm.Struct(sound), volume) - wasm.Free(fl...) -} - -// SetSoundPitch - Set pitch for a sound (1.0 is base level) -func SetSoundPitch(sound Sound, pitch float32) { - _, fl := setSoundPitch.Call(wasm.Struct(sound), pitch) - wasm.Free(fl...) -} - -// SetSoundPan - Set pan for a sound (0.5 is center) -func SetSoundPan(sound Sound, pan float32) { - _, fl := setSoundPan.Call(wasm.Struct(sound), pan) - wasm.Free(fl...) -} - -// WaveCopy - Copy a wave to a new wave -func WaveCopy(wave Wave) Wave { - ret, fl := waveCopy.Call(wasm.Struct(wave)) - v := wasm.ReadStruct[Wave](ret) - wasm.Free(fl...) - return v -} - -// WaveCrop - Crop a wave to defined frames range -func WaveCrop(wave *Wave, initFrame int32, finalFrame int32) { - _, fl := waveCrop.Call(wave, initFrame, finalFrame) - wasm.Free(fl...) -} - -// WaveFormat - Convert wave data to desired format -func WaveFormat(wave *Wave, sampleRate int32, sampleSize int32, channels int32) { - _, fl := waveFormat.Call(wave, sampleRate, sampleSize, channels) - wasm.Free(fl...) -} - -// LoadWaveSamples - Load samples data from wave as a 32bit float data array -func LoadWaveSamples(wave Wave) []float32 { - var zero []float32 - return zero -} - -// UnloadWaveSamples - Unload samples data loaded with LoadWaveSamples() -func UnloadWaveSamples(samples []float32) { - _, fl := unloadWaveSamples.Call(samples) - wasm.Free(fl...) -} - -// LoadMusicStream - Load music stream from file -func LoadMusicStream(fileName string) Music { - ret, fl := loadMusicStream.Call(fileName) - v := wasm.ReadStruct[Music](ret) - wasm.Free(fl...) - return v -} - -// LoadMusicStreamFromMemory - Load music stream from data -func LoadMusicStreamFromMemory(fileType string, data []byte, dataSize int32) Music { - ret, fl := loadMusicStreamFromMemory.Call(fileType, data, dataSize) - v := wasm.ReadStruct[Music](ret) - wasm.Free(fl...) - return v -} - -// IsMusicValid - Checks if a music stream is valid (context and buffers initialized) -func IsMusicValid(music Music) bool { - ret, fl := isMusicValid.Call(wasm.Struct(music)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// UnloadMusicStream - Unload music stream -func UnloadMusicStream(music Music) { - _, fl := unloadMusicStream.Call(wasm.Struct(music)) - wasm.Free(fl...) -} - -// PlayMusicStream - Start music playing -func PlayMusicStream(music Music) { - _, fl := playMusicStream.Call(wasm.Struct(music)) - wasm.Free(fl...) -} - -// IsMusicStreamPlaying - Check if music is playing -func IsMusicStreamPlaying(music Music) bool { - ret, fl := isMusicStreamPlaying.Call(wasm.Struct(music)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// UpdateMusicStream - Updates buffers for music streaming -func UpdateMusicStream(music Music) { - _, fl := updateMusicStream.Call(wasm.Struct(music)) - wasm.Free(fl...) -} - -// StopMusicStream - Stop music playing -func StopMusicStream(music Music) { - _, fl := stopMusicStream.Call(wasm.Struct(music)) - wasm.Free(fl...) -} - -// PauseMusicStream - Pause music playing -func PauseMusicStream(music Music) { - _, fl := pauseMusicStream.Call(wasm.Struct(music)) - wasm.Free(fl...) -} - -// ResumeMusicStream - Resume playing paused music -func ResumeMusicStream(music Music) { - _, fl := resumeMusicStream.Call(wasm.Struct(music)) - wasm.Free(fl...) -} - -// SeekMusicStream - Seek music to a position (in seconds) -func SeekMusicStream(music Music, position float32) { - _, fl := seekMusicStream.Call(wasm.Struct(music), position) - wasm.Free(fl...) -} - -// SetMusicVolume - Set volume for music (1.0 is max level) -func SetMusicVolume(music Music, volume float32) { - _, fl := setMusicVolume.Call(wasm.Struct(music), volume) - wasm.Free(fl...) -} - -// SetMusicPitch - Set pitch for a music (1.0 is base level) -func SetMusicPitch(music Music, pitch float32) { - _, fl := setMusicPitch.Call(wasm.Struct(music), pitch) - wasm.Free(fl...) -} - -// SetMusicPan - Set pan for a music (0.5 is center) -func SetMusicPan(music Music, pan float32) { - _, fl := setMusicPan.Call(wasm.Struct(music), pan) - wasm.Free(fl...) -} - -// GetMusicTimeLength - Get music time length (in seconds) -func GetMusicTimeLength(music Music) float32 { - ret, fl := getMusicTimeLength.Call(wasm.Struct(music)) - v := wasm.Numeric[float32](ret) - wasm.Free(fl...) - return v -} - -// GetMusicTimePlayed - Get current music time played (in seconds) -func GetMusicTimePlayed(music Music) float32 { - ret, fl := getMusicTimePlayed.Call(wasm.Struct(music)) - v := wasm.Numeric[float32](ret) - wasm.Free(fl...) - return v -} - -// LoadAudioStream - Load audio stream (to stream raw audio pcm data) -func LoadAudioStream(sampleRate uint32, sampleSize uint32, channels uint32) AudioStream { - ret, fl := loadAudioStream.Call(sampleRate, sampleSize, channels) - v := wasm.ReadStruct[AudioStream](ret) - wasm.Free(fl...) - return v -} - -// IsAudioStreamValid - Checks if an audio stream is valid (buffers initialized) -func IsAudioStreamValid(stream AudioStream) bool { - ret, fl := isAudioStreamValid.Call(wasm.Struct(stream)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// UnloadAudioStream - Unload audio stream and free memory -func UnloadAudioStream(stream AudioStream) { - _, fl := unloadAudioStream.Call(wasm.Struct(stream)) - wasm.Free(fl...) -} - -// UpdateAudioStream - Update audio stream buffers with data -func UpdateAudioStream(stream AudioStream, data []float32) { - _, fl := updateAudioStream.Call(wasm.Struct(stream), data) - wasm.Free(fl...) -} - -// IsAudioStreamProcessed - Check if any audio stream buffers requires refill -func IsAudioStreamProcessed(stream AudioStream) bool { - ret, fl := isAudioStreamProcessed.Call(wasm.Struct(stream)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// PlayAudioStream - Play audio stream -func PlayAudioStream(stream AudioStream) { - _, fl := playAudioStream.Call(wasm.Struct(stream)) - wasm.Free(fl...) -} - -// PauseAudioStream - Pause audio stream -func PauseAudioStream(stream AudioStream) { - _, fl := pauseAudioStream.Call(wasm.Struct(stream)) - wasm.Free(fl...) -} - -// ResumeAudioStream - Resume audio stream -func ResumeAudioStream(stream AudioStream) { - _, fl := resumeAudioStream.Call(wasm.Struct(stream)) - wasm.Free(fl...) -} - -// IsAudioStreamPlaying - Check if audio stream is playing -func IsAudioStreamPlaying(stream AudioStream) bool { - ret, fl := isAudioStreamPlaying.Call(wasm.Struct(stream)) - v := wasm.Boolean(ret) - wasm.Free(fl...) - return v -} - -// StopAudioStream - Stop audio stream -func StopAudioStream(stream AudioStream) { - _, fl := stopAudioStream.Call(wasm.Struct(stream)) - wasm.Free(fl...) -} - -// SetAudioStreamVolume - Set volume for audio stream (1.0 is max level) -func SetAudioStreamVolume(stream AudioStream, volume float32) { - _, fl := setAudioStreamVolume.Call(wasm.Struct(stream), volume) - wasm.Free(fl...) -} - -// SetAudioStreamPitch - Set pitch for audio stream (1.0 is base level) -func SetAudioStreamPitch(stream AudioStream, pitch float32) { - _, fl := setAudioStreamPitch.Call(wasm.Struct(stream), pitch) - wasm.Free(fl...) -} - -// SetAudioStreamPan - Set pan for audio stream (0.5 is centered) -func SetAudioStreamPan(stream AudioStream, pan float32) { - _, fl := setAudioStreamPan.Call(wasm.Struct(stream), pan) - wasm.Free(fl...) -} - -// SetAudioStreamBufferSizeDefault - Default size for new audio streams -func SetAudioStreamBufferSizeDefault(size int32) { - _, fl := setAudioStreamBufferSizeDefault.Call(size) - wasm.Free(fl...) -} - -// SetAudioStreamCallback - Audio thread callback to request new data -func SetAudioStreamCallback(stream AudioStream, callback AudioCallback) { - _, fl := setAudioStreamCallback.Call(wasm.Struct(stream), callback) - wasm.Free(fl...) -} - -// AttachAudioStreamProcessor - Attach audio stream processor to stream, receives the samples as s -func AttachAudioStreamProcessor(stream AudioStream, processor AudioCallback) { - _, fl := attachAudioStreamProcessor.Call(wasm.Struct(stream), processor) - wasm.Free(fl...) -} - -// DetachAudioStreamProcessor - Detach audio stream processor from stream -func DetachAudioStreamProcessor(stream AudioStream, processor AudioCallback) { - _, fl := detachAudioStreamProcessor.Call(wasm.Struct(stream), processor) - wasm.Free(fl...) -} - -// AttachAudioMixedProcessor - Attach audio stream processor to the entire audio pipeline, receives the samples as s -func AttachAudioMixedProcessor(processor AudioCallback) { - _, fl := attachAudioMixedProcessor.Call(processor) - wasm.Free(fl...) -} - -// DetachAudioMixedProcessor - Detach audio stream processor from the entire audio pipeline -func DetachAudioMixedProcessor(processor AudioCallback) { - _, fl := detachAudioMixedProcessor.Call(processor) - wasm.Free(fl...) -} - -// SetCallbackFunc - Sets callback function -func SetCallbackFunc() { - _, fl := setCallbackFunc.Call() - wasm.Free(fl...) -} - - -// ToImage converts a Image to Go image.Image -func ToImage() image.Image { - // ret, fl := toImage.Call() - // // v := wasm.Numeric[image.Image](ret) - // wasm.Free(fl...) - // return v - return nil -} - -// OpenAsset - Open asset -func OpenAsset(name string) Asset { - // ret, fl := openAsset.Call(name) - // v := wasm.Numeric[Asset](ret) - // wasm.Free(fl...) - // return v - return nil -} - -// HomeDir - Returns user home directory -// NOTE: On Android this returns internal data path and must be called after InitWindow -func HomeDir() string { - ret, fl := homeDir.Call() - v := wasm.Numeric[string](ret) - wasm.Free(fl...) - return v -} From 0b195411fb29274adea9cb80973dba7e457e22ca Mon Sep 17 00:00:00 2001 From: BrownNPC Date: Wed, 28 Jan 2026 06:00:07 +0500 Subject: [PATCH 02/12] experimental go:wasmimport based runtime --- .gitignore | 1 + index/.gitignore | 1 - index/index.html | 51 ---- index/index.js | 53 ++-- index/rl/raylib.js | 2 +- index/rl/raylib.wasm | Bin index/runtime.js | 105 +++++++ raylib/go.mod | 2 - raylib/go.sum | 2 - raylib/raylib.go | 332 ++++++++++++++------- raylib/rcamera.go | 696 +++++++++++++++++++++---------------------- raylib/wasm.go | 69 +++++ 12 files changed, 782 insertions(+), 532 deletions(-) create mode 100644 .gitignore delete mode 100644 index/.gitignore mode change 100755 => 100644 index/rl/raylib.wasm create mode 100644 index/runtime.js create mode 100644 raylib/wasm.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5c7e047 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +# index/main.wasm diff --git a/index/.gitignore b/index/.gitignore deleted file mode 100644 index f7aa9b7..0000000 --- a/index/.gitignore +++ /dev/null @@ -1 +0,0 @@ -main.wasm diff --git a/index/index.html b/index/index.html index 6a1d51c..a4c777f 100644 --- a/index/index.html +++ b/index/index.html @@ -1,64 +1,13 @@ - - -
-
-
-
Loading…
-
-
- - diff --git a/index/index.js b/index/index.js index d19f170..9429325 100644 --- a/index/index.js +++ b/index/index.js @@ -1,30 +1,41 @@ -const overlay = document.getElementById('loading-overlay'); -function hideOverlay() { overlay.style.display = 'none' } -function showOverlay() { overlay.style.display = 'flex' } - -// show loading overlay -showOverlay(); +// disable right click context menu +document.getElementById("canvas").addEventListener( + "contextmenu", + (e) => e.preventDefault(), +); +// INITIALIZE RAYLIB import Module from "./rl/raylib.js"; - const wasmBinary = await fetch("./rl/raylib.wasm") - .then(r => r.arrayBuffer()); - -// disable right click context menu -document.getElementById("canvas").addEventListener('contextmenu', e => e.preventDefault()) + .then((r) => r.arrayBuffer()); -let mod = await Module({ - canvas: document.getElementById('canvas'), +const raylib = await Module({ + canvas: document.getElementById("canvas"), wasmBinary: new Uint8Array(wasmBinary), }); -window.mod = mod +// INITIALIZE GO const go = new Go(); -WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject) - .then(result => { - // hide loading overlay before running code - hideOverlay(); - go.run(result.instance); - }) - .catch(console.error); +// inject raylib +go.importObject.raylib = raylib; +globalThis.raylib = raylib; + +import { Runtime } from "./runtime.js"; // helper funtions +//init +const runtime = new Runtime(); +// inject custom runtime methods +Object.assign(go.importObject.gojs, { + array: runtime.array.bind(runtime), + struct: runtime.struct.bind(runtime), + CStringFromGoString: runtime.CStringFromGoString.bind(runtime), + CopyToC: runtime.CopyToC.bind(runtime), +}); + +WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then( + (result) => { + const instance = result.instance; + globalThis.goInstance = instance; + go.run(instance); + }, +); diff --git a/index/rl/raylib.js b/index/rl/raylib.js index 8f20ef6..f26bcd2 100644 --- a/index/rl/raylib.js +++ b/index/rl/raylib.js @@ -13,4 +13,4 @@ var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;Module["ready"]= ); })(); ; -export default Module; \ No newline at end of file +export default Module; diff --git a/index/rl/raylib.wasm b/index/rl/raylib.wasm old mode 100755 new mode 100644 diff --git a/index/runtime.js b/index/runtime.js new file mode 100644 index 0000000..4ea2132 --- /dev/null +++ b/index/runtime.js @@ -0,0 +1,105 @@ +// Helper functions called from Go via go:wasmimport + +class Runtime { + constructor() { + } + get mem() { + return new DataView(globalThis.goInstance.exports.mem.buffer); + } + getmem(addr, len) { + return new Uint8Array(globalThis.goInstance.exports.mem.buffer, addr, len); + } + get Sp() { + return globalThis.goInstance.exports.getsp() >>> 0; + } + // ---- Helpers from wasm_exec.js ---- + setInt32 = (addr, v) => { + return this.mem.setUint32(addr + 0, v, true); + }; + getInt32 = (addr) => { + return this.mem.getUint32(addr + 0, true); + }; + + setInt64 = (addr, v) => { + this.mem.setUint32(addr + 0, v, true); + // this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true); + this.mem.setUint32(addr + 4, 0, true) + }; + + getInt64 = (addr) => { + const low = this.mem.getUint32(addr + 0, true); + const high = this.mem.getInt32(addr + 4, true); + return low + high * 4294967296; + }; + + loadSlice = (addr) => { + const array = getInt64(addr + 0); + const len = getInt64(addr + 8); + return this.getmem(array, len); + }; + + // ---- Runtime helpers ---- + array = (sp) => { + // messing around with slice + sp >>>= 0; + console.log(sp); + // slice capacity + console.log(this.getInt64(sp + 8 + 8)); + console.log(sp + 8); + }; + // function messing around with struct + struct = (sp) => { + sp >>>= 0; + const ptr = this.getInt64(sp + 8); + this.setInt32(ptr, 99); + // 2nd field of struct + this.setInt32(ptr + 4, 69); + // return + this.setInt64(sp + 16, ptr); + }; + + getRaylibU8Array(cptr, len) { + return new Uint8Array( // js slice + globalThis.raylib.HEAPU8.buffer, + cptr, + len, + ); + } + // func(string) int32 + // returns pointer to C string in raylib memory + CStringFromGoString = (sp) => { + sp >>>= 0; + let arg = 1; + // get string addr and length + const saddr = this.getInt64(sp + 8 * arg++); // go string address + const len = this.getInt64(sp + 8 * arg++); // go string length + + const goStrView = this.getmem(saddr, len); // js slice + + // malloc cstr with room for null terminator + const cstr = globalThis.raylib._malloc(len + 1); + const cStrView = this.getRaylibU8Array(cstr, len + 1); + + // copy Go string to C + cStrView.set(goStrView); + // // set last byte to null terminator + cStrView[len] = 0; + // return cstr + this.setInt32(sp + 8 * arg++, cstr); + }; + // func(dstCArray, srcSize int32, src any) + // copies Go memory to C memory. Useful for copying slices and structs. + // Destination C array must have enough space. + // src must be a type. cannot be a slice. To pass a slice, use unsafe.SliceData + CopyToC = (sp) => { + sp >>>= 0; + const dstCArray = this.getInt32(sp + 8 * 1); + const srcSize = this.getInt32(sp + 8 * 2); + const srcPtr = this.getInt64(sp + 8 * 3); + + const goBytes = this.getmem(srcPtr, srcSize); + this.getRaylibU8Array(dstCArray, srcSize).set(goBytes); + }; +} + +export { Runtime }; diff --git a/raylib/go.mod b/raylib/go.mod index 3214f14..764c26a 100644 --- a/raylib/go.mod +++ b/raylib/go.mod @@ -1,5 +1,3 @@ module github.com/BrownNPC/Raylib-Go-Wasm/raylib -require github.com/BrownNPC/wasm-ffi-go v1.2.0 - go 1.24.1 diff --git a/raylib/go.sum b/raylib/go.sum index 808648e..e69de29 100644 --- a/raylib/go.sum +++ b/raylib/go.sum @@ -1,2 +0,0 @@ -github.com/BrownNPC/wasm-ffi-go v1.1.0 h1:oashfuQflpB+qx/xI71Gvim3YN/0iIny5TMIpzEFz0Y= -github.com/BrownNPC/wasm-ffi-go v1.1.0/go.mod h1:D5+RBMb672fgw6vPz4HOWYxpyrmPrIao8VqlXihOFFg= diff --git a/raylib/raylib.go b/raylib/raylib.go index 92a7d3f..47f99c1 100644 --- a/raylib/raylib.go +++ b/raylib/raylib.go @@ -11,16 +11,9 @@ package rl import ( "image/color" "io" - "io/fs" - "runtime" - "unsafe" + "structs" ) -func init() { - // Make sure the main goroutine is bound to the main thread. - runtime.LockOSThread() -} - // Wave type, defines audio wave data type Wave struct { // Number of samples @@ -32,14 +25,21 @@ type Wave struct { // Number of channels (1-mono, 2-stereo) Channels uint32 // Buffer data pointer - Data unsafe.Pointer + Data cptr + __ structs.HostLayout } // NewWave - Returns new Wave func NewWave(sampleCount, sampleRate, sampleSize, channels uint32, data []byte) Wave { - d := unsafe.Pointer(&data[0]) - return Wave{sampleCount, sampleRate, sampleSize, channels, d} + return Wave{ + FrameCount: sampleCount, + SampleRate: sampleRate, + SampleSize: sampleSize, + Channels: channels, + Data: 0, + __: structs.HostLayout{}, + } } // AudioCallback function. @@ -50,6 +50,7 @@ type Sound struct { Stream AudioStream FrameCount uint32 _ [4]byte + __ structs.HostLayout } // Music type (file streaming from memory) @@ -59,7 +60,8 @@ type Music struct { FrameCount uint32 Looping bool CtxType int32 - CtxData unsafe.Pointer + CtxData cptr + __ structs.HostLayout } // AudioStream type @@ -76,6 +78,7 @@ type AudioStream struct { // Number of channels (1-mono, 2-stereo) Channels uint32 _ [4]byte + __ structs.HostLayout } type maDataConverter struct { @@ -96,6 +99,7 @@ type maDataConverter struct { IsPassthrough uint8 X_ownsHeap uint8 X_pHeap *byte + __ structs.HostLayout } type maChannelConverter struct { @@ -111,6 +115,7 @@ type maChannelConverter struct { X_pHeap *byte X_ownsHeap uint32 Pad_cgo_0 [4]byte + __ structs.HostLayout } type maResampler struct { @@ -125,6 +130,7 @@ type maResampler struct { X_pHeap *byte X_ownsHeap uint32 Pad_cgo_0 [4]byte + __ structs.HostLayout } type maResamplingBackendVtable struct { @@ -138,6 +144,7 @@ type maResamplingBackendVtable struct { OnGetRequiredInputFrameCount *[0]byte OnGetExpectedOutputFrameCount *[0]byte OnReset *[0]byte + __ structs.HostLayout } type AudioBuffer struct { @@ -158,12 +165,14 @@ type AudioBuffer struct { Data *uint8 Next *AudioBuffer Prev *AudioBuffer + __ structs.HostLayout } type AudioProcessor struct { Process *[0]byte Next *AudioProcessor Prev *AudioProcessor + __ structs.HostLayout } // AutomationEvent - Automation event @@ -171,6 +180,7 @@ type AutomationEvent struct { Frame uint32 Type uint32 Params [4]int32 + __ structs.HostLayout } // AutomationEventList - Automation event list @@ -181,14 +191,15 @@ type AutomationEventList struct { // // Use AutomationEventList.GetEvents instead (go slice) Events *AutomationEvent + __ structs.HostLayout } -func (a *AutomationEventList) GetEvents() []AutomationEvent { - return unsafe.Slice(a.Events, a.Count) -} +// func (a *AutomationEventList) GetEvents() []AutomationEvent { +// return wasm.Slice(a.Events, a.Count) +// } // CameraMode type -type CameraMode int32 +type CameraMode = int32 // Camera system modes const ( @@ -200,7 +211,7 @@ const ( ) // CameraProjection type -type CameraProjection int32 +type CameraProjection = int32 // Camera projection modes const ( @@ -374,7 +385,7 @@ const ( MouseMiddleButton = MouseButtonMiddle ) -type MouseButton int32 +type MouseButton = int32 // Mouse Buttons const ( @@ -497,11 +508,16 @@ var ( type Vector2 struct { X float32 Y float32 + __ structs.HostLayout } // NewVector2 - Returns new Vector2 func NewVector2(x, y float32) Vector2 { - return Vector2{x, y} + return Vector2{ + X: x, + Y: y, + __: structs.HostLayout{}, + } } // Vector3 type @@ -509,11 +525,17 @@ type Vector3 struct { X float32 Y float32 Z float32 + __ structs.HostLayout } // NewVector3 - Returns new Vector3 func NewVector3(x, y, z float32) Vector3 { - return Vector3{x, y, z} + return Vector3{ + X: x, + Y: y, + Z: z, + __: structs.HostLayout{}, + } } // Vector4 type @@ -522,11 +544,18 @@ type Vector4 struct { Y float32 Z float32 W float32 + __ structs.HostLayout } // NewVector4 - Returns new Vector4 func NewVector4(x, y, z, w float32) Vector4 { - return Vector4{x, y, z, w} + return Vector4{ + X: x, + Y: y, + Z: z, + W: w, + __: structs.HostLayout{}, + } } // Matrix type (OpenGL style 4x4 - right handed, column major) @@ -535,11 +564,30 @@ type Matrix struct { M1, M5, M9, M13 float32 M2, M6, M10, M14 float32 M3, M7, M11, M15 float32 + __ structs.HostLayout } // NewMatrix - Returns new Matrix func NewMatrix(m0, m4, m8, m12, m1, m5, m9, m13, m2, m6, m10, m14, m3, m7, m11, m15 float32) Matrix { - return Matrix{m0, m4, m8, m12, m1, m5, m9, m13, m2, m6, m10, m14, m3, m7, m11, m15} + return Matrix{ + M0: m0, + M4: m4, + M8: m8, + M12: m12, + M1: m1, + M5: m5, + M9: m9, + M13: m1, + M2: m2, + M6: m6, + M10: m1, + M14: m1, + M3: m3, + M7: m7, + M11: m1, + M15: m1, + __: structs.HostLayout{}, + } } // Mat2 type (used for polygon shape rotation matrix) @@ -548,11 +596,18 @@ type Mat2 struct { M01 float32 M10 float32 M11 float32 + __ structs.HostLayout } // NewMat2 - Returns new Mat2 func NewMat2(m0, m1, m10, m11 float32) Mat2 { - return Mat2{m0, m1, m10, m11} + return Mat2{ + M00: m0, + M01: m0, + M10: m1, + M11: m1, + __: structs.HostLayout{}, + } } // Quaternion, 4 components (Vector4 alias) @@ -560,7 +615,13 @@ type Quaternion = Vector4 // NewQuaternion - Returns new Quaternion func NewQuaternion(x, y, z, w float32) Quaternion { - return Quaternion{x, y, z, w} + return Quaternion{ + X: x, + Y: y, + Z: z, + W: w, + __: structs.HostLayout{}, + } } // Color type, RGBA (32bit) @@ -578,11 +639,18 @@ type Rectangle struct { Y float32 Width float32 Height float32 + __ structs.HostLayout } // NewRectangle - Returns new Rectangle func NewRectangle(x, y, width, height float32) Rectangle { - return Rectangle{x, y, width, height} + return Rectangle{ + X: x, + Y: y, + Width: width, + Height: height, + __: structs.HostLayout{}, + } } // ToInt32 converts rectangle to int32 variant @@ -602,6 +670,7 @@ type RectangleInt32 struct { Y int32 Width int32 Height int32 + __ structs.HostLayout } // ToFloat32 converts rectangle to float32 variant @@ -627,6 +696,7 @@ type Camera3D struct { Fovy float32 // Camera type, controlling projection type, either CameraPerspective or CameraOrthographic. Projection CameraProjection + __ structs.HostLayout } // Camera type fallback, defaults to Camera3D @@ -634,7 +704,14 @@ type Camera = Camera3D // NewCamera3D - Returns new Camera3D func NewCamera3D(pos, target, up Vector3, fovy float32, ct CameraProjection) Camera3D { - return Camera3D{pos, target, up, fovy, ct} + return Camera3D{ + Position: pos, + Target: target, + Up: up, + Fovy: fovy, + Projection: ct, + __: structs.HostLayout{}, + } } // Camera2D type, defines a 2d camera @@ -647,11 +724,18 @@ type Camera2D struct { Rotation float32 // Camera zoom (scaling), should be 1.0f by default Zoom float32 + __ structs.HostLayout } // NewCamera2D - Returns new Camera2D func NewCamera2D(offset, target Vector2, rotation, zoom float32) Camera2D { - return Camera2D{offset, target, rotation, zoom} + return Camera2D{ + Offset: offset, + Target: target, + Rotation: rotation, + Zoom: zoom, + __: structs.HostLayout{}, + } } // BoundingBox type @@ -660,41 +744,26 @@ type BoundingBox struct { Min Vector3 // Maximum vertex box-corner Max Vector3 + __ structs.HostLayout } // NewBoundingBox - Returns new BoundingBox func NewBoundingBox(min, max Vector3) BoundingBox { - return BoundingBox{min, max} -} - -// Asset implements fs.FS interfaces -type Asset struct { - root string - fsys fs.FS -} - -// NewAsset - creates a new Asset filesystem -// For Android: root should be empty or a directory path within assets -// For Desktop: root should be the filesystem path to assets -func NewAsset(root string) *Asset { - return &Asset{root: root} -} - -// NewAssetFromFS - creates a new Asset filesystem from a fs.FS -// The root parameter specifies a subdirectory within the embedded filesystem (can be empty for root) -func NewAssetFromFS(fsys fs.FS, root string) *Asset { - return &Asset{root: root, fsys: fsys} + return BoundingBox{ + Min: min, + Max: max, + __: structs.HostLayout{}, + } } -// AssetFile represents an opened asset file -type AssetFile interface { +// Asset file +type Asset interface { io.ReadSeeker io.Closer - Stat() (fs.FileInfo, error) } // Gestures type -type Gestures int32 +type Gestures = int32 // Gestures types // NOTE: It could be used as flags to enable only some gestures @@ -746,7 +815,7 @@ const ( ) // ShaderUniformDataType type -type ShaderUniformDataType int32 +type ShaderUniformDataType = int32 // ShaderUniformDataType enumeration const ( @@ -841,6 +910,7 @@ type Mesh struct { VaoID uint32 // OpenGL Vertex Buffer Objects id (7 types of vertex data) VboID *uint32 + __ structs.HostLayout } // Material type @@ -851,12 +921,13 @@ type Material struct { Maps *MaterialMap // Generic parameters (if required) Params [4]float32 + __ structs.HostLayout } -// GetMap - Get pointer to MaterialMap by map type -func (mt Material) GetMap(index int32) *MaterialMap { - return (*MaterialMap)(unsafe.Pointer(uintptr(unsafe.Pointer(mt.Maps)) + uintptr(index)*unsafe.Sizeof(MaterialMap{}))) -} +// // GetMap - Get pointer to MaterialMap by map type +// func (mt Material) GetMap(index int32) *MaterialMap { +// return (*MaterialMap)(cptr(uintptr(cptr(mt.Maps)) + uintptr(index)*wasm.Sizeof(MaterialMap{}))) +// } // MaterialMap type type MaterialMap struct { @@ -866,6 +937,7 @@ type MaterialMap struct { Color color.RGBA // Value Value float32 + __ structs.HostLayout } // Model is struct of model, meshes, materials and animation data @@ -896,32 +968,34 @@ type Model struct { // // Use Model.GetBindPose instead (go slice) BindPose *Transform + __ structs.HostLayout } -// GetMeshes returns the meshes of a model as go slice -func (m Model) GetMeshes() []Mesh { - return unsafe.Slice(m.Meshes, m.MeshCount) -} +// // GetMeshes returns the meshes of a model as go slice +// func (m Model) GetMeshes() []Mesh { +// return wasm.Slice(m.Meshes, m.MeshCount) +// } -// GetMaterials returns the materials of a model as go slice -func (m Model) GetMaterials() []Material { - return unsafe.Slice(m.Materials, m.MaterialCount) -} +// // GetMaterials returns the materials of a model as go slice +// func (m Model) GetMaterials() []Material { +// return wasm.Slice(m.Materials, m.MaterialCount) +// } -// GetBones returns the bones information (skeleton) of a model as go slice -func (m Model) GetBones() []BoneInfo { - return unsafe.Slice(m.Bones, m.BoneCount) -} +// // GetBones returns the bones information (skeleton) of a model as go slice +// func (m Model) GetBones() []BoneInfo { +// return wasm.Slice(m.Bones, m.BoneCount) +// } -// GetBindPose returns the bones base transformation of a model as go slice -func (m Model) GetBindPose() []Transform { - return unsafe.Slice(m.BindPose, m.BoneCount) -} +// // GetBindPose returns the bones base transformation of a model as go slice +// func (m Model) GetBindPose() []Transform { +// return wasm.Slice(m.BindPose, m.BoneCount) +// } // BoneInfo type type BoneInfo struct { Name [32]int8 Parent int32 + __ structs.HostLayout } // Transform type @@ -929,6 +1003,7 @@ type Transform struct { Translation Vector3 Rotation Vector4 Scale Vector3 + __ structs.HostLayout } // Ray type (useful for raycast) @@ -937,11 +1012,16 @@ type Ray struct { Position Vector3 // Ray direction Direction Vector3 + __ structs.HostLayout } // NewRay - Returns new Ray func NewRay(position, direction Vector3) Ray { - return Ray{position, direction} + return Ray{ + Position: position, + Direction: direction, + __: structs.HostLayout{}, + } } // ModelAnimation type @@ -951,18 +1031,19 @@ type ModelAnimation struct { Bones *BoneInfo FramePoses **Transform Name [32]uint8 + __ structs.HostLayout } -// GetBones returns the bones information (skeleton) of a ModelAnimation as go slice -func (m ModelAnimation) GetBones() []BoneInfo { - return unsafe.Slice(m.Bones, m.BoneCount) -} +// // GetBones returns the bones information (skeleton) of a ModelAnimation as go slice +// func (m ModelAnimation) GetBones() []BoneInfo { +// return wasm.Slice(m.Bones, m.BoneCount) +// } -// GetFramePose returns the Transform for a specific bone at a specific frame -func (m ModelAnimation) GetFramePose(frame, bone int) Transform { - framePoses := unsafe.Slice(m.FramePoses, m.FrameCount) - return unsafe.Slice(framePoses[frame], m.BoneCount)[bone] -} +// // GetFramePose returns the Transform for a specific bone at a specific frame +// func (m ModelAnimation) GetFramePose(frame, bone int) Transform { +// framePoses := wasm.Slice(m.FramePoses, m.FrameCount) +// return wasm.Slice(framePoses[frame], m.BoneCount)[bone] +// } // GetName returns the ModelAnimation's name as go string func (m ModelAnimation) GetName() string { @@ -981,15 +1062,22 @@ type RayCollision struct { Distance float32 Point Vector3 Normal Vector3 + __ structs.HostLayout } // NewRayCollision - Returns new RayCollision func NewRayCollision(hit bool, distance float32, point, normal Vector3) RayCollision { - return RayCollision{hit, distance, point, normal} + return RayCollision{ + Hit: hit, + Distance: distance, + Point: point, + Normal: normal, + __: structs.HostLayout{}, + } } // BlendMode type -type BlendMode int32 +type BlendMode = int32 // Color blending modes (pre-defined) const ( @@ -1009,22 +1097,27 @@ type Shader struct { ID uint32 // Shader locations array Locs *int32 + __ structs.HostLayout } // NewShader - Returns new Shader func NewShader(id uint32, locs *int32) Shader { - return Shader{id, locs} + return Shader{ + ID: id, + Locs: locs, + __: structs.HostLayout{}, + } } -// GetLocation - Get shader value's location -func (sh Shader) GetLocation(index int32) int32 { - return *(*int32)(unsafe.Pointer(uintptr(unsafe.Pointer(sh.Locs)) + uintptr(index*4))) -} +// // GetLocation - Get shader value's location +// func (sh Shader) GetLocation(index int32) int32 { +// return *(*int32)(cptr(uintptr(cptr(sh.Locs)) + uintptr(index*4))) +// } -// UpdateLocation - Update shader value's location -func (sh Shader) UpdateLocation(index int32, loc int32) { - *(*int32)(unsafe.Pointer(uintptr(unsafe.Pointer(sh.Locs)) + uintptr(index*4))) = loc -} +// // UpdateLocation - Update shader value's location +// func (sh Shader) UpdateLocation(index int32, loc int32) { +// *(*int32)(cptr(uintptr(cptr(sh.Locs)) + uintptr(index*4))) = loc +// } // GlyphInfo - Font character info type GlyphInfo struct { @@ -1038,11 +1131,19 @@ type GlyphInfo struct { AdvanceX int32 // Character image data Image Image + __ structs.HostLayout } // NewGlyphInfo - Returns new CharInfo func NewGlyphInfo(value int32, offsetX, offsetY, advanceX int32, image Image) GlyphInfo { - return GlyphInfo{value, offsetX, offsetY, advanceX, image} + return GlyphInfo{ + Value: value, + OffsetX: offsetX, + OffsetY: offsetY, + AdvanceX: advanceX, + Image: image, + __: structs.HostLayout{}, + } } // Font type, includes texture and charSet array data @@ -1059,6 +1160,7 @@ type Font struct { Recs *Rectangle // Characters info data Chars *GlyphInfo + __ structs.HostLayout } // Font type, defines generation method @@ -1119,7 +1221,7 @@ const ( ) // TextureFilterMode - Texture filter mode -type TextureFilterMode int32 +type TextureFilterMode = int32 // Texture parameters: filter mode // NOTE 1: Filtering considers mipmaps if available in the texture @@ -1140,7 +1242,7 @@ const ( ) // TextureWrapMode - Texture wrap mode -type TextureWrapMode int32 +type TextureWrapMode = int32 // Texture parameters: wrap mode const ( @@ -1163,7 +1265,7 @@ const ( // NOTE: Data stored in CPU memory (RAM) type Image struct { // Image raw Data - Data unsafe.Pointer + Data cptr // Image base width Width int32 // Image base height @@ -1172,14 +1274,15 @@ type Image struct { Mipmaps int32 // Data format (PixelFormat) Format PixelFormat + __ structs.HostLayout } -// NewImage - Returns new Image -func NewImage(data []byte, width, height, mipmaps int32, format PixelFormat) *Image { - d := unsafe.Pointer(&data[0]) +// // NewImage - Returns new Image +// func NewImage(data []byte, width, height, mipmaps int32, format PixelFormat) *Image { +// d := cptr(&data[0]) - return &Image{d, width, height, mipmaps, format} -} +// return &Image{d, width, height, mipmaps, format} +// } // Texture2D type, bpp always RGBA (32bit) // NOTE: Data stored in GPU memory @@ -1194,11 +1297,19 @@ type Texture2D struct { Mipmaps int32 // Data format (PixelFormat) Format PixelFormat + __ structs.HostLayout } // NewTexture2D - Returns new Texture2D func NewTexture2D(id uint32, width, height, mipmaps int32, format PixelFormat) Texture2D { - return Texture2D{id, width, height, mipmaps, format} + return Texture2D{ + ID: id, + Width: width, + Height: height, + Mipmaps: mipmaps, + Format: format, + __: structs.HostLayout{}, + } } // RenderTexture2D type, for texture rendering @@ -1209,18 +1320,24 @@ type RenderTexture2D struct { Texture Texture2D // Depth buffer attachment texture Depth Texture2D + __ structs.HostLayout } // NewRenderTexture2D - Returns new RenderTexture2D func NewRenderTexture2D(id uint32, texture, depth Texture2D) RenderTexture2D { - return RenderTexture2D{id, texture, depth} + return RenderTexture2D{ + ID: id, + Texture: texture, + Depth: depth, + __: structs.HostLayout{}, + } } // TraceLogCallbackFun - function that will recive the trace log messages type TraceLogCallbackFun func(int, string) // TraceLogLevel parameter of trace log message -type TraceLogLevel int +type TraceLogLevel = int // Trace log level // NOTE: Organized by priority level @@ -1244,7 +1361,7 @@ const ( ) // N-patch layout -type NPatchLayout int32 +type NPatchLayout = int32 const ( NPatchNinePatch NPatchLayout = iota // Npatch layout: 3x3 tiles @@ -1260,6 +1377,7 @@ type NPatchInfo struct { Right int32 // Right border offset Bottom int32 // Bottom border offset Layout NPatchLayout // Layout of the n-patch: 3x3, 1x3 or 3x1 + __ structs.HostLayout } // VrStereoConfig, VR stereo rendering configuration for simulator @@ -1272,6 +1390,7 @@ type VrStereoConfig struct { RightScreenCenter [2]float32 // VR right screen center Scale [2]float32 // VR distortion scale ScaleIn [2]float32 // VR distortion scale in + __ structs.HostLayout } // VrDeviceInfo, Head-Mounted-Display device parameters @@ -1285,4 +1404,5 @@ type VrDeviceInfo struct { InterpupillaryDistance float32 // IPD (distance between pupils) in meters LensDistortionValues [4]float32 // Lens distortion constant parameters ChromaAbCorrection [4]float32 // Chromatic aberration correction parameters + __ structs.HostLayout } diff --git a/raylib/rcamera.go b/raylib/rcamera.go index d0df645..a772014 100644 --- a/raylib/rcamera.go +++ b/raylib/rcamera.go @@ -1,350 +1,350 @@ package rl -// GetCameraForward - Returns the cameras forward vector (normalized) -func GetCameraForward(camera *Camera) Vector3 { - return Vector3Normalize(Vector3Subtract(camera.Target, camera.Position)) -} - -// GetCameraUp - Returns the cameras up vector (normalized) -// Note: The up vector might not be perpendicular to the forward vector -func GetCameraUp(camera *Camera) Vector3 { - return Vector3Normalize(camera.Up) -} - -// GetCameraRight - Returns the cameras right vector (normalized) -func GetCameraRight(camera *Camera) Vector3 { - forward := GetCameraForward(camera) - up := GetCameraUp(camera) - - return Vector3CrossProduct(forward, up) -} - -// CameraMoveForward - Moves the camera in its forward direction -func CameraMoveForward(camera *Camera, distance float32, moveInWorldPlane uint8) { - forward := GetCameraForward(camera) - - if moveInWorldPlane != 0 { - // Project vector onto world plane - forward.Y = float32(0) - forward = Vector3Normalize(forward) - } - - // Scale by distance - forward = Vector3Scale(forward, distance) - - // Move position and target - camera.Position = Vector3Add(camera.Position, forward) - camera.Target = Vector3Add(camera.Target, forward) -} - -// CameraMoveUp - Moves the camera in its up direction -func CameraMoveUp(camera *Camera, distance float32) { - up := GetCameraUp(camera) - - // Scale by distance - up = Vector3Scale(up, distance) - - // Move position and target - camera.Position = Vector3Add(camera.Position, up) - camera.Target = Vector3Add(camera.Target, up) -} - -// CameraMoveRight - Moves the camera target in its current right direction -func CameraMoveRight(camera *Camera, distance float32, moveInWorldPlane uint8) { - right := GetCameraRight(camera) - - if moveInWorldPlane != 0 { - // Project vector onto world plane - right.Y = float32(0) - right = Vector3Normalize(right) - } - - // Scale by distance - right = Vector3Scale(right, distance) - - // Move position and target - camera.Position = Vector3Add(camera.Position, right) - camera.Target = Vector3Add(camera.Target, right) -} - -// CameraMoveToTarget - Moves the camera position closer/farther to/from the camera target -func CameraMoveToTarget(camera *Camera, delta float32) { - distance := Vector3Distance(camera.Position, camera.Target) - - // Apply delta - distance = distance + delta - - // Distance must be greater than 0 - if distance <= float32(0) { - distance = 0.001 - } - - // Set new distance by moving the position along the forward vector - forward := GetCameraForward(camera) - camera.Position = Vector3Add(camera.Target, Vector3Scale(forward, -distance)) -} - -// CameraYaw - 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 -func CameraYaw(camera *Camera, angle float32, rotateAroundTarget uint8) { - // Rotation axis - var up = GetCameraUp(camera) - - // View vector - var targetPosition = Vector3Subtract(camera.Target, camera.Position) - - // Rotate view vector around up axis - targetPosition = Vector3RotateByAxisAngle(targetPosition, up, angle) - - if rotateAroundTarget != 0 { - // Move position relative to target - camera.Position = Vector3Subtract(camera.Target, targetPosition) - } else { - // Move target relative to position - camera.Target = Vector3Add(camera.Position, targetPosition) - } -} - -// CameraPitch - 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 -func CameraPitch(camera *Camera, angle float32, lockView uint8, rotateAroundTarget uint8, rotateUp uint8) { - // Up direction - var up = GetCameraUp(camera) - - // View vector - var targetPosition = Vector3Subtract(camera.Target, camera.Position) - - if lockView != 0 { - // In these camera modes we clamp the Pitch angle - // to allow only viewing straight up or down. - - // Clamp view up - maxAngleUp := Vector3Angle(up, targetPosition) - maxAngleUp = maxAngleUp - 0.001 // avoid numerical errors - if angle > maxAngleUp { - angle = maxAngleUp - } - - // Clamp view down - maxAngleDown := Vector3Angle(Vector3Negate(up), targetPosition) - maxAngleDown = maxAngleDown * -1.0 // downwards angle is negative - maxAngleDown = maxAngleDown + 0.001 // avoid numerical errors - if angle < maxAngleDown { - angle = maxAngleDown - } - } - - // Rotation axis - var right = GetCameraRight(camera) - - // Rotate view vector around right axis - targetPosition = Vector3RotateByAxisAngle(targetPosition, right, angle) - - if rotateAroundTarget != 0 { - // Move position relative to target - camera.Position = Vector3Subtract(camera.Target, targetPosition) - } else { - // Move target relative to position - camera.Target = Vector3Add(camera.Position, targetPosition) - } - - if rotateUp != 0 { - // Rotate up direction around right axis - camera.Up = Vector3RotateByAxisAngle(camera.Up, right, angle) - } -} - -// CameraRoll - 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 -func CameraRoll(camera *Camera, angle float32) { - // Rotation axis - var forward = GetCameraForward(camera) - - // Rotate up direction around forward axis - camera.Up = Vector3RotateByAxisAngle(camera.Up, forward, angle) -} - -// GetCameraViewMatrix - Returns the camera view matrix -func GetCameraViewMatrix(camera *Camera) Matrix { - return MatrixLookAt(camera.Position, camera.Target, camera.Up) -} - -// GetCameraProjectionMatrix - Returns the camera projection matrix -func GetCameraProjectionMatrix(camera *Camera, aspect float32) Matrix { - if camera.Projection == CameraPerspective { - return MatrixPerspective(camera.Fovy*(Pi/180.0), aspect, 0.01, 1000.0) - } else if camera.Projection == CameraOrthographic { - top := camera.Fovy / 2.0 - right := top * aspect - - return MatrixOrtho(-right, right, -top, top, 0.01, 1000.0) - } - - return MatrixIdentity() -} - -// UpdateCamera - Update camera position for selected mode -// Camera mode: CameraFree, CameraFirstPerson, CameraThirdPerson, CameraOrbital or Custom -func UpdateCamera(camera *Camera, mode CameraMode) { - var mousePositionDelta = GetMouseDelta() - - moveInWorldPlaneBool := mode == CameraFirstPerson || mode == CameraThirdPerson - var moveInWorldPlane uint8 - if moveInWorldPlaneBool { - moveInWorldPlane = 1 - } - - rotateAroundTargetBool := mode == CameraThirdPerson || mode == CameraOrbital - var rotateAroundTarget uint8 - if rotateAroundTargetBool { - rotateAroundTarget = 1 - } - - lockViewBool := mode == CameraFirstPerson || mode == CameraThirdPerson || mode == CameraOrbital - var lockView uint8 - if lockViewBool { - lockView = 1 - } - - var rotateUp uint8 - - if mode == CameraOrbital { - // Orbital can just orbit - var rotation = MatrixRotate(GetCameraUp(camera), 0.5*GetFrameTime()) - var view = Vector3Subtract(camera.Position, camera.Target) - view = Vector3Transform(view, rotation) - camera.Position = Vector3Add(camera.Target, view) - } else { - // Camera rotation - if IsKeyDown(KeyDown) { - CameraPitch(camera, -0.03, lockView, rotateAroundTarget, rotateUp) - } - if IsKeyDown(KeyUp) { - CameraPitch(camera, 0.03, lockView, rotateAroundTarget, rotateUp) - } - if IsKeyDown(KeyRight) { - CameraYaw(camera, -0.03, rotateAroundTarget) - } - if IsKeyDown(KeyLeft) { - CameraYaw(camera, 0.03, rotateAroundTarget) - } - if IsKeyDown(KeyQ) { - CameraRoll(camera, -0.03) - } - if IsKeyDown(KeyE) { - CameraRoll(camera, 0.03) - } - - // Camera movement - if !(IsGamepadAvailable(0)) { - // Camera pan (for CameraFree) - if mode == CameraFree && IsMouseButtonDown(MouseMiddleButton) { - var mouseDelta = GetMouseDelta() - if mouseDelta.X > 0.0 { - CameraMoveRight(camera, 0.2, moveInWorldPlane) - } - if mouseDelta.X < 0.0 { - CameraMoveRight(camera, -0.2, moveInWorldPlane) - } - if mouseDelta.Y > 0.0 { - CameraMoveUp(camera, -0.2) - } - if mouseDelta.Y < 0.0 { - CameraMoveUp(camera, 0.2) - } - } else { - // Mouse support - CameraYaw(camera, -mousePositionDelta.X*0.003, rotateAroundTarget) - CameraPitch(camera, -mousePositionDelta.Y*0.003, lockView, rotateAroundTarget, rotateUp) - } - - // Keyboard support - if IsKeyDown(KeyW) { - CameraMoveForward(camera, 0.09, moveInWorldPlane) - } - if IsKeyDown(KeyA) { - CameraMoveRight(camera, -0.09, moveInWorldPlane) - } - if IsKeyDown(KeyS) { - CameraMoveForward(camera, -0.09, moveInWorldPlane) - } - if IsKeyDown(KeyD) { - CameraMoveRight(camera, 0.09, moveInWorldPlane) - } - } else { - // Gamepad controller support - CameraYaw(camera, -(GetGamepadAxisMovement(0, GamepadAxisRightX)*float32(2))*0.003, rotateAroundTarget) - CameraPitch(camera, -(GetGamepadAxisMovement(0, GamepadAxisRightY)*float32(2))*0.003, lockView, rotateAroundTarget, rotateUp) - - if GetGamepadAxisMovement(0, GamepadAxisLeftY) <= -0.25 { - CameraMoveForward(camera, 0.09, moveInWorldPlane) - } - if GetGamepadAxisMovement(0, GamepadAxisLeftX) <= -0.25 { - CameraMoveRight(camera, -0.09, moveInWorldPlane) - } - if GetGamepadAxisMovement(0, GamepadAxisLeftY) >= 0.25 { - CameraMoveForward(camera, -0.09, moveInWorldPlane) - } - if GetGamepadAxisMovement(0, GamepadAxisLeftX) >= 0.25 { - CameraMoveRight(camera, 0.09, moveInWorldPlane) - } - } - - if mode == CameraFree { - if IsKeyDown(KeySpace) { - CameraMoveUp(camera, 0.09) - } - if IsKeyDown(KeyLeftControl) { - CameraMoveUp(camera, -0.09) - } - } - } - - if mode == CameraThirdPerson || mode == CameraOrbital || mode == CameraFree { - // Zoom target distance - CameraMoveToTarget(camera, -GetMouseWheelMove()) - if IsKeyPressed(KeyKpSubtract) { - CameraMoveToTarget(camera, 2.0) - } - if IsKeyPressed(KeyKpAdd) { - CameraMoveToTarget(camera, -2.0) - } - } -} - -// UpdateCameraPro - Update camera movement, movement/rotation values should be provided by user -func UpdateCameraPro(camera *Camera, movement Vector3, rotation Vector3, zoom float32) { - // Required values - // movement.X - Move forward/backward - // movement.Y - Move right/left - // movement.Z - Move up/down - // rotation.X - yaw - // rotation.Y - pitch - // rotation.Z - roll - // zoom - Move towards target - - lockView := uint8(1) - rotateAroundTarget := uint8(0) - rotateUp := uint8(0) - moveInWorldPlane := uint8(1) - - // Camera rotation - CameraPitch(camera, -rotation.Y*(Pi/180.0), lockView, rotateAroundTarget, rotateUp) - CameraYaw(camera, -rotation.X*(Pi/180.0), rotateAroundTarget) - CameraRoll(camera, rotation.Z*(Pi/180.0)) - - // Camera movement - CameraMoveForward(camera, movement.X, moveInWorldPlane) - CameraMoveRight(camera, movement.Y, moveInWorldPlane) - CameraMoveUp(camera, movement.Z) - - // Zoom target distance - CameraMoveToTarget(camera, zoom) -} +// // GetCameraForward - Returns the cameras forward vector (normalized) +// func GetCameraForward(camera *Camera) Vector3 { +// return Vector3Normalize(Vector3Subtract(camera.Target, camera.Position)) +// } + +// // GetCameraUp - Returns the cameras up vector (normalized) +// // Note: The up vector might not be perpendicular to the forward vector +// func GetCameraUp(camera *Camera) Vector3 { +// return Vector3Normalize(camera.Up) +// } + +// // GetCameraRight - Returns the cameras right vector (normalized) +// func GetCameraRight(camera *Camera) Vector3 { +// forward := GetCameraForward(camera) +// up := GetCameraUp(camera) + +// return Vector3CrossProduct(forward, up) +// } + +// // CameraMoveForward - Moves the camera in its forward direction +// func CameraMoveForward(camera *Camera, distance float32, moveInWorldPlane uint8) { +// forward := GetCameraForward(camera) + +// if moveInWorldPlane != 0 { +// // Project vector onto world plane +// forward.Y = float32(0) +// forward = Vector3Normalize(forward) +// } + +// // Scale by distance +// forward = Vector3Scale(forward, distance) + +// // Move position and target +// camera.Position = Vector3Add(camera.Position, forward) +// camera.Target = Vector3Add(camera.Target, forward) +// } + +// // CameraMoveUp - Moves the camera in its up direction +// func CameraMoveUp(camera *Camera, distance float32) { +// up := GetCameraUp(camera) + +// // Scale by distance +// up = Vector3Scale(up, distance) + +// // Move position and target +// camera.Position = Vector3Add(camera.Position, up) +// camera.Target = Vector3Add(camera.Target, up) +// } + +// // CameraMoveRight - Moves the camera target in its current right direction +// func CameraMoveRight(camera *Camera, distance float32, moveInWorldPlane uint8) { +// right := GetCameraRight(camera) + +// if moveInWorldPlane != 0 { +// // Project vector onto world plane +// right.Y = float32(0) +// right = Vector3Normalize(right) +// } + +// // Scale by distance +// right = Vector3Scale(right, distance) + +// // Move position and target +// camera.Position = Vector3Add(camera.Position, right) +// camera.Target = Vector3Add(camera.Target, right) +// } + +// // CameraMoveToTarget - Moves the camera position closer/farther to/from the camera target +// func CameraMoveToTarget(camera *Camera, delta float32) { +// distance := Vector3Distance(camera.Position, camera.Target) + +// // Apply delta +// distance = distance + delta + +// // Distance must be greater than 0 +// if distance <= float32(0) { +// distance = 0.001 +// } + +// // Set new distance by moving the position along the forward vector +// forward := GetCameraForward(camera) +// camera.Position = Vector3Add(camera.Target, Vector3Scale(forward, -distance)) +// } + +// // CameraYaw - 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 +// func CameraYaw(camera *Camera, angle float32, rotateAroundTarget uint8) { +// // Rotation axis +// var up = GetCameraUp(camera) + +// // View vector +// var targetPosition = Vector3Subtract(camera.Target, camera.Position) + +// // Rotate view vector around up axis +// targetPosition = Vector3RotateByAxisAngle(targetPosition, up, angle) + +// if rotateAroundTarget != 0 { +// // Move position relative to target +// camera.Position = Vector3Subtract(camera.Target, targetPosition) +// } else { +// // Move target relative to position +// camera.Target = Vector3Add(camera.Position, targetPosition) +// } +// } + +// // CameraPitch - 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 +// func CameraPitch(camera *Camera, angle float32, lockView uint8, rotateAroundTarget uint8, rotateUp uint8) { +// // Up direction +// var up = GetCameraUp(camera) + +// // View vector +// var targetPosition = Vector3Subtract(camera.Target, camera.Position) + +// if lockView != 0 { +// // In these camera modes we clamp the Pitch angle +// // to allow only viewing straight up or down. + +// // Clamp view up +// maxAngleUp := Vector3Angle(up, targetPosition) +// maxAngleUp = maxAngleUp - 0.001 // avoid numerical errors +// if angle > maxAngleUp { +// angle = maxAngleUp +// } + +// // Clamp view down +// maxAngleDown := Vector3Angle(Vector3Negate(up), targetPosition) +// maxAngleDown = maxAngleDown * -1.0 // downwards angle is negative +// maxAngleDown = maxAngleDown + 0.001 // avoid numerical errors +// if angle < maxAngleDown { +// angle = maxAngleDown +// } +// } + +// // Rotation axis +// var right = GetCameraRight(camera) + +// // Rotate view vector around right axis +// targetPosition = Vector3RotateByAxisAngle(targetPosition, right, angle) + +// if rotateAroundTarget != 0 { +// // Move position relative to target +// camera.Position = Vector3Subtract(camera.Target, targetPosition) +// } else { +// // Move target relative to position +// camera.Target = Vector3Add(camera.Position, targetPosition) +// } + +// if rotateUp != 0 { +// // Rotate up direction around right axis +// camera.Up = Vector3RotateByAxisAngle(camera.Up, right, angle) +// } +// } + +// // CameraRoll - 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 +// func CameraRoll(camera *Camera, angle float32) { +// // Rotation axis +// var forward = GetCameraForward(camera) + +// // Rotate up direction around forward axis +// camera.Up = Vector3RotateByAxisAngle(camera.Up, forward, angle) +// } + +// // GetCameraViewMatrix - Returns the camera view matrix +// func GetCameraViewMatrix(camera *Camera) Matrix { +// return MatrixLookAt(camera.Position, camera.Target, camera.Up) +// } + +// // GetCameraProjectionMatrix - Returns the camera projection matrix +// func GetCameraProjectionMatrix(camera *Camera, aspect float32) Matrix { +// if camera.Projection == CameraPerspective { +// return MatrixPerspective(camera.Fovy*(Pi/180.0), aspect, 0.01, 1000.0) +// } else if camera.Projection == CameraOrthographic { +// top := camera.Fovy / 2.0 +// right := top * aspect + +// return MatrixOrtho(-right, right, -top, top, 0.01, 1000.0) +// } + +// return MatrixIdentity() +// } + +// // UpdateCamera - Update camera position for selected mode +// // Camera mode: CameraFree, CameraFirstPerson, CameraThirdPerson, CameraOrbital or Custom +// func UpdateCamera(camera *Camera, mode CameraMode) { +// var mousePositionDelta = GetMouseDelta() + +// moveInWorldPlaneBool := mode == CameraFirstPerson || mode == CameraThirdPerson +// var moveInWorldPlane uint8 +// if moveInWorldPlaneBool { +// moveInWorldPlane = 1 +// } + +// rotateAroundTargetBool := mode == CameraThirdPerson || mode == CameraOrbital +// var rotateAroundTarget uint8 +// if rotateAroundTargetBool { +// rotateAroundTarget = 1 +// } + +// lockViewBool := mode == CameraFirstPerson || mode == CameraThirdPerson || mode == CameraOrbital +// var lockView uint8 +// if lockViewBool { +// lockView = 1 +// } + +// var rotateUp uint8 + +// if mode == CameraOrbital { +// // Orbital can just orbit +// var rotation = MatrixRotate(GetCameraUp(camera), 0.5*GetFrameTime()) +// var view = Vector3Subtract(camera.Position, camera.Target) +// view = Vector3Transform(view, rotation) +// camera.Position = Vector3Add(camera.Target, view) +// } else { +// // Camera rotation +// if IsKeyDown(KeyDown) { +// CameraPitch(camera, -0.03, lockView, rotateAroundTarget, rotateUp) +// } +// if IsKeyDown(KeyUp) { +// CameraPitch(camera, 0.03, lockView, rotateAroundTarget, rotateUp) +// } +// if IsKeyDown(KeyRight) { +// CameraYaw(camera, -0.03, rotateAroundTarget) +// } +// if IsKeyDown(KeyLeft) { +// CameraYaw(camera, 0.03, rotateAroundTarget) +// } +// if IsKeyDown(KeyQ) { +// CameraRoll(camera, -0.03) +// } +// if IsKeyDown(KeyE) { +// CameraRoll(camera, 0.03) +// } + +// // Camera movement +// if !(IsGamepadAvailable(0)) { +// // Camera pan (for CameraFree) +// if mode == CameraFree && IsMouseButtonDown(MouseMiddleButton) { +// var mouseDelta = GetMouseDelta() +// if mouseDelta.X > 0.0 { +// CameraMoveRight(camera, 0.2, moveInWorldPlane) +// } +// if mouseDelta.X < 0.0 { +// CameraMoveRight(camera, -0.2, moveInWorldPlane) +// } +// if mouseDelta.Y > 0.0 { +// CameraMoveUp(camera, -0.2) +// } +// if mouseDelta.Y < 0.0 { +// CameraMoveUp(camera, 0.2) +// } +// } else { +// // Mouse support +// CameraYaw(camera, -mousePositionDelta.X*0.003, rotateAroundTarget) +// CameraPitch(camera, -mousePositionDelta.Y*0.003, lockView, rotateAroundTarget, rotateUp) +// } + +// // Keyboard support +// if IsKeyDown(KeyW) { +// CameraMoveForward(camera, 0.09, moveInWorldPlane) +// } +// if IsKeyDown(KeyA) { +// CameraMoveRight(camera, -0.09, moveInWorldPlane) +// } +// if IsKeyDown(KeyS) { +// CameraMoveForward(camera, -0.09, moveInWorldPlane) +// } +// if IsKeyDown(KeyD) { +// CameraMoveRight(camera, 0.09, moveInWorldPlane) +// } +// } else { +// // Gamepad controller support +// CameraYaw(camera, -(GetGamepadAxisMovement(0, GamepadAxisRightX)*float32(2))*0.003, rotateAroundTarget) +// CameraPitch(camera, -(GetGamepadAxisMovement(0, GamepadAxisRightY)*float32(2))*0.003, lockView, rotateAroundTarget, rotateUp) + +// if GetGamepadAxisMovement(0, GamepadAxisLeftY) <= -0.25 { +// CameraMoveForward(camera, 0.09, moveInWorldPlane) +// } +// if GetGamepadAxisMovement(0, GamepadAxisLeftX) <= -0.25 { +// CameraMoveRight(camera, -0.09, moveInWorldPlane) +// } +// if GetGamepadAxisMovement(0, GamepadAxisLeftY) >= 0.25 { +// CameraMoveForward(camera, -0.09, moveInWorldPlane) +// } +// if GetGamepadAxisMovement(0, GamepadAxisLeftX) >= 0.25 { +// CameraMoveRight(camera, 0.09, moveInWorldPlane) +// } +// } + +// if mode == CameraFree { +// if IsKeyDown(KeySpace) { +// CameraMoveUp(camera, 0.09) +// } +// if IsKeyDown(KeyLeftControl) { +// CameraMoveUp(camera, -0.09) +// } +// } +// } + +// if mode == CameraThirdPerson || mode == CameraOrbital || mode == CameraFree { +// // Zoom target distance +// CameraMoveToTarget(camera, -GetMouseWheelMove()) +// if IsKeyPressed(KeyKpSubtract) { +// CameraMoveToTarget(camera, 2.0) +// } +// if IsKeyPressed(KeyKpAdd) { +// CameraMoveToTarget(camera, -2.0) +// } +// } +// } + +// // UpdateCameraPro - Update camera movement, movement/rotation values should be provided by user +// func UpdateCameraPro(camera *Camera, movement Vector3, rotation Vector3, zoom float32) { +// // Required values +// // movement.X - Move forward/backward +// // movement.Y - Move right/left +// // movement.Z - Move up/down +// // rotation.X - yaw +// // rotation.Y - pitch +// // rotation.Z - roll +// // zoom - Move towards target + +// lockView := uint8(1) +// rotateAroundTarget := uint8(0) +// rotateUp := uint8(0) +// moveInWorldPlane := uint8(1) + +// // Camera rotation +// CameraPitch(camera, -rotation.Y*(Pi/180.0), lockView, rotateAroundTarget, rotateUp) +// CameraYaw(camera, -rotation.X*(Pi/180.0), rotateAroundTarget) +// CameraRoll(camera, rotation.Z*(Pi/180.0)) + +// // Camera movement +// CameraMoveForward(camera, movement.X, moveInWorldPlane) +// CameraMoveRight(camera, movement.Y, moveInWorldPlane) +// CameraMoveUp(camera, movement.Z) + +// // Zoom target distance +// CameraMoveToTarget(camera, zoom) +// } diff --git a/raylib/wasm.go b/raylib/wasm.go new file mode 100644 index 0000000..50b34f1 --- /dev/null +++ b/raylib/wasm.go @@ -0,0 +1,69 @@ +package rl + +import ( + "unsafe" +) + +// cptr is a pointer to raylib wasm memory +type cptr = int32 + +// Allocates memory on raylib heap +// +//go:wasmimport raylib _malloc +//go:noescape +func malloc(size int32) cptr + +// free memory allocated on raylib heap +// +//go:wasmimport raylib _free +//go:noescape +func free(cptr) + +// copyToC copies a Go type/struct to C memory. Useful for copying slices and structs. +// +// Destination C array must have enough space. +// +// NOTE: Value must be a type, it cannot be a slice. +// To pass a slice, use [unsafe.SliceData] +// +//go:wasmimport gojs CopyToC +//go:noescape +func copyToC(dstCArray cptr, srcSize int32, Value any) + +// The alocated C string lives on the raylib heap and must be free()'d +//go:wasmimport gojs CStringFromGoString +//go:noescape +func cStringFromGoString(string) cptr + + +// allocValueInC allocates a copy of a concrete type (not a slice) in C memory and returns a cptr to it. +// +// NOTE: v cannot be a pointer +// +// NOTE: For slices use [allocSliceInC] +func allocValueInC[T any](Value T) cptr { + size := int32(unsafe.Sizeof(Value)) + // allocate C array to hold Value + ptr := malloc(size) + copyToC(ptr, size, Value) + return ptr +} + +// allocValueInC allocates a copy of a slice in C memory and returns a cptr to it. +// +// NOTE: Value MUST be a slice +// +// NOTE: For slices use [allocSliceInC] +func allocSliceInC[Slice ~[]E, E any](s Slice) cptr { + // size of the slice's underlying array in bytes + sliceSize := int32(unsafe.Sizeof(s[0])) * int32(len(s)) + + // allocate C array to hold Value + ptr := malloc(sliceSize) + + // copy underlying array memory to C + copyToC(ptr, sliceSize, unsafe.SliceData(s)) + + return ptr +} + From b2955a97f391b6e76e496531b810c853ea32faf2 Mon Sep 17 00:00:00 2001 From: BrownNPC Date: Wed, 28 Jan 2026 08:35:59 +0500 Subject: [PATCH 03/12] more helpers --- .gitignore | 2 +- index/index.js | 1 + index/runtime.js | 35 ++++++++++++++++++++++++---- raylib/raylib.go | 6 +++-- raylib/rcore_wasm.go | 2 ++ raylib/wasm.go | 54 ++++++++++++++++++++++++++++++++++++-------- 6 files changed, 84 insertions(+), 16 deletions(-) create mode 100644 raylib/rcore_wasm.go diff --git a/.gitignore b/.gitignore index 5c7e047..d33fa92 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -# index/main.wasm +index/main.wasm diff --git a/index/index.js b/index/index.js index 9429325..552b2c8 100644 --- a/index/index.js +++ b/index/index.js @@ -30,6 +30,7 @@ Object.assign(go.importObject.gojs, { struct: runtime.struct.bind(runtime), CStringFromGoString: runtime.CStringFromGoString.bind(runtime), CopyToC: runtime.CopyToC.bind(runtime), + CopyToGo: runtime.CopyToGo.bind(runtime), }); WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then( diff --git a/index/runtime.js b/index/runtime.js index 4ea2132..36ad903 100644 --- a/index/runtime.js +++ b/index/runtime.js @@ -23,7 +23,7 @@ class Runtime { setInt64 = (addr, v) => { this.mem.setUint32(addr + 0, v, true); // this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true); - this.mem.setUint32(addr + 4, 0, true) + this.mem.setUint32(addr + 4, 0, true); }; getInt64 = (addr) => { @@ -51,9 +51,9 @@ class Runtime { struct = (sp) => { sp >>>= 0; const ptr = this.getInt64(sp + 8); - this.setInt32(ptr, 99); - // 2nd field of struct - this.setInt32(ptr + 4, 69); + // this.setInt32(ptr, 99); + // // 2nd field of struct + // this.setInt32(ptr + 4, 69); // return this.setInt64(sp + 16, ptr); }; @@ -100,6 +100,33 @@ class Runtime { const goBytes = this.getmem(srcPtr, srcSize); this.getRaylibU8Array(dstCArray, srcSize).set(goBytes); }; + // func(dstGoPtr unsafe.Pointer, size int32, src cptr) + // copies C memory to a Go pointer. Useful for copying C structs into Go structs + // + // example usage: + // type Person struct{ + // Age string + // } + // + // var cPtrToPersonInCHeap cptr = ... + // + // var p Person + // CopyToGo(unsafe.Pointer(&p),unsafe.SizeOf(p),cPtrToPersonInCHeap) + // + // p.Age == (whatever it was in C) + CopyToGo = (sp) => { + sp >>>= 0; + const dstGoPtr = this.getInt64(sp + 8 * 1); + const size = this.getInt32(sp + 8 * 2); // size of the dstGoPtr + + // size and pointer are packed into a single 64bit int by Go's compiler + const srcCptr = this.getInt32(sp + 8 * 2 + 4); + + const srcCBytes = this.getRaylibU8Array(srcCptr, size); + const dstGoBytes = this.getmem(dstGoPtr, size); + // copy C bytes to Go + dstGoBytes.set(srcCBytes); + }; } export { Runtime }; diff --git a/raylib/raylib.go b/raylib/raylib.go index 47f99c1..22ed7b0 100644 --- a/raylib/raylib.go +++ b/raylib/raylib.go @@ -1157,9 +1157,11 @@ type Font struct { // Characters texture atlas Texture Texture2D // Characters rectangles in texture - Recs *Rectangle + // Recs *Rectangle + Recs cptr // Characters info data - Chars *GlyphInfo + // Chars *GlyphInfo + Chars cptr __ structs.HostLayout } diff --git a/raylib/rcore_wasm.go b/raylib/rcore_wasm.go new file mode 100644 index 0000000..8cf5cf5 --- /dev/null +++ b/raylib/rcore_wasm.go @@ -0,0 +1,2 @@ +package rl + diff --git a/raylib/wasm.go b/raylib/wasm.go index 50b34f1..320db7c 100644 --- a/raylib/wasm.go +++ b/raylib/wasm.go @@ -5,13 +5,13 @@ import ( ) // cptr is a pointer to raylib wasm memory -type cptr = int32 +type cptr = uint32 // Allocates memory on raylib heap // //go:wasmimport raylib _malloc //go:noescape -func malloc(size int32) cptr +func malloc(size cptr) cptr // free memory allocated on raylib heap // @@ -28,21 +28,40 @@ func free(cptr) // //go:wasmimport gojs CopyToC //go:noescape -func copyToC(dstCArray cptr, srcSize int32, Value any) +func copyToC(dstCArray cptr, srcSize cptr, Value any) + +// copies C memory to a Go pointer. Useful for copying C structs into Go structs +// +// example usage: +// +// type Person struct{ +// Age string +// } +// +// var cPtrToPersonInCHeap cptr = ... +// +// var p Person +// CopyToGo(unsafe.Pointer(&p),unsafe.SizeOf(p),cPtrToPersonInCHeap) +// +// p.Age == (whatever it was in C) +// +//go:wasmimport gojs CopyToGo +//go:noescape +func copyToGo(dstGoPtr unsafe.Pointer, size cptr, src cptr) // The alocated C string lives on the raylib heap and must be free()'d +// //go:wasmimport gojs CStringFromGoString //go:noescape func cStringFromGoString(string) cptr - // allocValueInC allocates a copy of a concrete type (not a slice) in C memory and returns a cptr to it. // // NOTE: v cannot be a pointer // // NOTE: For slices use [allocSliceInC] func allocValueInC[T any](Value T) cptr { - size := int32(unsafe.Sizeof(Value)) + size := cptr(unsafe.Sizeof(Value)) // allocate C array to hold Value ptr := malloc(size) copyToC(ptr, size, Value) @@ -56,14 +75,31 @@ func allocValueInC[T any](Value T) cptr { // NOTE: For slices use [allocSliceInC] func allocSliceInC[Slice ~[]E, E any](s Slice) cptr { // size of the slice's underlying array in bytes - sliceSize := int32(unsafe.Sizeof(s[0])) * int32(len(s)) - + sliceSize := cptr(unsafe.Sizeof(s[0])) * cptr(len(s)) // allocate C array to hold Value ptr := malloc(sliceSize) - // copy underlying array memory to C copyToC(ptr, sliceSize, unsafe.SliceData(s)) - return ptr } +// copyValueToGo copies a value from C memory to Go memory. +// Useful for copying structs +// +// NOTE: Slices are not supported. Use [copyArrayToGo] +func copyValueToGo[T any](srcPtr cptr) T { + var value T + size := cptr(unsafe.Sizeof(value)) + copyToGo(unsafe.Pointer(&value), size, srcPtr) + return value +} + +// copyArrayToGo copies a C array into a Go Slice. +// +// It copies bytes to the underlying array of the slice. +func copyArrayToGo[Slice ~[]E, E any](s Slice, srcPtr cptr) { + // size of underlying array + size := cptr(unsafe.Sizeof(s[0])) * cptr(len(s)) + dstPtr := unsafe.SliceData(s) + copyToGo(unsafe.Pointer(dstPtr), size, srcPtr) +} From 0d37efafedd829088762b49eeedf35723b39e729 Mon Sep 17 00:00:00 2001 From: BrownNPC Date: Thu, 29 Jan 2026 02:22:35 +0500 Subject: [PATCH 04/12] begin implementing rcore.go --- examples/messingAround/go.mod | 7 + examples/messingAround/go.sum | 0 examples/messingAround/main.go | 73 ++ index/index.js | 2 + index/runtime.js | 20 +- raylib/raylib.go | 114 +-- raylib/rcore_wasm.go | 1195 ++++++++++++++++++++++++++++++++ raylib/wasm.go | 18 + 8 files changed, 1368 insertions(+), 61 deletions(-) create mode 100644 examples/messingAround/go.mod create mode 100644 examples/messingAround/go.sum create mode 100644 examples/messingAround/main.go diff --git a/examples/messingAround/go.mod b/examples/messingAround/go.mod new file mode 100644 index 0000000..d9ef7ee --- /dev/null +++ b/examples/messingAround/go.mod @@ -0,0 +1,7 @@ +module main + +replace github.com/gen2brain/raylib-go/raylib => ../../raylib + +go 1.25.6 + +require github.com/gen2brain/raylib-go/raylib v0.55.1 diff --git a/examples/messingAround/go.sum b/examples/messingAround/go.sum new file mode 100644 index 0000000..e69de29 diff --git a/examples/messingAround/main.go b/examples/messingAround/main.go new file mode 100644 index 0000000..86c80c0 --- /dev/null +++ b/examples/messingAround/main.go @@ -0,0 +1,73 @@ +package main + +import ( + "structs" + "unsafe" +) + +type cptr = uint32 + +//go:wasmimport raylib _malloc +func malloc(cptr) cptr + +//go:wasmimport raylib _InitWindow +func InitWindow(width, height int32, cstr cptr) + +//go:wasmimport raylib _DrawText +func DrawText(textPtr, x, y, fontsize, color cptr) + +//go:wasmimport raylib _ClearBackground +func ClearBackground(bg cptr) + +//go:wasmimport raylib _BeginDrawing +func BeginDrawing() + +//go:wasmimport raylib _EndDrawing +func EndDrawing() + +//go:wasmimport raylib _IsWindowReady +func IsWindowReady() bool + +type Test struct { + structs.HostLayout + Age int32 + Height int32 +} +type Test2 struct { + structs.HostLayout + Name string +} + +//go:wasmimport gojs array +//go:noescape +func getRandomData(r []byte) + +//go:wasmimport gojs struct +//go:noescape +func passStruct(r unsafe.Pointer) unsafe.Pointer + +//go:wasmimport raylib _free +func free(cptr) + +//go:wasmimport raylib _GetMousePosition +func GetMousePosition(cptr) + +//go:wasmimport raylib _GetColor +//go:noescape +func GetColor(cptr, uint32) + +//go:wasmimport gojs CopyToGo +//go:noescape +func CopyToGo(dstGoPtr unsafe.Pointer, size cptr, src cptr) + +func main() { + // title := malloc(2) + // InitWindow(300, 300, title) + // var c rl.Color + // size := cptr(unsafe.Sizeof(c)) // 4 bytes + // p := malloc(uint32(size)) // allocate memory in C/wasm + // GetColor(p, 0xFF0000FF) // fill memory + // fmt.Println("passed cptr", p) + // CopyToGo(unsafe.Pointer(&c), size, p) // copy memory to Go + // fmt.Println(c) // now prints the color +} diff --git a/index/index.js b/index/index.js index 552b2c8..93a9ce8 100644 --- a/index/index.js +++ b/index/index.js @@ -19,6 +19,7 @@ const raylib = await Module({ const go = new Go(); // inject raylib go.importObject.raylib = raylib; +go.importObject.globalThis = globalThis; globalThis.raylib = raylib; import { Runtime } from "./runtime.js"; // helper funtions @@ -31,6 +32,7 @@ Object.assign(go.importObject.gojs, { CStringFromGoString: runtime.CStringFromGoString.bind(runtime), CopyToC: runtime.CopyToC.bind(runtime), CopyToGo: runtime.CopyToGo.bind(runtime), + Alert: runtime.Alert.bind(runtime), }); WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then( diff --git a/index/runtime.js b/index/runtime.js index 36ad903..88eeb20 100644 --- a/index/runtime.js +++ b/index/runtime.js @@ -22,8 +22,7 @@ class Runtime { setInt64 = (addr, v) => { this.mem.setUint32(addr + 0, v, true); - // this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true); - this.mem.setUint32(addr + 4, 0, true); + this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true); }; getInt64 = (addr) => { @@ -33,8 +32,8 @@ class Runtime { }; loadSlice = (addr) => { - const array = getInt64(addr + 0); - const len = getInt64(addr + 8); + const array = this.getInt64(addr + 0); + const len = this.getInt64(addr + 8); return this.getmem(array, len); }; @@ -65,7 +64,7 @@ class Runtime { len, ); } - // func(string) int32 + // func(string) int32wasnt // returns pointer to C string in raylib memory CStringFromGoString = (sp) => { sp >>>= 0; @@ -127,6 +126,17 @@ class Runtime { // copy C bytes to Go dstGoBytes.set(srcCBytes); }; + // func alert(string) + Alert = (sp) => { + sp >>>= 0; + const saddr = this.getInt64(sp + 8 * 1); + const len = this.getInt64(sp + 8 * 2); + const strU8 = this.getmem(saddr, len); + + const decoder = new TextDecoder("utf-8"); // 'utf-8' is the default encoding + const str = decoder.decode(strU8); + alert(str); + }; } export { Runtime }; diff --git a/raylib/raylib.go b/raylib/raylib.go index 22ed7b0..e9ab716 100644 --- a/raylib/raylib.go +++ b/raylib/raylib.go @@ -1,3 +1,5 @@ +//go:build js + /* Package raylib - Go bindings for raylib, a simple and easy-to-use library to enjoy videogames programming. @@ -26,18 +28,18 @@ type Wave struct { Channels uint32 // Buffer data pointer Data cptr - __ structs.HostLayout + __ structs.HostLayout } // NewWave - Returns new Wave func NewWave(sampleCount, sampleRate, sampleSize, channels uint32, data []byte) Wave { - + ptr := allocSliceInC(data) return Wave{ FrameCount: sampleCount, SampleRate: sampleRate, SampleSize: sampleSize, Channels: channels, - Data: 0, + Data: ptr, __: structs.HostLayout{}, } } @@ -50,7 +52,7 @@ type Sound struct { Stream AudioStream FrameCount uint32 _ [4]byte - __ structs.HostLayout + __ structs.HostLayout } // Music type (file streaming from memory) @@ -61,7 +63,7 @@ type Music struct { Looping bool CtxType int32 CtxData cptr - __ structs.HostLayout + __ structs.HostLayout } // AudioStream type @@ -78,7 +80,7 @@ type AudioStream struct { // Number of channels (1-mono, 2-stereo) Channels uint32 _ [4]byte - __ structs.HostLayout + __ structs.HostLayout } type maDataConverter struct { @@ -99,7 +101,7 @@ type maDataConverter struct { IsPassthrough uint8 X_ownsHeap uint8 X_pHeap *byte - __ structs.HostLayout + __ structs.HostLayout } type maChannelConverter struct { @@ -115,7 +117,7 @@ type maChannelConverter struct { X_pHeap *byte X_ownsHeap uint32 Pad_cgo_0 [4]byte - __ structs.HostLayout + __ structs.HostLayout } type maResampler struct { @@ -130,7 +132,7 @@ type maResampler struct { X_pHeap *byte X_ownsHeap uint32 Pad_cgo_0 [4]byte - __ structs.HostLayout + __ structs.HostLayout } type maResamplingBackendVtable struct { @@ -144,7 +146,7 @@ type maResamplingBackendVtable struct { OnGetRequiredInputFrameCount *[0]byte OnGetExpectedOutputFrameCount *[0]byte OnReset *[0]byte - __ structs.HostLayout + __ structs.HostLayout } type AudioBuffer struct { @@ -165,14 +167,14 @@ type AudioBuffer struct { Data *uint8 Next *AudioBuffer Prev *AudioBuffer - __ structs.HostLayout + __ structs.HostLayout } type AudioProcessor struct { Process *[0]byte Next *AudioProcessor Prev *AudioProcessor - __ structs.HostLayout + __ structs.HostLayout } // AutomationEvent - Automation event @@ -180,7 +182,7 @@ type AutomationEvent struct { Frame uint32 Type uint32 Params [4]int32 - __ structs.HostLayout + __ structs.HostLayout } // AutomationEventList - Automation event list @@ -191,7 +193,7 @@ type AutomationEventList struct { // // Use AutomationEventList.GetEvents instead (go slice) Events *AutomationEvent - __ structs.HostLayout + __ structs.HostLayout } // func (a *AutomationEventList) GetEvents() []AutomationEvent { @@ -506,8 +508,8 @@ var ( // Vector2 type type Vector2 struct { - X float32 - Y float32 + X float32 + Y float32 __ structs.HostLayout } @@ -522,9 +524,9 @@ func NewVector2(x, y float32) Vector2 { // Vector3 type type Vector3 struct { - X float32 - Y float32 - Z float32 + X float32 + Y float32 + Z float32 __ structs.HostLayout } @@ -540,10 +542,10 @@ func NewVector3(x, y, z float32) Vector3 { // Vector4 type type Vector4 struct { - X float32 - Y float32 - Z float32 - W float32 + X float32 + Y float32 + Z float32 + W float32 __ structs.HostLayout } @@ -564,7 +566,7 @@ type Matrix struct { M1, M5, M9, M13 float32 M2, M6, M10, M14 float32 M3, M7, M11, M15 float32 - __ structs.HostLayout + __ structs.HostLayout } // NewMatrix - Returns new Matrix @@ -577,15 +579,15 @@ func NewMatrix(m0, m4, m8, m12, m1, m5, m9, m13, m2, m6, m10, m14, m3, m7, m11, M1: m1, M5: m5, M9: m9, - M13: m1, + M13: m13, M2: m2, M6: m6, - M10: m1, - M14: m1, + M10: m10, + M14: m14, M3: m3, M7: m7, - M11: m1, - M15: m1, + M11: m11, + M15: m15, __: structs.HostLayout{}, } } @@ -596,16 +598,16 @@ type Mat2 struct { M01 float32 M10 float32 M11 float32 - __ structs.HostLayout + __ structs.HostLayout } // NewMat2 - Returns new Mat2 func NewMat2(m0, m1, m10, m11 float32) Mat2 { return Mat2{ M00: m0, - M01: m0, - M10: m1, - M11: m1, + M01: m1, + M10: m10, + M11: m11, __: structs.HostLayout{}, } } @@ -639,7 +641,7 @@ type Rectangle struct { Y float32 Width float32 Height float32 - __ structs.HostLayout + __ structs.HostLayout } // NewRectangle - Returns new Rectangle @@ -670,7 +672,7 @@ type RectangleInt32 struct { Y int32 Width int32 Height int32 - __ structs.HostLayout + __ structs.HostLayout } // ToFloat32 converts rectangle to float32 variant @@ -696,7 +698,7 @@ type Camera3D struct { Fovy float32 // Camera type, controlling projection type, either CameraPerspective or CameraOrthographic. Projection CameraProjection - __ structs.HostLayout + __ structs.HostLayout } // Camera type fallback, defaults to Camera3D @@ -724,7 +726,7 @@ type Camera2D struct { Rotation float32 // Camera zoom (scaling), should be 1.0f by default Zoom float32 - __ structs.HostLayout + __ structs.HostLayout } // NewCamera2D - Returns new Camera2D @@ -744,7 +746,7 @@ type BoundingBox struct { Min Vector3 // Maximum vertex box-corner Max Vector3 - __ structs.HostLayout + __ structs.HostLayout } // NewBoundingBox - Returns new BoundingBox @@ -910,7 +912,7 @@ type Mesh struct { VaoID uint32 // OpenGL Vertex Buffer Objects id (7 types of vertex data) VboID *uint32 - __ structs.HostLayout + __ structs.HostLayout } // Material type @@ -921,7 +923,7 @@ type Material struct { Maps *MaterialMap // Generic parameters (if required) Params [4]float32 - __ structs.HostLayout + __ structs.HostLayout } // // GetMap - Get pointer to MaterialMap by map type @@ -937,7 +939,7 @@ type MaterialMap struct { Color color.RGBA // Value Value float32 - __ structs.HostLayout + __ structs.HostLayout } // Model is struct of model, meshes, materials and animation data @@ -968,7 +970,7 @@ type Model struct { // // Use Model.GetBindPose instead (go slice) BindPose *Transform - __ structs.HostLayout + __ structs.HostLayout } // // GetMeshes returns the meshes of a model as go slice @@ -995,7 +997,7 @@ type Model struct { type BoneInfo struct { Name [32]int8 Parent int32 - __ structs.HostLayout + __ structs.HostLayout } // Transform type @@ -1003,7 +1005,7 @@ type Transform struct { Translation Vector3 Rotation Vector4 Scale Vector3 - __ structs.HostLayout + __ structs.HostLayout } // Ray type (useful for raycast) @@ -1012,7 +1014,7 @@ type Ray struct { Position Vector3 // Ray direction Direction Vector3 - __ structs.HostLayout + __ structs.HostLayout } // NewRay - Returns new Ray @@ -1031,7 +1033,7 @@ type ModelAnimation struct { Bones *BoneInfo FramePoses **Transform Name [32]uint8 - __ structs.HostLayout + __ structs.HostLayout } // // GetBones returns the bones information (skeleton) of a ModelAnimation as go slice @@ -1062,7 +1064,7 @@ type RayCollision struct { Distance float32 Point Vector3 Normal Vector3 - __ structs.HostLayout + __ structs.HostLayout } // NewRayCollision - Returns new RayCollision @@ -1097,7 +1099,7 @@ type Shader struct { ID uint32 // Shader locations array Locs *int32 - __ structs.HostLayout + __ structs.HostLayout } // NewShader - Returns new Shader @@ -1131,7 +1133,7 @@ type GlyphInfo struct { AdvanceX int32 // Character image data Image Image - __ structs.HostLayout + __ structs.HostLayout } // NewGlyphInfo - Returns new CharInfo @@ -1162,7 +1164,7 @@ type Font struct { // Characters info data // Chars *GlyphInfo Chars cptr - __ structs.HostLayout + __ structs.HostLayout } // Font type, defines generation method @@ -1276,7 +1278,7 @@ type Image struct { Mipmaps int32 // Data format (PixelFormat) Format PixelFormat - __ structs.HostLayout + __ structs.HostLayout } // // NewImage - Returns new Image @@ -1299,7 +1301,7 @@ type Texture2D struct { Mipmaps int32 // Data format (PixelFormat) Format PixelFormat - __ structs.HostLayout + __ structs.HostLayout } // NewTexture2D - Returns new Texture2D @@ -1322,7 +1324,7 @@ type RenderTexture2D struct { Texture Texture2D // Depth buffer attachment texture Depth Texture2D - __ structs.HostLayout + __ structs.HostLayout } // NewRenderTexture2D - Returns new RenderTexture2D @@ -1379,7 +1381,7 @@ type NPatchInfo struct { Right int32 // Right border offset Bottom int32 // Bottom border offset Layout NPatchLayout // Layout of the n-patch: 3x3, 1x3 or 3x1 - __ structs.HostLayout + __ structs.HostLayout } // VrStereoConfig, VR stereo rendering configuration for simulator @@ -1392,7 +1394,7 @@ type VrStereoConfig struct { RightScreenCenter [2]float32 // VR right screen center Scale [2]float32 // VR distortion scale ScaleIn [2]float32 // VR distortion scale in - __ structs.HostLayout + __ structs.HostLayout } // VrDeviceInfo, Head-Mounted-Display device parameters @@ -1406,5 +1408,5 @@ type VrDeviceInfo struct { InterpupillaryDistance float32 // IPD (distance between pupils) in meters LensDistortionValues [4]float32 // Lens distortion constant parameters ChromaAbCorrection [4]float32 // Chromatic aberration correction parameters - __ structs.HostLayout + __ structs.HostLayout } diff --git a/raylib/rcore_wasm.go b/raylib/rcore_wasm.go index 8cf5cf5..752c56e 100644 --- a/raylib/rcore_wasm.go +++ b/raylib/rcore_wasm.go @@ -1,2 +1,1197 @@ +//go:build js + package rl +// WindowShouldClose - Check if KeyEscape pressed or Close icon pressed +func WindowShouldClose() bool { + const err = "WindowShouldClose is unsupported on the web, use SetMain" + alert(err) + panic(err) +} + +//go:wasmimport globalThis innerWidth +//go:noescape +func __innerWidth() int32 + +//go:wasmimport globalThis innerHeight +//go:noescape +func __innerHeight() int32 + +//go:wasmimport raylib _InitWindow +func initWindow(width, height int32, cstr cptr) + +// InitWindow - Initialize Window and OpenGL Graphics +func InitWindow(width int32, height int32, title string) { + // prevents crash. + if width == 0 { + width = __innerWidth() + } + if height == 0 { + height = __innerHeight() + } + ctitle := cStringFromGoString(title) + defer free(ctitle) + initWindow(width, height, ctitle) +} + +// CloseWindow - Close Window and Terminate Context +// +//go:wasmimport raylib _CloseWindow +//go:noescape +func CloseWindow() + +// IsWindowReady - Check if window has been initialized successfully +// +//go:wasmimport raylib _IsWindowReady +//go:noescape +func IsWindowReady() bool + +// IsWindowFullscreen - Check if window is currently fullscreen +// +//go:wasmimport raylib _IsWindowFullscreen +//go:noescape +func IsWindowFullscreen() bool + +// IsWindowHidden - Check if window is currently hidden +// +//go:wasmimport raylib _IsWindowHidden +//go:noescape +func IsWindowHidden() bool + +// IsWindowMinimized - Check if window is currently minimized +// +//go:wasmimport raylib _IsWindowMinimized +//go:noescape +func IsWindowMinimized() bool + +// IsWindowMaximized - Check if window is currently maximized +// +//go:wasmimport raylib _IsWindowMaximized +//go:noescape +func IsWindowMaximized() bool + +// IsWindowFocused - Check if window is currently focused +// +//go:wasmimport raylib _IsWindowFocused +//go:noescape +func IsWindowFocused() bool + +// IsWindowResized - Check if window has been resized +// +//go:wasmimport raylib _IsWindowResized +//go:noescape +func IsWindowResized() bool + +// IsWindowState - Check if one specific window flag is enabled +// +//go:wasmimport raylib _IsWindowState +//go:noescape +func IsWindowState(flag uint32) bool + +// SetWindowFocused - Sets the window to have focus +// +//go:wasmimport raylib _SetWindowFocused +//go:noescape +func SetWindowFocused() + +// SetWindowState - Set window configuration state using flags +// +//go:wasmimport raylib _SetWindowState +//go:noescape +func SetWindowState(flags uint32) + +// ClearWindowState - Clear window configuration state flags +// +//go:wasmimport raylib _ClearWindowState +//go:noescape +func ClearWindowState(flags uint32) + +// ToggleFullscreen - Fullscreen toggle (only PLATFORM_DESKTOP) +// +//go:wasmimport raylib _ToggleFullscreen +//go:noescape +func ToggleFullscreen() + +// ToggleBorderlessWindowed - Borderless fullscreen toggle (only PLATFORM_DESKTOP) +// +//go:wasmimport raylib _ToggleBorderlessWindowed +//go:noescape +func ToggleBorderlessWindowed() + +// MaximizeWindow - Set window state: maximized, if resizable +// +//go:wasmimport raylib _MaximizeWindow +//go:noescape +func MaximizeWindow() + +// MinimizeWindow - Set window state: minimized, if resizable +// +//go:wasmimport raylib _MinimizeWindow +//go:noescape +func MinimizeWindow() + +// RestoreWindow - Set window state: not minimized/maximized +// +//go:wasmimport raylib _RestoreWindow +//go:noescape +func RestoreWindow() + +// SetWindowIcon - Set icon for window (single image, RGBA 32bit, only PLATFORM_DESKTOP) +// +//go:wasmimport raylib _SetWindowIcon +//go:noescape +func SetWindowIcon(image Image) + +// SetWindowIcons - Set icon for window (multiple images, RGBA 32bit, only PLATFORM_DESKTOP) +// +//go:wasmimport raylib _SetWindowIcons +//go:noescape +func SetWindowIcons(images []Image, count int32) + +// SetWindowTitle - Set title for window +// +//go:wasmimport raylib _SetWindowTitle +//go:noescape +func setWindowTitle(title cptr) + +// SetWindowTitle - Set title for window (only PLATFORM_DESKTOP) +func SetWindowTitle(title string) { + ptr := cStringFromGoString(title) + defer free(ptr) + setWindowTitle(ptr) +} + +// SetWindowPosition - Set window position on screen (only PLATFORM_DESKTOP) +// +//go:wasmimport raylib _SetWindowPosition +//go:noescape +func setWindowPosition(x, y int32) + +// SetWindowPosition - Set window position on screen (only PLATFORM_DESKTOP) +func SetWindowPosition(x, y int) { + cx := int32(x) + cy := int32(y) + setWindowPosition(cx, cy) +} + +// SetWindowMonitor - Set monitor for the current window (fullscreen mode) +// +//go:wasmimport raylib _SetWindowMonitor +//go:noescape +func setWindowMonitor(monitor int32) + +// SetWindowMonitor - Set monitor for the current window (fullscreen mode) +func SetWindowMonitor(monitor int) { + cmonitor := (int32)(monitor) + setWindowMonitor(cmonitor) +} + +// SetWindowMinSize - Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) +// +//go:wasmimport raylib _SetWindowMinSize +//go:noescape +func setWindowMinSize(w, h int32) + +// SetWindowMinSize - Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) +func SetWindowMinSize(w, h int) { + cw := (int32)(w) + ch := (int32)(h) + setWindowMinSize(cw, ch) +} + +/* + +// SetWindowMaxSize - Set window maximum dimensions (for FLAG_WINDOW_RESIZABLE) +func SetWindowMaxSize(w, h int) { + cw := (int32)(w) + ch := (int32)(h) + C.SetWindowMaxSize(cw, ch) +} + +// SetWindowSize - Set window dimensions +func SetWindowSize(w, h int) { + cw := (int32)(w) + ch := (int32)(h) + C.SetWindowSize(cw, ch) +} + +// SetWindowOpacity - Set window opacity [0.0f..1.0f] (only PLATFORM_DESKTOP) +func SetWindowOpacity(opacity float32) { + copacity := (C.float)(opacity) + C.SetWindowOpacity(copacity) +} + +// GetWindowHandle - Get native window handle +func GetWindowHandle() unsafe.Pointer { + v := C.GetWindowHandle() + return v +} + +// GetScreenWidth - Get current screen width +func GetScreenWidth() int { + ret := C.GetScreenWidth() + v := (int)(ret) + return v +} + +// GetScreenHeight - Get current screen height +func GetScreenHeight() int { + ret := C.GetScreenHeight() + v := (int)(ret) + return v +} + +// GetRenderWidth - Get current render width (it considers HiDPI) +func GetRenderWidth() int { + ret := C.GetRenderWidth() + v := (int)(ret) + return v +} + +// GetRenderHeight - Get current render height (it considers HiDPI) +func GetRenderHeight() int { + ret := C.GetRenderHeight() + v := (int)(ret) + return v +} + +// GetMonitorCount - Get number of connected monitors +func GetMonitorCount() int { + ret := C.GetMonitorCount() + v := (int)(ret) + return v +} + +// GetCurrentMonitor - Get current monitor where window is placed +func GetCurrentMonitor() int { + ret := C.GetCurrentMonitor() + v := (int)(ret) + return v +} + +// GetMonitorPosition - Get specified monitor position +func GetMonitorPosition(monitor int) Vector2 { + cmonitor := (int32)(monitor) + ret := C.GetMonitorPosition(cmonitor) + v := newVector2FromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetMonitorWidth - Get primary monitor width +func GetMonitorWidth(monitor int) int { + cmonitor := (int32)(monitor) + ret := C.GetMonitorWidth(cmonitor) + v := (int)(ret) + return v +} + +// GetMonitorHeight - Get primary monitor height +func GetMonitorHeight(monitor int) int { + cmonitor := (int32)(monitor) + ret := C.GetMonitorHeight(cmonitor) + v := (int)(ret) + return v +} + +// GetMonitorPhysicalWidth - Get primary monitor physical width in millimetres +func GetMonitorPhysicalWidth(monitor int) int { + cmonitor := (int32)(monitor) + ret := C.GetMonitorPhysicalWidth(cmonitor) + v := (int)(ret) + return v +} + +// GetMonitorPhysicalHeight - Get primary monitor physical height in millimetres +func GetMonitorPhysicalHeight(monitor int) int { + cmonitor := (int32)(monitor) + ret := C.GetMonitorPhysicalHeight(cmonitor) + v := (int)(ret) + return v +} + +// GetMonitorRefreshRate - Get specified monitor refresh rate +func GetMonitorRefreshRate(monitor int) int { + cmonitor := (int32)(monitor) + ret := C.GetMonitorRefreshRate(cmonitor) + v := (int)(ret) + return v +} + +// GetWindowPosition - Get window position XY on monitor +func GetWindowPosition() Vector2 { + ret := C.GetWindowPosition() + v := newVector2FromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetWindowScaleDPI - Get window scale DPI factor +func GetWindowScaleDPI() Vector2 { + ret := C.GetWindowScaleDPI() + v := newVector2FromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetMonitorName - Get the human-readable, UTF-8 encoded name of the primary monitor +func GetMonitorName(monitor int) string { + cmonitor := (int32)(monitor) + ret := C.GetMonitorName(cmonitor) + v := C.GoString(ret) + return v +} + +// SetClipboardText - Set clipboard text content +func SetClipboardText(data string) { + cdata := C.CString(data) + defer C.free(unsafe.Pointer(cdata)) + C.SetClipboardText(cdata) +} + +// GetClipboardText - Get clipboard text content +func GetClipboardText() string { + ret := C.GetClipboardText() + v := C.GoString(ret) + return v +} + +// GetClipboardImage - Get clipboard image content +// +// Only works with SDL3 backend or Windows with GLFW/RGFW +func GetClipboardImage() Image { + ret := C.GetClipboardImage() + v := newImageFromPointer(unsafe.Pointer(&ret)) + return *v +} + +// EnableEventWaiting - Enable waiting for events on EndDrawing(), no automatic event polling +func EnableEventWaiting() { + C.EnableEventWaiting() +} + +// DisableEventWaiting - Disable waiting for events on EndDrawing(), automatic events polling +func DisableEventWaiting() { + C.DisableEventWaiting() +} + +// ClearBackground - Sets Background Color +func ClearBackground(col color.RGBA) { + ccolor := colorCptr(col) + C.ClearBackground(*ccolor) +} + +// BeginDrawing - Setup drawing canvas to start drawing +func BeginDrawing() { + C.BeginDrawing() +} + +// EndDrawing - End canvas drawing and Swap Buffers (Double Buffering) +func EndDrawing() { + C.EndDrawing() +} + +// BeginMode2D - Initialize 2D mode with custom camera +func BeginMode2D(camera Camera2D) { + ccamera := camera.cptr() + C.BeginMode2D(*ccamera) +} + +// EndMode2D - Ends 2D mode custom camera usage +func EndMode2D() { + C.EndMode2D() +} + +// BeginMode3D - Initializes 3D mode for drawing (Camera setup) +func BeginMode3D(camera Camera) { + ccamera := camera.cptr() + C.BeginMode3D(*ccamera) +} + +// EndMode3D - Ends 3D mode and returns to default 2D orthographic mode +func EndMode3D() { + C.EndMode3D() +} + +// BeginTextureMode - Initializes render texture for drawing +func BeginTextureMode(target RenderTexture2D) { + ctarget := target.cptr() + C.BeginTextureMode(*ctarget) +} + +// EndTextureMode - Ends drawing to render texture +func EndTextureMode() { + C.EndTextureMode() +} + +// BeginScissorMode - Begins scissor mode (define screen area for following drawing) +func BeginScissorMode(x, y, width, height int32) { + cx := (int32)(x) + cy := (int32)(y) + cwidth := (int32)(width) + cheight := (int32)(height) + C.BeginScissorMode(cx, cy, cwidth, cheight) +} + +// EndScissorMode - Ends scissor mode +func EndScissorMode() { + C.EndScissorMode() +} + +// LoadShader - Load a custom shader and bind default locations +func LoadShader(vsFileName string, fsFileName string) Shader { + cvsFileName := C.CString(vsFileName) + defer C.free(unsafe.Pointer(cvsFileName)) + + cfsFileName := C.CString(fsFileName) + defer C.free(unsafe.Pointer(cfsFileName)) + + if vsFileName == "" { + cvsFileName = nil + } + + if fsFileName == "" { + cfsFileName = nil + } + + ret := C.LoadShader(cvsFileName, cfsFileName) + v := newShaderFromPointer(unsafe.Pointer(&ret)) + + return v +} + +// LoadShaderFromMemory - Load shader from code strings and bind default locations +func LoadShaderFromMemory(vsCode string, fsCode string) Shader { + cvsCode := C.CString(vsCode) + defer C.free(unsafe.Pointer(cvsCode)) + + cfsCode := C.CString(fsCode) + defer C.free(unsafe.Pointer(cfsCode)) + + if vsCode == "" { + cvsCode = nil + } + + if fsCode == "" { + cfsCode = nil + } + + ret := C.LoadShaderFromMemory(cvsCode, cfsCode) + v := newShaderFromPointer(unsafe.Pointer(&ret)) + + return v +} + +// IsShaderValid - Check if a shader is valid (loaded on GPU) +func IsShaderValid(shader Shader) bool { + cshader := shader.cptr() + ret := C.IsShaderValid(*cshader) + v := bool(ret) + return v +} + +// GetShaderLocation - Get shader uniform location +func GetShaderLocation(shader Shader, uniformName string) int32 { + cshader := shader.cptr() + cuniformName := C.CString(uniformName) + defer C.free(unsafe.Pointer(cuniformName)) + + ret := C.GetShaderLocation(*cshader, cuniformName) + v := (int32)(ret) + return v +} + +// GetShaderLocationAttrib - Get shader attribute location +func GetShaderLocationAttrib(shader Shader, attribName string) int32 { + cshader := shader.cptr() + cuniformName := C.CString(attribName) + defer C.free(unsafe.Pointer(cuniformName)) + + ret := C.GetShaderLocationAttrib(*cshader, cuniformName) + v := (int32)(ret) + return v +} + +// SetShaderValue - Set shader uniform value (float) +func SetShaderValue(shader Shader, locIndex int32, value []float32, uniformType ShaderUniformDataType) { + cshader := shader.cptr() + clocIndex := (int32)(locIndex) + cvalue := (*C.float)(unsafe.Pointer(&value[0])) + cuniformType := (int32)(uniformType) + C.SetShaderValue(*cshader, clocIndex, unsafe.Pointer(cvalue), cuniformType) +} + +// SetShaderValueV - Set shader uniform value (float) +func SetShaderValueV(shader Shader, locIndex int32, value []float32, uniformType ShaderUniformDataType, count int32) { + cshader := shader.cptr() + clocIndex := (int32)(locIndex) + cvalue := (*C.float)(unsafe.Pointer(&value[0])) + cuniformType := (int32)(uniformType) + ccount := (int32)(count) + C.SetShaderValueV(*cshader, clocIndex, unsafe.Pointer(cvalue), cuniformType, ccount) +} + +// SetShaderValueMatrix - Set shader uniform value (matrix 4x4) +func SetShaderValueMatrix(shader Shader, locIndex int32, mat Matrix) { + cshader := shader.cptr() + clocIndex := (int32)(locIndex) + cmat := mat.cptr() + C.SetShaderValueMatrix(*cshader, clocIndex, *cmat) +} + +// SetShaderValueTexture - Set shader uniform value for texture (sampler2d) +func SetShaderValueTexture(shader Shader, locIndex int32, texture Texture2D) { + cshader := shader.cptr() + clocIndex := (int32)(locIndex) + ctexture := texture.cptr() + C.SetShaderValueTexture(*cshader, clocIndex, *ctexture) +} + +// UnloadShader - Unload a custom shader from memory +func UnloadShader(shader Shader) { + cshader := shader.cptr() + C.UnloadShader(*cshader) +} + +// GetMouseRay - Get a ray trace from mouse position +// +// Deprecated: Use [GetScreenToWorldRay] instead. +func GetMouseRay(mousePosition Vector2, camera Camera) Ray { + return GetScreenToWorldRay(mousePosition, camera) +} + +// GetScreenToWorldRay - Get a ray trace from screen position (i.e mouse) +func GetScreenToWorldRay(position Vector2, camera Camera) Ray { + cposition := position.cptr() + ccamera := camera.cptr() + ret := C.GetScreenToWorldRay(*cposition, *ccamera) + v := newRayFromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetScreenToWorldRayEx - Get a ray trace from screen position (i.e mouse) in a viewport +func GetScreenToWorldRayEx(position Vector2, camera Camera, width, height int32) Ray { + cposition := position.cptr() + ccamera := camera.cptr() + cwidth := (int32)(width) + cheight := (int32)(height) + ret := C.GetScreenToWorldRayEx(*cposition, *ccamera, cwidth, cheight) + v := newRayFromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetCameraMatrix - Returns camera transform matrix (view matrix) +func GetCameraMatrix(camera Camera) Matrix { + ccamera := camera.cptr() + ret := C.GetCameraMatrix(*ccamera) + v := newMatrixFromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetCameraMatrix2D - Returns camera 2d transform matrix +func GetCameraMatrix2D(camera Camera2D) Matrix { + ccamera := camera.cptr() + ret := C.GetCameraMatrix2D(*ccamera) + v := newMatrixFromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetWorldToScreen - Returns the screen space position from a 3d world space position +func GetWorldToScreen(position Vector3, camera Camera) Vector2 { + cposition := position.cptr() + ccamera := camera.cptr() + ret := C.GetWorldToScreen(*cposition, *ccamera) + v := newVector2FromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetScreenToWorld2D - Returns the world space position for a 2d camera screen space position +func GetScreenToWorld2D(position Vector2, camera Camera2D) Vector2 { + cposition := position.cptr() + ccamera := camera.cptr() + ret := C.GetScreenToWorld2D(*cposition, *ccamera) + v := newVector2FromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetWorldToScreenEx - Get size position for a 3d world space position +func GetWorldToScreenEx(position Vector3, camera Camera, width int32, height int32) Vector2 { + cposition := position.cptr() + ccamera := camera.cptr() + cwidth := (int32)(width) + cheight := (int32)(height) + ret := C.GetWorldToScreenEx(*cposition, *ccamera, cwidth, cheight) + v := newVector2FromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetWorldToScreen2D - Returns the screen space position for a 2d camera world space position +func GetWorldToScreen2D(position Vector2, camera Camera2D) Vector2 { + cposition := position.cptr() + ccamera := camera.cptr() + ret := C.GetWorldToScreen2D(*cposition, *ccamera) + v := newVector2FromPointer(unsafe.Pointer(&ret)) + return v +} + +// SetTargetFPS - Set target FPS (maximum) +func SetTargetFPS(fps int32) { + cfps := (int32)(fps) + C.SetTargetFPS(cfps) +} + +// GetFPS - Returns current FPS +func GetFPS() int32 { + ret := C.GetFPS() + v := (int32)(ret) + return v +} + +// GetFrameTime - Returns time in seconds for one frame +func GetFrameTime() float32 { + ret := C.GetFrameTime() + v := (float32)(ret) + return v +} + +// GetTime - Return time in seconds +func GetTime() float64 { + ret := C.GetTime() + v := (float64)(ret) + return v +} + +// Custom frame control functions +// NOTE: SwapScreenBuffer and PollInputEvents are intended for advanced users that want full control over the frame processing +// By default EndDrawing() does this job: draws everything + SwapScreenBuffer() + manage frame timing + PollInputEvents() +// To avoid that behaviour and control frame processes manually you can either enable in config.h: SUPPORT_CUSTOM_FRAME_CONTROL +// or add CGO_CFLAGS="-DSUPPORT_CUSTOM_FRAME_CONTROL=1" to your build + +// SwapScreenBuffer - Swap back buffer to front buffer +func SwapScreenBuffer() { + C.SwapScreenBuffer() +} + +// Register all input events +func PollInputEvents() { + C.PollInputEvents() +} + +// WaitTime - Wait for some time (halt program execution) +func WaitTime(seconds float64) { + cseconds := (C.double)(seconds) + C.WaitTime(cseconds) +} + +// Fade - Returns color with alpha applied, alpha goes from 0.0f to 1.0f +func Fade(col color.RGBA, alpha float32) color.RGBA { + ccolor := colorCptr(col) + calpha := (C.float)(alpha) + ret := C.Fade(*ccolor, calpha) + v := newColorFromPointer(unsafe.Pointer(&ret)) + return v +} + +// ColorToInt - Get hexadecimal value for a Color (0xRRGGBBAA) +func ColorToInt(col color.RGBA) int32 { + ccolor := colorCptr(col) + ret := C.ColorToInt(*ccolor) + v := (int32)(ret) + return v +} + +// ColorNormalize - Returns color normalized as float [0..1] +func ColorNormalize(col color.RGBA) Vector4 { + result := Vector4{} + r, g, b, a := col.R, col.G, col.B, col.A + result.X = float32(r) / 255 + result.Y = float32(g) / 255 + result.Z = float32(b) / 255 + result.W = float32(a) / 255 + + return result +} + +// ColorFromNormalized - Returns Color from normalized values [0..1] +func ColorFromNormalized(normalized Vector4) color.RGBA { + cnormalized := normalized.cptr() + ret := C.ColorFromNormalized(*cnormalized) + v := newColorFromPointer(unsafe.Pointer(&ret)) + return v +} + +// ColorToHSV - Returns HSV values for a Color, hue [0..360], saturation/value [0..1] +func ColorToHSV(col color.RGBA) Vector3 { + ccolor := colorCptr(col) + ret := C.ColorToHSV(*ccolor) + v := newVector3FromPointer(unsafe.Pointer(&ret)) + return v +} + +// ColorFromHSV - Returns a Color from HSV values, hue [0..360], saturation/value [0..1] +func ColorFromHSV(hue, saturation, value float32) color.RGBA { + chue := (C.float)(hue) + csaturation := (C.float)(saturation) + cvalue := (C.float)(value) + ret := C.ColorFromHSV(chue, csaturation, cvalue) + v := newColorFromPointer(unsafe.Pointer(&ret)) + return v +} + +// ColorTint - Get color multiplied with another color +func ColorTint(col color.RGBA, tint color.RGBA) color.RGBA { + ccolor := colorCptr(col) + ctint := colorCptr(tint) + ret := C.ColorTint(*ccolor, *ctint) + v := newColorFromPointer(unsafe.Pointer(&ret)) + return v +} + +// ColorBrightness - Get color with brightness correction, brightness factor goes from -1.0f to 1.0f +func ColorBrightness(col color.RGBA, factor float32) color.RGBA { + ccolor := colorCptr(col) + cfactor := C.float(factor) + ret := C.ColorBrightness(*ccolor, cfactor) + v := newColorFromPointer(unsafe.Pointer(&ret)) + return v +} + +// ColorContrast - Get color with contrast correction, contrast values between -1.0f and 1.0f +func ColorContrast(col color.RGBA, contrast float32) color.RGBA { + ccolor := colorCptr(col) + ccontrast := C.float(contrast) + ret := C.ColorContrast(*ccolor, ccontrast) + v := newColorFromPointer(unsafe.Pointer(&ret)) + return v +} + +// ColorAlpha - Returns color with alpha applied, alpha goes from 0.0f to 1.0f +func ColorAlpha(col color.RGBA, alpha float32) color.RGBA { + return Fade(col, alpha) +} + +// ColorAlphaBlend - Returns src alpha-blended into dst color with tint +func ColorAlphaBlend(src, dst, tint color.RGBA) color.RGBA { + csrc := colorCptr(src) + cdst := colorCptr(dst) + ctint := colorCptr(tint) + ret := C.ColorAlphaBlend(*csrc, *cdst, *ctint) + v := newColorFromPointer(unsafe.Pointer(&ret)) + return v +} + +// ColorLerp - Get color lerp interpolation between two colors, factor [0.0f..1.0f] +func ColorLerp(col1, col2 color.RGBA, factor float32) color.RGBA { + ccol1 := colorCptr(col1) + ccol2 := colorCptr(col2) + ret := C.ColorLerp(*ccol1, *ccol2, C.float(factor)) + v := newColorFromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetColor - Returns a Color struct from hexadecimal value +func GetColor(hexValue uint) color.RGBA { + chexValue := (C.uint)(hexValue) + ret := C.GetColor(chexValue) + v := newColorFromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetPixelDataSize - Get pixel data size in bytes for certain format +func GetPixelDataSize(width, height, format int32) int32 { + cwidth := (int32)(width) + cheight := (int32)(height) + cformat := (int32)(format) + ret := C.GetPixelDataSize(cwidth, cheight, cformat) + v := (int32)(ret) + return v +} + +// GetRandomValue - Returns a random value between min and max (both included) +func GetRandomValue(min, max int32) int32 { + cmin := (int32)(min) + cmax := (int32)(max) + ret := C.GetRandomValue(cmin, cmax) + v := (int32)(ret) + return v +} + +// OpenURL - Open URL with default system browser (if available) +func OpenURL(url string) { + curl := C.CString(url) + defer C.free(unsafe.Pointer(curl)) + C.OpenURL(curl) +} + +// SetConfigFlags - Setup some window configuration flags +func SetConfigFlags(flags uint32) { + cflags := (C.uint)(flags) + C.SetConfigFlags(cflags) +} + +// TakeScreenshot - Takes a screenshot of current screen (saved a .png) +func TakeScreenshot(name string) { + cname := C.CString(name) + defer C.free(unsafe.Pointer(cname)) + C.TakeScreenshot(cname) +} + +// LoadAutomationEventList - Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS +func LoadAutomationEventList(fileName string) AutomationEventList { + cfileName := C.CString(fileName) + defer C.free(unsafe.Pointer(cfileName)) + + ret := C.LoadAutomationEventList(cfileName) + v := newAutomationEventListFromPointer(unsafe.Pointer(&ret)) + + return v +} + +// UnloadAutomationEventList - Unload automation events list from file +func UnloadAutomationEventList(list *AutomationEventList) { + C.UnloadAutomationEventList(*list.cptr()) +} + +// ExportAutomationEventList - Export automation events list as text file +func ExportAutomationEventList(list AutomationEventList, fileName string) bool { + cfileName := C.CString(fileName) + defer C.free(unsafe.Pointer(cfileName)) + + ret := C.ExportAutomationEventList(*list.cptr(), cfileName) + v := bool(ret) + + return v +} + +// SetAutomationEventList - Set automation event list to record to +func SetAutomationEventList(list *AutomationEventList) { + C.SetAutomationEventList(list.cptr()) +} + +// SetAutomationEventBaseFrame - Set automation event internal base frame to start recording +func SetAutomationEventBaseFrame(frame int) { + cframe := (int32)(frame) + C.SetAutomationEventBaseFrame(cframe) +} + +// StartAutomationEventRecording - Start recording automation events (AutomationEventList must be set) +func StartAutomationEventRecording() { + C.StartAutomationEventRecording() +} + +// StopAutomationEventRecording - Stop recording automation events +func StopAutomationEventRecording() { + C.StopAutomationEventRecording() +} + +// PlayAutomationEvent - Play a recorded automation event +func PlayAutomationEvent(event AutomationEvent) { + C.PlayAutomationEvent(*event.cptr()) +} + +// IsKeyPressed - Detect if a key has been pressed once +func IsKeyPressed(key int32) bool { + ckey := (int32)(key) + ret := C.IsKeyPressed(ckey) + v := bool(ret) + return v +} + +// IsKeyPressedRepeat - Detect if a key has been pressed again (Only PLATFORM_DESKTOP) +func IsKeyPressedRepeat(key int32) bool { + ckey := (int32)(key) + ret := C.IsKeyPressedRepeat(ckey) + v := bool(ret) + return v +} + +// IsKeyDown - Detect if a key is being pressed +func IsKeyDown(key int32) bool { + ckey := (int32)(key) + ret := C.IsKeyDown(ckey) + v := bool(ret) + return v +} + +// IsKeyReleased - Detect if a key has been released once +func IsKeyReleased(key int32) bool { + ckey := (int32)(key) + ret := C.IsKeyReleased(ckey) + v := bool(ret) + return v +} + +// IsKeyUp - Detect if a key is NOT being pressed +func IsKeyUp(key int32) bool { + ckey := (int32)(key) + ret := C.IsKeyUp(ckey) + v := bool(ret) + return v +} + +// GetKeyPressed - Get latest key pressed +func GetKeyPressed() int32 { + ret := C.GetKeyPressed() + v := (int32)(ret) + return v +} + +// GetCharPressed - Get the last char pressed +func GetCharPressed() int32 { + ret := C.GetCharPressed() + v := (int32)(ret) + return v +} + +// SetExitKey - Set a custom key to exit program (default is ESC) +func SetExitKey(key int32) { + ckey := (int32)(key) + C.SetExitKey(ckey) +} + +// IsGamepadAvailable - Detect if a gamepad is available +func IsGamepadAvailable(gamepad int32) bool { + cgamepad := (int32)(gamepad) + ret := C.IsGamepadAvailable(cgamepad) + v := bool(ret) + return v +} + +// GetGamepadName - Return gamepad internal name id +func GetGamepadName(gamepad int32) string { + cgamepad := (int32)(gamepad) + ret := C.GetGamepadName(cgamepad) + v := C.GoString(ret) + return v +} + +// IsGamepadButtonPressed - Detect if a gamepad button has been pressed once +func IsGamepadButtonPressed(gamepad, button int32) bool { + cgamepad := (int32)(gamepad) + cbutton := (int32)(button) + ret := C.IsGamepadButtonPressed(cgamepad, cbutton) + v := bool(ret) + return v +} + +// IsGamepadButtonDown - Detect if a gamepad button is being pressed +func IsGamepadButtonDown(gamepad, button int32) bool { + cgamepad := (int32)(gamepad) + cbutton := (int32)(button) + ret := C.IsGamepadButtonDown(cgamepad, cbutton) + v := bool(ret) + return v +} + +// IsGamepadButtonReleased - Detect if a gamepad button has been released once +func IsGamepadButtonReleased(gamepad, button int32) bool { + cgamepad := (int32)(gamepad) + cbutton := (int32)(button) + ret := C.IsGamepadButtonReleased(cgamepad, cbutton) + v := bool(ret) + return v +} + +// IsGamepadButtonUp - Detect if a gamepad button is NOT being pressed +func IsGamepadButtonUp(gamepad, button int32) bool { + cgamepad := (int32)(gamepad) + cbutton := (int32)(button) + ret := C.IsGamepadButtonUp(cgamepad, cbutton) + v := bool(ret) + return v +} + +// GetGamepadButtonPressed - Get the last gamepad button pressed +func GetGamepadButtonPressed() int32 { + ret := C.GetGamepadButtonPressed() + v := (int32)(ret) + return v +} + +// GetGamepadAxisCount - Return gamepad axis count for a gamepad +func GetGamepadAxisCount(gamepad int32) int32 { + cgamepad := (int32)(gamepad) + ret := C.GetGamepadAxisCount(cgamepad) + v := (int32)(ret) + return v +} + +// GetGamepadAxisMovement - Return axis movement value for a gamepad axis +func GetGamepadAxisMovement(gamepad, axis int32) float32 { + cgamepad := (int32)(gamepad) + caxis := (int32)(axis) + ret := C.GetGamepadAxisMovement(cgamepad, caxis) + v := (float32)(ret) + return v +} + +// SetGamepadMappings - Set internal gamepad mappings (SDL_GameControllerDB) +func SetGamepadMappings(mappings string) int32 { + cmappings := C.CString(mappings) + defer C.free(unsafe.Pointer(cmappings)) + ret := C.SetGamepadMappings(cmappings) + v := (int32)(ret) + return v +} + +// SetGamepadVibration - Set gamepad vibration for both motors (duration in seconds) +func SetGamepadVibration(gamepad int32, leftMotor, rightMotor, duration float32) { + C.SetGamepadVibration(int32(gamepad), C.float(leftMotor), C.float(rightMotor), C.float(duration)) +} + +// IsMouseButtonPressed - Detect if a mouse button has been pressed once +func IsMouseButtonPressed(button MouseButton) bool { + cbutton := (int32)(button) + ret := C.IsMouseButtonPressed(cbutton) + v := bool(ret) + return v +} + +// IsMouseButtonDown - Detect if a mouse button is being pressed +func IsMouseButtonDown(button MouseButton) bool { + cbutton := (int32)(button) + ret := C.IsMouseButtonDown(cbutton) + v := bool(ret) + return v +} + +// IsMouseButtonReleased - Detect if a mouse button has been released once +func IsMouseButtonReleased(button MouseButton) bool { + cbutton := (int32)(button) + ret := C.IsMouseButtonReleased(cbutton) + v := bool(ret) + return v +} + +// IsMouseButtonUp - Detect if a mouse button is NOT being pressed +func IsMouseButtonUp(button MouseButton) bool { + cbutton := (int32)(button) + ret := C.IsMouseButtonUp(cbutton) + v := bool(ret) + return v +} + +// GetMouseX - Returns mouse position X +func GetMouseX() int32 { + ret := C.GetMouseX() + v := (int32)(ret) + return v +} + +// GetMouseY - Returns mouse position Y +func GetMouseY() int32 { + ret := C.GetMouseY() + v := (int32)(ret) + return v +} + +// GetMousePosition - Returns mouse position XY +func GetMousePosition() Vector2 { + ret := C.GetMousePosition() + v := newVector2FromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetMouseDelta - Get mouse delta between frames +func GetMouseDelta() Vector2 { + ret := C.GetMouseDelta() + v := newVector2FromPointer(unsafe.Pointer(&ret)) + return v +} + +// SetMousePosition - Set mouse position XY +func SetMousePosition(x, y int) { + cx := (int32)(x) + cy := (int32)(y) + C.SetMousePosition(cx, cy) +} + +// SetMouseOffset - Set mouse offset +func SetMouseOffset(offsetX, offsetY int) { + ox := (int32)(offsetX) + oy := (int32)(offsetY) + C.SetMouseOffset(ox, oy) +} + +// SetMouseScale - Set mouse scaling +func SetMouseScale(scaleX, scaleY float32) { + cscaleX := (C.float)(scaleX) + cscaleY := (C.float)(scaleY) + C.SetMouseScale(cscaleX, cscaleY) +} + +// GetMouseWheelMove - Get mouse wheel movement for X or Y, whichever is larger +func GetMouseWheelMove() float32 { + ret := C.GetMouseWheelMove() + v := (float32)(ret) + return v +} + +// GetMouseWheelMoveV - Get mouse wheel movement for both X and Y +func GetMouseWheelMoveV() Vector2 { + ret := C.GetMouseWheelMoveV() + v := newVector2FromPointer(unsafe.Pointer(&ret)) + return v +} + +// SetMouseCursor - Set mouse cursor +func SetMouseCursor(cursor int32) { + ccursor := (int32)(cursor) + C.SetMouseCursor(ccursor) +} + +// GetTouchX - Returns touch position X for touch point 0 (relative to screen size) +func GetTouchX() int32 { + ret := C.GetTouchX() + v := (int32)(ret) + return v +} + +// GetTouchY - Returns touch position Y for touch point 0 (relative to screen size) +func GetTouchY() int32 { + ret := C.GetTouchY() + v := (int32)(ret) + return v +} + +// GetTouchPosition - Returns touch position XY for a touch point index (relative to screen size) +func GetTouchPosition(index int32) Vector2 { + cindex := (int32)(index) + ret := C.GetTouchPosition(cindex) + v := newVector2FromPointer(unsafe.Pointer(&ret)) + return v +} + +// GetTouchPointId - Get touch point identifier for given index +func GetTouchPointId(index int32) int32 { + cindex := (int32)(index) + ret := C.GetTouchPointId(cindex) + v := (int32)(ret) + return v +} + +// GetTouchPointCount - Get number of touch points +func GetTouchPointCount() int32 { + ret := C.GetTouchPointCount() + v := (int32)(ret) + return v +} + +// BeginVrStereoMode - Begin stereo rendering (requires VR simulator) +func BeginVrStereoMode(config VrStereoConfig) { + C.BeginVrStereoMode(*(*C.VrStereoConfig)(unsafe.Pointer(&config))) +} + +// EndVrStereoMode - End stereo rendering (requires VR simulator) +func EndVrStereoMode() { + C.EndVrStereoMode() +} + +// LoadVrStereoConfig - Load VR stereo config for VR simulator device parameters +func LoadVrStereoConfig(device VrDeviceInfo) VrStereoConfig { + ret := C.LoadVrStereoConfig(*(*C.VrDeviceInfo)(unsafe.Pointer(&device))) + return *(*VrStereoConfig)(unsafe.Pointer(&ret)) +} + +// UnloadVrStereoConfig - Unload VR stereo config +func UnloadVrStereoConfig(config VrStereoConfig) { + C.UnloadVrStereoConfig(*(*C.VrStereoConfig)(unsafe.Pointer(&config))) +} +*/ diff --git a/raylib/wasm.go b/raylib/wasm.go index 320db7c..4179f00 100644 --- a/raylib/wasm.go +++ b/raylib/wasm.go @@ -1,6 +1,9 @@ +//go:build js + package rl import ( + "syscall/js" "unsafe" ) @@ -103,3 +106,18 @@ func copyArrayToGo[Slice ~[]E, E any](s Slice, srcPtr cptr) { dstPtr := unsafe.SliceData(s) copyToGo(unsafe.Pointer(dstPtr), size, srcPtr) } + +//go:wasmimport gojs Alert +//go:noescape +func alert(string) + +// Use this instead of a for loop on web platform +func SetMain(UpdateAndDrawFrame func()) { + var updateLoop js.Func + updateLoop = js.FuncOf(func(this js.Value, args []js.Value) any { + UpdateAndDrawFrame() + js.Global().Call("requestAnimationFrame", updateLoop) + return nil + }) + js.Global().Call("requestAnimationFrame", updateLoop) +} From f5db38a660e931237e2a84b0e792e71bb0aa32f6 Mon Sep 17 00:00:00 2001 From: BrownNPC Date: Thu, 29 Jan 2026 09:20:27 +0500 Subject: [PATCH 05/12] tests and consistent functions and string functions --- examples/messingAround/main.go | 72 +---- index/index.js | 1 + index/runtime.js | 35 ++- raylib/raylib.go | 2 +- raylib/rcore_wasm.go | 461 +++++++++++++++++++-------------- raylib/wasm.go | 86 +++--- raylib/wasm_test.go | 117 +++++++++ 7 files changed, 462 insertions(+), 312 deletions(-) create mode 100644 raylib/wasm_test.go diff --git a/examples/messingAround/main.go b/examples/messingAround/main.go index 86c80c0..b960f37 100644 --- a/examples/messingAround/main.go +++ b/examples/messingAround/main.go @@ -1,73 +1,9 @@ -package main - -import ( - "structs" - "unsafe" -) - -type cptr = uint32 - -//go:wasmimport raylib _malloc -func malloc(cptr) cptr - -//go:wasmimport raylib _InitWindow -func InitWindow(width, height int32, cstr cptr) - -//go:wasmimport raylib _DrawText -func DrawText(textPtr, x, y, fontsize, color cptr) - -//go:wasmimport raylib _ClearBackground -func ClearBackground(bg cptr) - -//go:wasmimport raylib _BeginDrawing -func BeginDrawing() - -//go:wasmimport raylib _EndDrawing -func EndDrawing() +//go:build js -//go:wasmimport raylib _IsWindowReady -func IsWindowReady() bool - -type Test struct { - structs.HostLayout - Age int32 - Height int32 -} -type Test2 struct { - structs.HostLayout - Name string -} - -//go:wasmimport gojs array -//go:noescape -func getRandomData(r []byte) - -//go:wasmimport gojs struct -//go:noescape -func passStruct(r unsafe.Pointer) unsafe.Pointer - -//go:wasmimport raylib _free -func free(cptr) - -//go:wasmimport raylib _GetMousePosition -func GetMousePosition(cptr) - -//go:wasmimport raylib _GetColor -//go:noescape -func GetColor(cptr, uint32) +package main -//go:wasmimport gojs CopyToGo -//go:noescape -func CopyToGo(dstGoPtr unsafe.Pointer, size cptr, src cptr) +import rl "github.com/gen2brain/raylib-go/raylib" func main() { - // title := malloc(2) - // InitWindow(300, 300, title) - // var c rl.Color - // size := cptr(unsafe.Sizeof(c)) // 4 bytes - // p := malloc(uint32(size)) // allocate memory in C/wasm - // GetColor(p, 0xFF0000FF) // fill memory - // fmt.Println("passed cptr", p) - // CopyToGo(unsafe.Pointer(&c), size, p) // copy memory to Go - // fmt.Println(c) // now prints the color + rl.InitWindow(0,0,"Hello WASM") } diff --git a/index/index.js b/index/index.js index 93a9ce8..aa7996c 100644 --- a/index/index.js +++ b/index/index.js @@ -30,6 +30,7 @@ Object.assign(go.importObject.gojs, { array: runtime.array.bind(runtime), struct: runtime.struct.bind(runtime), CStringFromGoString: runtime.CStringFromGoString.bind(runtime), + CStringGetLength: runtime.CStringGetLength.bind(runtime), CopyToC: runtime.CopyToC.bind(runtime), CopyToGo: runtime.CopyToGo.bind(runtime), Alert: runtime.Alert.bind(runtime), diff --git a/index/runtime.js b/index/runtime.js index 88eeb20..9c78be4 100644 --- a/index/runtime.js +++ b/index/runtime.js @@ -64,14 +64,25 @@ class Runtime { len, ); } - // func(string) int32wasnt + // func(cptr) cstr + // Scans for null terminator and returns the length + CStringGetLength = (sp) => { + sp >>>= 0; + const cStr = this.getInt32(sp + 8 * 1); + const view = raylib.HEAPU8.subarray(cStr); + let len = 0; + while (view[len] !== 0) { + len++; + } + this.setInt32(sp + 8 * 2, len); + }; + // func(string) cptr // returns pointer to C string in raylib memory CStringFromGoString = (sp) => { sp >>>= 0; - let arg = 1; // get string addr and length - const saddr = this.getInt64(sp + 8 * arg++); // go string address - const len = this.getInt64(sp + 8 * arg++); // go string length + const saddr = this.getInt64(sp + 8 * 1); // go string address + const len = this.getInt64(sp + 8 * 2); // go string length const goStrView = this.getmem(saddr, len); // js slice @@ -84,20 +95,21 @@ class Runtime { // // set last byte to null terminator cStrView[len] = 0; // return cstr - this.setInt32(sp + 8 * arg++, cstr); + this.setInt32(sp + 8 * 3, cstr); }; - // func(dstCArray, srcSize int32, src any) + // func(src unsafe.Pointer, srcSize, dstCptr cptr) // copies Go memory to C memory. Useful for copying slices and structs. // Destination C array must have enough space. // src must be a type. cannot be a slice. To pass a slice, use unsafe.SliceData CopyToC = (sp) => { sp >>>= 0; - const dstCArray = this.getInt32(sp + 8 * 1); - const srcSize = this.getInt32(sp + 8 * 2); - const srcPtr = this.getInt64(sp + 8 * 3); + const srcGoPtr = this.getInt64(sp + 8 * 1); + const srcSize = this.getInt32(sp + 8 * 2); // size of the dstGoPtr + // size and pointer are packed into a single 64bit int by Go's compiler + const dstCptr = this.getInt32(sp + 8 * 2 + 4); - const goBytes = this.getmem(srcPtr, srcSize); - this.getRaylibU8Array(dstCArray, srcSize).set(goBytes); + const goBytes = this.getmem(srcGoPtr, srcSize); + this.getRaylibU8Array(dstCptr, srcSize).set(goBytes); }; // func(dstGoPtr unsafe.Pointer, size int32, src cptr) // copies C memory to a Go pointer. Useful for copying C structs into Go structs @@ -117,7 +129,6 @@ class Runtime { sp >>>= 0; const dstGoPtr = this.getInt64(sp + 8 * 1); const size = this.getInt32(sp + 8 * 2); // size of the dstGoPtr - // size and pointer are packed into a single 64bit int by Go's compiler const srcCptr = this.getInt32(sp + 8 * 2 + 4); diff --git a/raylib/raylib.go b/raylib/raylib.go index e9ab716..ea91f1b 100644 --- a/raylib/raylib.go +++ b/raylib/raylib.go @@ -33,7 +33,7 @@ type Wave struct { // NewWave - Returns new Wave func NewWave(sampleCount, sampleRate, sampleSize, channels uint32, data []byte) Wave { - ptr := allocSliceInC(data) + ptr := copySliceToC(data) return Wave{ FrameCount: sampleCount, SampleRate: sampleRate, diff --git a/raylib/rcore_wasm.go b/raylib/rcore_wasm.go index 752c56e..dcbc090 100644 --- a/raylib/rcore_wasm.go +++ b/raylib/rcore_wasm.go @@ -2,6 +2,11 @@ package rl +import ( + "syscall/js" + "unsafe" +) + // WindowShouldClose - Check if KeyEscape pressed or Close icon pressed func WindowShouldClose() bool { const err = "WindowShouldClose is unsupported on the web, use SetMain" @@ -9,14 +14,6 @@ func WindowShouldClose() bool { panic(err) } -//go:wasmimport globalThis innerWidth -//go:noescape -func __innerWidth() int32 - -//go:wasmimport globalThis innerHeight -//go:noescape -func __innerHeight() int32 - //go:wasmimport raylib _InitWindow func initWindow(width, height int32, cstr cptr) @@ -24,12 +21,12 @@ func initWindow(width, height int32, cstr cptr) func InitWindow(width int32, height int32, title string) { // prevents crash. if width == 0 { - width = __innerWidth() + width = int32(js.Global().Get("innerWidth").Int()) } if height == 0 { - height = __innerHeight() + height = int32(js.Global().Get("innerHeight").Int()) } - ctitle := cStringFromGoString(title) + ctitle := cString(title) defer free(ctitle) initWindow(width, height, ctitle) } @@ -137,16 +134,10 @@ func MinimizeWindow() func RestoreWindow() // SetWindowIcon - Set icon for window (single image, RGBA 32bit, only PLATFORM_DESKTOP) -// -//go:wasmimport raylib _SetWindowIcon -//go:noescape -func SetWindowIcon(image Image) +func SetWindowIcon(image Image) {} // SetWindowIcons - Set icon for window (multiple images, RGBA 32bit, only PLATFORM_DESKTOP) -// -//go:wasmimport raylib _SetWindowIcons -//go:noescape -func SetWindowIcons(images []Image, count int32) +func SetWindowIcons(images []Image, count int32) {} // SetWindowTitle - Set title for window // @@ -156,7 +147,7 @@ func setWindowTitle(title cptr) // SetWindowTitle - Set title for window (only PLATFORM_DESKTOP) func SetWindowTitle(title string) { - ptr := cStringFromGoString(title) + ptr := cString(title) defer free(ptr) setWindowTitle(ptr) } @@ -199,157 +190,231 @@ func SetWindowMinSize(w, h int) { setWindowMinSize(cw, ch) } -/* +//go:wasmimport raylib _SetWindowMaxSize +//go:noescape +func setWindowMaxSize(w, h int32) // SetWindowMaxSize - Set window maximum dimensions (for FLAG_WINDOW_RESIZABLE) func SetWindowMaxSize(w, h int) { cw := (int32)(w) ch := (int32)(h) - C.SetWindowMaxSize(cw, ch) + setWindowMaxSize(cw, ch) } +//go:wasmimport raylib _SetWindowSize +//go:noescape +func setWindowSize(w, h int32) + // SetWindowSize - Set window dimensions func SetWindowSize(w, h int) { cw := (int32)(w) ch := (int32)(h) - C.SetWindowSize(cw, ch) + setWindowSize(cw, ch) } // SetWindowOpacity - Set window opacity [0.0f..1.0f] (only PLATFORM_DESKTOP) -func SetWindowOpacity(opacity float32) { - copacity := (C.float)(opacity) - C.SetWindowOpacity(copacity) -} +// +//go:wasmimport raylib _SetWindowOpacity +//go:noescape +func SetWindowOpacity(opacity float32) // GetWindowHandle - Get native window handle func GetWindowHandle() unsafe.Pointer { - v := C.GetWindowHandle() - return v + return nil } +//go:wasmimport raylib _GetScreenWidth +//go:noescape +func getScreenWidth() int32 + // GetScreenWidth - Get current screen width func GetScreenWidth() int { - ret := C.GetScreenWidth() + ret := getScreenWidth() v := (int)(ret) return v } +//go:wasmimport raylib _GetScreenHeight +//go:noescape +func getScreenHeight() int32 + // GetScreenHeight - Get current screen height func GetScreenHeight() int { - ret := C.GetScreenHeight() + ret := getScreenHeight() v := (int)(ret) return v } +//go:wasmimport raylib _GetRenderWidth +//go:noescape +func getRenderWidth() int32 + // GetRenderWidth - Get current render width (it considers HiDPI) func GetRenderWidth() int { - ret := C.GetRenderWidth() + ret := getRenderWidth() v := (int)(ret) return v } // GetRenderHeight - Get current render height (it considers HiDPI) +// +//go:wasmimport raylib _GetRenderHeight +//go:noescape +func getRenderHeight() int32 func GetRenderHeight() int { - ret := C.GetRenderHeight() + ret := getRenderHeight() v := (int)(ret) return v } +// GetMonitorCount - Get number of connected monitors +// +//go:wasmimport raylib _GetMonitorCount +//go:noescape +func getMonitorCount() int32 + // GetMonitorCount - Get number of connected monitors func GetMonitorCount() int { - ret := C.GetMonitorCount() + ret := getMonitorCount() v := (int)(ret) return v } +//go:wasmimport raylib _GetCurrentMonitor +//go:noescape +func getCurrentMonitor() int32 + // GetCurrentMonitor - Get current monitor where window is placed func GetCurrentMonitor() int { - ret := C.GetCurrentMonitor() + ret := getCurrentMonitor() v := (int)(ret) return v } +//go:wasmimport raylib _GetMonitorPosition +//go:noescape +func getMonitorPosition(vector2 cptr, monitor int32) + // GetMonitorPosition - Get specified monitor position func GetMonitorPosition(monitor int) Vector2 { + var v Vector2 cmonitor := (int32)(monitor) - ret := C.GetMonitorPosition(cmonitor) - v := newVector2FromPointer(unsafe.Pointer(&ret)) + + ret := mallocV(v) + defer free(ret) + getMonitorPosition(ret, cmonitor) + copyValueToGo(ret, &v) return v } +//go:wasmimport raylib _GetMonitorWidth +//go:noescape +func getMonitorWidth(monitor int32) int32 + // GetMonitorWidth - Get primary monitor width func GetMonitorWidth(monitor int) int { cmonitor := (int32)(monitor) - ret := C.GetMonitorWidth(cmonitor) + ret := getMonitorWidth(cmonitor) v := (int)(ret) return v } +//go:wasmimport raylib _GetMonitorHeight +//go:noescape +func getMonitorHeight(monitor int32) int32 + // GetMonitorHeight - Get primary monitor height func GetMonitorHeight(monitor int) int { cmonitor := (int32)(monitor) - ret := C.GetMonitorHeight(cmonitor) + ret := getMonitorHeight(cmonitor) v := (int)(ret) return v } +// +//go:wasmimport raylib _GetMonitorPhysicalWidth +//go:noescape +func getMonitorPhysicalWidth(monitor int32) int32 + // GetMonitorPhysicalWidth - Get primary monitor physical width in millimetres func GetMonitorPhysicalWidth(monitor int) int { cmonitor := (int32)(monitor) - ret := C.GetMonitorPhysicalWidth(cmonitor) + ret := getMonitorPhysicalWidth(cmonitor) v := (int)(ret) return v } +//go:wasmimport raylib _GetMonitorPhysicalHeight +//go:noescape +func getMonitorPhysicalHeight(monitor int32) int32 + // GetMonitorPhysicalHeight - Get primary monitor physical height in millimetres func GetMonitorPhysicalHeight(monitor int) int { cmonitor := (int32)(monitor) - ret := C.GetMonitorPhysicalHeight(cmonitor) + ret := getMonitorPhysicalHeight(cmonitor) v := (int)(ret) return v } +//go:wasmimport raylib _GetMonitorRefreshRate +//go:noescape +func getMonitorRefreshRate(monitor int32) int32 + // GetMonitorRefreshRate - Get specified monitor refresh rate func GetMonitorRefreshRate(monitor int) int { cmonitor := (int32)(monitor) - ret := C.GetMonitorRefreshRate(cmonitor) + ret := getMonitorRefreshRate(cmonitor) v := (int)(ret) return v } +//go:wasmimport raylib _GetWindowPosition +//go:noescape +func getWindowPosition(vector2 cptr) + // GetWindowPosition - Get window position XY on monitor func GetWindowPosition() Vector2 { - ret := C.GetWindowPosition() - v := newVector2FromPointer(unsafe.Pointer(&ret)) + var v Vector2 + ret := mallocV(v) + defer free(ret) + getWindowPosition(ret) + copyValueToGo(ret, &v) return v } +//go:wasmimport raylib _GetWindowScaleDPI +//go:noescape +func getWindowScaleDPI(vector2 cptr) + // GetWindowScaleDPI - Get window scale DPI factor func GetWindowScaleDPI() Vector2 { - ret := C.GetWindowScaleDPI() - v := newVector2FromPointer(unsafe.Pointer(&ret)) + var v Vector2 + ret := mallocV(v) + defer free(ret) + getWindowScaleDPI(ret) + copyValueToGo(ret, &v) return v } // GetMonitorName - Get the human-readable, UTF-8 encoded name of the primary monitor -func GetMonitorName(monitor int) string { - cmonitor := (int32)(monitor) - ret := C.GetMonitorName(cmonitor) - v := C.GoString(ret) - return v -} +func GetMonitorName(monitor int) string { return "" } // SetClipboardText - Set clipboard text content +// +//go:wasmimport raylib _SetClipboardText +//go:noescape +func setClipboardText(data cptr) func SetClipboardText(data string) { - cdata := C.CString(data) - defer C.free(unsafe.Pointer(cdata)) - C.SetClipboardText(cdata) + cdata := cString(data) + defer free(cdata) + setClipboardText(cdata) } +/* // GetClipboardText - Get clipboard text content func GetClipboardText() string { - ret := C.GetClipboardText() - v := C.GoString(ret) + ret := getClipboardText() + v := goString(ret) return v } @@ -357,68 +422,68 @@ func GetClipboardText() string { // // Only works with SDL3 backend or Windows with GLFW/RGFW func GetClipboardImage() Image { - ret := C.GetClipboardImage() + ret := getClipboardImage() v := newImageFromPointer(unsafe.Pointer(&ret)) return *v } // EnableEventWaiting - Enable waiting for events on EndDrawing(), no automatic event polling func EnableEventWaiting() { - C.EnableEventWaiting() + enableEventWaiting() } // DisableEventWaiting - Disable waiting for events on EndDrawing(), automatic events polling func DisableEventWaiting() { - C.DisableEventWaiting() + disableEventWaiting() } // ClearBackground - Sets Background Color func ClearBackground(col color.RGBA) { ccolor := colorCptr(col) - C.ClearBackground(*ccolor) + clearBackground(*ccolor) } // BeginDrawing - Setup drawing canvas to start drawing func BeginDrawing() { - C.BeginDrawing() + beginDrawing() } // EndDrawing - End canvas drawing and Swap Buffers (Double Buffering) func EndDrawing() { - C.EndDrawing() + endDrawing() } // BeginMode2D - Initialize 2D mode with custom camera func BeginMode2D(camera Camera2D) { ccamera := camera.cptr() - C.BeginMode2D(*ccamera) + beginMode2D(*ccamera) } // EndMode2D - Ends 2D mode custom camera usage func EndMode2D() { - C.EndMode2D() + endMode2D() } // BeginMode3D - Initializes 3D mode for drawing (Camera setup) func BeginMode3D(camera Camera) { ccamera := camera.cptr() - C.BeginMode3D(*ccamera) + beginMode3D(*ccamera) } // EndMode3D - Ends 3D mode and returns to default 2D orthographic mode func EndMode3D() { - C.EndMode3D() + endMode3D() } // BeginTextureMode - Initializes render texture for drawing func BeginTextureMode(target RenderTexture2D) { ctarget := target.cptr() - C.BeginTextureMode(*ctarget) + beginTextureMode(*ctarget) } // EndTextureMode - Ends drawing to render texture func EndTextureMode() { - C.EndTextureMode() + endTextureMode() } // BeginScissorMode - Begins scissor mode (define screen area for following drawing) @@ -427,21 +492,21 @@ func BeginScissorMode(x, y, width, height int32) { cy := (int32)(y) cwidth := (int32)(width) cheight := (int32)(height) - C.BeginScissorMode(cx, cy, cwidth, cheight) + beginScissorMode(cx, cy, cwidth, cheight) } // EndScissorMode - Ends scissor mode func EndScissorMode() { - C.EndScissorMode() + endScissorMode() } // LoadShader - Load a custom shader and bind default locations func LoadShader(vsFileName string, fsFileName string) Shader { - cvsFileName := C.CString(vsFileName) - defer C.free(unsafe.Pointer(cvsFileName)) + cvsFileName := cString(vsFileName) + defer free(unsafe.Pointer(cvsFileName)) - cfsFileName := C.CString(fsFileName) - defer C.free(unsafe.Pointer(cfsFileName)) + cfsFileName := cString(fsFileName) + defer free(unsafe.Pointer(cfsFileName)) if vsFileName == "" { cvsFileName = nil @@ -451,7 +516,7 @@ func LoadShader(vsFileName string, fsFileName string) Shader { cfsFileName = nil } - ret := C.LoadShader(cvsFileName, cfsFileName) + ret := loadShader(cvsFileName, cfsFileName) v := newShaderFromPointer(unsafe.Pointer(&ret)) return v @@ -459,11 +524,11 @@ func LoadShader(vsFileName string, fsFileName string) Shader { // LoadShaderFromMemory - Load shader from code strings and bind default locations func LoadShaderFromMemory(vsCode string, fsCode string) Shader { - cvsCode := C.CString(vsCode) - defer C.free(unsafe.Pointer(cvsCode)) + cvsCode := cString(vsCode) + defer free(unsafe.Pointer(cvsCode)) - cfsCode := C.CString(fsCode) - defer C.free(unsafe.Pointer(cfsCode)) + cfsCode := cString(fsCode) + defer free(unsafe.Pointer(cfsCode)) if vsCode == "" { cvsCode = nil @@ -473,7 +538,7 @@ func LoadShaderFromMemory(vsCode string, fsCode string) Shader { cfsCode = nil } - ret := C.LoadShaderFromMemory(cvsCode, cfsCode) + ret := loadShaderFromMemory(cvsCode, cfsCode) v := newShaderFromPointer(unsafe.Pointer(&ret)) return v @@ -482,7 +547,7 @@ func LoadShaderFromMemory(vsCode string, fsCode string) Shader { // IsShaderValid - Check if a shader is valid (loaded on GPU) func IsShaderValid(shader Shader) bool { cshader := shader.cptr() - ret := C.IsShaderValid(*cshader) + ret := isShaderValid(*cshader) v := bool(ret) return v } @@ -490,10 +555,10 @@ func IsShaderValid(shader Shader) bool { // GetShaderLocation - Get shader uniform location func GetShaderLocation(shader Shader, uniformName string) int32 { cshader := shader.cptr() - cuniformName := C.CString(uniformName) - defer C.free(unsafe.Pointer(cuniformName)) + cuniformName := cString(uniformName) + defer free(unsafe.Pointer(cuniformName)) - ret := C.GetShaderLocation(*cshader, cuniformName) + ret := getShaderLocation(*cshader, cuniformName) v := (int32)(ret) return v } @@ -501,10 +566,10 @@ func GetShaderLocation(shader Shader, uniformName string) int32 { // GetShaderLocationAttrib - Get shader attribute location func GetShaderLocationAttrib(shader Shader, attribName string) int32 { cshader := shader.cptr() - cuniformName := C.CString(attribName) - defer C.free(unsafe.Pointer(cuniformName)) + cuniformName := cString(attribName) + defer free(unsafe.Pointer(cuniformName)) - ret := C.GetShaderLocationAttrib(*cshader, cuniformName) + ret := getShaderLocationAttrib(*cshader, cuniformName) v := (int32)(ret) return v } @@ -513,19 +578,19 @@ func GetShaderLocationAttrib(shader Shader, attribName string) int32 { func SetShaderValue(shader Shader, locIndex int32, value []float32, uniformType ShaderUniformDataType) { cshader := shader.cptr() clocIndex := (int32)(locIndex) - cvalue := (*C.float)(unsafe.Pointer(&value[0])) + cvalue := (*float)(unsafe.Pointer(&value[0])) cuniformType := (int32)(uniformType) - C.SetShaderValue(*cshader, clocIndex, unsafe.Pointer(cvalue), cuniformType) + setShaderValue(*cshader, clocIndex, unsafe.Pointer(cvalue), cuniformType) } // SetShaderValueV - Set shader uniform value (float) func SetShaderValueV(shader Shader, locIndex int32, value []float32, uniformType ShaderUniformDataType, count int32) { cshader := shader.cptr() clocIndex := (int32)(locIndex) - cvalue := (*C.float)(unsafe.Pointer(&value[0])) + cvalue := (*float)(unsafe.Pointer(&value[0])) cuniformType := (int32)(uniformType) ccount := (int32)(count) - C.SetShaderValueV(*cshader, clocIndex, unsafe.Pointer(cvalue), cuniformType, ccount) + setShaderValueV(*cshader, clocIndex, unsafe.Pointer(cvalue), cuniformType, ccount) } // SetShaderValueMatrix - Set shader uniform value (matrix 4x4) @@ -533,7 +598,7 @@ func SetShaderValueMatrix(shader Shader, locIndex int32, mat Matrix) { cshader := shader.cptr() clocIndex := (int32)(locIndex) cmat := mat.cptr() - C.SetShaderValueMatrix(*cshader, clocIndex, *cmat) + setShaderValueMatrix(*cshader, clocIndex, *cmat) } // SetShaderValueTexture - Set shader uniform value for texture (sampler2d) @@ -541,13 +606,13 @@ func SetShaderValueTexture(shader Shader, locIndex int32, texture Texture2D) { cshader := shader.cptr() clocIndex := (int32)(locIndex) ctexture := texture.cptr() - C.SetShaderValueTexture(*cshader, clocIndex, *ctexture) + setShaderValueTexture(*cshader, clocIndex, *ctexture) } // UnloadShader - Unload a custom shader from memory func UnloadShader(shader Shader) { cshader := shader.cptr() - C.UnloadShader(*cshader) + unloadShader(*cshader) } // GetMouseRay - Get a ray trace from mouse position @@ -561,7 +626,7 @@ func GetMouseRay(mousePosition Vector2, camera Camera) Ray { func GetScreenToWorldRay(position Vector2, camera Camera) Ray { cposition := position.cptr() ccamera := camera.cptr() - ret := C.GetScreenToWorldRay(*cposition, *ccamera) + ret := getScreenToWorldRay(*cposition, *ccamera) v := newRayFromPointer(unsafe.Pointer(&ret)) return v } @@ -572,7 +637,7 @@ func GetScreenToWorldRayEx(position Vector2, camera Camera, width, height int32) ccamera := camera.cptr() cwidth := (int32)(width) cheight := (int32)(height) - ret := C.GetScreenToWorldRayEx(*cposition, *ccamera, cwidth, cheight) + ret := getScreenToWorldRayEx(*cposition, *ccamera, cwidth, cheight) v := newRayFromPointer(unsafe.Pointer(&ret)) return v } @@ -580,7 +645,7 @@ func GetScreenToWorldRayEx(position Vector2, camera Camera, width, height int32) // GetCameraMatrix - Returns camera transform matrix (view matrix) func GetCameraMatrix(camera Camera) Matrix { ccamera := camera.cptr() - ret := C.GetCameraMatrix(*ccamera) + ret := getCameraMatrix(*ccamera) v := newMatrixFromPointer(unsafe.Pointer(&ret)) return v } @@ -588,7 +653,7 @@ func GetCameraMatrix(camera Camera) Matrix { // GetCameraMatrix2D - Returns camera 2d transform matrix func GetCameraMatrix2D(camera Camera2D) Matrix { ccamera := camera.cptr() - ret := C.GetCameraMatrix2D(*ccamera) + ret := getCameraMatrix2D(*ccamera) v := newMatrixFromPointer(unsafe.Pointer(&ret)) return v } @@ -597,7 +662,7 @@ func GetCameraMatrix2D(camera Camera2D) Matrix { func GetWorldToScreen(position Vector3, camera Camera) Vector2 { cposition := position.cptr() ccamera := camera.cptr() - ret := C.GetWorldToScreen(*cposition, *ccamera) + ret := getWorldToScreen(*cposition, *ccamera) v := newVector2FromPointer(unsafe.Pointer(&ret)) return v } @@ -606,7 +671,7 @@ func GetWorldToScreen(position Vector3, camera Camera) Vector2 { func GetScreenToWorld2D(position Vector2, camera Camera2D) Vector2 { cposition := position.cptr() ccamera := camera.cptr() - ret := C.GetScreenToWorld2D(*cposition, *ccamera) + ret := getScreenToWorld2D(*cposition, *ccamera) v := newVector2FromPointer(unsafe.Pointer(&ret)) return v } @@ -617,7 +682,7 @@ func GetWorldToScreenEx(position Vector3, camera Camera, width int32, height int ccamera := camera.cptr() cwidth := (int32)(width) cheight := (int32)(height) - ret := C.GetWorldToScreenEx(*cposition, *ccamera, cwidth, cheight) + ret := getWorldToScreenEx(*cposition, *ccamera, cwidth, cheight) v := newVector2FromPointer(unsafe.Pointer(&ret)) return v } @@ -626,7 +691,7 @@ func GetWorldToScreenEx(position Vector3, camera Camera, width int32, height int func GetWorldToScreen2D(position Vector2, camera Camera2D) Vector2 { cposition := position.cptr() ccamera := camera.cptr() - ret := C.GetWorldToScreen2D(*cposition, *ccamera) + ret := getWorldToScreen2D(*cposition, *ccamera) v := newVector2FromPointer(unsafe.Pointer(&ret)) return v } @@ -634,26 +699,26 @@ func GetWorldToScreen2D(position Vector2, camera Camera2D) Vector2 { // SetTargetFPS - Set target FPS (maximum) func SetTargetFPS(fps int32) { cfps := (int32)(fps) - C.SetTargetFPS(cfps) + setTargetFPS(cfps) } // GetFPS - Returns current FPS func GetFPS() int32 { - ret := C.GetFPS() + ret := getFPS() v := (int32)(ret) return v } // GetFrameTime - Returns time in seconds for one frame func GetFrameTime() float32 { - ret := C.GetFrameTime() + ret := getFrameTime() v := (float32)(ret) return v } // GetTime - Return time in seconds func GetTime() float64 { - ret := C.GetTime() + ret := getTime() v := (float64)(ret) return v } @@ -666,25 +731,25 @@ func GetTime() float64 { // SwapScreenBuffer - Swap back buffer to front buffer func SwapScreenBuffer() { - C.SwapScreenBuffer() + swapScreenBuffer() } // Register all input events func PollInputEvents() { - C.PollInputEvents() + pollInputEvents() } // WaitTime - Wait for some time (halt program execution) func WaitTime(seconds float64) { - cseconds := (C.double)(seconds) - C.WaitTime(cseconds) + cseconds := (double)(seconds) + waitTime(cseconds) } // Fade - Returns color with alpha applied, alpha goes from 0.0f to 1.0f func Fade(col color.RGBA, alpha float32) color.RGBA { ccolor := colorCptr(col) - calpha := (C.float)(alpha) - ret := C.Fade(*ccolor, calpha) + calpha := (float)(alpha) + ret := fade(*ccolor, calpha) v := newColorFromPointer(unsafe.Pointer(&ret)) return v } @@ -692,7 +757,7 @@ func Fade(col color.RGBA, alpha float32) color.RGBA { // ColorToInt - Get hexadecimal value for a Color (0xRRGGBBAA) func ColorToInt(col color.RGBA) int32 { ccolor := colorCptr(col) - ret := C.ColorToInt(*ccolor) + ret := colorToInt(*ccolor) v := (int32)(ret) return v } @@ -712,7 +777,7 @@ func ColorNormalize(col color.RGBA) Vector4 { // ColorFromNormalized - Returns Color from normalized values [0..1] func ColorFromNormalized(normalized Vector4) color.RGBA { cnormalized := normalized.cptr() - ret := C.ColorFromNormalized(*cnormalized) + ret := colorFromNormalized(*cnormalized) v := newColorFromPointer(unsafe.Pointer(&ret)) return v } @@ -720,17 +785,17 @@ func ColorFromNormalized(normalized Vector4) color.RGBA { // ColorToHSV - Returns HSV values for a Color, hue [0..360], saturation/value [0..1] func ColorToHSV(col color.RGBA) Vector3 { ccolor := colorCptr(col) - ret := C.ColorToHSV(*ccolor) + ret := colorToHSV(*ccolor) v := newVector3FromPointer(unsafe.Pointer(&ret)) return v } // ColorFromHSV - Returns a Color from HSV values, hue [0..360], saturation/value [0..1] func ColorFromHSV(hue, saturation, value float32) color.RGBA { - chue := (C.float)(hue) - csaturation := (C.float)(saturation) - cvalue := (C.float)(value) - ret := C.ColorFromHSV(chue, csaturation, cvalue) + chue := (float)(hue) + csaturation := (float)(saturation) + cvalue := (float)(value) + ret := colorFromHSV(chue, csaturation, cvalue) v := newColorFromPointer(unsafe.Pointer(&ret)) return v } @@ -739,7 +804,7 @@ func ColorFromHSV(hue, saturation, value float32) color.RGBA { func ColorTint(col color.RGBA, tint color.RGBA) color.RGBA { ccolor := colorCptr(col) ctint := colorCptr(tint) - ret := C.ColorTint(*ccolor, *ctint) + ret := colorTint(*ccolor, *ctint) v := newColorFromPointer(unsafe.Pointer(&ret)) return v } @@ -747,8 +812,8 @@ func ColorTint(col color.RGBA, tint color.RGBA) color.RGBA { // ColorBrightness - Get color with brightness correction, brightness factor goes from -1.0f to 1.0f func ColorBrightness(col color.RGBA, factor float32) color.RGBA { ccolor := colorCptr(col) - cfactor := C.float(factor) - ret := C.ColorBrightness(*ccolor, cfactor) + cfactor := float(factor) + ret := colorBrightness(*ccolor, cfactor) v := newColorFromPointer(unsafe.Pointer(&ret)) return v } @@ -756,8 +821,8 @@ func ColorBrightness(col color.RGBA, factor float32) color.RGBA { // ColorContrast - Get color with contrast correction, contrast values between -1.0f and 1.0f func ColorContrast(col color.RGBA, contrast float32) color.RGBA { ccolor := colorCptr(col) - ccontrast := C.float(contrast) - ret := C.ColorContrast(*ccolor, ccontrast) + ccontrast := float(contrast) + ret := colorContrast(*ccolor, ccontrast) v := newColorFromPointer(unsafe.Pointer(&ret)) return v } @@ -772,7 +837,7 @@ func ColorAlphaBlend(src, dst, tint color.RGBA) color.RGBA { csrc := colorCptr(src) cdst := colorCptr(dst) ctint := colorCptr(tint) - ret := C.ColorAlphaBlend(*csrc, *cdst, *ctint) + ret := colorAlphaBlend(*csrc, *cdst, *ctint) v := newColorFromPointer(unsafe.Pointer(&ret)) return v } @@ -781,15 +846,15 @@ func ColorAlphaBlend(src, dst, tint color.RGBA) color.RGBA { func ColorLerp(col1, col2 color.RGBA, factor float32) color.RGBA { ccol1 := colorCptr(col1) ccol2 := colorCptr(col2) - ret := C.ColorLerp(*ccol1, *ccol2, C.float(factor)) + ret := colorLerp(*ccol1, *ccol2, float(factor)) v := newColorFromPointer(unsafe.Pointer(&ret)) return v } // GetColor - Returns a Color struct from hexadecimal value func GetColor(hexValue uint) color.RGBA { - chexValue := (C.uint)(hexValue) - ret := C.GetColor(chexValue) + chexValue := (uint)(hexValue) + ret := getColor(chexValue) v := newColorFromPointer(unsafe.Pointer(&ret)) return v } @@ -799,7 +864,7 @@ func GetPixelDataSize(width, height, format int32) int32 { cwidth := (int32)(width) cheight := (int32)(height) cformat := (int32)(format) - ret := C.GetPixelDataSize(cwidth, cheight, cformat) + ret := getPixelDataSize(cwidth, cheight, cformat) v := (int32)(ret) return v } @@ -808,37 +873,37 @@ func GetPixelDataSize(width, height, format int32) int32 { func GetRandomValue(min, max int32) int32 { cmin := (int32)(min) cmax := (int32)(max) - ret := C.GetRandomValue(cmin, cmax) + ret := getRandomValue(cmin, cmax) v := (int32)(ret) return v } // OpenURL - Open URL with default system browser (if available) func OpenURL(url string) { - curl := C.CString(url) - defer C.free(unsafe.Pointer(curl)) - C.OpenURL(curl) + curl := cString(url) + defer free(unsafe.Pointer(curl)) + openURL(curl) } // SetConfigFlags - Setup some window configuration flags func SetConfigFlags(flags uint32) { - cflags := (C.uint)(flags) - C.SetConfigFlags(cflags) + cflags := (uint)(flags) + setConfigFlags(cflags) } // TakeScreenshot - Takes a screenshot of current screen (saved a .png) func TakeScreenshot(name string) { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - C.TakeScreenshot(cname) + cname := cString(name) + defer free(unsafe.Pointer(cname)) + takeScreenshot(cname) } // LoadAutomationEventList - Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS func LoadAutomationEventList(fileName string) AutomationEventList { - cfileName := C.CString(fileName) - defer C.free(unsafe.Pointer(cfileName)) + cfileName := cString(fileName) + defer free(unsafe.Pointer(cfileName)) - ret := C.LoadAutomationEventList(cfileName) + ret := loadAutomationEventList(cfileName) v := newAutomationEventListFromPointer(unsafe.Pointer(&ret)) return v @@ -846,15 +911,15 @@ func LoadAutomationEventList(fileName string) AutomationEventList { // UnloadAutomationEventList - Unload automation events list from file func UnloadAutomationEventList(list *AutomationEventList) { - C.UnloadAutomationEventList(*list.cptr()) + unloadAutomationEventList(*list.cptr()) } // ExportAutomationEventList - Export automation events list as text file func ExportAutomationEventList(list AutomationEventList, fileName string) bool { - cfileName := C.CString(fileName) - defer C.free(unsafe.Pointer(cfileName)) + cfileName := cString(fileName) + defer free(unsafe.Pointer(cfileName)) - ret := C.ExportAutomationEventList(*list.cptr(), cfileName) + ret := exportAutomationEventList(*list.cptr(), cfileName) v := bool(ret) return v @@ -862,34 +927,34 @@ func ExportAutomationEventList(list AutomationEventList, fileName string) bool { // SetAutomationEventList - Set automation event list to record to func SetAutomationEventList(list *AutomationEventList) { - C.SetAutomationEventList(list.cptr()) + setAutomationEventList(list.cptr()) } // SetAutomationEventBaseFrame - Set automation event internal base frame to start recording func SetAutomationEventBaseFrame(frame int) { cframe := (int32)(frame) - C.SetAutomationEventBaseFrame(cframe) + setAutomationEventBaseFrame(cframe) } // StartAutomationEventRecording - Start recording automation events (AutomationEventList must be set) func StartAutomationEventRecording() { - C.StartAutomationEventRecording() + startAutomationEventRecording() } // StopAutomationEventRecording - Stop recording automation events func StopAutomationEventRecording() { - C.StopAutomationEventRecording() + stopAutomationEventRecording() } // PlayAutomationEvent - Play a recorded automation event func PlayAutomationEvent(event AutomationEvent) { - C.PlayAutomationEvent(*event.cptr()) + playAutomationEvent(*event.cptr()) } // IsKeyPressed - Detect if a key has been pressed once func IsKeyPressed(key int32) bool { ckey := (int32)(key) - ret := C.IsKeyPressed(ckey) + ret := isKeyPressed(ckey) v := bool(ret) return v } @@ -897,7 +962,7 @@ func IsKeyPressed(key int32) bool { // IsKeyPressedRepeat - Detect if a key has been pressed again (Only PLATFORM_DESKTOP) func IsKeyPressedRepeat(key int32) bool { ckey := (int32)(key) - ret := C.IsKeyPressedRepeat(ckey) + ret := isKeyPressedRepeat(ckey) v := bool(ret) return v } @@ -905,7 +970,7 @@ func IsKeyPressedRepeat(key int32) bool { // IsKeyDown - Detect if a key is being pressed func IsKeyDown(key int32) bool { ckey := (int32)(key) - ret := C.IsKeyDown(ckey) + ret := isKeyDown(ckey) v := bool(ret) return v } @@ -913,7 +978,7 @@ func IsKeyDown(key int32) bool { // IsKeyReleased - Detect if a key has been released once func IsKeyReleased(key int32) bool { ckey := (int32)(key) - ret := C.IsKeyReleased(ckey) + ret := isKeyReleased(ckey) v := bool(ret) return v } @@ -921,21 +986,21 @@ func IsKeyReleased(key int32) bool { // IsKeyUp - Detect if a key is NOT being pressed func IsKeyUp(key int32) bool { ckey := (int32)(key) - ret := C.IsKeyUp(ckey) + ret := isKeyUp(ckey) v := bool(ret) return v } // GetKeyPressed - Get latest key pressed func GetKeyPressed() int32 { - ret := C.GetKeyPressed() + ret := getKeyPressed() v := (int32)(ret) return v } // GetCharPressed - Get the last char pressed func GetCharPressed() int32 { - ret := C.GetCharPressed() + ret := getCharPressed() v := (int32)(ret) return v } @@ -943,13 +1008,13 @@ func GetCharPressed() int32 { // SetExitKey - Set a custom key to exit program (default is ESC) func SetExitKey(key int32) { ckey := (int32)(key) - C.SetExitKey(ckey) + setExitKey(ckey) } // IsGamepadAvailable - Detect if a gamepad is available func IsGamepadAvailable(gamepad int32) bool { cgamepad := (int32)(gamepad) - ret := C.IsGamepadAvailable(cgamepad) + ret := isGamepadAvailable(cgamepad) v := bool(ret) return v } @@ -957,8 +1022,8 @@ func IsGamepadAvailable(gamepad int32) bool { // GetGamepadName - Return gamepad internal name id func GetGamepadName(gamepad int32) string { cgamepad := (int32)(gamepad) - ret := C.GetGamepadName(cgamepad) - v := C.GoString(ret) + ret := getGamepadName(cgamepad) + v := goString(ret) return v } @@ -966,7 +1031,7 @@ func GetGamepadName(gamepad int32) string { func IsGamepadButtonPressed(gamepad, button int32) bool { cgamepad := (int32)(gamepad) cbutton := (int32)(button) - ret := C.IsGamepadButtonPressed(cgamepad, cbutton) + ret := isGamepadButtonPressed(cgamepad, cbutton) v := bool(ret) return v } @@ -975,7 +1040,7 @@ func IsGamepadButtonPressed(gamepad, button int32) bool { func IsGamepadButtonDown(gamepad, button int32) bool { cgamepad := (int32)(gamepad) cbutton := (int32)(button) - ret := C.IsGamepadButtonDown(cgamepad, cbutton) + ret := isGamepadButtonDown(cgamepad, cbutton) v := bool(ret) return v } @@ -984,7 +1049,7 @@ func IsGamepadButtonDown(gamepad, button int32) bool { func IsGamepadButtonReleased(gamepad, button int32) bool { cgamepad := (int32)(gamepad) cbutton := (int32)(button) - ret := C.IsGamepadButtonReleased(cgamepad, cbutton) + ret := isGamepadButtonReleased(cgamepad, cbutton) v := bool(ret) return v } @@ -993,14 +1058,14 @@ func IsGamepadButtonReleased(gamepad, button int32) bool { func IsGamepadButtonUp(gamepad, button int32) bool { cgamepad := (int32)(gamepad) cbutton := (int32)(button) - ret := C.IsGamepadButtonUp(cgamepad, cbutton) + ret := isGamepadButtonUp(cgamepad, cbutton) v := bool(ret) return v } // GetGamepadButtonPressed - Get the last gamepad button pressed func GetGamepadButtonPressed() int32 { - ret := C.GetGamepadButtonPressed() + ret := getGamepadButtonPressed() v := (int32)(ret) return v } @@ -1008,7 +1073,7 @@ func GetGamepadButtonPressed() int32 { // GetGamepadAxisCount - Return gamepad axis count for a gamepad func GetGamepadAxisCount(gamepad int32) int32 { cgamepad := (int32)(gamepad) - ret := C.GetGamepadAxisCount(cgamepad) + ret := getGamepadAxisCount(cgamepad) v := (int32)(ret) return v } @@ -1017,29 +1082,29 @@ func GetGamepadAxisCount(gamepad int32) int32 { func GetGamepadAxisMovement(gamepad, axis int32) float32 { cgamepad := (int32)(gamepad) caxis := (int32)(axis) - ret := C.GetGamepadAxisMovement(cgamepad, caxis) + ret := getGamepadAxisMovement(cgamepad, caxis) v := (float32)(ret) return v } // SetGamepadMappings - Set internal gamepad mappings (SDL_GameControllerDB) func SetGamepadMappings(mappings string) int32 { - cmappings := C.CString(mappings) - defer C.free(unsafe.Pointer(cmappings)) - ret := C.SetGamepadMappings(cmappings) + cmappings := cString(mappings) + defer free(unsafe.Pointer(cmappings)) + ret := setGamepadMappings(cmappings) v := (int32)(ret) return v } // SetGamepadVibration - Set gamepad vibration for both motors (duration in seconds) func SetGamepadVibration(gamepad int32, leftMotor, rightMotor, duration float32) { - C.SetGamepadVibration(int32(gamepad), C.float(leftMotor), C.float(rightMotor), C.float(duration)) + setGamepadVibration(int32(gamepad), float(leftMotor), float(rightMotor), float(duration)) } // IsMouseButtonPressed - Detect if a mouse button has been pressed once func IsMouseButtonPressed(button MouseButton) bool { cbutton := (int32)(button) - ret := C.IsMouseButtonPressed(cbutton) + ret := isMouseButtonPressed(cbutton) v := bool(ret) return v } @@ -1047,7 +1112,7 @@ func IsMouseButtonPressed(button MouseButton) bool { // IsMouseButtonDown - Detect if a mouse button is being pressed func IsMouseButtonDown(button MouseButton) bool { cbutton := (int32)(button) - ret := C.IsMouseButtonDown(cbutton) + ret := isMouseButtonDown(cbutton) v := bool(ret) return v } @@ -1055,7 +1120,7 @@ func IsMouseButtonDown(button MouseButton) bool { // IsMouseButtonReleased - Detect if a mouse button has been released once func IsMouseButtonReleased(button MouseButton) bool { cbutton := (int32)(button) - ret := C.IsMouseButtonReleased(cbutton) + ret := isMouseButtonReleased(cbutton) v := bool(ret) return v } @@ -1063,35 +1128,35 @@ func IsMouseButtonReleased(button MouseButton) bool { // IsMouseButtonUp - Detect if a mouse button is NOT being pressed func IsMouseButtonUp(button MouseButton) bool { cbutton := (int32)(button) - ret := C.IsMouseButtonUp(cbutton) + ret := isMouseButtonUp(cbutton) v := bool(ret) return v } // GetMouseX - Returns mouse position X func GetMouseX() int32 { - ret := C.GetMouseX() + ret := getMouseX() v := (int32)(ret) return v } // GetMouseY - Returns mouse position Y func GetMouseY() int32 { - ret := C.GetMouseY() + ret := getMouseY() v := (int32)(ret) return v } // GetMousePosition - Returns mouse position XY func GetMousePosition() Vector2 { - ret := C.GetMousePosition() + ret := getMousePosition() v := newVector2FromPointer(unsafe.Pointer(&ret)) return v } // GetMouseDelta - Get mouse delta between frames func GetMouseDelta() Vector2 { - ret := C.GetMouseDelta() + ret := getMouseDelta() v := newVector2FromPointer(unsafe.Pointer(&ret)) return v } @@ -1100,33 +1165,33 @@ func GetMouseDelta() Vector2 { func SetMousePosition(x, y int) { cx := (int32)(x) cy := (int32)(y) - C.SetMousePosition(cx, cy) + setMousePosition(cx, cy) } // SetMouseOffset - Set mouse offset func SetMouseOffset(offsetX, offsetY int) { ox := (int32)(offsetX) oy := (int32)(offsetY) - C.SetMouseOffset(ox, oy) + setMouseOffset(ox, oy) } // SetMouseScale - Set mouse scaling func SetMouseScale(scaleX, scaleY float32) { - cscaleX := (C.float)(scaleX) - cscaleY := (C.float)(scaleY) - C.SetMouseScale(cscaleX, cscaleY) + cscaleX := (float)(scaleX) + cscaleY := (float)(scaleY) + setMouseScale(cscaleX, cscaleY) } // GetMouseWheelMove - Get mouse wheel movement for X or Y, whichever is larger func GetMouseWheelMove() float32 { - ret := C.GetMouseWheelMove() + ret := getMouseWheelMove() v := (float32)(ret) return v } // GetMouseWheelMoveV - Get mouse wheel movement for both X and Y func GetMouseWheelMoveV() Vector2 { - ret := C.GetMouseWheelMoveV() + ret := getMouseWheelMoveV() v := newVector2FromPointer(unsafe.Pointer(&ret)) return v } @@ -1134,19 +1199,19 @@ func GetMouseWheelMoveV() Vector2 { // SetMouseCursor - Set mouse cursor func SetMouseCursor(cursor int32) { ccursor := (int32)(cursor) - C.SetMouseCursor(ccursor) + setMouseCursor(ccursor) } // GetTouchX - Returns touch position X for touch point 0 (relative to screen size) func GetTouchX() int32 { - ret := C.GetTouchX() + ret := getTouchX() v := (int32)(ret) return v } // GetTouchY - Returns touch position Y for touch point 0 (relative to screen size) func GetTouchY() int32 { - ret := C.GetTouchY() + ret := getTouchY() v := (int32)(ret) return v } @@ -1154,7 +1219,7 @@ func GetTouchY() int32 { // GetTouchPosition - Returns touch position XY for a touch point index (relative to screen size) func GetTouchPosition(index int32) Vector2 { cindex := (int32)(index) - ret := C.GetTouchPosition(cindex) + ret := getTouchPosition(cindex) v := newVector2FromPointer(unsafe.Pointer(&ret)) return v } @@ -1162,36 +1227,36 @@ func GetTouchPosition(index int32) Vector2 { // GetTouchPointId - Get touch point identifier for given index func GetTouchPointId(index int32) int32 { cindex := (int32)(index) - ret := C.GetTouchPointId(cindex) + ret := getTouchPointId(cindex) v := (int32)(ret) return v } // GetTouchPointCount - Get number of touch points func GetTouchPointCount() int32 { - ret := C.GetTouchPointCount() + ret := getTouchPointCount() v := (int32)(ret) return v } // BeginVrStereoMode - Begin stereo rendering (requires VR simulator) func BeginVrStereoMode(config VrStereoConfig) { - C.BeginVrStereoMode(*(*C.VrStereoConfig)(unsafe.Pointer(&config))) + beginVrStereoMode(*(*vrStereoConfig)(unsafe.Pointer(&config))) } // EndVrStereoMode - End stereo rendering (requires VR simulator) func EndVrStereoMode() { - C.EndVrStereoMode() + endVrStereoMode() } // LoadVrStereoConfig - Load VR stereo config for VR simulator device parameters func LoadVrStereoConfig(device VrDeviceInfo) VrStereoConfig { - ret := C.LoadVrStereoConfig(*(*C.VrDeviceInfo)(unsafe.Pointer(&device))) + ret := loadVrStereoConfig(*(*vrDeviceInfo)(unsafe.Pointer(&device))) return *(*VrStereoConfig)(unsafe.Pointer(&ret)) } // UnloadVrStereoConfig - Unload VR stereo config func UnloadVrStereoConfig(config VrStereoConfig) { - C.UnloadVrStereoConfig(*(*C.VrStereoConfig)(unsafe.Pointer(&config))) + unloadVrStereoConfig(*(*vrStereoConfig)(unsafe.Pointer(&config))) } */ diff --git a/raylib/wasm.go b/raylib/wasm.go index 4179f00..5c80d93 100644 --- a/raylib/wasm.go +++ b/raylib/wasm.go @@ -16,13 +16,18 @@ type cptr = uint32 //go:noescape func malloc(size cptr) cptr +// malloc the size of V +func mallocV[T any](V T) cptr { + return malloc(sizeof(V)) +} + // free memory allocated on raylib heap // //go:wasmimport raylib _free //go:noescape func free(cptr) -// copyToC copies a Go type/struct to C memory. Useful for copying slices and structs. +// _copyToC copies a Go type/struct to C memory. Useful for copying slices and structs. // // Destination C array must have enough space. // @@ -31,14 +36,14 @@ func free(cptr) // //go:wasmimport gojs CopyToC //go:noescape -func copyToC(dstCArray cptr, srcSize cptr, Value any) +func _copyToC(Value unsafe.Pointer, srcSize, dstCptr cptr) // copies C memory to a Go pointer. Useful for copying C structs into Go structs // // example usage: // // type Person struct{ -// Age string +// Age int32 // } // // var cPtrToPersonInCHeap cptr = ... @@ -50,61 +55,72 @@ func copyToC(dstCArray cptr, srcSize cptr, Value any) // //go:wasmimport gojs CopyToGo //go:noescape -func copyToGo(dstGoPtr unsafe.Pointer, size cptr, src cptr) +func _copyToGo(dstGoPtr unsafe.Pointer, size cptr, src cptr) // The alocated C string lives on the raylib heap and must be free()'d // //go:wasmimport gojs CStringFromGoString //go:noescape -func cStringFromGoString(string) cptr +func cString(string) cptr -// allocValueInC allocates a copy of a concrete type (not a slice) in C memory and returns a cptr to it. -// -// NOTE: v cannot be a pointer +// Scan for null terminator and return length excluding the null terminator. // -// NOTE: For slices use [allocSliceInC] -func allocValueInC[T any](Value T) cptr { - size := cptr(unsafe.Sizeof(Value)) - // allocate C array to hold Value - ptr := malloc(size) - copyToC(ptr, size, Value) - return ptr +//go:wasmimport gojs CStringGetLength +//go:noescape +func _cStringGetLength(cstr cptr) cptr + +// Copies a C string to Go memory without freeing the C string. +func goString(cstr cptr) string { + size := _cStringGetLength(cstr) + dstStr := make([]byte, size) + copySliceToGo(cstr, dstStr) + return string(dstStr) +} + +// copyValueToC copies a value to C and returns a pointer to it. +// +// NOTE: Value cannot be a slice. For a slice, use [copySliceToC] +func copyValueToC[T any](srcValue T) cptr { + size := sizeof(srcValue) + dst := malloc(size) + _copyToC(unsafe.Pointer(&srcValue), size, dst) + return dst } -// allocValueInC allocates a copy of a slice in C memory and returns a cptr to it. +// copySliceToC allocates a copy of a slice in C memory and returns a cptr to it. // // NOTE: Value MUST be a slice -// -// NOTE: For slices use [allocSliceInC] -func allocSliceInC[Slice ~[]E, E any](s Slice) cptr { +func copySliceToC[Slice ~[]E, E any](s Slice) cptr { // size of the slice's underlying array in bytes sliceSize := cptr(unsafe.Sizeof(s[0])) * cptr(len(s)) // allocate C array to hold Value - ptr := malloc(sliceSize) + dstCptr := malloc(sliceSize) // copy underlying array memory to C - copyToC(ptr, sliceSize, unsafe.SliceData(s)) - return ptr + _copyToC(unsafe.Pointer(unsafe.SliceData(s)), sliceSize, dstCptr) + return dstCptr } // copyValueToGo copies a value from C memory to Go memory. // Useful for copying structs // -// NOTE: Slices are not supported. Use [copyArrayToGo] -func copyValueToGo[T any](srcPtr cptr) T { - var value T - size := cptr(unsafe.Sizeof(value)) - copyToGo(unsafe.Pointer(&value), size, srcPtr) - return value +// NOTE: Slices are not supported. Use [copySliceToGo] +func copyValueToGo[T any](src cptr, dst *T) { + size := sizeof(*dst) + _copyToGo(unsafe.Pointer(dst), size, src) } -// copyArrayToGo copies a C array into a Go Slice. +// copySliceToGo copies a C array into a Go Slice. // // It copies bytes to the underlying array of the slice. -func copyArrayToGo[Slice ~[]E, E any](s Slice, srcPtr cptr) { +func copySliceToGo[Slice ~[]E, E any](src cptr, dst Slice) { // size of underlying array - size := cptr(unsafe.Sizeof(s[0])) * cptr(len(s)) - dstPtr := unsafe.SliceData(s) - copyToGo(unsafe.Pointer(dstPtr), size, srcPtr) + var occupiedSize = len(dst) + if occupiedSize == 0 { + occupiedSize = cap(dst) + } + size := cptr(unsafe.Sizeof(dst[0])) * cptr(occupiedSize) + dstPtr := unsafe.SliceData(dst) + _copyToGo(unsafe.Pointer(dstPtr), size, src) } //go:wasmimport gojs Alert @@ -112,6 +128,7 @@ func copyArrayToGo[Slice ~[]E, E any](s Slice, srcPtr cptr) { func alert(string) // Use this instead of a for loop on web platform +// Everything that you would do inside the for-loop must be done inside UpdateAndDrawFrame func SetMain(UpdateAndDrawFrame func()) { var updateLoop js.Func updateLoop = js.FuncOf(func(this js.Value, args []js.Value) any { @@ -121,3 +138,6 @@ func SetMain(UpdateAndDrawFrame func()) { }) js.Global().Call("requestAnimationFrame", updateLoop) } + +// return sizeof of v in bytes +func sizeof[T any](v T) cptr { return cptr(unsafe.Sizeof(v)) } diff --git a/raylib/wasm_test.go b/raylib/wasm_test.go new file mode 100644 index 0000000..3fefffb --- /dev/null +++ b/raylib/wasm_test.go @@ -0,0 +1,117 @@ +//go:build js + +package rl + +import ( + "reflect" + "testing" +) + +// Test copyValueToC + copyValueToGo round-trip for a struct and for a primitive. +func TestCopyValueToCAndBack(t *testing.T) { + type Person struct { + Age int32 + Score float32 + } + + original := Person{Age: 42, Score: 3.14} + // copy struct to C + cptr := copyValueToC(original) + if cptr == 0 { + t.Fatalf("copyValueToC returned null pointer") + } + // ensure we free at the end + defer free(cptr) + + var got Person + copyValueToGo(cptr, &got) + + if !reflect.DeepEqual(original, got) { + t.Fatalf("person round-trip mismatch: want %+v, got %+v", original, got) + } + + // test primitive type (int64) + var originalInt int64 = -1234567890 + cptr2 := copyValueToC(originalInt) + if cptr2 == 0 { + t.Fatalf("copyValueToC returned null pointer for primitive") + } + defer free(cptr2) + + var gotInt int64 + copyValueToGo(cptr2, &gotInt) + if originalInt != gotInt { + t.Fatalf("primitive round-trip mismatch: want %d, got %d", originalInt, gotInt) + } +} + +// Test copySliceToC + copySliceToGo round-trip for a byte slice and for an int slice. +func TestCopySliceToCAndBack(t *testing.T) { + // byte slice + origBytes := []byte("hello, raylib wasm") + cptr := copySliceToC(origBytes) + if cptr == 0 { + t.Fatalf("copySliceToC returned null pointer for bytes") + } + defer free(cptr) + + dstBytes := make([]byte, len(origBytes)) + copySliceToGo(cptr, dstBytes) + if !reflect.DeepEqual(origBytes, dstBytes) { + t.Fatalf("byte slice round-trip mismatch: want %v, got %v", origBytes, dstBytes) + } + + // int slice + origInts := []int32{1, 2, 3, 4, 5} + cptrInts := copySliceToC(origInts) + if cptrInts == 0 { + t.Fatalf("copySliceToC returned null pointer for ints") + } + defer free(cptrInts) + + dstInts := make([]int32, len(origInts)) + copySliceToGo(cptrInts, dstInts) + if !reflect.DeepEqual(origInts, dstInts) { + t.Fatalf("int slice round-trip mismatch: want %v, got %v", origInts, dstInts) + } +} + +// Test copySliceToGo behavior when dst has len==0 but cap>0. +// The function should copy into the underlying array (up to cap). +func TestCopySliceToGoCopiesToUnderlyingArrayWhenLenZero(t *testing.T) { + orig := []int32{10, 20, 30} + cptr := copySliceToC(orig) + if cptr == 0 { + t.Fatalf("copySliceToC returned null pointer") + } + defer free(cptr) + + // dst has length 0 but capacity 3 + dst := make([]int32, 0, 3) + // perform copy; after this the content should be in dst[:cap(dst)] + copySliceToGo(cptr, dst) + + // inspect underlying array by slicing up to capacity + gotUnderlying := dst[:cap(dst)] + if !reflect.DeepEqual(orig, gotUnderlying) { + t.Fatalf("underlying array mismatch: want %v, got %v", orig, gotUnderlying) + } +} + +// Test goString - constructs a C string via cString (wasm import) and reads it back via goString. +// Note: this test relies on cString and _cStringGetLength being available in the environment. +func TestGoString(t *testing.T) { + const s = "testing goString 🚀" + cstr := cString(s) + if cstr == 0 { + t.Fatalf("cString returned null pointer") + } + // cString allocates on raylib heap; free after test + defer free(cstr) + + got := goString(cstr) + if got != s { + t.Fatalf("goString returned %q, want %q", got, s) + } +} + From 15248ae342d9592f1ef5e8b5322951240ee84b9f Mon Sep 17 00:00:00 2001 From: BrownNPC Date: Sat, 31 Jan 2026 10:06:35 +0500 Subject: [PATCH 06/12] more bindings --- examples/messingAround/main.go | 5 +- raylib/raylib.go | 29 +-- raylib/rcore_wasm.go | 415 +++++++++++++++++++++------------ raylib/wasm.go | 22 +- wakatime.log | 65 ++++++ 5 files changed, 371 insertions(+), 165 deletions(-) create mode 100644 wakatime.log diff --git a/examples/messingAround/main.go b/examples/messingAround/main.go index b960f37..4eb27cf 100644 --- a/examples/messingAround/main.go +++ b/examples/messingAround/main.go @@ -5,5 +5,8 @@ package main import rl "github.com/gen2brain/raylib-go/raylib" func main() { - rl.InitWindow(0,0,"Hello WASM") + rl.SetMain(func() { + rl.BeginDrawing() + rl.EndDrawing() + }) } diff --git a/raylib/raylib.go b/raylib/raylib.go index ea91f1b..d405426 100644 --- a/raylib/raylib.go +++ b/raylib/raylib.go @@ -33,7 +33,7 @@ type Wave struct { // NewWave - Returns new Wave func NewWave(sampleCount, sampleRate, sampleSize, channels uint32, data []byte) Wave { - ptr := copySliceToC(data) + ptr, _ := copySliceToC(data) return Wave{ FrameCount: sampleCount, SampleRate: sampleRate, @@ -1098,28 +1098,31 @@ type Shader struct { // Shader program id ID uint32 // Shader locations array - Locs *int32 + Locs cptr __ structs.HostLayout } // NewShader - Returns new Shader func NewShader(id uint32, locs *int32) Shader { return Shader{ - ID: id, - Locs: locs, - __: structs.HostLayout{}, + ID: id, + __: structs.HostLayout{}, } } -// // GetLocation - Get shader value's location -// func (sh Shader) GetLocation(index int32) int32 { -// return *(*int32)(cptr(uintptr(cptr(sh.Locs)) + uintptr(index*4))) -// } +// GetLocation - Get shader value's location +func (sh Shader) GetLocation(index int32) int32 { + var v int32 + locAddr := sh.Locs + cptr(index)*4 + copyValueToGo(locAddr, &v) + return v +} -// // UpdateLocation - Update shader value's location -// func (sh Shader) UpdateLocation(index int32, loc int32) { -// *(*int32)(cptr(uintptr(cptr(sh.Locs)) + uintptr(index*4))) = loc -// } +// UpdateLocation - Update shader value's location +func (sh Shader) UpdateLocation(index int32, loc int32) { + locAddr := sh.Locs * cptr(index) * 4 + copyToC(&loc, locAddr) +} // GlyphInfo - Font character info type GlyphInfo struct { diff --git a/raylib/rcore_wasm.go b/raylib/rcore_wasm.go index dcbc090..78b7ba5 100644 --- a/raylib/rcore_wasm.go +++ b/raylib/rcore_wasm.go @@ -3,6 +3,7 @@ package rl import ( + "image/color" "syscall/js" "unsafe" ) @@ -300,8 +301,8 @@ func GetMonitorPosition(monitor int) Vector2 { var v Vector2 cmonitor := (int32)(monitor) - ret := mallocV(v) - defer free(ret) + ret, f := mallocV(v) + defer f() getMonitorPosition(ret, cmonitor) copyValueToGo(ret, &v) return v @@ -375,8 +376,8 @@ func getWindowPosition(vector2 cptr) // GetWindowPosition - Get window position XY on monitor func GetWindowPosition() Vector2 { var v Vector2 - ret := mallocV(v) - defer free(ret) + ret, f := mallocV(v) + defer f() getWindowPosition(ret) copyValueToGo(ret, &v) return v @@ -389,8 +390,8 @@ func getWindowScaleDPI(vector2 cptr) // GetWindowScaleDPI - Get window scale DPI factor func GetWindowScaleDPI() Vector2 { var v Vector2 - ret := mallocV(v) - defer free(ret) + ret, f := mallocV(v) + defer f() getWindowScaleDPI(ret) copyValueToGo(ret, &v) return v @@ -399,220 +400,313 @@ func GetWindowScaleDPI() Vector2 { // GetMonitorName - Get the human-readable, UTF-8 encoded name of the primary monitor func GetMonitorName(monitor int) string { return "" } -// SetClipboardText - Set clipboard text content -// //go:wasmimport raylib _SetClipboardText //go:noescape func setClipboardText(data cptr) + +// SetClipboardText - Set clipboard text content func SetClipboardText(data string) { cdata := cString(data) defer free(cdata) setClipboardText(cdata) } -/* +//go:wasmimport raylib _GetClipboardText +//go:noescape +func getClipboardText() cptr + // GetClipboardText - Get clipboard text content func GetClipboardText() string { ret := getClipboardText() + defer free(ret) v := goString(ret) return v } +//go:wasmimport raylib _GetClipboardImage +//go:noescape +func getClipboardImage(img cptr) + // GetClipboardImage - Get clipboard image content // // Only works with SDL3 backend or Windows with GLFW/RGFW func GetClipboardImage() Image { - ret := getClipboardImage() - v := newImageFromPointer(unsafe.Pointer(&ret)) - return *v + var v Image + ret, f := mallocV(v) + defer f() + getClipboardImage(ret) + copyValueToGo(ret, &v) + return v } // EnableEventWaiting - Enable waiting for events on EndDrawing(), no automatic event polling -func EnableEventWaiting() { - enableEventWaiting() -} +// +//go:wasmimport raylib _EnableEventWaiting +//go:noescape +func EnableEventWaiting() // DisableEventWaiting - Disable waiting for events on EndDrawing(), automatic events polling -func DisableEventWaiting() { - disableEventWaiting() -} +// +//go:wasmimport raylib _DisableEventWaiting +//go:noescape +func DisableEventWaiting() + +//go:wasmimport raylib _ClearBackground +//go:noescape +func clearBackground(col cptr) // ClearBackground - Sets Background Color func ClearBackground(col color.RGBA) { - ccolor := colorCptr(col) - clearBackground(*ccolor) + ccolor, f := copyValueToC(col) + defer f() + clearBackground(ccolor) } // BeginDrawing - Setup drawing canvas to start drawing -func BeginDrawing() { - beginDrawing() -} +// +//go:wasmimport raylib _BeginDrawing +//go:noescape +func BeginDrawing() // EndDrawing - End canvas drawing and Swap Buffers (Double Buffering) -func EndDrawing() { - endDrawing() -} +// +//go:wasmimport raylib _EndDrawing +//go:noescape +func EndDrawing() + +//go:wasmimport raylib _BeginMode2D +//go:noescape +func beginMode2D(camera cptr) // BeginMode2D - Initialize 2D mode with custom camera func BeginMode2D(camera Camera2D) { - ccamera := camera.cptr() - beginMode2D(*ccamera) + ccamera, f := copyValueToC(camera) + defer f() + beginMode2D(ccamera) } // EndMode2D - Ends 2D mode custom camera usage -func EndMode2D() { - endMode2D() -} +// +//go:wasmimport raylib _EndMode2D +//go:noescape +func EndMode2D() + +//go:wasmimport raylib _BeginMode3D +//go:noescape +func beginMode3D(camera cptr) // BeginMode3D - Initializes 3D mode for drawing (Camera setup) func BeginMode3D(camera Camera) { - ccamera := camera.cptr() - beginMode3D(*ccamera) + c, f := copyValueToC(camera) + defer f() + beginMode3D(c) } // EndMode3D - Ends 3D mode and returns to default 2D orthographic mode -func EndMode3D() { - endMode3D() -} +// +//go:wasmimport raylib _EndMode3D +//go:noescape +func EndMode3D() + +//go:wasmimport raylib _BeginTextureMode +//go:noescape +func beginTextureMode(target cptr) // BeginTextureMode - Initializes render texture for drawing func BeginTextureMode(target RenderTexture2D) { - ctarget := target.cptr() - beginTextureMode(*ctarget) + c, f := copyValueToC(target) + defer f() + beginTextureMode(c) } // EndTextureMode - Ends drawing to render texture -func EndTextureMode() { - endTextureMode() -} +// +//go:wasmimport raylib _EndTextureMode +//go:noescape +func EndTextureMode() // BeginScissorMode - Begins scissor mode (define screen area for following drawing) -func BeginScissorMode(x, y, width, height int32) { - cx := (int32)(x) - cy := (int32)(y) - cwidth := (int32)(width) - cheight := (int32)(height) - beginScissorMode(cx, cy, cwidth, cheight) -} +// +//go:wasmimport raylib _BeginScissorMode +//go:noescape +func BeginScissorMode(x, y, width, height int32) // EndScissorMode - Ends scissor mode -func EndScissorMode() { - endScissorMode() -} +// +//go:wasmimport raylib _EndScissorMode +//go:noescape +func EndScissorMode() + +// LoadShader - Load a custom shader and bind default locations +// +//go:wasmimport raylib _LoadShader +//go:noescape +func loadShader(shader, vsFileName cptr, fsFileName cptr) // LoadShader - Load a custom shader and bind default locations func LoadShader(vsFileName string, fsFileName string) Shader { cvsFileName := cString(vsFileName) - defer free(unsafe.Pointer(cvsFileName)) + defer free(cvsFileName) cfsFileName := cString(fsFileName) - defer free(unsafe.Pointer(cfsFileName)) - - if vsFileName == "" { - cvsFileName = nil - } - - if fsFileName == "" { - cfsFileName = nil - } - - ret := loadShader(cvsFileName, cfsFileName) - v := newShaderFromPointer(unsafe.Pointer(&ret)) + defer free(cfsFileName) + var v Shader + ret, f := mallocV(v) + defer f() + loadShader(ret, cvsFileName, cfsFileName) + copyValueToGo(ret, &v) return v } +// LoadShaderFromMemory - Load shader from code strings and bind default locations +// +//go:wasmimport raylib _LoadShaderFromMemory +//go:noescape +func loadShaderFromMemory(shader, vsCode cptr, fsCode cptr) + // LoadShaderFromMemory - Load shader from code strings and bind default locations func LoadShaderFromMemory(vsCode string, fsCode string) Shader { cvsCode := cString(vsCode) - defer free(unsafe.Pointer(cvsCode)) + defer free(cvsCode) cfsCode := cString(fsCode) - defer free(unsafe.Pointer(cfsCode)) - - if vsCode == "" { - cvsCode = nil - } - - if fsCode == "" { - cfsCode = nil - } - - ret := loadShaderFromMemory(cvsCode, cfsCode) - v := newShaderFromPointer(unsafe.Pointer(&ret)) + defer free(cfsCode) + var v Shader + ret, f := mallocV(v) + defer f() + loadShaderFromMemory(ret, cvsCode, cfsCode) + copyValueToGo(ret, &v) return v } +// IsShaderValid - Check if a shader is valid (loaded on GPU) +// +//go:wasmimport raylib _IsShaderValid +//go:noescape +func isShaderValid(shader cptr) bool + // IsShaderValid - Check if a shader is valid (loaded on GPU) func IsShaderValid(shader Shader) bool { - cshader := shader.cptr() - ret := isShaderValid(*cshader) - v := bool(ret) + c, f := copyValueToC(shader) + defer f() + v := isShaderValid(c) return v } +// GetShaderLocation - Get shader uniform location +// +//go:wasmimport raylib _GetShaderLocation +//go:noescape +func getShaderLocation(shader cptr, uniformName cptr) int32 + // GetShaderLocation - Get shader uniform location func GetShaderLocation(shader Shader, uniformName string) int32 { - cshader := shader.cptr() + cshader, f := copyValueToC(shader) + defer f() + cuniformName := cString(uniformName) - defer free(unsafe.Pointer(cuniformName)) + defer free(cuniformName) - ret := getShaderLocation(*cshader, cuniformName) - v := (int32)(ret) + v := getShaderLocation(cshader, cuniformName) return v } +// GetShaderLocationAttrib - Get shader attribute location +// +//go:wasmimport raylib _GetShaderLocationAttrib +//go:noescape +func getShaderLocationAttrib(shader cptr, attribName cptr) int32 + // GetShaderLocationAttrib - Get shader attribute location func GetShaderLocationAttrib(shader Shader, attribName string) int32 { - cshader := shader.cptr() + cshader, f := copyValueToC(shader) + defer f() cuniformName := cString(attribName) - defer free(unsafe.Pointer(cuniformName)) - - ret := getShaderLocationAttrib(*cshader, cuniformName) - v := (int32)(ret) - return v + defer free(cuniformName) + return getShaderLocationAttrib(cshader, cuniformName) } +// SetShaderValue - Set shader uniform value (float) +// +//go:wasmimport raylib _SetShaderValue +//go:noescape +func setShaderValue(shader cptr, locIndex int32, value cptr, uniformType ShaderUniformDataType) + // SetShaderValue - Set shader uniform value (float) func SetShaderValue(shader Shader, locIndex int32, value []float32, uniformType ShaderUniformDataType) { - cshader := shader.cptr() + cshader, f := copyValueToC(shader) + defer f() clocIndex := (int32)(locIndex) - cvalue := (*float)(unsafe.Pointer(&value[0])) + cvalue, f := copySliceToC(value) + defer f() cuniformType := (int32)(uniformType) - setShaderValue(*cshader, clocIndex, unsafe.Pointer(cvalue), cuniformType) + setShaderValue(cshader, clocIndex, cvalue, cuniformType) } +// SetShaderValueV - Set shader uniform value (float) +// +//go:wasmimport raylib _SetShaderValueV +//go:noescape +func setShaderValueV(shader cptr, locIndex int32, value cptr, uniformType ShaderUniformDataType, count int32) + // SetShaderValueV - Set shader uniform value (float) func SetShaderValueV(shader Shader, locIndex int32, value []float32, uniformType ShaderUniformDataType, count int32) { - cshader := shader.cptr() + cshader, f := copyValueToC(shader) + defer f() clocIndex := (int32)(locIndex) - cvalue := (*float)(unsafe.Pointer(&value[0])) + cvalue, f := copySliceToC(value) + defer f() cuniformType := (int32)(uniformType) ccount := (int32)(count) - setShaderValueV(*cshader, clocIndex, unsafe.Pointer(cvalue), cuniformType, ccount) + setShaderValueV(cshader, clocIndex, cvalue, cuniformType, ccount) } +// SetShaderValueMatrix - Set shader uniform value (matrix 4x4) +// +//go:wasmimport raylib _SetShaderValueMatrix +//go:noescape +func setShaderValueMatrix(shader cptr, locIndex int32, mat cptr) + // SetShaderValueMatrix - Set shader uniform value (matrix 4x4) func SetShaderValueMatrix(shader Shader, locIndex int32, mat Matrix) { - cshader := shader.cptr() + cshader, f := copyValueToC(shader) + defer f() clocIndex := (int32)(locIndex) - cmat := mat.cptr() - setShaderValueMatrix(*cshader, clocIndex, *cmat) + cmat, f := copyValueToC(mat) + defer f() + setShaderValueMatrix(cshader, clocIndex, cmat) } +// SetShaderValueTexture - Set shader uniform value for texture (sampler2d) +// +//go:wasmimport raylib _SetShaderValueTexture +//go:noescape +func setShaderValueTexture(shader cptr, locIndex int32, texture cptr) + // SetShaderValueTexture - Set shader uniform value for texture (sampler2d) func SetShaderValueTexture(shader Shader, locIndex int32, texture Texture2D) { - cshader := shader.cptr() + cshader, f := copyValueToC(shader) + defer f() clocIndex := (int32)(locIndex) - ctexture := texture.cptr() - setShaderValueTexture(*cshader, clocIndex, *ctexture) + ctexture, f := copyValueToC(texture) + defer f() + setShaderValueTexture(cshader, clocIndex, ctexture) } +// UnloadShader - Unload a custom shader from memory +// +//go:wasmimport raylib _UnloadShader +//go:noescape +func unloadShader(shader cptr) + // UnloadShader - Unload a custom shader from memory func UnloadShader(shader Shader) { - cshader := shader.cptr() - unloadShader(*cshader) + + cshader, f := copyValueToC(shader) + defer f() + unloadShader(cshader) } // GetMouseRay - Get a ray trace from mouse position @@ -622,39 +716,72 @@ func GetMouseRay(mousePosition Vector2, camera Camera) Ray { return GetScreenToWorldRay(mousePosition, camera) } +// GetScreenToWorldRay - Get a ray trace from screen position (i.e mouse) +// +//go:wasmimport raylib _GetScreenToWorldRay +//go:noescape +func getScreenToWorldRay(ray cptr, position cptr, camera cptr) + // GetScreenToWorldRay - Get a ray trace from screen position (i.e mouse) func GetScreenToWorldRay(position Vector2, camera Camera) Ray { - cposition := position.cptr() - ccamera := camera.cptr() - ret := getScreenToWorldRay(*cposition, *ccamera) - v := newRayFromPointer(unsafe.Pointer(&ret)) + cposition, f := copyValueToC(position) + defer f() + ccamera, f := copyValueToC(camera) + defer f() + var v Ray + ret, f := mallocV(v) + defer f() + getScreenToWorldRay(ret, cposition, ccamera) + copyValueToGo(ret, &v) return v } +// GetScreenToWorldRayEx - Get a ray trace from screen position (i.e mouse) in a viewport +// +//go:wasmimport raylib _GetScreenToWorldRayEx +//go:noescape +func getScreenToWorldRayEx(ray cptr, position cptr, camera cptr, width, height int32) + // GetScreenToWorldRayEx - Get a ray trace from screen position (i.e mouse) in a viewport func GetScreenToWorldRayEx(position Vector2, camera Camera, width, height int32) Ray { - cposition := position.cptr() - ccamera := camera.cptr() + cposition, f := copyValueToC(position) + defer f() + ccamera, f := copyValueToC(camera) cwidth := (int32)(width) cheight := (int32)(height) - ret := getScreenToWorldRayEx(*cposition, *ccamera, cwidth, cheight) - v := newRayFromPointer(unsafe.Pointer(&ret)) + var v Ray + ret, f := mallocV(v) + defer f() + getScreenToWorldRayEx(ret, cposition, ccamera, cwidth, cheight) + copyValueToGo(ret, &v) return v } +// GetCameraMatrix - Returns camera transform matrix (view matrix) +// +//go:wasmimport raylib _GetCameraMatrix +//go:noescape +func getCameraMatrix(mat cptr, camera cptr) + // GetCameraMatrix - Returns camera transform matrix (view matrix) func GetCameraMatrix(camera Camera) Matrix { - ccamera := camera.cptr() - ret := getCameraMatrix(*ccamera) - v := newMatrixFromPointer(unsafe.Pointer(&ret)) + ccamera, f := copyValueToC(camera) + defer f() + var v Matrix + ret, f := mallocV(v) + defer f() + + getCameraMatrix(ret, ccamera) + copyValueToGo(ret, &v) return v } +/* // GetCameraMatrix2D - Returns camera 2d transform matrix func GetCameraMatrix2D(camera Camera2D) Matrix { ccamera := camera.cptr() ret := getCameraMatrix2D(*ccamera) - v := newMatrixFromPointer(unsafe.Pointer(&ret)) + v := newMatrixFromPointer(&ret) return v } @@ -663,7 +790,7 @@ func GetWorldToScreen(position Vector3, camera Camera) Vector2 { cposition := position.cptr() ccamera := camera.cptr() ret := getWorldToScreen(*cposition, *ccamera) - v := newVector2FromPointer(unsafe.Pointer(&ret)) + v := newVector2FromPointer(&ret) return v } @@ -672,7 +799,7 @@ func GetScreenToWorld2D(position Vector2, camera Camera2D) Vector2 { cposition := position.cptr() ccamera := camera.cptr() ret := getScreenToWorld2D(*cposition, *ccamera) - v := newVector2FromPointer(unsafe.Pointer(&ret)) + v := newVector2FromPointer(&ret) return v } @@ -683,7 +810,7 @@ func GetWorldToScreenEx(position Vector3, camera Camera, width int32, height int cwidth := (int32)(width) cheight := (int32)(height) ret := getWorldToScreenEx(*cposition, *ccamera, cwidth, cheight) - v := newVector2FromPointer(unsafe.Pointer(&ret)) + v := newVector2FromPointer(&ret) return v } @@ -692,7 +819,7 @@ func GetWorldToScreen2D(position Vector2, camera Camera2D) Vector2 { cposition := position.cptr() ccamera := camera.cptr() ret := getWorldToScreen2D(*cposition, *ccamera) - v := newVector2FromPointer(unsafe.Pointer(&ret)) + v := newVector2FromPointer(&ret) return v } @@ -750,7 +877,7 @@ func Fade(col color.RGBA, alpha float32) color.RGBA { ccolor := colorCptr(col) calpha := (float)(alpha) ret := fade(*ccolor, calpha) - v := newColorFromPointer(unsafe.Pointer(&ret)) + v := newColorFromPointer(&ret) return v } @@ -778,7 +905,7 @@ func ColorNormalize(col color.RGBA) Vector4 { func ColorFromNormalized(normalized Vector4) color.RGBA { cnormalized := normalized.cptr() ret := colorFromNormalized(*cnormalized) - v := newColorFromPointer(unsafe.Pointer(&ret)) + v := newColorFromPointer(&ret) return v } @@ -786,7 +913,7 @@ func ColorFromNormalized(normalized Vector4) color.RGBA { func ColorToHSV(col color.RGBA) Vector3 { ccolor := colorCptr(col) ret := colorToHSV(*ccolor) - v := newVector3FromPointer(unsafe.Pointer(&ret)) + v := newVector3FromPointer(&ret) return v } @@ -796,7 +923,7 @@ func ColorFromHSV(hue, saturation, value float32) color.RGBA { csaturation := (float)(saturation) cvalue := (float)(value) ret := colorFromHSV(chue, csaturation, cvalue) - v := newColorFromPointer(unsafe.Pointer(&ret)) + v := newColorFromPointer(&ret) return v } @@ -805,7 +932,7 @@ func ColorTint(col color.RGBA, tint color.RGBA) color.RGBA { ccolor := colorCptr(col) ctint := colorCptr(tint) ret := colorTint(*ccolor, *ctint) - v := newColorFromPointer(unsafe.Pointer(&ret)) + v := newColorFromPointer(&ret) return v } @@ -814,7 +941,7 @@ func ColorBrightness(col color.RGBA, factor float32) color.RGBA { ccolor := colorCptr(col) cfactor := float(factor) ret := colorBrightness(*ccolor, cfactor) - v := newColorFromPointer(unsafe.Pointer(&ret)) + v := newColorFromPointer(&ret) return v } @@ -823,7 +950,7 @@ func ColorContrast(col color.RGBA, contrast float32) color.RGBA { ccolor := colorCptr(col) ccontrast := float(contrast) ret := colorContrast(*ccolor, ccontrast) - v := newColorFromPointer(unsafe.Pointer(&ret)) + v := newColorFromPointer(&ret) return v } @@ -838,7 +965,7 @@ func ColorAlphaBlend(src, dst, tint color.RGBA) color.RGBA { cdst := colorCptr(dst) ctint := colorCptr(tint) ret := colorAlphaBlend(*csrc, *cdst, *ctint) - v := newColorFromPointer(unsafe.Pointer(&ret)) + v := newColorFromPointer(&ret) return v } @@ -847,7 +974,7 @@ func ColorLerp(col1, col2 color.RGBA, factor float32) color.RGBA { ccol1 := colorCptr(col1) ccol2 := colorCptr(col2) ret := colorLerp(*ccol1, *ccol2, float(factor)) - v := newColorFromPointer(unsafe.Pointer(&ret)) + v := newColorFromPointer(&ret) return v } @@ -855,7 +982,7 @@ func ColorLerp(col1, col2 color.RGBA, factor float32) color.RGBA { func GetColor(hexValue uint) color.RGBA { chexValue := (uint)(hexValue) ret := getColor(chexValue) - v := newColorFromPointer(unsafe.Pointer(&ret)) + v := newColorFromPointer(&ret) return v } @@ -881,7 +1008,7 @@ func GetRandomValue(min, max int32) int32 { // OpenURL - Open URL with default system browser (if available) func OpenURL(url string) { curl := cString(url) - defer free(unsafe.Pointer(curl)) + defer free(curl) openURL(curl) } @@ -894,17 +1021,17 @@ func SetConfigFlags(flags uint32) { // TakeScreenshot - Takes a screenshot of current screen (saved a .png) func TakeScreenshot(name string) { cname := cString(name) - defer free(unsafe.Pointer(cname)) + defer free(cname) takeScreenshot(cname) } // LoadAutomationEventList - Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS func LoadAutomationEventList(fileName string) AutomationEventList { cfileName := cString(fileName) - defer free(unsafe.Pointer(cfileName)) + defer free(cfileName) ret := loadAutomationEventList(cfileName) - v := newAutomationEventListFromPointer(unsafe.Pointer(&ret)) + v := newAutomationEventListFromPointer(&ret) return v } @@ -917,7 +1044,7 @@ func UnloadAutomationEventList(list *AutomationEventList) { // ExportAutomationEventList - Export automation events list as text file func ExportAutomationEventList(list AutomationEventList, fileName string) bool { cfileName := cString(fileName) - defer free(unsafe.Pointer(cfileName)) + defer free(cfileName) ret := exportAutomationEventList(*list.cptr(), cfileName) v := bool(ret) @@ -1090,7 +1217,7 @@ func GetGamepadAxisMovement(gamepad, axis int32) float32 { // SetGamepadMappings - Set internal gamepad mappings (SDL_GameControllerDB) func SetGamepadMappings(mappings string) int32 { cmappings := cString(mappings) - defer free(unsafe.Pointer(cmappings)) + defer free(cmappings) ret := setGamepadMappings(cmappings) v := (int32)(ret) return v @@ -1150,14 +1277,14 @@ func GetMouseY() int32 { // GetMousePosition - Returns mouse position XY func GetMousePosition() Vector2 { ret := getMousePosition() - v := newVector2FromPointer(unsafe.Pointer(&ret)) + v := newVector2FromPointer(&ret) return v } // GetMouseDelta - Get mouse delta between frames func GetMouseDelta() Vector2 { ret := getMouseDelta() - v := newVector2FromPointer(unsafe.Pointer(&ret)) + v := newVector2FromPointer(&ret) return v } @@ -1192,7 +1319,7 @@ func GetMouseWheelMove() float32 { // GetMouseWheelMoveV - Get mouse wheel movement for both X and Y func GetMouseWheelMoveV() Vector2 { ret := getMouseWheelMoveV() - v := newVector2FromPointer(unsafe.Pointer(&ret)) + v := newVector2FromPointer(&ret) return v } @@ -1220,7 +1347,7 @@ func GetTouchY() int32 { func GetTouchPosition(index int32) Vector2 { cindex := (int32)(index) ret := getTouchPosition(cindex) - v := newVector2FromPointer(unsafe.Pointer(&ret)) + v := newVector2FromPointer(&ret) return v } @@ -1241,7 +1368,7 @@ func GetTouchPointCount() int32 { // BeginVrStereoMode - Begin stereo rendering (requires VR simulator) func BeginVrStereoMode(config VrStereoConfig) { - beginVrStereoMode(*(*vrStereoConfig)(unsafe.Pointer(&config))) + beginVrStereoMode(*(*vrStereoConfig)(&config)) } // EndVrStereoMode - End stereo rendering (requires VR simulator) @@ -1251,12 +1378,12 @@ func EndVrStereoMode() { // LoadVrStereoConfig - Load VR stereo config for VR simulator device parameters func LoadVrStereoConfig(device VrDeviceInfo) VrStereoConfig { - ret := loadVrStereoConfig(*(*vrDeviceInfo)(unsafe.Pointer(&device))) - return *(*VrStereoConfig)(unsafe.Pointer(&ret)) + ret := loadVrStereoConfig(*(*vrDeviceInfo)(&device)) + return *(*VrStereoConfig)(&ret) } // UnloadVrStereoConfig - Unload VR stereo config func UnloadVrStereoConfig(config VrStereoConfig) { - unloadVrStereoConfig(*(*vrStereoConfig)(unsafe.Pointer(&config))) + unloadVrStereoConfig(*(*vrStereoConfig)(&config)) } */ diff --git a/raylib/wasm.go b/raylib/wasm.go index 5c80d93..2a43f3d 100644 --- a/raylib/wasm.go +++ b/raylib/wasm.go @@ -17,8 +17,9 @@ type cptr = uint32 func malloc(size cptr) cptr // malloc the size of V -func mallocV[T any](V T) cptr { - return malloc(sizeof(V)) +func mallocV[T any](V T) (cptr, func()) { + ptr := malloc(sizeof(V)) + return ptr, func() { free(ptr) } } // free memory allocated on raylib heap @@ -57,6 +58,12 @@ func _copyToC(Value unsafe.Pointer, srcSize, dstCptr cptr) //go:noescape func _copyToGo(dstGoPtr unsafe.Pointer, size cptr, src cptr) +// Copies the src value to the dst cptr +func copyToC[T any](src *T, dst cptr) { + size := sizeof(src) + _copyToC(unsafe.Pointer(src), size, dst) +} + // The alocated C string lives on the raylib heap and must be free()'d // //go:wasmimport gojs CStringFromGoString @@ -80,24 +87,24 @@ func goString(cstr cptr) string { // copyValueToC copies a value to C and returns a pointer to it. // // NOTE: Value cannot be a slice. For a slice, use [copySliceToC] -func copyValueToC[T any](srcValue T) cptr { +func copyValueToC[T any](srcValue T) (cptr, func()) { size := sizeof(srcValue) dst := malloc(size) - _copyToC(unsafe.Pointer(&srcValue), size, dst) - return dst + copyToC(&srcValue, dst) + return dst, func() { free(dst) } } // copySliceToC allocates a copy of a slice in C memory and returns a cptr to it. // // NOTE: Value MUST be a slice -func copySliceToC[Slice ~[]E, E any](s Slice) cptr { +func copySliceToC[Slice ~[]E, E any](s Slice) (cptr, func()) { // size of the slice's underlying array in bytes sliceSize := cptr(unsafe.Sizeof(s[0])) * cptr(len(s)) // allocate C array to hold Value dstCptr := malloc(sliceSize) // copy underlying array memory to C _copyToC(unsafe.Pointer(unsafe.SliceData(s)), sliceSize, dstCptr) - return dstCptr + return dstCptr, func() { free(dstCptr) } } // copyValueToGo copies a value from C memory to Go memory. @@ -137,6 +144,7 @@ func SetMain(UpdateAndDrawFrame func()) { return nil }) js.Global().Call("requestAnimationFrame", updateLoop) + select {} } // return sizeof of v in bytes diff --git a/wakatime.log b/wakatime.log new file mode 100644 index 0000000..7b4a839 --- /dev/null +++ b/wakatime.log @@ -0,0 +1,65 @@ +Command line interface used by all WakaTime text editor plugins. + +Usage: + wakatime-cli [flags] + +Flags: + --ai-line-changes int Optional number of lines added or removed by AI since last heartbeat in the current file. + --alternate-branch string Optional alternate branch name. Auto-detected branch takes priority. + --alternate-language string Optional alternate language name. Auto-detected language takes priority. + --alternate-project string Optional alternate project name. Auto-detected project takes priority. + --api-url string API base url used when sending heartbeats and fetching code stats. Defaults to https://api.wakatime.com/api/v1/. + --category string Category of this heartbeat activity. Can be "coding", "ai coding", "building", "indexing", "debugging", "learning", "notes", "meeting", "planning", "researching", "communicating", "supporting", "advising", "running tests", "writing tests", "manual testing", "writing docs", "code reviewing", "browsing", "translating", or "designing". Defaults to "coding". + --config string Optional config file. Defaults to '~/.wakatime.cfg'. + --config-read string Prints value for the given config key, then exits. + --config-section string Optional config section when reading or writing a config key. Defaults to [settings]. (default "settings") + --config-write stringToString Writes value to a config key, then exits. Expects two arguments, key and value. (default []) + --cursorpos int Optional cursor position in the current file. + --disable-offline Disables offline time logging instead of queuing logged time. + --entity string Absolute path to file for the heartbeat. Can also be a url, domain or app when --entity-type is not file. + --entity-type string Entity type for this heartbeat. Can be "file", "domain", "url", or "app". Defaults to "file". + --exclude strings Filename patterns to exclude from logging. POSIX regex syntax. Can be used more than once. + --exclude-unknown-project When set, any activity where the project cannot be detected will be ignored. + --extra-heartbeats Reads extra heartbeats from STDIN as a JSON array until EOF. + --file-experts Prints the top developer within a team for the given entity, then exits. + --guess-language Enable detecting language from file contents. + --heartbeat-rate-limit-seconds int Only sync heartbeats to the API once per these seconds, instead saving to the offline db. Defaults to 120. Use zero to disable. (default 120) + -h, --help help for wakatime-cli + --hide-branch-names string Obfuscate branch names. Will not send revision control branch names to api. + --hide-file-names string Obfuscate filenames. Will not send file names to api. + --hide-project-folder When set, send the file's path relative to the project folder. For ex: /User/me/projects/bar/src/file.ts is sent as src/file.ts so the server never sees the full path. When the project folder cannot be detected, only the file name is sent. For ex: file.ts. + --hide-project-names string Obfuscate project names. When a project folder is detected instead of using the folder name as the project, a .wakatime-project file is created with a random project name. + --hostname string Optional name of local machine. Defaults to local machine name read from system. + --human-line-changes int Optional number of lines added or removed by humans since last heartbeat in the current file. + --include strings Filename patterns to log. When used in combination with --exclude, files matching include will still be logged. POSIX regex syntax. Can be used more than once. + --include-only-with-project-file Disables tracking folders unless they contain a .wakatime-project file. Defaults to false. + --internal-config string Optional internal config file. Defaults to '~/.wakatime/wakatime-internal.cfg'. + --is-unsaved-entity Normally files that don't exist on disk are skipped and not tracked. When this option is present, the main heartbeat file will be tracked even if it doesn't exist. To set this flag on extra heartbeats, use the 'is_unsaved_entity' json key. + --key string Your wakatime api key; uses api_key from ~/.wakatime.cfg by default. + --language string Optional language name. If valid, takes priority over auto-detected language. + --lineno int Optional line number. This is the current line being edited. + --lines-in-file int Optional lines in the file. Normally, this is detected automatically but can be provided manually for performance, accuracy, or when using --local-file. + --local-file string Absolute path to local file for the heartbeat. When --entity is a remote file, this local file will be used for stats and just the value of --entity is sent with the heartbeat. + --log-file string Optional log file. Defaults to '~/.wakatime/wakatime.log'. + --log-to-stdout If enabled, logs will go to stdout. Will overwrite logfile configs. + --metrics When set, collects metrics usage in '~/.wakatime/metrics' folder. Defaults to false. + --no-ssl-verify Disables SSL certificate verification for HTTPS requests. By default, SSL certificates are verified. + --offline-count Prints the number of heartbeats in the offline db, then exits. + --output string Format output. Can be "text", "json" or "raw-json". Defaults to "text". + --plugin string Optional text editor plugin name and version for User-Agent header. + --print-offline-heartbeats int Prints offline heartbeats to stdout. (default 10) + --project string Override auto-detected project. Use --alternate-project to supply a fallback project if one can't be auto-detected. + --project-folder string Optional workspace path. Usually used when hiding the project folder, or when a project root folder can't be auto detected. + --proxy string Optional proxy configuration. Supports HTTPS SOCKS and NTLM proxies. For example: 'https://user:pass@host:port' or 'socks5://user:pass@host:port' or 'domain\user:pass' + --send-diagnostics-on-errors When --verbose or debug enabled, also sends diagnostics on any error not just crashes. + --ssl-certs-file string Override the bundled CA certs file. By default, uses system ca certs. + --sync-offline-activity int Amount of offline activity to sync from your local ~/.wakatime/offline_heartbeats.bdb bolt file to your WakaTime Dashboard before exiting. Can be zero or a positive integer. Defaults to 1000, meaning after sending a heartbeat while online, all queued offline heartbeats are sent to WakaTime API, up to a limit of 1000. Zero syncs all offline heartbeats. Can be used without --entity to only sync offline activity without generating new heartbeats. (default 1000) + --time float Optional floating-point unix epoch timestamp. Uses current time by default. + --timeout int Number of seconds to wait when sending heartbeats to api. Defaults to 120 seconds. (default 120) + --today Prints dashboard time for today, then exits. + --today-goal string Prints time for the given goal id today, then exits Visit wakatime.com/api/v1/users/current/goals to find your goal id. + --today-hide-categories string When optionally included with --today, causes output to show total code time today without categories. Defaults to false. + --verbose Turns on debug messages in log file, and sends diagnostics if a crash occurs. + --version Prints the wakatime-cli version number, then exits. + --write When set, tells api this heartbeat was triggered from writing to a file. + From b830961c6b87118f4ae82472cdce4b8979dd6950 Mon Sep 17 00:00:00 2001 From: BrownNPC Date: Sat, 31 Jan 2026 12:03:07 +0500 Subject: [PATCH 07/12] more bindings --- examples/messingAround/main.go | 5 +- raylib/raylib.go | 146 ++++++++++------------- raylib/rcore_wasm.go | 212 +++++++++++++++++++++++---------- 3 files changed, 217 insertions(+), 146 deletions(-) diff --git a/examples/messingAround/main.go b/examples/messingAround/main.go index 4eb27cf..59e966a 100644 --- a/examples/messingAround/main.go +++ b/examples/messingAround/main.go @@ -2,9 +2,12 @@ package main -import rl "github.com/gen2brain/raylib-go/raylib" +import ( + rl "github.com/gen2brain/raylib-go/raylib" +) func main() { + rl.InitWindow(300, 300, "We are on web bois") rl.SetMain(func() { rl.BeginDrawing() rl.EndDrawing() diff --git a/raylib/raylib.go b/raylib/raylib.go index d405426..59de771 100644 --- a/raylib/raylib.go +++ b/raylib/raylib.go @@ -18,6 +18,7 @@ import ( // Wave type, defines audio wave data type Wave struct { + _ structs.HostLayout // Number of samples FrameCount uint32 // Frequency (samples per second) @@ -28,7 +29,6 @@ type Wave struct { Channels uint32 // Buffer data pointer Data cptr - __ structs.HostLayout } // NewWave - Returns new Wave @@ -40,7 +40,6 @@ func NewWave(sampleCount, sampleRate, sampleSize, channels uint32, data []byte) SampleSize: sampleSize, Channels: channels, Data: ptr, - __: structs.HostLayout{}, } } @@ -49,26 +48,27 @@ type AudioCallback func(data []float32, frames int) // Sound source type type Sound struct { + _ structs.HostLayout Stream AudioStream FrameCount uint32 _ [4]byte - __ structs.HostLayout } // Music type (file streaming from memory) // NOTE: Anything longer than ~10 seconds should be streamed type Music struct { + _ structs.HostLayout Stream AudioStream FrameCount uint32 Looping bool CtxType int32 CtxData cptr - __ structs.HostLayout } // AudioStream type // NOTE: Useful to create custom audio streams not bound to a specific file type AudioStream struct { + _ structs.HostLayout // Buffer Buffer *AudioBuffer // Processor @@ -80,10 +80,10 @@ type AudioStream struct { // Number of channels (1-mono, 2-stereo) Channels uint32 _ [4]byte - __ structs.HostLayout } type maDataConverter struct { + _ structs.HostLayout FormatIn uint32 FormatOut uint32 ChannelsIn uint32 @@ -101,10 +101,10 @@ type maDataConverter struct { IsPassthrough uint8 X_ownsHeap uint8 X_pHeap *byte - __ structs.HostLayout } type maChannelConverter struct { + _ structs.HostLayout Format uint32 ChannelsIn uint32 ChannelsOut uint32 @@ -117,10 +117,10 @@ type maChannelConverter struct { X_pHeap *byte X_ownsHeap uint32 Pad_cgo_0 [4]byte - __ structs.HostLayout } type maResampler struct { + _ structs.HostLayout PBackend *byte PBackendVTable *maResamplingBackendVtable PBackendUserData *byte @@ -132,10 +132,10 @@ type maResampler struct { X_pHeap *byte X_ownsHeap uint32 Pad_cgo_0 [4]byte - __ structs.HostLayout } type maResamplingBackendVtable struct { + _ structs.HostLayout OnGetHeapSize *[0]byte OnInit *[0]byte OnUninit *[0]byte @@ -146,10 +146,10 @@ type maResamplingBackendVtable struct { OnGetRequiredInputFrameCount *[0]byte OnGetExpectedOutputFrameCount *[0]byte OnReset *[0]byte - __ structs.HostLayout } type AudioBuffer struct { + _ structs.HostLayout Converter maDataConverter Callback *[0]byte Processor *AudioProcessor @@ -167,33 +167,32 @@ type AudioBuffer struct { Data *uint8 Next *AudioBuffer Prev *AudioBuffer - __ structs.HostLayout } type AudioProcessor struct { + _ structs.HostLayout Process *[0]byte Next *AudioProcessor Prev *AudioProcessor - __ structs.HostLayout } // AutomationEvent - Automation event type AutomationEvent struct { + _ structs.HostLayout Frame uint32 Type uint32 Params [4]int32 - __ structs.HostLayout } // AutomationEventList - Automation event list type AutomationEventList struct { + _ structs.HostLayout Capacity uint32 Count uint32 // Events array (c array) // // Use AutomationEventList.GetEvents instead (go slice) Events *AutomationEvent - __ structs.HostLayout } // func (a *AutomationEventList) GetEvents() []AutomationEvent { @@ -508,65 +507,64 @@ var ( // Vector2 type type Vector2 struct { - X float32 - Y float32 - __ structs.HostLayout + _ structs.HostLayout + X float32 + Y float32 } // NewVector2 - Returns new Vector2 func NewVector2(x, y float32) Vector2 { return Vector2{ - X: x, - Y: y, - __: structs.HostLayout{}, + X: x, + Y: y, } } // Vector3 type type Vector3 struct { - X float32 - Y float32 - Z float32 - __ structs.HostLayout + _ structs.HostLayout + _ structs.HostLayout + X float32 + Y float32 + Z float32 } // NewVector3 - Returns new Vector3 func NewVector3(x, y, z float32) Vector3 { return Vector3{ - X: x, - Y: y, - Z: z, - __: structs.HostLayout{}, + X: x, + Y: y, + Z: z, } } // Vector4 type type Vector4 struct { - X float32 - Y float32 - Z float32 - W float32 - __ structs.HostLayout + _ structs.HostLayout + _ structs.HostLayout + X float32 + Y float32 + Z float32 + W float32 } // NewVector4 - Returns new Vector4 func NewVector4(x, y, z, w float32) Vector4 { return Vector4{ - X: x, - Y: y, - Z: z, - W: w, - __: structs.HostLayout{}, + X: x, + Y: y, + Z: z, + W: w, } } // Matrix type (OpenGL style 4x4 - right handed, column major) type Matrix struct { + _ structs.HostLayout M0, M4, M8, M12 float32 M1, M5, M9, M13 float32 M2, M6, M10, M14 float32 M3, M7, M11, M15 float32 - __ structs.HostLayout } // NewMatrix - Returns new Matrix @@ -588,17 +586,16 @@ func NewMatrix(m0, m4, m8, m12, m1, m5, m9, m13, m2, m6, m10, m14, m3, m7, m11, M7: m7, M11: m11, M15: m15, - __: structs.HostLayout{}, } } // Mat2 type (used for polygon shape rotation matrix) type Mat2 struct { + _ structs.HostLayout M00 float32 M01 float32 M10 float32 M11 float32 - __ structs.HostLayout } // NewMat2 - Returns new Mat2 @@ -608,7 +605,6 @@ func NewMat2(m0, m1, m10, m11 float32) Mat2 { M01: m1, M10: m10, M11: m11, - __: structs.HostLayout{}, } } @@ -618,11 +614,10 @@ type Quaternion = Vector4 // NewQuaternion - Returns new Quaternion func NewQuaternion(x, y, z, w float32) Quaternion { return Quaternion{ - X: x, - Y: y, - Z: z, - W: w, - __: structs.HostLayout{}, + X: x, + Y: y, + Z: z, + W: w, } } @@ -637,11 +632,11 @@ func NewColor(r, g, b, a uint8) color.RGBA { // Rectangle type type Rectangle struct { + _ structs.HostLayout X float32 Y float32 Width float32 Height float32 - __ structs.HostLayout } // NewRectangle - Returns new Rectangle @@ -651,7 +646,6 @@ func NewRectangle(x, y, width, height float32) Rectangle { Y: y, Width: width, Height: height, - __: structs.HostLayout{}, } } @@ -668,11 +662,11 @@ func (r *Rectangle) ToInt32() RectangleInt32 { // RectangleInt32 type type RectangleInt32 struct { + _ structs.HostLayout X int32 Y int32 Width int32 Height int32 - __ structs.HostLayout } // ToFloat32 converts rectangle to float32 variant @@ -688,6 +682,7 @@ func (r *RectangleInt32) ToFloat32() Rectangle { // Camera3D type, defines a camera position/orientation in 3d space type Camera3D struct { + _ structs.HostLayout // Camera position Position Vector3 // Camera target it looks-at @@ -698,7 +693,6 @@ type Camera3D struct { Fovy float32 // Camera type, controlling projection type, either CameraPerspective or CameraOrthographic. Projection CameraProjection - __ structs.HostLayout } // Camera type fallback, defaults to Camera3D @@ -712,12 +706,12 @@ func NewCamera3D(pos, target, up Vector3, fovy float32, ct CameraProjection) Cam Up: up, Fovy: fovy, Projection: ct, - __: structs.HostLayout{}, } } // Camera2D type, defines a 2d camera type Camera2D struct { + _ structs.HostLayout // Camera offset (displacement from target) Offset Vector2 // Camera target (rotation and zoom origin) @@ -726,7 +720,6 @@ type Camera2D struct { Rotation float32 // Camera zoom (scaling), should be 1.0f by default Zoom float32 - __ structs.HostLayout } // NewCamera2D - Returns new Camera2D @@ -736,17 +729,16 @@ func NewCamera2D(offset, target Vector2, rotation, zoom float32) Camera2D { Target: target, Rotation: rotation, Zoom: zoom, - __: structs.HostLayout{}, } } // BoundingBox type type BoundingBox struct { + _ structs.HostLayout // Minimum vertex box-corner Min Vector3 // Maximum vertex box-corner Max Vector3 - __ structs.HostLayout } // NewBoundingBox - Returns new BoundingBox @@ -754,7 +746,6 @@ func NewBoundingBox(min, max Vector3) BoundingBox { return BoundingBox{ Min: min, Max: max, - __: structs.HostLayout{}, } } @@ -878,6 +869,7 @@ const ( // Mesh - Vertex data definning a mesh type Mesh struct { + _ structs.HostLayout // Number of vertices stored in arrays VertexCount int32 // Number of triangles stored (indexed or not) @@ -912,18 +904,17 @@ type Mesh struct { VaoID uint32 // OpenGL Vertex Buffer Objects id (7 types of vertex data) VboID *uint32 - __ structs.HostLayout } // Material type type Material struct { + _ structs.HostLayout // Shader Shader Shader // Maps Maps *MaterialMap // Generic parameters (if required) Params [4]float32 - __ structs.HostLayout } // // GetMap - Get pointer to MaterialMap by map type @@ -933,17 +924,18 @@ type Material struct { // MaterialMap type type MaterialMap struct { + _ structs.HostLayout // Texture Texture Texture2D // Color Color color.RGBA // Value Value float32 - __ structs.HostLayout } // Model is struct of model, meshes, materials and animation data type Model struct { + _ structs.HostLayout // Local transform matrix Transform Matrix // Number of meshes @@ -970,7 +962,6 @@ type Model struct { // // Use Model.GetBindPose instead (go slice) BindPose *Transform - __ structs.HostLayout } // // GetMeshes returns the meshes of a model as go slice @@ -995,26 +986,26 @@ type Model struct { // BoneInfo type type BoneInfo struct { + _ structs.HostLayout Name [32]int8 Parent int32 - __ structs.HostLayout } // Transform type type Transform struct { + _ structs.HostLayout Translation Vector3 Rotation Vector4 Scale Vector3 - __ structs.HostLayout } // Ray type (useful for raycast) type Ray struct { + _ structs.HostLayout // Ray position (origin) Position Vector3 // Ray direction Direction Vector3 - __ structs.HostLayout } // NewRay - Returns new Ray @@ -1022,18 +1013,17 @@ func NewRay(position, direction Vector3) Ray { return Ray{ Position: position, Direction: direction, - __: structs.HostLayout{}, } } // ModelAnimation type type ModelAnimation struct { + _ structs.HostLayout BoneCount int32 FrameCount int32 Bones *BoneInfo FramePoses **Transform Name [32]uint8 - __ structs.HostLayout } // // GetBones returns the bones information (skeleton) of a ModelAnimation as go slice @@ -1060,11 +1050,11 @@ func (m ModelAnimation) GetName() string { // RayCollision type - ray hit information type RayCollision struct { + _ structs.HostLayout Hit bool Distance float32 Point Vector3 Normal Vector3 - __ structs.HostLayout } // NewRayCollision - Returns new RayCollision @@ -1074,7 +1064,6 @@ func NewRayCollision(hit bool, distance float32, point, normal Vector3) RayColli Distance: distance, Point: point, Normal: normal, - __: structs.HostLayout{}, } } @@ -1095,18 +1084,18 @@ const ( // Shader type (generic shader) type Shader struct { + _ structs.HostLayout // Shader program id ID uint32 // Shader locations array Locs cptr - __ structs.HostLayout } // NewShader - Returns new Shader func NewShader(id uint32, locs *int32) Shader { return Shader{ - ID: id, - __: structs.HostLayout{}, + ID: id, + Locs: cptr(*locs), } } @@ -1126,6 +1115,7 @@ func (sh Shader) UpdateLocation(index int32, loc int32) { // GlyphInfo - Font character info type GlyphInfo struct { + _ structs.HostLayout // Character value (Unicode) Value int32 // Character offset X when drawing @@ -1136,7 +1126,6 @@ type GlyphInfo struct { AdvanceX int32 // Character image data Image Image - __ structs.HostLayout } // NewGlyphInfo - Returns new CharInfo @@ -1147,12 +1136,12 @@ func NewGlyphInfo(value int32, offsetX, offsetY, advanceX int32, image Image) Gl OffsetY: offsetY, AdvanceX: advanceX, Image: image, - __: structs.HostLayout{}, } } // Font type, includes texture and charSet array data type Font struct { + _ structs.HostLayout // Base size (default chars height) BaseSize int32 // Number of characters @@ -1167,7 +1156,6 @@ type Font struct { // Characters info data // Chars *GlyphInfo Chars cptr - __ structs.HostLayout } // Font type, defines generation method @@ -1271,6 +1259,7 @@ const ( // Image type, bpp always RGBA (32bit) // NOTE: Data stored in CPU memory (RAM) type Image struct { + _ structs.HostLayout // Image raw Data Data cptr // Image base width @@ -1281,7 +1270,6 @@ type Image struct { Mipmaps int32 // Data format (PixelFormat) Format PixelFormat - __ structs.HostLayout } // // NewImage - Returns new Image @@ -1294,6 +1282,7 @@ type Image struct { // Texture2D type, bpp always RGBA (32bit) // NOTE: Data stored in GPU memory type Texture2D struct { + _ structs.HostLayout // OpenGL texture id ID uint32 // Texture base width @@ -1304,7 +1293,6 @@ type Texture2D struct { Mipmaps int32 // Data format (PixelFormat) Format PixelFormat - __ structs.HostLayout } // NewTexture2D - Returns new Texture2D @@ -1315,19 +1303,18 @@ func NewTexture2D(id uint32, width, height, mipmaps int32, format PixelFormat) T Height: height, Mipmaps: mipmaps, Format: format, - __: structs.HostLayout{}, } } // RenderTexture2D type, for texture rendering type RenderTexture2D struct { + _ structs.HostLayout // Render texture (fbo) id ID uint32 // Color buffer attachment texture Texture Texture2D // Depth buffer attachment texture Depth Texture2D - __ structs.HostLayout } // NewRenderTexture2D - Returns new RenderTexture2D @@ -1336,7 +1323,6 @@ func NewRenderTexture2D(id uint32, texture, depth Texture2D) RenderTexture2D { ID: id, Texture: texture, Depth: depth, - __: structs.HostLayout{}, } } @@ -1378,17 +1364,18 @@ const ( // NPatchInfo type, n-patch layout info type NPatchInfo struct { + _ structs.HostLayout Source Rectangle // Texture source rectangle Left int32 // Left border offset Top int32 // Top border offset Right int32 // Right border offset Bottom int32 // Bottom border offset Layout NPatchLayout // Layout of the n-patch: 3x3, 1x3 or 3x1 - __ structs.HostLayout } // VrStereoConfig, VR stereo rendering configuration for simulator type VrStereoConfig struct { + _ structs.HostLayout Projection [2]Matrix // VR projection matrices (per eye) ViewOffset [2]Matrix // VR view offset matrices (per eye) LeftLensCenter [2]float32 // VR left lens center @@ -1397,11 +1384,11 @@ type VrStereoConfig struct { RightScreenCenter [2]float32 // VR right screen center Scale [2]float32 // VR distortion scale ScaleIn [2]float32 // VR distortion scale in - __ structs.HostLayout } // VrDeviceInfo, Head-Mounted-Display device parameters type VrDeviceInfo struct { + _ structs.HostLayout HResolution int32 // Horizontal resolution in pixels VResolution int32 // Vertical resolution in pixels HScreenSize float32 // Horizontal size in meters @@ -1411,5 +1398,4 @@ type VrDeviceInfo struct { InterpupillaryDistance float32 // IPD (distance between pupils) in meters LensDistortionValues [4]float32 // Lens distortion constant parameters ChromaAbCorrection [4]float32 // Chromatic aberration correction parameters - __ structs.HostLayout } diff --git a/raylib/rcore_wasm.go b/raylib/rcore_wasm.go index 78b7ba5..b166c25 100644 --- a/raylib/rcore_wasm.go +++ b/raylib/rcore_wasm.go @@ -776,117 +776,182 @@ func GetCameraMatrix(camera Camera) Matrix { return v } -/* +// GetCameraMatrix2D - Returns camera 2d transform matrix +// +//go:wasmimport raylib _GetCameraMatrix2D +//go:noescape +func getCameraMatrix2D(mat, camera cptr) + // GetCameraMatrix2D - Returns camera 2d transform matrix func GetCameraMatrix2D(camera Camera2D) Matrix { - ccamera := camera.cptr() - ret := getCameraMatrix2D(*ccamera) - v := newMatrixFromPointer(&ret) + ccamera, f := copyValueToC(camera) + defer f() + var v Matrix + ret, f := mallocV(v) + defer f() + getCameraMatrix2D(ret, ccamera) + copyValueToGo(ret, &v) return v } +// GetWorldToScreen - Returns the screen space position from a 3d world space position +// +//go:wasmimport raylib _GetWorldToScreen +//go:noescape +func getWorldToScreen(vector2, position, camera cptr) + // GetWorldToScreen - Returns the screen space position from a 3d world space position func GetWorldToScreen(position Vector3, camera Camera) Vector2 { - cposition := position.cptr() - ccamera := camera.cptr() - ret := getWorldToScreen(*cposition, *ccamera) - v := newVector2FromPointer(&ret) + cposition, f := copyValueToC(position) + defer f() + ccamera, f := copyValueToC(position) + defer f() + var v Vector2 + ret, f := mallocV(v) + defer f() + getWorldToScreen(ret, cposition, ccamera) + copyValueToGo(ret, &v) return v } +// GetScreenToWorld2D - Returns the world space position for a 2d camera screen space position +// +//go:wasmimport raylib _GetScreenToWorld2D +//go:noescape +func getScreenToWorld2D(vector2, position cptr, camera cptr) + // GetScreenToWorld2D - Returns the world space position for a 2d camera screen space position func GetScreenToWorld2D(position Vector2, camera Camera2D) Vector2 { - cposition := position.cptr() - ccamera := camera.cptr() - ret := getScreenToWorld2D(*cposition, *ccamera) - v := newVector2FromPointer(&ret) + cposition, f := copyValueToC(position) + defer f() + ccamera, f := copyValueToC(camera) + defer f() + var v Vector2 + ret, f := mallocV(v) + defer f() + getScreenToWorld2D(ret, cposition, ccamera) + copyValueToGo(ret, &v) return v } +// GetWorldToScreenEx - Get size position for a 3d world space position +// +//go:wasmimport raylib _GetWorldToScreenEx +//go:noescape +func getWorldToScreenEx(vector2, position, camera cptr, width int32, height int32) + // GetWorldToScreenEx - Get size position for a 3d world space position func GetWorldToScreenEx(position Vector3, camera Camera, width int32, height int32) Vector2 { - cposition := position.cptr() - ccamera := camera.cptr() + cposition, f := copyValueToC(position) + defer f() + ccamera, f := copyValueToC(camera) + defer f() cwidth := (int32)(width) cheight := (int32)(height) - ret := getWorldToScreenEx(*cposition, *ccamera, cwidth, cheight) - v := newVector2FromPointer(&ret) + var v Vector2 + ret, f := mallocV(v) + defer f() + + getWorldToScreenEx(ret, cposition, ccamera, cwidth, cheight) + copyValueToGo(ret, &v) return v } +// GetWorldToScreen2D - Returns the screen space position for a 2d camera world space position +// +//go:wasmimport raylib _GetWorldToScreen2D +//go:noescape +func getWorldToScreen2D(vector2, position, camera cptr) + // GetWorldToScreen2D - Returns the screen space position for a 2d camera world space position func GetWorldToScreen2D(position Vector2, camera Camera2D) Vector2 { - cposition := position.cptr() - ccamera := camera.cptr() - ret := getWorldToScreen2D(*cposition, *ccamera) - v := newVector2FromPointer(&ret) + cposition, f := copyValueToC(position) + defer f() + ccamera, f := copyValueToC(camera) + defer f() + var v Vector2 + ret, f := mallocV(v) + defer f() + + getWorldToScreen2D(ret, cposition, ccamera) + copyValueToGo(ret, &v) return v } // SetTargetFPS - Set target FPS (maximum) -func SetTargetFPS(fps int32) { - cfps := (int32)(fps) - setTargetFPS(cfps) -} +// +//go:wasmimport raylib _SetTargetFPS +//go:noescape +func SetTargetFPS(fps int32) // GetFPS - Returns current FPS -func GetFPS() int32 { - ret := getFPS() - v := (int32)(ret) - return v -} +// +//go:wasmimport raylib _GetFPS +//go:noescape +func GetFPS() int32 // GetFrameTime - Returns time in seconds for one frame -func GetFrameTime() float32 { - ret := getFrameTime() - v := (float32)(ret) - return v -} +// +//go:wasmimport raylib _GetFrameTime +//go:noescape +func GetFrameTime() float32 // GetTime - Return time in seconds -func GetTime() float64 { - ret := getTime() - v := (float64)(ret) - return v -} +// +//go:wasmimport raylib _GetTime +//go:noescape +func GetTime() float64 // Custom frame control functions // NOTE: SwapScreenBuffer and PollInputEvents are intended for advanced users that want full control over the frame processing // By default EndDrawing() does this job: draws everything + SwapScreenBuffer() + manage frame timing + PollInputEvents() // To avoid that behaviour and control frame processes manually you can either enable in config.h: SUPPORT_CUSTOM_FRAME_CONTROL // or add CGO_CFLAGS="-DSUPPORT_CUSTOM_FRAME_CONTROL=1" to your build - // SwapScreenBuffer - Swap back buffer to front buffer -func SwapScreenBuffer() { - swapScreenBuffer() -} +// +//go:wasmimport raylib _SwapScreenBuffer +//go:noescape +func SwapScreenBuffer() // Register all input events -func PollInputEvents() { - pollInputEvents() -} +// +//go:wasmimport raylib _PollInputEvents +//go:noescape +func PollInputEvents() // WaitTime - Wait for some time (halt program execution) -func WaitTime(seconds float64) { - cseconds := (double)(seconds) - waitTime(cseconds) -} +// +//go:wasmimport raylib _WaitTime +//go:noescape +func WaitTime(seconds float64) + +// Fade - Returns color with alpha applied, alpha goes from 0.0f to 1.0f +// +//go:wasmimport raylib _Fade +func fade(color, col cptr, alpha float32) // Fade - Returns color with alpha applied, alpha goes from 0.0f to 1.0f func Fade(col color.RGBA, alpha float32) color.RGBA { - ccolor := colorCptr(col) - calpha := (float)(alpha) - ret := fade(*ccolor, calpha) - v := newColorFromPointer(&ret) + ccolor, f := copyValueToC(col) + defer f() + var v Color + ret, f := mallocV(v) + defer f() + fade(ret, ccolor, alpha) + copyValueToGo(ret, &v) return v } +// ColorToInt - Get hexadecimal value for a Color (0xRRGGBBAA) +// +//go:wasmimport raylib _ColorToInt +func colorToInt(col cptr) int32 + // ColorToInt - Get hexadecimal value for a Color (0xRRGGBBAA) func ColorToInt(col color.RGBA) int32 { - ccolor := colorCptr(col) - ret := colorToInt(*ccolor) - v := (int32)(ret) - return v + ccolor, f := copyValueToC(col) + defer f() + return colorToInt(ccolor) } // ColorNormalize - Returns color normalized as float [0..1] @@ -897,26 +962,43 @@ func ColorNormalize(col color.RGBA) Vector4 { result.Y = float32(g) / 255 result.Z = float32(b) / 255 result.W = float32(a) / 255 - return result } +// ColorFromNormalized - Returns Color from normalized values [0..1] +// +//go:wasmimport raylib _ColorNormalized +func colorFromNormalized(col, normalized cptr) + // ColorFromNormalized - Returns Color from normalized values [0..1] func ColorFromNormalized(normalized Vector4) color.RGBA { - cnormalized := normalized.cptr() - ret := colorFromNormalized(*cnormalized) - v := newColorFromPointer(&ret) + cnormalized, f := copyValueToC(normalized) + defer f() + var v Color + ret, f := mallocV(v) + colorFromNormalized(ret, cnormalized) + copyValueToGo(ret, &v) return v } +// ColorToHSV - Returns HSV values for a Color, hue [0..360], saturation/value [0..1] +func colorToHSV(vector3, col cptr) + // ColorToHSV - Returns HSV values for a Color, hue [0..360], saturation/value [0..1] func ColorToHSV(col color.RGBA) Vector3 { - ccolor := colorCptr(col) - ret := colorToHSV(*ccolor) - v := newVector3FromPointer(&ret) + ccolor, f := copyValueToC(col) + defer f() + var v Vector3 + ret, f := mallocV(v) + defer f() + colorToHSV(ret, ccolor) + copyValueToGo(ret, &v) return v } +/* + + // ColorFromHSV - Returns a Color from HSV values, hue [0..360], saturation/value [0..1] func ColorFromHSV(hue, saturation, value float32) color.RGBA { chue := (float)(hue) From 20ca91caa2ec293c895f323d4fd741fa8bde21c1 Mon Sep 17 00:00:00 2001 From: BrownNPC Date: Sat, 31 Jan 2026 13:23:29 +0500 Subject: [PATCH 08/12] codegen skeleton --- codegen/extractFuncs.go | 85 - codegen/fn.go | 30 - codegen/generateBind.go | 64 - codegen/genstubs.go | 53 - codegen/main.go | 79 - codegen/modeBind.go | 54 - codegen/strings.go | 23 - raylib/rcore_wasm.go | 51 +- testdata/api/rlapi.go | 72 + testdata/{rcore.json => api/rlapi.json} | 507 +++- testdata/codegen.go | 6 + testdata/rcore_defines.txt | 2920 ----------------------- wakatime.log | 65 - 13 files changed, 518 insertions(+), 3491 deletions(-) delete mode 100644 codegen/extractFuncs.go delete mode 100644 codegen/fn.go delete mode 100644 codegen/generateBind.go delete mode 100644 codegen/genstubs.go delete mode 100644 codegen/main.go delete mode 100644 codegen/modeBind.go delete mode 100644 codegen/strings.go create mode 100644 testdata/api/rlapi.go rename testdata/{rcore.json => api/rlapi.json} (96%) create mode 100644 testdata/codegen.go delete mode 100644 testdata/rcore_defines.txt delete mode 100644 wakatime.log diff --git a/codegen/extractFuncs.go b/codegen/extractFuncs.go deleted file mode 100644 index e92c25c..0000000 --- a/codegen/extractFuncs.go +++ /dev/null @@ -1,85 +0,0 @@ -// yes, it's Gippity -package main - -import ( - "bytes" - "go/ast" - "go/parser" - "go/printer" - "go/token" -) - -// Function holds the metadata for one top‐level function, including its doc comment. -type Function struct { - Name string - Description string // the text of the leading comment group, or "" if none - Params []Param - ReturnType string // "" if none, otherwise the first return’s type - ReturnsStruct bool -} - -// Param holds one parameter’s name and type. -type Param struct { - Name, Type string - isReference bool - isStruct bool -} - -// ExtractFuncs parses src and returns all top-level FuncDecls along with their comments. -func ExtractFuncs(src string) []Function { - fset := token.NewFileSet() - file, err := parser.ParseFile(fset, "", src, parser.ParseComments) - if err != nil { - panic(err) - } - - var funcs []Function - for _, decl := range file.Decls { - fd, ok := decl.(*ast.FuncDecl) - if !ok || fd.Name == nil { - continue - } - - f := Function{ - Name: fd.Name.Name, - Description: "", - Params: nil, - ReturnType: "", - } - - // --- extract the doc-comment text, if any --- - if fd.Doc != nil { - // Doc.Text() returns the comment text with line breaks - f.Description = fd.Doc.Text() - } - - // --- collect parameters --- - if fd.Type.Params != nil { - for _, field := range fd.Type.Params.List { - // render the type expression to a string - buf := new(bytes.Buffer) - printer.Fprint(buf, fset, field.Type) - typ := buf.String() - - for _, name := range field.Names { - f.Params = append(f.Params, Param{ - Name: name.Name, - Type: typ, - }) - } - // (could handle anonymous params here if needed) - } - } - - // --- collect a single return type, if any --- - if fd.Type.Results != nil && len(fd.Type.Results.List) > 0 { - buf := new(bytes.Buffer) - printer.Fprint(buf, fset, fd.Type.Results.List[0].Type) - f.ReturnType = buf.String() - } - - funcs = append(funcs, f) - } - - return funcs -} diff --git a/codegen/fn.go b/codegen/fn.go deleted file mode 100644 index 2a7a93b..0000000 --- a/codegen/fn.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import "fmt" - - - -func (fn Function) RegisterSignature() string { - var out string - var ProcOrFunction = fmt.Sprintf("wasm.Func[%s](\"%s\")", fn.ReturnType, fn.Name) - if fn.ReturnType == "" { - ProcOrFunction = fmt.Sprintf("wasm.Proc(\"%s\")", fn.Name) - } - out += fmt.Sprintf("var %s = %s ", Uncapitalize(fn.Name), ProcOrFunction) - return out -} - -func (fn Function) Signature(code string) string { - var out string - out += fmt.Sprintf("func %s(%s) %s {\n%s}\n", fn.Name, fn.Expand(), fn.ReturnType, code) - return out -} - -func (fn Function) Expand() string { - var out string - for _, p := range fn.Params { - out += fmt.Sprintf("%s %s,", p.Name, p.Type) - } - return out -} - diff --git a/codegen/generateBind.go b/codegen/generateBind.go deleted file mode 100644 index 8c027ac..0000000 --- a/codegen/generateBind.go +++ /dev/null @@ -1,64 +0,0 @@ -package main - -import ( - "fmt" - "strings" -) - -func (fn Function) BindingCode() string { - if strings.Contains(fn.Description, "(only PLATFORM_DESKTOP)") || fn.ReturnType == "unsafe.Pointer" { - if fn.ReturnType == "" { - return "" - } else { - return fmt.Sprintf("var zero %s;return zero", fn.ReturnType) - } - } - if (len(fn.ReturnType) > 0) && (fn.ReturnType[:1] == "*" || fn.ReturnType[:1] == "[") { - return fmt.Sprintf("var zero %s;return zero", fn.ReturnType) - } - var out string - var param_names string - // generate reference binding code - // func CheckCollisionLines(startPos1 Vector2, endPos1 Vector2, startPos2 Vector2, endPos2 Vector2, collisionPoint *Vector2) bool { - // _collisionPoint := wasm.Struct(*collisionPoint) - // ret, fl := checkCollisionLines.Call(wasm.Struct(startPos1), wasm.Struct(endPos1), wasm.Struct(startPos2), wasm.Struct(endPos2), _collisionPoint) - // v := wasm.Boolean(ret) - // *collisionPoint = wasm.BytesToStruct[Vector2](wasm.ReadFromWASM(_collisionPoint.Mem, _collisionPoint.Size)) - // wasm.Free(fl...) - // return v - // } - var referenceBinding string - for _, p := range fn.Params { - if p.isReference { - referenceBinding += fmt.Sprintf("_%s := wasm.Struct(*%s)\n", p.Name, p.Name) - } - } - for _, p := range fn.Params { - if !p.isStruct && !p.isReference { - param_names += fmt.Sprintf("%s,", p.Name) - } else if p.isStruct && !p.isReference { - param_names += fmt.Sprintf("wasm.Struct(%s),", p.Name) - } else if p.isReference { - param_names += fmt.Sprintf("_%s", p.Name) - } - } - var returnV bool - if fn.ReturnType == "" { - out += fmt.Sprintf("_,fl :=%s.Call(%s)\n", Uncapitalize(fn.Name), param_names) - } else { - out += fmt.Sprintf("ret,fl :=%s.Call(%s)\n", Uncapitalize(fn.Name), param_names) - if fn.ReturnType == "bool" { - out += "v := wasm.Boolean(ret)\n" - } else if !fn.ReturnsStruct { - out += fmt.Sprintf("v := wasm.Numeric[%s](ret)\n", fn.ReturnType) - } else { - out += fmt.Sprintf("v := wasm.ReadStruct[%s](ret)\n", fn.ReturnType) - } - returnV = true - } - out += "wasm.Free(fl...)\n" - if returnV { - out += "return v" - } - return out -} diff --git a/codegen/genstubs.go b/codegen/genstubs.go deleted file mode 100644 index 137c1ed..0000000 --- a/codegen/genstubs.go +++ /dev/null @@ -1,53 +0,0 @@ -package main - -import ( - "fmt" - "go/format" - "slices" - "strings" -) - -// make empty definitions -func ModeStub(file string, structs []string) { - - funcs := ExtractFuncs(file) - // check which parameters are struct types - // and which functions return structs - for i := range funcs { - f := &funcs[i] - if slices.Contains(structs, f.ReturnType) { - f.ReturnsStruct = true - } - - for j := range f.Params { - p := &f.Params[j] - if slices.Contains(structs, p.Type) { - p.isStruct = true - } else if p.Type[0] == '*' { - // *Vector2 - p.isReference = true - } - } - } - - var out string = fmt.Sprintln("//go:build !js") + imports - for _, f := range funcs { - comments := strings.SplitSeq(f.Description, "\n") - for comment := range comments { - out += fmt.Sprintln("//", comment) - } - // func InitWindow(width int32, height int32, title string){//binding code} - var stub string = "//empty code to make gopls happy on non-web\n" - if f.ReturnType != "" { - stub += fmt.Sprintf("var zero %s ;return zero", f.ReturnType) - } - out += fmt.Sprintln(f.Signature(stub)) - } - - formatted, err := format.Source([]byte(out)) - if err != nil { - fmt.Println(out) - panic(fmt.Errorf("format error: %s ", err)) - } - fmt.Println(string(formatted)) -} diff --git a/codegen/main.go b/codegen/main.go deleted file mode 100644 index 65d8bdd..0000000 --- a/codegen/main.go +++ /dev/null @@ -1,79 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "os" - "slices" -) - -var help string = fmt.Sprintf("Supported libraries to generate bindings for are: %s\npassing a third argument 'stub' will generate stubs", supportedLibs) - -var mode int - -// files to bind for -var supportedLibs = []string{"rcore"} - -// go bindings for raylib dont have aliases for some structs -var additions = []string{"color.RGBA", "Texture2D", "RenderTexture2D"} - -var imports = ` -package rl -import ( - "image/color" - "unsafe" - wasm github.com/BrownNPC/wasm-ffi-go -) -` - -// get data codegen data for a supported lib -func CodegenDataFor(libname string) (defines string, structNames []string, err error) { - var DefinesPath = fmt.Sprintf("testdata/%s_defines.txt", libname) - var JsonPath = fmt.Sprintf("testdata/%s.json", libname) - var f []byte - f, err = os.ReadFile(DefinesPath) - if err != nil { - return - } - defines = string(f) - - // get struct names - type Value struct { - Name string `json:"name"` - } - var ApiJson map[string][]Value - var file *os.File - file, err = os.Open(JsonPath) - if err != nil { - return - } - err = json.NewDecoder(file).Decode(&ApiJson) - if err != nil { - panic(err) - } - for _, s := range ApiJson["structs"] { - structNames = append(structNames, s.Name) - } - structNames = append(structNames, additions...) - return -} - -func main() { - if len(os.Args) < 2 { - fmt.Println(help) - os.Exit(0) - } else if slices.Contains(supportedLibs, os.Args[1]) { - var LibraryToBind = os.Args[1] - defines, structNames, err := CodegenDataFor(LibraryToBind) - if err != nil { - os.Exit(1) - } - if len(os.Args) == 3 && os.Args[2] == "stub" { - ModeStub(defines, structNames) - } else { - ModeBind(defines, structNames) - } - } else { - fmt.Println(help) - } -} diff --git a/codegen/modeBind.go b/codegen/modeBind.go deleted file mode 100644 index 62491c4..0000000 --- a/codegen/modeBind.go +++ /dev/null @@ -1,54 +0,0 @@ -package main - -import ( - "fmt" - "go/format" - "slices" - "strings" -) - - -func ModeBind(file string, structs []string) { - - funcs := ExtractFuncs(file) - // check which parameters are struct types - // and which functions return structs - for i := range funcs { - f := &funcs[i] - if slices.Contains(structs, f.ReturnType) { - f.ReturnsStruct = true - } - - for j := range f.Params { - p := &f.Params[j] - if slices.Contains(structs, p.Type) { - p.isStruct = true - } - } - } - - var out string = imports - // - for _, f := range funcs { - if strings.Contains(f.Description, "(only PLATFORM_DESKTOP)") { - continue - } - // var initWindow = wasm.Proc("InitWindow") - out += fmt.Sprintln(f.RegisterSignature()) - } - for _, f := range funcs { - comments := strings.SplitSeq(f.Description, "\n") - for comment := range comments { - out += fmt.Sprintln("//", comment) - } - // func InitWindow(width int32, height int32, title string){//binding code} - out += fmt.Sprintln(f.Signature(f.BindingCode())) - } - - formatted, err := format.Source([]byte(out)) - if err != nil { - fmt.Println(out) - panic(fmt.Errorf("format error: %s ", err)) - } - fmt.Println(string(formatted)) -} diff --git a/codegen/strings.go b/codegen/strings.go deleted file mode 100644 index 45f0af4..0000000 --- a/codegen/strings.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import "unicode" - - - -func Capitalize(s string) string { - if s == "" { - return s - } - runes := []rune(s) - runes[0] = unicode.ToUpper(runes[0]) - return string(runes) -} - -func Uncapitalize(s string) string { - if s == "" { - return s - } - runes := []rune(s) - runes[0] = unicode.ToLower(runes[0]) - return string(runes) -} diff --git a/raylib/rcore_wasm.go b/raylib/rcore_wasm.go index b166c25..9ef7f35 100644 --- a/raylib/rcore_wasm.go +++ b/raylib/rcore_wasm.go @@ -928,6 +928,7 @@ func WaitTime(seconds float64) // Fade - Returns color with alpha applied, alpha goes from 0.0f to 1.0f // //go:wasmimport raylib _Fade +//go:noescape func fade(color, col cptr, alpha float32) // Fade - Returns color with alpha applied, alpha goes from 0.0f to 1.0f @@ -945,6 +946,7 @@ func Fade(col color.RGBA, alpha float32) color.RGBA { // ColorToInt - Get hexadecimal value for a Color (0xRRGGBBAA) // //go:wasmimport raylib _ColorToInt +//go:noescape func colorToInt(col cptr) int32 // ColorToInt - Get hexadecimal value for a Color (0xRRGGBBAA) @@ -968,6 +970,7 @@ func ColorNormalize(col color.RGBA) Vector4 { // ColorFromNormalized - Returns Color from normalized values [0..1] // //go:wasmimport raylib _ColorNormalized +//go:noescape func colorFromNormalized(col, normalized cptr) // ColorFromNormalized - Returns Color from normalized values [0..1] @@ -982,6 +985,9 @@ func ColorFromNormalized(normalized Vector4) color.RGBA { } // ColorToHSV - Returns HSV values for a Color, hue [0..360], saturation/value [0..1] +// +//go:wasmimport raylib _ColorToHSV +//go:noescape func colorToHSV(vector3, col cptr) // ColorToHSV - Returns HSV values for a Color, hue [0..360], saturation/value [0..1] @@ -996,37 +1002,44 @@ func ColorToHSV(col color.RGBA) Vector3 { return v } -/* - +// ColorFromHSV - Returns a Color from HSV values, hue [0..360], saturation/value [0..1] +// +//go:wasmimport raylib _ColorFromHSV +//go:noescape +func colorFromHSV(col cptr, hue, saturation, value float32) // ColorFromHSV - Returns a Color from HSV values, hue [0..360], saturation/value [0..1] func ColorFromHSV(hue, saturation, value float32) color.RGBA { - chue := (float)(hue) - csaturation := (float)(saturation) - cvalue := (float)(value) - ret := colorFromHSV(chue, csaturation, cvalue) - v := newColorFromPointer(&ret) + var v Color + ret, f := mallocV(v) + defer f() + colorFromHSV(ret, hue, saturation, value) + copyValueToGo(ret, &v) return v } +// ColorTint - Get color multiplied with another color +// +//go:wasmimport raylib _ColorTint +//go:noescape +func colorTint(color, col, tint cptr) + // ColorTint - Get color multiplied with another color func ColorTint(col color.RGBA, tint color.RGBA) color.RGBA { - ccolor := colorCptr(col) - ctint := colorCptr(tint) - ret := colorTint(*ccolor, *ctint) - v := newColorFromPointer(&ret) - return v -} + ccolor, f := copyValueToC(col) + defer f() -// ColorBrightness - Get color with brightness correction, brightness factor goes from -1.0f to 1.0f -func ColorBrightness(col color.RGBA, factor float32) color.RGBA { - ccolor := colorCptr(col) - cfactor := float(factor) - ret := colorBrightness(*ccolor, cfactor) - v := newColorFromPointer(&ret) + ctint, f := copyValueToC(tint) + defer f() + var v Color + ret, f := mallocV(v) + defer f() + colorTint(ret, ccolor, ctint) return v } +/* + // ColorContrast - Get color with contrast correction, contrast values between -1.0f and 1.0f func ColorContrast(col color.RGBA, contrast float32) color.RGBA { ccolor := colorCptr(col) diff --git a/testdata/api/rlapi.go b/testdata/api/rlapi.go new file mode 100644 index 0000000..a16b779 --- /dev/null +++ b/testdata/api/rlapi.go @@ -0,0 +1,72 @@ +package api + +import ( + _ "embed" + "encoding/json" +) + +var Api RlApi + +//go:embed rlapi.json +var rlApiJson []byte + +func init() { + err := json.Unmarshal(rlApiJson, &Api) + panic(err) +} + +type RlDefine struct { + Name string `json:"name"` + Type string `json:"type"` + Value string `json:"value"` + Description string `json:"description"` +} +type RlField struct { + Type string `json:"type"` + Name string `json:"name"` + Description string `json:"description"` +} +type RlStruct struct { + Name string `json:"name"` + Description string `json:"description"` + Fields []RlField `json:"fields"` +} +type RlAlias struct { + Type string `json:"type"` + Name string `json:"name"` + Description string `json:"description"` +} +type RlValue struct { + Name string `json:"name"` + Value int `json:"value"` + Description string `json:"description"` +} +type RlEnum struct { + Name string `json:"name"` + Description string `json:"description"` + Values []RlValue `json:"values"` +} +type RlParam struct { + Type string `json:"type"` + Name string `json:"name"` +} +type RlCallback struct { + Name string `json:"name"` + Description string `json:"description"` + ReturnType string `json:"returnType"` + Params []RlParam `json:"params"` +} +type RlFunction struct { + Name string `json:"name"` + Description string `json:"description"` + ReturnType string `json:"returnType"` + Params []RlParam `json:"params,omitempty"` +} +type RlApi struct { + Defines []RlDefine `json:"defines"` + Structs []RlStruct `json:"structs"` + Aliases []RlAlias `json:"aliases"` + Enums []RlEnum `json:"enums"` + Callbacks []RlCallback `json:"callbacks"` + Functions []RlFunction `json:"functions"` +} diff --git a/testdata/rcore.json b/testdata/api/rlapi.json similarity index 96% rename from testdata/rcore.json rename to testdata/api/rlapi.json index 1e330c6..d4c059c 100644 --- a/testdata/rcore.json +++ b/testdata/api/rlapi.json @@ -40,7 +40,7 @@ "name": "RLAPI", "type": "UNKNOWN", "value": "__declspec(dllexport)", - "description": "We are building the library as a Win32 shared library (.dll)" + "description": "Building the library as a Win32 shared library (.dll)" }, { "name": "PI", @@ -753,7 +753,7 @@ { "type": "float", "name": "fovy", - "description": "Camera field-of-view aperture in Y (degrees) in perspective, used as near plane width in orthographic" + "description": "Camera field-of-view aperture in Y (degrees) in perspective, used as near plane height in world units in orthographic" }, { "type": "int", @@ -769,22 +769,22 @@ { "type": "Vector2", "name": "offset", - "description": "Camera offset (displacement from target)" + "description": "Camera offset (screen space offset from window origin)" }, { "type": "Vector2", "name": "target", - "description": "Camera target (rotation and zoom origin)" + "description": "Camera target (world space target point that is mapped to screen space offset)" }, { "type": "float", "name": "rotation", - "description": "Camera rotation in degrees" + "description": "Camera rotation in degrees (pivots around target)" }, { "type": "float", "name": "zoom", - "description": "Camera zoom (scaling), should be 1.0f by default" + "description": "Camera zoom (scaling around target), must not be set to 0, set to 1.0f for no scale" } ] }, @@ -1324,11 +1324,6 @@ "name": "FilePathList", "description": "File path list", "fields": [ - { - "type": "unsigned int", - "name": "capacity", - "description": "Filepaths max entries" - }, { "type": "unsigned int", "name": "count", @@ -2300,7 +2295,7 @@ }, { "name": "GamepadAxis", - "description": "Gamepad axis", + "description": "Gamepad axes", "values": [ { "name": "GAMEPAD_AXIS_LEFT_X", @@ -3139,7 +3134,7 @@ "name": "fileName" }, { - "type": "char *", + "type": "const char *", "name": "text" } ] @@ -3161,6 +3156,25 @@ } ], "functions": [ + { + "name": "InitWindow", + "description": "Initialize window and OpenGL context", + "returnType": "void", + "params": [ + { + "type": "int", + "name": "width" + }, + { + "type": "int", + "name": "height" + }, + { + "type": "const char *", + "name": "title" + } + ] + }, { "name": "CloseWindow", "description": "Close window and unload OpenGL context", @@ -4172,6 +4186,17 @@ } ] }, + { + "name": "SetTraceLogLevel", + "description": "Set the current threshold (minimum) log level", + "returnType": "void", + "params": [ + { + "type": "int", + "name": "logLevel" + } + ] + }, { "name": "TraceLog", "description": "Show trace log messages (LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR...)", @@ -4192,13 +4217,13 @@ ] }, { - "name": "SetTraceLogLevel", - "description": "Set the current threshold (minimum) log level", + "name": "SetTraceLogCallback", + "description": "Set custom trace log", "returnType": "void", "params": [ { - "type": "int", - "name": "logLevel" + "type": "TraceLogCallback", + "name": "callback" } ] }, @@ -4240,13 +4265,103 @@ ] }, { - "name": "SetTraceLogCallback", - "description": "Set custom trace log", + "name": "LoadFileData", + "description": "Load file data as byte array (read)", + "returnType": "unsigned char *", + "params": [ + { + "type": "const char *", + "name": "fileName" + }, + { + "type": "int *", + "name": "dataSize" + } + ] + }, + { + "name": "UnloadFileData", + "description": "Unload file data allocated by LoadFileData()", "returnType": "void", "params": [ { - "type": "TraceLogCallback", - "name": "callback" + "type": "unsigned char *", + "name": "data" + } + ] + }, + { + "name": "SaveFileData", + "description": "Save data to file from byte array (write), returns true on success", + "returnType": "bool", + "params": [ + { + "type": "const char *", + "name": "fileName" + }, + { + "type": "void *", + "name": "data" + }, + { + "type": "int", + "name": "dataSize" + } + ] + }, + { + "name": "ExportDataAsCode", + "description": "Export data to code (.h), returns true on success", + "returnType": "bool", + "params": [ + { + "type": "const unsigned char *", + "name": "data" + }, + { + "type": "int", + "name": "dataSize" + }, + { + "type": "const char *", + "name": "fileName" + } + ] + }, + { + "name": "LoadFileText", + "description": "Load text data from file (read), returns a '\\0' terminated string", + "returnType": "char *", + "params": [ + { + "type": "const char *", + "name": "fileName" + } + ] + }, + { + "name": "UnloadFileText", + "description": "Unload file text data allocated by LoadFileText()", + "returnType": "void", + "params": [ + { + "type": "char *", + "name": "text" + } + ] + }, + { + "name": "SaveFileText", + "description": "Save text data to file (write), string must be '\\0' terminated, returns true on success", + "returnType": "bool", + "params": [ + { + "type": "const char *", + "name": "fileName" + }, + { + "type": "const char *", + "name": "text" } ] }, @@ -4295,103 +4410,92 @@ ] }, { - "name": "LoadFileData", - "description": "Load file data as byte array (read)", - "returnType": "unsigned char *", + "name": "FileRename", + "description": "Rename file (if exists)", + "returnType": "int", "params": [ { "type": "const char *", "name": "fileName" }, { - "type": "int *", - "name": "dataSize" + "type": "const char *", + "name": "fileRename" } ] }, { - "name": "UnloadFileData", - "description": "Unload file data allocated by LoadFileData()", - "returnType": "void", + "name": "FileRemove", + "description": "Remove file (if exists)", + "returnType": "int", "params": [ { - "type": "unsigned char *", - "name": "data" + "type": "const char *", + "name": "fileName" } ] }, { - "name": "SaveFileData", - "description": "Save data to file from byte array (write), returns true on success", - "returnType": "bool", + "name": "FileCopy", + "description": "Copy file from one path to another, dstPath created if it doesn't exist", + "returnType": "int", "params": [ { "type": "const char *", - "name": "fileName" + "name": "srcPath" }, { - "type": "void *", - "name": "data" - }, - { - "type": "int", - "name": "dataSize" + "type": "const char *", + "name": "dstPath" } ] }, { - "name": "ExportDataAsCode", - "description": "Export data to code (.h), returns true on success", - "returnType": "bool", + "name": "FileMove", + "description": "Move file from one directory to another, dstPath created if it doesn't exist", + "returnType": "int", "params": [ { - "type": "const unsigned char *", - "name": "data" - }, - { - "type": "int", - "name": "dataSize" + "type": "const char *", + "name": "srcPath" }, { "type": "const char *", - "name": "fileName" + "name": "dstPath" } ] }, { - "name": "LoadFileText", - "description": "Load text data from file (read), returns a '\\0' terminated string", - "returnType": "char *", + "name": "FileTextReplace", + "description": "Replace text in an existing file", + "returnType": "int", "params": [ { "type": "const char *", "name": "fileName" - } - ] - }, - { - "name": "UnloadFileText", - "description": "Unload file text data allocated by LoadFileText()", - "returnType": "void", - "params": [ + }, { - "type": "char *", - "name": "text" + "type": "const char *", + "name": "search" + }, + { + "type": "const char *", + "name": "replacement" } ] }, { - "name": "SaveFileText", - "description": "Save text data to file (write), string must be '\\0' terminated, returns true on success", - "returnType": "bool", + "name": "FileTextFindIndex", + "description": "Find text in existing file", + "returnType": "int", "params": [ { "type": "const char *", "name": "fileName" }, { - "type": "char *", - "name": "text" + "type": "const char *", + "name": "search" } ] }, @@ -4419,7 +4523,7 @@ }, { "name": "IsFileExtension", - "description": "Check file extension (including point: .png, .wav)", + "description": "Check file extension (recommended include point: .png, .wav)", "returnType": "bool", "params": [ { @@ -4443,6 +4547,17 @@ } ] }, + { + "name": "GetFileModTime", + "description": "Get file modification time (last write time)", + "returnType": "long", + "params": [ + { + "type": "const char *", + "name": "fileName" + } + ] + }, { "name": "GetFileExtension", "description": "Get pointer to extension for a filename string (includes dot: '.png')", @@ -4526,7 +4641,7 @@ "params": [ { "type": "const char *", - "name": "dir" + "name": "dirPath" } ] }, @@ -4615,13 +4730,32 @@ ] }, { - "name": "GetFileModTime", - "description": "Get file modification time (last write time)", - "returnType": "long", + "name": "GetDirectoryFileCount", + "description": "Get the file count in a directory", + "returnType": "unsigned int", "params": [ { "type": "const char *", - "name": "fileName" + "name": "dirPath" + } + ] + }, + { + "name": "GetDirectoryFileCountEx", + "description": "Get the file count in a directory with extension filtering and recursive directory scan. Use 'DIR' in the filter string to include directories in the result", + "returnType": "unsigned int", + "params": [ + { + "type": "const char *", + "name": "basePath" + }, + { + "type": "const char *", + "name": "filter" + }, + { + "type": "bool", + "name": "scanSubdirs" } ] }, @@ -4665,7 +4799,7 @@ }, { "name": "EncodeDataBase64", - "description": "Encode data to Base64 string, memory must be MemFree()", + "description": "Encode data to Base64 string (includes NULL terminator), memory must be MemFree()", "returnType": "char *", "params": [ { @@ -4684,12 +4818,12 @@ }, { "name": "DecodeDataBase64", - "description": "Decode Base64 string data, memory must be MemFree()", + "description": "Decode Base64 string (expected NULL terminated), memory must be MemFree()", "returnType": "unsigned char *", "params": [ { - "type": "const unsigned char *", - "name": "data" + "type": "const char *", + "name": "text" }, { "type": "int *", @@ -4742,6 +4876,21 @@ } ] }, + { + "name": "ComputeSHA256", + "description": "Compute SHA256 hash code, returns static int[8] (32 bytes)", + "returnType": "unsigned int *", + "params": [ + { + "type": "unsigned char *", + "name": "data" + }, + { + "type": "int", + "name": "dataSize" + } + ] + }, { "name": "LoadAutomationEventList", "description": "Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS", @@ -4998,7 +5147,7 @@ }, { "name": "GetGamepadAxisCount", - "description": "Get gamepad axis count for a gamepad", + "description": "Get axis count for a gamepad", "returnType": "int", "params": [ { @@ -5009,7 +5158,7 @@ }, { "name": "GetGamepadAxisMovement", - "description": "Get axis movement value for a gamepad axis", + "description": "Get movement value for a gamepad axis", "returnType": "float", "params": [ { @@ -5483,6 +5632,33 @@ } ] }, + { + "name": "DrawLineDashed", + "description": "Draw a dashed line", + "returnType": "void", + "params": [ + { + "type": "Vector2", + "name": "startPos" + }, + { + "type": "Vector2", + "name": "endPos" + }, + { + "type": "int", + "name": "dashSize" + }, + { + "type": "int", + "name": "spaceSize" + }, + { + "type": "Color", + "name": "color" + } + ] + }, { "name": "DrawCircle", "description": "Draw a color-filled circle", @@ -5683,6 +5859,29 @@ } ] }, + { + "name": "DrawEllipseV", + "description": "Draw ellipse (Vector version)", + "returnType": "void", + "params": [ + { + "type": "Vector2", + "name": "center" + }, + { + "type": "float", + "name": "radiusH" + }, + { + "type": "float", + "name": "radiusV" + }, + { + "type": "Color", + "name": "color" + } + ] + }, { "name": "DrawEllipseLines", "description": "Draw ellipse outline", @@ -5710,6 +5909,29 @@ } ] }, + { + "name": "DrawEllipseLinesV", + "description": "Draw ellipse outline (Vector version)", + "returnType": "void", + "params": [ + { + "type": "Vector2", + "name": "center" + }, + { + "type": "float", + "name": "radiusH" + }, + { + "type": "float", + "name": "radiusV" + }, + { + "type": "Color", + "name": "color" + } + ] + }, { "name": "DrawRing", "description": "Draw ring", @@ -5945,11 +6167,11 @@ }, { "type": "Color", - "name": "topRight" + "name": "bottomRight" }, { "type": "Color", - "name": "bottomRight" + "name": "topRight" } ] }, @@ -8237,7 +8459,7 @@ "name": "dst" }, { - "type": "Vector2 *", + "type": "const Vector2 *", "name": "points" }, { @@ -8260,7 +8482,7 @@ "name": "dst" }, { - "type": "Vector2 *", + "type": "const Vector2 *", "name": "points" }, { @@ -8464,7 +8686,7 @@ }, { "name": "UpdateTexture", - "description": "Update GPU texture with new data", + "description": "Update GPU texture with new data (pixels should be able to fill texture)", "returnType": "void", "params": [ { @@ -8479,7 +8701,7 @@ }, { "name": "UpdateTextureRec", - "description": "Update GPU texture rectangle with new data", + "description": "Update GPU texture rectangle with new data (pixels and rec should fit in texture)", "returnType": "void", "params": [ { @@ -8976,7 +9198,7 @@ "name": "fontSize" }, { - "type": "int *", + "type": "const int *", "name": "codepoints" }, { @@ -9026,7 +9248,7 @@ "name": "fontSize" }, { - "type": "int *", + "type": "const int *", "name": "codepoints" }, { @@ -9064,7 +9286,7 @@ "name": "fontSize" }, { - "type": "int *", + "type": "const int *", "name": "codepoints" }, { @@ -9074,6 +9296,10 @@ { "type": "int", "name": "type" + }, + { + "type": "int *", + "name": "glyphCount" } ] }, @@ -9540,6 +9766,36 @@ } ] }, + { + "name": "LoadTextLines", + "description": "Load text as separate lines ('\\n')", + "returnType": "char **", + "params": [ + { + "type": "const char *", + "name": "text" + }, + { + "type": "int *", + "name": "count" + } + ] + }, + { + "name": "UnloadTextLines", + "description": "Unload text lines", + "returnType": "void", + "params": [ + { + "type": "char **", + "name": "text" + }, + { + "type": "int", + "name": "lineCount" + } + ] + }, { "name": "TextCopy", "description": "Copy one string to another, returns bytes copied", @@ -9615,6 +9871,36 @@ } ] }, + { + "name": "TextRemoveSpaces", + "description": "Remove text spaces, concat words", + "returnType": "const char *", + "params": [ + { + "type": "const char *", + "name": "text" + } + ] + }, + { + "name": "GetTextBetween", + "description": "Get text between two strings", + "returnType": "char *", + "params": [ + { + "type": "const char *", + "name": "text" + }, + { + "type": "const char *", + "name": "begin" + }, + { + "type": "const char *", + "name": "end" + } + ] + }, { "name": "TextReplace", "description": "Replace text string (WARNING: memory must be freed!)", @@ -9626,11 +9912,34 @@ }, { "type": "const char *", - "name": "replace" + "name": "search" + }, + { + "type": "const char *", + "name": "replacement" + } + ] + }, + { + "name": "TextReplaceBetween", + "description": "Replace text between two specific strings (WARNING: memory must be freed!)", + "returnType": "char *", + "params": [ + { + "type": "const char *", + "name": "text" + }, + { + "type": "const char *", + "name": "begin" + }, + { + "type": "const char *", + "name": "end" }, { "type": "const char *", - "name": "by" + "name": "replacement" } ] }, @@ -9674,7 +9983,7 @@ }, { "name": "TextSplit", - "description": "Split text into multiple strings", + "description": "Split text into multiple strings, using MAX_TEXTSPLIT_COUNT static strings", "returnType": "char **", "params": [ { @@ -9693,7 +10002,7 @@ }, { "name": "TextAppend", - "description": "Append text at specific position and move cursor!", + "description": "Append text at specific position and move cursor", "returnType": "void", "params": [ { @@ -9712,7 +10021,7 @@ }, { "name": "TextFindIndex", - "description": "Find first text occurrence within a string", + "description": "Find first text occurrence within a string, -1 if not found", "returnType": "int", "params": [ { @@ -9721,7 +10030,7 @@ }, { "type": "const char *", - "name": "find" + "name": "search" } ] }, @@ -11446,7 +11755,7 @@ }, { "name": "UpdateSound", - "description": "Update sound buffer with new data", + "description": "Update sound buffer with new data (default data format: 32 bit float, stereo)", "returnType": "void", "params": [ { @@ -11613,7 +11922,7 @@ }, { "name": "SetSoundPan", - "description": "Set pan for a sound (0.5 is center)", + "description": "Set pan for a sound (-1.0 left, 0.0 center, 1.0 right)", "returnType": "void", "params": [ { @@ -11866,7 +12175,7 @@ }, { "name": "SetMusicPan", - "description": "Set pan for a music (0.5 is center)", + "description": "Set pan for a music (-1.0 left, 0.0 center, 1.0 right)", "returnType": "void", "params": [ { diff --git a/testdata/codegen.go b/testdata/codegen.go new file mode 100644 index 0000000..6a3f65e --- /dev/null +++ b/testdata/codegen.go @@ -0,0 +1,6 @@ +package main + +import "./api" + +func main() { +} diff --git a/testdata/rcore_defines.txt b/testdata/rcore_defines.txt deleted file mode 100644 index e032786..0000000 --- a/testdata/rcore_defines.txt +++ /dev/null @@ -1,2920 +0,0 @@ -package fake - -import ( - "fmt" - "image" - "image/color" - "os" - "reflect" - "unsafe" - - "github.com/ebitengine/purego" - "golang.org/x/sys/windows" -) - - -// CloseWindow - Close window and unload OpenGL context -func CloseWindow() { - closeWindow() -} - -// IsWindowReady - Check if window has been initialized successfully -func IsWindowReady() bool { - return isWindowReady() -} - -// IsWindowFullscreen - Check if window is currently fullscreen -func IsWindowFullscreen() bool { - return isWindowFullscreen() -} - -// IsWindowHidden - Check if window is currently hidden (only PLATFORM_DESKTOP) -func IsWindowHidden() bool { - return isWindowHidden() -} - -// IsWindowMinimized - Check if window is currently minimized (only PLATFORM_DESKTOP) -func IsWindowMinimized() bool { - return isWindowMinimized() -} - -// IsWindowMaximized - Check if window is currently maximized (only PLATFORM_DESKTOP) -func IsWindowMaximized() bool { - return isWindowMaximized() -} - -// IsWindowFocused - Check if window is currently focused (only PLATFORM_DESKTOP) -func IsWindowFocused() bool { - return isWindowFocused() -} - -// IsWindowResized - Check if window has been resized last frame -func IsWindowResized() bool { - return isWindowResized() -} - -// IsWindowState - Check if one specific window flag is enabled -func IsWindowState(flag uint32) bool { - return isWindowState(flag) -} - -// SetWindowState - Set window configuration state using flags (only PLATFORM_DESKTOP) -func SetWindowState(flags uint32) { - setWindowState(flags) -} - -// ClearWindowState - Clear window configuration state flags -func ClearWindowState(flags uint32) { - clearWindowState(flags) -} - -// ToggleFullscreen - Toggle window state: fullscreen/windowed (only PLATFORM_DESKTOP) -func ToggleFullscreen() { - toggleFullscreen() -} - -// ToggleBorderlessWindowed - Toggle window state: borderless windowed (only PLATFORM_DESKTOP) -func ToggleBorderlessWindowed() { - toggleBorderlessWindowed() -} - -// MaximizeWindow - Set window state: maximized, if resizable (only PLATFORM_DESKTOP) -func MaximizeWindow() { - maximizeWindow() -} - -// MinimizeWindow - Set window state: minimized, if resizable (only PLATFORM_DESKTOP) -func MinimizeWindow() { - minimizeWindow() -} - -// RestoreWindow - Set window state: not minimized/maximized (only PLATFORM_DESKTOP) -func RestoreWindow() { - restoreWindow() -} - -// SetWindowIcon - Set icon for window (single image, RGBA 32bit, only PLATFORM_DESKTOP) -func SetWindowIcon(image Image) { - setWindowIcon(uintptr(unsafe.Pointer(&image))) -} - -// SetWindowIcons - Set icon for window (multiple images, RGBA 32bit, only PLATFORM_DESKTOP) -func SetWindowIcons(images []Image, count int32) { - setWindowIcons(uintptr(unsafe.Pointer(&images[0])), int32(len(images))) -} - -// SetWindowTitle - Set title for window (only PLATFORM_DESKTOP and PLATFORM_WEB) -func SetWindowTitle(title string) { - setWindowTitle(title) -} - -// SetWindowPosition - Set window position on screen (only PLATFORM_DESKTOP) -func SetWindowPosition(x int, y int) { - setWindowPosition(int32(x), int32(y)) -} - -// SetWindowMonitor - Set monitor for the current window -func SetWindowMonitor(monitor int) { - setWindowMonitor(int32(monitor)) -} - -// SetWindowMinSize - Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) -func SetWindowMinSize(width int, height int) { - setWindowMinSize(int32(width), int32(height)) -} - -// SetWindowMaxSize - Set window maximum dimensions (for FLAG_WINDOW_RESIZABLE) -func SetWindowMaxSize(width int, height int) { - setWindowMaxSize(int32(width), int32(height)) -} - -// SetWindowSize - Set window dimensions -func SetWindowSize(width int, height int) { - setWindowSize(int32(width), int32(height)) -} - -// SetWindowOpacity - Set window opacity [0.0f..1.0f] (only PLATFORM_DESKTOP) -func SetWindowOpacity(opacity float32) { - setWindowOpacity(opacity) -} - -// SetWindowFocused - Set window focused (only PLATFORM_DESKTOP) -func SetWindowFocused() { - setWindowFocused() -} - -// GetWindowHandle - Get native window handle -func GetWindowHandle() unsafe.Pointer { - return getWindowHandle() -} - -// GetScreenWidth - Get current screen width -func GetScreenWidth() int { - return int(getScreenWidth()) -} - -// GetScreenHeight - Get current screen height -func GetScreenHeight() int { - return int(getScreenHeight()) -} - -// GetRenderWidth - Get current render width (it considers HiDPI) -func GetRenderWidth() int { - return int(getRenderWidth()) -} - -// GetRenderHeight - Get current render height (it considers HiDPI) -func GetRenderHeight() int { - return int(getRenderHeight()) -} - -// GetMonitorCount - Get number of connected monitors -func GetMonitorCount() int { - return int(getMonitorCount()) -} - -// GetCurrentMonitor - Get current monitor where window is placed -func GetCurrentMonitor() int { - return int(getCurrentMonitor()) -} - -// GetMonitorPosition - Get specified monitor position -func GetMonitorPosition(monitor int) Vector2 { - ret := getMonitorPosition(int32(monitor)) - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetMonitorWidth - Get specified monitor width (current video mode used by monitor) -func GetMonitorWidth(monitor int) int { - return int(getMonitorWidth(int32(monitor))) -} - -// GetMonitorHeight - Get specified monitor height (current video mode used by monitor) -func GetMonitorHeight(monitor int) int { - return int(getMonitorHeight(int32(monitor))) -} - -// GetMonitorPhysicalWidth - Get specified monitor physical width in millimetres -func GetMonitorPhysicalWidth(monitor int) int { - return int(getMonitorPhysicalWidth(int32(monitor))) -} - -// GetMonitorPhysicalHeight - Get specified monitor physical height in millimetres -func GetMonitorPhysicalHeight(monitor int) int { - return int(getMonitorPhysicalHeight(int32(monitor))) -} - -// GetMonitorRefreshRate - Get specified monitor refresh rate -func GetMonitorRefreshRate(monitor int) int { - return int(getMonitorRefreshRate(int32(monitor))) -} - -// GetWindowPosition - Get window position XY on monitor -func GetWindowPosition() Vector2 { - ret := getWindowPosition() - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetWindowScaleDPI - Get window scale DPI factor -func GetWindowScaleDPI() Vector2 { - ret := getWindowScaleDPI() - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetMonitorName - Get the human-readable, UTF-8 encoded name of the specified monitor -func GetMonitorName(monitor int) string { - return getMonitorName(int32(monitor)) -} - -// SetClipboardText - Set clipboard text content -func SetClipboardText(text string) { - setClipboardText(text) -} - -// GetClipboardText - Get clipboard text content -func GetClipboardText() string { - return getClipboardText() -} - -// GetClipboardImage - Get clipboard image content -// -// Only works with SDL3 backend or Windows with RGFW/GLFW -func GetClipboardImage() Image { - var img Image - getClipboardImage(uintptr(unsafe.Pointer(&img))) - return img -} - -// EnableEventWaiting - Enable waiting for events on EndDrawing(), no automatic event polling -func EnableEventWaiting() { - enableEventWaiting() -} - -// DisableEventWaiting - Disable waiting for events on EndDrawing(), automatic events polling -func DisableEventWaiting() { - disableEventWaiting() -} - -// ShowCursor - Shows cursor -func ShowCursor() { - showCursor() -} - -// HideCursor - Hides cursor -func HideCursor() { - hideCursor() -} - -// IsCursorHidden - Check if cursor is not visible -func IsCursorHidden() bool { - return isCursorHidden() -} - -// EnableCursor - Enables cursor (unlock cursor) -func EnableCursor() { - enableCursor() -} - -// DisableCursor - Disables cursor (lock cursor) -func DisableCursor() { - disableCursor() -} - -// IsCursorOnScreen - Check if cursor is on the screen -func IsCursorOnScreen() bool { - return isCursorOnScreen() -} - -// ClearBackground - Set background color (framebuffer clear color) -func ClearBackground(col color.RGBA) { - clearBackground(*(*uintptr)(unsafe.Pointer(&col))) -} - -// BeginDrawing - Setup canvas (framebuffer) to start drawing -func BeginDrawing() { - beginDrawing() -} - -// EndDrawing - End canvas drawing and swap buffers (double buffering) -func EndDrawing() { - endDrawing() -} - -// BeginMode2D - Begin 2D mode with custom camera (2D) -func BeginMode2D(camera Camera2D) { - beginMode2D(uintptr(unsafe.Pointer(&camera))) -} - -// EndMode2D - Ends 2D mode with custom camera -func EndMode2D() { - endMode2D() -} - -// BeginMode3D - Begin 3D mode with custom camera (3D) -func BeginMode3D(camera Camera3D) { - beginMode3D(uintptr(unsafe.Pointer(&camera))) -} - -// EndMode3D - Ends 3D mode and returns to default 2D orthographic mode -func EndMode3D() { - endMode3D() -} - -// BeginTextureMode - Begin drawing to render texture -func BeginTextureMode(target RenderTexture2D) { - beginTextureMode(uintptr(unsafe.Pointer(&target))) -} - -// EndTextureMode - Ends drawing to render texture -func EndTextureMode() { - endTextureMode() -} - -// BeginShaderMode - Begin custom shader drawing -func BeginShaderMode(shader Shader) { - beginShaderMode(uintptr(unsafe.Pointer(&shader))) -} - -// EndShaderMode - End custom shader drawing (use default shader) -func EndShaderMode() { - endShaderMode() -} - -// BeginBlendMode - Begin blending mode (alpha, additive, multiplied, subtract, custom) -func BeginBlendMode(mode BlendMode) { - beginBlendMode(int32(mode)) -} - -// EndBlendMode - End blending mode (reset to default: alpha blending) -func EndBlendMode() { - endBlendMode() -} - -// BeginScissorMode - Begin scissor mode (define screen area for following drawing) -func BeginScissorMode(x int32, y int32, width int32, height int32) { - beginScissorMode(x, y, width, height) -} - -// EndScissorMode - End scissor mode -func EndScissorMode() { - endScissorMode() -} - -// BeginVrStereoMode - Begin stereo rendering (requires VR simulator) -func BeginVrStereoMode(config VrStereoConfig) { - beginVrStereoMode(uintptr(unsafe.Pointer(&config))) -} - -// EndVrStereoMode - End stereo rendering (requires VR simulator) -func EndVrStereoMode() { - endVrStereoMode() -} - -// LoadVrStereoConfig - Load VR stereo config for VR simulator device parameters -func LoadVrStereoConfig(device VrDeviceInfo) VrStereoConfig { - var config VrStereoConfig - loadVrStereoConfig(uintptr(unsafe.Pointer(&config)), uintptr(unsafe.Pointer(&device))) - return config -} - -// UnloadVrStereoConfig - Unload VR stereo config -func UnloadVrStereoConfig(config VrStereoConfig) { - unloadVrStereoConfig(uintptr(unsafe.Pointer(&config))) -} - -// LoadShader - Load shader from files and bind default locations -func LoadShader(vsFileName string, fsFileName string) Shader { - var shader Shader - var cvsFileName, cfsFileName *byte - if vsFileName != "" { - var err error - cvsFileName, err = windows.BytePtrFromString(vsFileName) - if err != nil { - panic(err) - } - } - if fsFileName != "" { - var err error - cfsFileName, err = windows.BytePtrFromString(fsFileName) - if err != nil { - panic(err) - } - } - loadShader(uintptr(unsafe.Pointer(&shader)), uintptr(unsafe.Pointer(cvsFileName)), uintptr(unsafe.Pointer(cfsFileName))) - return shader -} - -// LoadShaderFromMemory - Load shader from code strings and bind default locations -func LoadShaderFromMemory(vsCode string, fsCode string) Shader { - var shader Shader - var cvsCode, cfsCode *byte - if vsCode != "" { - var err error - cvsCode, err = windows.BytePtrFromString(vsCode) - if err != nil { - panic(err) - } - } - if fsCode != "" { - var err error - cfsCode, err = windows.BytePtrFromString(fsCode) - if err != nil { - panic(err) - } - } - loadShaderFromMemory(uintptr(unsafe.Pointer(&shader)), uintptr(unsafe.Pointer(cvsCode)), uintptr(unsafe.Pointer(cfsCode))) - return shader -} - -// IsShaderValid - Check if a shader is valid (loaded on GPU) -func IsShaderValid(shader Shader) bool { - return isShaderValid(uintptr(unsafe.Pointer(&shader))) -} - -// GetShaderLocation - Get shader uniform location -func GetShaderLocation(shader Shader, uniformName string) int32 { - return getShaderLocation(uintptr(unsafe.Pointer(&shader)), uniformName) -} - -// GetShaderLocationAttrib - Get shader attribute location -func GetShaderLocationAttrib(shader Shader, attribName string) int32 { - return getShaderLocationAttrib(uintptr(unsafe.Pointer(&shader)), attribName) -} - -// SetShaderValue - Set shader uniform value -func SetShaderValue(shader Shader, locIndex int32, value []float32, uniformType ShaderUniformDataType) { - setShaderValue(uintptr(unsafe.Pointer(&shader)), locIndex, value, int32(uniformType)) -} - -// SetShaderValueV - Set shader uniform value vector -func SetShaderValueV(shader Shader, locIndex int32, value []float32, uniformType ShaderUniformDataType, count int32) { - setShaderValueV(uintptr(unsafe.Pointer(&shader)), locIndex, value, int32(uniformType), count) -} - -// SetShaderValueMatrix - Set shader uniform value (matrix 4x4) -func SetShaderValueMatrix(shader Shader, locIndex int32, mat Matrix) { - setShaderValueMatrix(uintptr(unsafe.Pointer(&shader)), locIndex, uintptr(unsafe.Pointer(&mat))) -} - -// SetShaderValueTexture - Set shader uniform value for texture (sampler2d) -func SetShaderValueTexture(shader Shader, locIndex int32, texture Texture2D) { - setShaderValueTexture(uintptr(unsafe.Pointer(&shader)), locIndex, uintptr(unsafe.Pointer(&texture))) -} - -// UnloadShader - Unload shader from GPU memory (VRAM) -func UnloadShader(shader Shader) { - unloadShader(uintptr(unsafe.Pointer(&shader))) -} - -// GetMouseRay - Get a ray trace from mouse position -// -// Deprecated: Use [GetScreenToWorldRay] instead. -func GetMouseRay(mousePosition Vector2, camera Camera) Ray { - return GetScreenToWorldRay(mousePosition, camera) -} - -// GetScreenToWorldRay - Get a ray trace from screen position (i.e mouse) -func GetScreenToWorldRay(position Vector2, camera Camera) Ray { - var ray Ray - getScreenToWorldRay(uintptr(unsafe.Pointer(&ray)), *(*uintptr)(unsafe.Pointer(&position)), uintptr(unsafe.Pointer(&camera))) - return ray -} - -// GetScreenToWorldRayEx - Get a ray trace from screen position (i.e mouse) in a viewport -func GetScreenToWorldRayEx(position Vector2, camera Camera, width, height int32) Ray { - var ray Ray - getScreenToWorldRayEx(uintptr(unsafe.Pointer(&ray)), *(*uintptr)(unsafe.Pointer(&position)), uintptr(unsafe.Pointer(&camera)), width, height) - return ray -} - -// GetCameraMatrix - Get camera transform matrix (view matrix) -func GetCameraMatrix(camera Camera) Matrix { - var mat Matrix - getCameraMatrix(uintptr(unsafe.Pointer(&mat)), uintptr(unsafe.Pointer(&camera))) - return mat -} - -// GetCameraMatrix2D - Get camera 2d transform matrix -func GetCameraMatrix2D(camera Camera2D) Matrix { - var mat Matrix - getCameraMatrix2D(uintptr(unsafe.Pointer(&mat)), uintptr(unsafe.Pointer(&camera))) - return mat -} - -// GetWorldToScreen - Get the screen space position for a 3d world space position -func GetWorldToScreen(position Vector3, camera Camera) Vector2 { - ret := getWorldToScreen(uintptr(unsafe.Pointer(&position)), uintptr(unsafe.Pointer(&camera))) - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetScreenToWorld2D - Get the world space position for a 2d camera screen space position -func GetScreenToWorld2D(position Vector2, camera Camera2D) Vector2 { - ret := getScreenToWorld2D(*(*uintptr)(unsafe.Pointer(&position)), uintptr(unsafe.Pointer(&camera))) - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetWorldToScreenEx - Get size position for a 3d world space position -func GetWorldToScreenEx(position Vector3, camera Camera, width int32, height int32) Vector2 { - ret := getWorldToScreenEx(uintptr(unsafe.Pointer(&position)), uintptr(unsafe.Pointer(&camera)), width, height) - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetWorldToScreen2D - Get the screen space position for a 2d camera world space position -func GetWorldToScreen2D(position Vector2, camera Camera2D) Vector2 { - ret := getWorldToScreen2D(*(*uintptr)(unsafe.Pointer(&position)), uintptr(unsafe.Pointer(&camera))) - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// SetTargetFPS - Set target FPS (maximum) -func SetTargetFPS(fps int32) { - setTargetFPS(fps) -} - -// GetFrameTime - Get time in seconds for last frame drawn (delta time) -func GetFrameTime() float32 { - return getFrameTime() -} - -// GetTime - Get elapsed time in seconds since InitWindow() -func GetTime() float64 { - return getTime() -} - -// GetFPS - Get current FPS -func GetFPS() int32 { - return getFPS() -} - -// Custom frame control functions -// NOTE: SwapScreenBuffer and PollInputEvents are intended for advanced users that want full control over the frame processing -// By default EndDrawing() does this job: draws everything + SwapScreenBuffer() + manage frame timing + PollInputEvents() -// To avoid that behaviour and control frame processes manually you must recompile raylib with SUPPORT_CUSTOM_FRAME_CONTROL enabled in config.h - -// SwapScreenBuffer - Swap back buffer with front buffer (screen drawing) -func SwapScreenBuffer() { - swapScreenBuffer() -} - -// PollInputEvents - Register all input events -func PollInputEvents() { - pollInputEvents() -} - -// WaitTime - Wait for some time (halt program execution) -func WaitTime(seconds float64) { - waitTime(seconds) -} - -// SetRandomSeed - Set the seed for the random number generator -// -// Note: You can use go's math/rand package instead -func SetRandomSeed(seed uint32) { - setRandomSeed(seed) -} - -// GetRandomValue - Get a random value between min and max (both included) -// -// Note: You can use go's math/rand package instead -func GetRandomValue(minimum int32, maximum int32) int32 { - return getRandomValue(minimum, maximum) -} - -// LoadRandomSequence - Load random values sequence, no values repeated -// -// Note: Use UnloadRandomSequence if you don't need the sequence any more. You can use go's math/rand.Perm function instead. -func LoadRandomSequence(count uint32, minimum int32, maximum int32) []int32 { - ret := loadRandomSequence(count, minimum, maximum) - return unsafe.Slice(ret, 10) -} - -// UnloadRandomSequence - Unload random values sequence -func UnloadRandomSequence(sequence []int32) { - unloadRandomSequence(unsafe.SliceData(sequence)) -} - -// TakeScreenshot - Takes a screenshot of current screen (filename extension defines format) -func TakeScreenshot(fileName string) { - takeScreenshot(fileName) -} - -// SetConfigFlags - Setup init configuration flags (view FLAGS) -func SetConfigFlags(flags uint32) { - setConfigFlags(flags) -} - -// OpenURL - Open URL with default system browser (if available) -func OpenURL(url string) { - openURL(url) -} - -// TraceLog - Show trace log messages (LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR...) -func TraceLog(logLevel TraceLogLevel, text string, args ...any) { - traceLog(int32(logLevel), fmt.Sprintf(text, args...)) -} - -// SetTraceLogLevel - Set the current threshold (minimum) log level -func SetTraceLogLevel(logLevel TraceLogLevel) { - setTraceLogLevel(int32(logLevel)) -} - -// MemAlloc - Internal memory allocator -func MemAlloc(size uint32) unsafe.Pointer { - return memAlloc(size) -} - -// MemRealloc - Internal memory reallocator -func MemRealloc(ptr unsafe.Pointer, size uint32) unsafe.Pointer { - return memRealloc(ptr, size) -} - -// MemFree - Internal memory free -func MemFree(ptr unsafe.Pointer) { - memFree(ptr) -} - - -// IsFileDropped - Check if a file has been dropped into window -func IsFileDropped() bool { - return isFileDropped() -} - -// LoadDroppedFiles - Load dropped filepaths -func LoadDroppedFiles() []string { - var filePathList = struct { - capacity uint32 - count uint32 - paths **byte - }{} - loadDroppedFiles(uintptr(unsafe.Pointer(&filePathList))) - defer unloadDroppedFiles(uintptr(unsafe.Pointer(&filePathList))) - - tmpslice := (*[1 << 24]*byte)(unsafe.Pointer(filePathList.paths))[:filePathList.count:filePathList.count] - - gostrings := make([]string, filePathList.count) - for i, s := range tmpslice { - gostrings[i] = func(p *byte) string { - if p == nil || *p == 0 { - return "" - } - - n := 0 - for ptr := unsafe.Pointer(p); *(*byte)(ptr) != 0; n++ { - ptr = unsafe.Pointer(uintptr(ptr) + 1) - } - - return string(unsafe.Slice(p, n)) - }(s) - } - - return gostrings -} - -// UnloadDroppedFiles - Unload dropped filepaths -func UnloadDroppedFiles() {} - -// LoadAutomationEventList - Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS -func LoadAutomationEventList(fileName string) AutomationEventList { - var automationEventList AutomationEventList - loadAutomationEventList(uintptr(unsafe.Pointer(&automationEventList)), fileName) - return automationEventList -} - -// UnloadAutomationEventList - Unload automation events list from file -func UnloadAutomationEventList(list *AutomationEventList) { - unloadAutomationEventList(uintptr(unsafe.Pointer(&list))) -} - -// ExportAutomationEventList - Export automation events list as text file -func ExportAutomationEventList(list AutomationEventList, fileName string) bool { - return exportAutomationEventList(uintptr(unsafe.Pointer(&list)), fileName) -} - -// SetAutomationEventList - Set automation event list to record to -func SetAutomationEventList(list *AutomationEventList) { - setAutomationEventList(uintptr(unsafe.Pointer(&list))) -} - -// SetAutomationEventBaseFrame - Set automation event internal base frame to start recording -func SetAutomationEventBaseFrame(frame int) { - setAutomationEventBaseFrame(int32(frame)) -} - -// StartAutomationEventRecording - Start recording automation events (AutomationEventList must be set) -func StartAutomationEventRecording() { - startAutomationEventRecording() -} - -// StopAutomationEventRecording - Stop recording automation events -func StopAutomationEventRecording() { - stopAutomationEventRecording() -} - -// PlayAutomationEvent - Play a recorded automation event -func PlayAutomationEvent(event AutomationEvent) { - playAutomationEvent(uintptr(unsafe.Pointer(&event))) -} - -// IsKeyPressed - Check if a key has been pressed once -func IsKeyPressed(key int32) bool { - return isKeyPressed(key) -} - -// IsKeyPressedRepeat - Check if a key has been pressed again (Only PLATFORM_DESKTOP) -func IsKeyPressedRepeat(key int32) bool { - return isKeyPressedRepeat(key) -} - -// IsKeyDown - Check if a key is being pressed -func IsKeyDown(key int32) bool { - return isKeyDown(key) -} - -// IsKeyReleased - Check if a key has been released once -func IsKeyReleased(key int32) bool { - return isKeyReleased(key) -} - -// IsKeyUp - Check if a key is NOT being pressed -func IsKeyUp(key int32) bool { - return isKeyUp(key) -} - -// GetKeyPressed - Get key pressed (keycode), call it multiple times for keys queued, returns 0 when the queue is empty -func GetKeyPressed() int32 { - return getKeyPressed() -} - -// GetCharPressed - Get char pressed (unicode), call it multiple times for chars queued, returns 0 when the queue is empty -func GetCharPressed() int32 { - return getCharPressed() -} - -// SetExitKey - Set a custom key to exit program (default is ESC) -func SetExitKey(key int32) { - setExitKey(key) -} - -// IsGamepadAvailable - Check if a gamepad is available -func IsGamepadAvailable(gamepad int32) bool { - return isGamepadAvailable(gamepad) -} - -// GetGamepadName - Get gamepad internal name id -func GetGamepadName(gamepad int32) string { - return getGamepadName(gamepad) -} - -// IsGamepadButtonPressed - Check if a gamepad button has been pressed once -func IsGamepadButtonPressed(gamepad int32, button int32) bool { - return isGamepadButtonPressed(gamepad, button) -} - -// IsGamepadButtonDown - Check if a gamepad button is being pressed -func IsGamepadButtonDown(gamepad int32, button int32) bool { - return isGamepadButtonDown(gamepad, button) -} - -// IsGamepadButtonReleased - Check if a gamepad button has been released once -func IsGamepadButtonReleased(gamepad int32, button int32) bool { - return isGamepadButtonReleased(gamepad, button) -} - -// IsGamepadButtonUp - Check if a gamepad button is NOT being pressed -func IsGamepadButtonUp(gamepad int32, button int32) bool { - return isGamepadButtonUp(gamepad, button) -} - -// GetGamepadButtonPressed - Get the last gamepad button pressed -func GetGamepadButtonPressed() int32 { - return getGamepadButtonPressed() -} - -// GetGamepadAxisCount - Get gamepad axis count for a gamepad -func GetGamepadAxisCount(gamepad int32) int32 { - return getGamepadAxisCount(gamepad) -} - -// GetGamepadAxisMovement - Get axis movement value for a gamepad axis -func GetGamepadAxisMovement(gamepad int32, axis int32) float32 { - return getGamepadAxisMovement(gamepad, axis) -} - -// SetGamepadMappings - Set internal gamepad mappings (SDL_GameControllerDB) -func SetGamepadMappings(mappings string) int32 { - return setGamepadMappings(mappings) -} - -// SetGamepadVibration - Set gamepad vibration for both motors (duration in seconds) -func SetGamepadVibration(gamepad int32, leftMotor, rightMotor, duration float32) { - setGamepadVibration(gamepad, leftMotor, rightMotor, duration) -} - -// IsMouseButtonPressed - Check if a mouse button has been pressed once -func IsMouseButtonPressed(button MouseButton) bool { - return isMouseButtonPressed(int32(button)) -} - -// IsMouseButtonDown - Check if a mouse button is being pressed -func IsMouseButtonDown(button MouseButton) bool { - return isMouseButtonDown(int32(button)) -} - -// IsMouseButtonReleased - Check if a mouse button has been released once -func IsMouseButtonReleased(button MouseButton) bool { - return isMouseButtonReleased(int32(button)) -} - -// IsMouseButtonUp - Check if a mouse button is NOT being pressed -func IsMouseButtonUp(button MouseButton) bool { - return isMouseButtonUp(int32(button)) -} - -// GetMouseX - Get mouse position X -func GetMouseX() int32 { - return getMouseX() -} - -// GetMouseY - Get mouse position Y -func GetMouseY() int32 { - return getMouseY() -} - -// GetMousePosition - Get mouse position XY -func GetMousePosition() Vector2 { - ret := getMousePosition() - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetMouseDelta - Get mouse delta between frames -func GetMouseDelta() Vector2 { - ret := getMouseDelta() - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// SetMousePosition - Set mouse position XY -func SetMousePosition(x int32, y int32) { - setMousePosition(x, y) -} - -// SetMouseOffset - Set mouse offset -func SetMouseOffset(offsetX int32, offsetY int32) { - setMouseOffset(offsetX, offsetY) -} - -// SetMouseScale - Set mouse scaling -func SetMouseScale(scaleX float32, scaleY float32) { - setMouseScale(scaleX, scaleY) -} - -// GetMouseWheelMove - Get mouse wheel movement for X or Y, whichever is larger -func GetMouseWheelMove() float32 { - return getMouseWheelMove() -} - -// GetMouseWheelMoveV - Get mouse wheel movement for both X and Y -func GetMouseWheelMoveV() Vector2 { - ret := getMouseWheelMoveV() - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// SetMouseCursor - Set mouse cursor -func SetMouseCursor(cursor int32) { - setMouseCursor(cursor) -} - -// GetTouchX - Get touch position X for touch point 0 (relative to screen size) -func GetTouchX() int32 { - return getTouchX() -} - -// GetTouchY - Get touch position Y for touch point 0 (relative to screen size) -func GetTouchY() int32 { - return getTouchY() -} - -// GetTouchPosition - Get touch position XY for a touch point index (relative to screen size) -func GetTouchPosition(index int32) Vector2 { - ret := getTouchPosition(index) - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetTouchPointId - Get touch point identifier for given index -func GetTouchPointId(index int32) int32 { - return getTouchPointId(index) -} - -// GetTouchPointCount - Get number of touch points -func GetTouchPointCount() int32 { - return getTouchPointCount() -} - -// SetGesturesEnabled - Enable a set of gestures using flags -func SetGesturesEnabled(flags uint32) { - setGesturesEnabled(flags) -} - -// IsGestureDetected - Check if a gesture have been detected -func IsGestureDetected(gesture Gestures) bool { - return isGestureDetected(uint32(gesture)) -} - -// GetGestureDetected - Get latest detected gesture -func GetGestureDetected() Gestures { - return Gestures(getGestureDetected()) -} - -// GetGestureHoldDuration - Get gesture hold time in milliseconds -func GetGestureHoldDuration() float32 { - return getGestureHoldDuration() -} - -// GetGestureDragVector - Get gesture drag vector -func GetGestureDragVector() Vector2 { - ret := getGestureDragVector() - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetGestureDragAngle - Get gesture drag angle -func GetGestureDragAngle() float32 { - return getGestureDragAngle() -} - -// GetGesturePinchVector - Get gesture pinch delta -func GetGesturePinchVector() Vector2 { - ret := getGesturePinchVector() - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetGesturePinchAngle - Get gesture pinch angle -func GetGesturePinchAngle() float32 { - return getGesturePinchAngle() -} - -// SetShapesTexture - Set texture and rectangle to be used on shapes drawing -func SetShapesTexture(texture Texture2D, source Rectangle) { - setShapesTexture(uintptr(unsafe.Pointer(&texture)), uintptr(unsafe.Pointer(&source))) -} - -// GetShapesTexture - Get texture that is used for shapes drawing -func GetShapesTexture() Texture2D { - var texture Texture2D - getShapesTexture(uintptr(unsafe.Pointer(&texture))) - return texture -} - -// GetShapesTextureRectangle - Get texture source rectangle that is used for shapes drawing -func GetShapesTextureRectangle() Rectangle { - var rec Rectangle - getShapesTextureRectangle(uintptr(unsafe.Pointer(&rec))) - return rec -} - -// DrawPixel - Draw a pixel -func DrawPixel(posX int32, posY int32, col color.RGBA) { - drawPixel(posX, posY, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawPixelV - Draw a pixel (Vector version) -func DrawPixelV(position Vector2, col color.RGBA) { - drawPixelV(*(*uintptr)(unsafe.Pointer(&position)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawLine - Draw a line -func DrawLine(startPosX int32, startPosY int32, endPosX int32, endPosY int32, col color.RGBA) { - drawLine(startPosX, startPosY, endPosX, endPosY, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawLineV - Draw a line (using gl lines) -func DrawLineV(startPos Vector2, endPos Vector2, col color.RGBA) { - drawLineV(*(*uintptr)(unsafe.Pointer(&startPos)), *(*uintptr)(unsafe.Pointer(&endPos)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawLineEx - Draw a line (using triangles/quads) -func DrawLineEx(startPos Vector2, endPos Vector2, thick float32, col color.RGBA) { - drawLineEx(*(*uintptr)(unsafe.Pointer(&startPos)), *(*uintptr)(unsafe.Pointer(&endPos)), thick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawLineStrip - Draw lines sequence (using gl lines) -func DrawLineStrip(points []Vector2, col color.RGBA) { - pointCount := int32(len(points)) - drawLineStrip((unsafe.SliceData(points)), pointCount, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawLineBezier - Draw line segment cubic-bezier in-out interpolation -func DrawLineBezier(startPos Vector2, endPos Vector2, thick float32, col color.RGBA) { - drawLineBezier(*(*uintptr)(unsafe.Pointer(&startPos)), *(*uintptr)(unsafe.Pointer(&endPos)), thick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCircle - Draw a color-filled circle -func DrawCircle(centerX int32, centerY int32, radius float32, col color.RGBA) { - drawCircle(centerX, centerY, radius, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCircleSector - Draw a piece of a circle -func DrawCircleSector(center Vector2, radius float32, startAngle float32, endAngle float32, segments int32, col color.RGBA) { - drawCircleSector(*(*uintptr)(unsafe.Pointer(¢er)), radius, startAngle, endAngle, segments, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCircleSectorLines - Draw circle sector outline -func DrawCircleSectorLines(center Vector2, radius float32, startAngle float32, endAngle float32, segments int32, col color.RGBA) { - drawCircleSectorLines(*(*uintptr)(unsafe.Pointer(¢er)), radius, startAngle, endAngle, segments, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCircleGradient - Draw a gradient-filled circle -func DrawCircleGradient(centerX int32, centerY int32, radius float32, inner color.RGBA, outer color.RGBA) { - drawCircleGradient(centerX, centerY, radius, *(*uintptr)(unsafe.Pointer(&inner)), *(*uintptr)(unsafe.Pointer(&outer))) -} - -// DrawCircleV - Draw a color-filled circle (Vector version) -func DrawCircleV(center Vector2, radius float32, col color.RGBA) { - drawCircleV(*(*uintptr)(unsafe.Pointer(¢er)), radius, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCircleLines - Draw circle outline -func DrawCircleLines(centerX int32, centerY int32, radius float32, col color.RGBA) { - drawCircleLines(centerX, centerY, radius, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCircleLinesV - Draw circle outline (Vector version) -func DrawCircleLinesV(center Vector2, radius float32, col color.RGBA) { - drawCircleLinesV(*(*uintptr)(unsafe.Pointer(¢er)), radius, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawEllipse - Draw ellipse -func DrawEllipse(centerX int32, centerY int32, radiusH float32, radiusV float32, col color.RGBA) { - drawEllipse(centerX, centerY, radiusH, radiusV, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawEllipseLines - Draw ellipse outline -func DrawEllipseLines(centerX int32, centerY int32, radiusH float32, radiusV float32, col color.RGBA) { - drawEllipseLines(centerX, centerY, radiusH, radiusV, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawRing - Draw ring -func DrawRing(center Vector2, innerRadius float32, outerRadius float32, startAngle float32, endAngle float32, segments int32, col color.RGBA) { - drawRing(*(*uintptr)(unsafe.Pointer(¢er)), innerRadius, outerRadius, startAngle, endAngle, segments, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawRingLines - Draw ring outline -func DrawRingLines(center Vector2, innerRadius float32, outerRadius float32, startAngle float32, endAngle float32, segments int32, col color.RGBA) { - drawRingLines(*(*uintptr)(unsafe.Pointer(¢er)), innerRadius, outerRadius, startAngle, endAngle, segments, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawRectangle - Draw a color-filled rectangle -func DrawRectangle(posX int32, posY int32, width int32, height int32, col color.RGBA) { - drawRectangle(posX, posY, width, height, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawRectangleV - Draw a color-filled rectangle (Vector version) -func DrawRectangleV(position Vector2, size Vector2, col color.RGBA) { - drawRectangleV(*(*uintptr)(unsafe.Pointer(&position)), *(*uintptr)(unsafe.Pointer(&size)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawRectangleRec - Draw a color-filled rectangle -func DrawRectangleRec(rec Rectangle, col color.RGBA) { - drawRectangleRec(uintptr(unsafe.Pointer(&rec)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawRectanglePro - Draw a color-filled rectangle with pro parameters -func DrawRectanglePro(rec Rectangle, origin Vector2, rotation float32, col color.RGBA) { - drawRectanglePro(uintptr(unsafe.Pointer(&rec)), *(*uintptr)(unsafe.Pointer(&origin)), rotation, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawRectangleGradientV - Draw a vertical-gradient-filled rectangle -func DrawRectangleGradientV(posX int32, posY int32, width int32, height int32, top color.RGBA, bottom color.RGBA) { - drawRectangleGradientV(posX, posY, width, height, *(*uintptr)(unsafe.Pointer(&top)), *(*uintptr)(unsafe.Pointer(&bottom))) -} - -// DrawRectangleGradientH - Draw a horizontal-gradient-filled rectangle -func DrawRectangleGradientH(posX int32, posY int32, width int32, height int32, left color.RGBA, right color.RGBA) { - drawRectangleGradientH(posX, posY, width, height, *(*uintptr)(unsafe.Pointer(&left)), *(*uintptr)(unsafe.Pointer(&right))) -} - -// DrawRectangleGradientEx - Draw a gradient-filled rectangle with custom vertex colors -func DrawRectangleGradientEx(rec Rectangle, topLeft color.RGBA, bottomLeft color.RGBA, topRight color.RGBA, bottomRight color.RGBA) { - drawRectangleGradientEx(uintptr(unsafe.Pointer(&rec)), *(*uintptr)(unsafe.Pointer(&topLeft)), *(*uintptr)(unsafe.Pointer(&bottomLeft)), *(*uintptr)(unsafe.Pointer(&topRight)), *(*uintptr)(unsafe.Pointer(&bottomRight))) -} - -// DrawRectangleLines - Draw rectangle outline -func DrawRectangleLines(posX int32, posY int32, width int32, height int32, col color.RGBA) { - drawRectangleLines(posX, posY, width, height, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawRectangleLinesEx - Draw rectangle outline with extended parameters -func DrawRectangleLinesEx(rec Rectangle, lineThick float32, col color.RGBA) { - drawRectangleLinesEx(uintptr(unsafe.Pointer(&rec)), lineThick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawRectangleRounded - Draw rectangle with rounded edges -func DrawRectangleRounded(rec Rectangle, roundness float32, segments int32, col color.RGBA) { - drawRectangleRounded(uintptr(unsafe.Pointer(&rec)), roundness, segments, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawRectangleRoundedLines - Draw rectangle lines with rounded edges -func DrawRectangleRoundedLines(rec Rectangle, roundness float32, segments int32, col color.RGBA) { - drawRectangleRoundedLines(uintptr(unsafe.Pointer(&rec)), roundness, segments, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawRectangleRoundedLinesEx - Draw rectangle with rounded edges outline -func DrawRectangleRoundedLinesEx(rec Rectangle, roundness float32, segments int32, lineThick float32, col color.RGBA) { - drawRectangleRoundedLinesEx(uintptr(unsafe.Pointer(&rec)), roundness, segments, lineThick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawTriangle - Draw a color-filled triangle (vertex in counter-clockwise order!) -func DrawTriangle(v1 Vector2, v2 Vector2, v3 Vector2, col color.RGBA) { - drawTriangle(*(*uintptr)(unsafe.Pointer(&v1)), *(*uintptr)(unsafe.Pointer(&v2)), *(*uintptr)(unsafe.Pointer(&v3)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawTriangleLines - Draw triangle outline (vertex in counter-clockwise order!) -func DrawTriangleLines(v1 Vector2, v2 Vector2, v3 Vector2, col color.RGBA) { - drawTriangleLines(*(*uintptr)(unsafe.Pointer(&v1)), *(*uintptr)(unsafe.Pointer(&v2)), *(*uintptr)(unsafe.Pointer(&v3)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawTriangleFan - Draw a triangle fan defined by points (first vertex is the center) -func DrawTriangleFan(points []Vector2, col color.RGBA) { - pointCount := int32(len(points)) - drawTriangleFan(unsafe.SliceData(points), pointCount, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawTriangleStrip - Draw a triangle strip defined by points -func DrawTriangleStrip(points []Vector2, col color.RGBA) { - pointCount := int32(len(points)) - drawTriangleStrip(unsafe.SliceData(points), pointCount, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawPoly - Draw a regular polygon (Vector version) -func DrawPoly(center Vector2, sides int32, radius float32, rotation float32, col color.RGBA) { - drawPoly(*(*uintptr)(unsafe.Pointer(¢er)), sides, radius, rotation, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawPolyLines - Draw a polygon outline of n sides -func DrawPolyLines(center Vector2, sides int32, radius float32, rotation float32, col color.RGBA) { - drawPolyLines(*(*uintptr)(unsafe.Pointer(¢er)), sides, radius, rotation, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawPolyLinesEx - Draw a polygon outline of n sides with extended parameters -func DrawPolyLinesEx(center Vector2, sides int32, radius float32, rotation float32, lineThick float32, col color.RGBA) { - drawPolyLinesEx(*(*uintptr)(unsafe.Pointer(¢er)), sides, radius, rotation, lineThick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawSplineLinear - Draw spline: Linear, minimum 2 points -func DrawSplineLinear(points []Vector2, thick float32, col color.RGBA) { - pointCount := int32(len(points)) - drawSplineLinear(unsafe.SliceData(points), pointCount, thick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawSplineBasis - Draw spline: B-Spline, minimum 4 points -func DrawSplineBasis(points []Vector2, thick float32, col color.RGBA) { - pointCount := int32(len(points)) - drawSplineBasis(unsafe.SliceData(points), pointCount, thick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawSplineCatmullRom - Draw spline: Catmull-Rom, minimum 4 points -func DrawSplineCatmullRom(points []Vector2, thick float32, col color.RGBA) { - pointCount := int32(len(points)) - drawSplineCatmullRom(unsafe.SliceData(points), pointCount, thick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawSplineBezierQuadratic - Draw spline: Quadratic Bezier, minimum 3 points (1 control point): [p1, c2, p3, c4...] -func DrawSplineBezierQuadratic(points []Vector2, thick float32, col color.RGBA) { - pointCount := int32(len(points)) - drawSplineBezierQuadratic(unsafe.SliceData(points), pointCount, thick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawSplineBezierCubic - Draw spline: Cubic Bezier, minimum 4 points (2 control points): [p1, c2, c3, p4, c5, c6...] -func DrawSplineBezierCubic(points []Vector2, thick float32, col color.RGBA) { - pointCount := int32(len(points)) - drawSplineBezierCubic(unsafe.SliceData(points), pointCount, thick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawSplineSegmentLinear - Draw spline segment: Linear, 2 points -func DrawSplineSegmentLinear(p1 Vector2, p2 Vector2, thick float32, col color.RGBA) { - drawSplineSegmentLinear(*(*uintptr)(unsafe.Pointer(&p1)), *(*uintptr)(unsafe.Pointer(&p2)), thick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawSplineSegmentBasis - Draw spline segment: B-Spline, 4 points -func DrawSplineSegmentBasis(p1 Vector2, p2 Vector2, p3 Vector2, p4 Vector2, thick float32, col color.RGBA) { - drawSplineSegmentBasis(*(*uintptr)(unsafe.Pointer(&p1)), *(*uintptr)(unsafe.Pointer(&p2)), *(*uintptr)(unsafe.Pointer(&p3)), *(*uintptr)(unsafe.Pointer(&p4)), thick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawSplineSegmentCatmullRom - Draw spline segment: Catmull-Rom, 4 points -func DrawSplineSegmentCatmullRom(p1 Vector2, p2 Vector2, p3 Vector2, p4 Vector2, thick float32, col color.RGBA) { - drawSplineSegmentCatmullRom(*(*uintptr)(unsafe.Pointer(&p1)), *(*uintptr)(unsafe.Pointer(&p2)), *(*uintptr)(unsafe.Pointer(&p3)), *(*uintptr)(unsafe.Pointer(&p4)), thick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawSplineSegmentBezierQuadratic - Draw spline segment: Quadratic Bezier, 2 points, 1 control point -func DrawSplineSegmentBezierQuadratic(p1 Vector2, c2 Vector2, p3 Vector2, thick float32, col color.RGBA) { - drawSplineSegmentBezierQuadratic(*(*uintptr)(unsafe.Pointer(&p1)), *(*uintptr)(unsafe.Pointer(&c2)), *(*uintptr)(unsafe.Pointer(&p3)), thick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawSplineSegmentBezierCubic - Draw spline segment: Cubic Bezier, 2 points, 2 control points -func DrawSplineSegmentBezierCubic(p1 Vector2, c2 Vector2, c3 Vector2, p4 Vector2, thick float32, col color.RGBA) { - drawSplineSegmentBezierCubic(*(*uintptr)(unsafe.Pointer(&p1)), *(*uintptr)(unsafe.Pointer(&c2)), *(*uintptr)(unsafe.Pointer(&c3)), *(*uintptr)(unsafe.Pointer(&p4)), thick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// GetSplinePointLinear - Get (evaluate) spline point: Linear -func GetSplinePointLinear(startPos Vector2, endPos Vector2, t float32) Vector2 { - ret := getSplinePointLinear(*(*uintptr)(unsafe.Pointer(&startPos)), *(*uintptr)(unsafe.Pointer(&endPos)), t) - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetSplinePointBasis - Get (evaluate) spline point: B-Spline -func GetSplinePointBasis(p1 Vector2, p2 Vector2, p3 Vector2, p4 Vector2, t float32) Vector2 { - ret := getSplinePointBasis(*(*uintptr)(unsafe.Pointer(&p1)), *(*uintptr)(unsafe.Pointer(&p2)), *(*uintptr)(unsafe.Pointer(&p3)), *(*uintptr)(unsafe.Pointer(&p4)), t) - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetSplinePointCatmullRom - Get (evaluate) spline point: Catmull-Rom -func GetSplinePointCatmullRom(p1 Vector2, p2 Vector2, p3 Vector2, p4 Vector2, t float32) Vector2 { - ret := getSplinePointCatmullRom(*(*uintptr)(unsafe.Pointer(&p1)), *(*uintptr)(unsafe.Pointer(&p2)), *(*uintptr)(unsafe.Pointer(&p3)), *(*uintptr)(unsafe.Pointer(&p4)), t) - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetSplinePointBezierQuad - Get (evaluate) spline point: Quadratic Bezier -func GetSplinePointBezierQuad(p1 Vector2, c2 Vector2, p3 Vector2, t float32) Vector2 { - ret := getSplinePointBezierQuad(*(*uintptr)(unsafe.Pointer(&p1)), *(*uintptr)(unsafe.Pointer(&c2)), *(*uintptr)(unsafe.Pointer(&p3)), t) - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetSplinePointBezierCubic - Get (evaluate) spline point: Cubic Bezier -func GetSplinePointBezierCubic(p1 Vector2, c2 Vector2, c3 Vector2, p4 Vector2, t float32) Vector2 { - ret := getSplinePointBezierCubic(*(*uintptr)(unsafe.Pointer(&p1)), *(*uintptr)(unsafe.Pointer(&c2)), *(*uintptr)(unsafe.Pointer(&c3)), *(*uintptr)(unsafe.Pointer(&p4)), t) - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// CheckCollisionRecs - Check collision between two rectangles -func CheckCollisionRecs(rec1 Rectangle, rec2 Rectangle) bool { - return checkCollisionRecs(uintptr(unsafe.Pointer(&rec1)), uintptr(unsafe.Pointer(&rec2))) -} - -// CheckCollisionCircles - Check collision between two circles -func CheckCollisionCircles(center1 Vector2, radius1 float32, center2 Vector2, radius2 float32) bool { - return checkCollisionCircles(*(*uintptr)(unsafe.Pointer(¢er1)), radius1, *(*uintptr)(unsafe.Pointer(¢er2)), radius2) -} - -// CheckCollisionCircleRec - Check collision between circle and rectangle -func CheckCollisionCircleRec(center Vector2, radius float32, rec Rectangle) bool { - return checkCollisionCircleRec(*(*uintptr)(unsafe.Pointer(¢er)), radius, uintptr(unsafe.Pointer(&rec))) -} - -// CheckCollisionCircleLine - Check if circle collides with a line created betweeen two points [p1] and [p2] -func CheckCollisionCircleLine(center Vector2, radius float32, p1, p2 Vector2) bool { - return checkCollisionCircleLine(*(*uintptr)(unsafe.Pointer(¢er)), radius, *(*uintptr)(unsafe.Pointer(&p1)), *(*uintptr)(unsafe.Pointer(&p2))) -} - -// CheckCollisionPointRec - Check if point is inside rectangle -func CheckCollisionPointRec(point Vector2, rec Rectangle) bool { - return checkCollisionPointRec(*(*uintptr)(unsafe.Pointer(&point)), uintptr(unsafe.Pointer(&rec))) -} - -// CheckCollisionPointCircle - Check if point is inside circle -func CheckCollisionPointCircle(point Vector2, center Vector2, radius float32) bool { - return checkCollisionPointCircle(*(*uintptr)(unsafe.Pointer(&point)), *(*uintptr)(unsafe.Pointer(¢er)), radius) -} - -// CheckCollisionPointTriangle - Check if point is inside a triangle -func CheckCollisionPointTriangle(point Vector2, p1 Vector2, p2 Vector2, p3 Vector2) bool { - return checkCollisionPointTriangle(*(*uintptr)(unsafe.Pointer(&point)), *(*uintptr)(unsafe.Pointer(&p1)), *(*uintptr)(unsafe.Pointer(&p2)), *(*uintptr)(unsafe.Pointer(&p3))) -} - -// CheckCollisionPointPoly - Check if point is within a polygon described by array of vertices -func CheckCollisionPointPoly(point Vector2, points []Vector2) bool { - pointCount := int32(len(points)) - return checkCollisionPointPoly(*(*uintptr)(unsafe.Pointer(&point)), unsafe.SliceData(points), pointCount) -} - -// CheckCollisionLines - Check the collision between two lines defined by two points each, returns collision point by reference -func CheckCollisionLines(startPos1 Vector2, endPos1 Vector2, startPos2 Vector2, endPos2 Vector2, collisionPoint *Vector2) bool { - return checkCollisionLines(*(*uintptr)(unsafe.Pointer(&startPos1)), *(*uintptr)(unsafe.Pointer(&endPos1)), *(*uintptr)(unsafe.Pointer(&startPos2)), *(*uintptr)(unsafe.Pointer(&endPos2)), collisionPoint) -} - -// CheckCollisionPointLine - Check if point belongs to line created between two points [p1] and [p2] with defined margin in pixels [threshold] -func CheckCollisionPointLine(point Vector2, p1 Vector2, p2 Vector2, threshold int32) bool { - return checkCollisionPointLine(*(*uintptr)(unsafe.Pointer(&point)), *(*uintptr)(unsafe.Pointer(&p1)), *(*uintptr)(unsafe.Pointer(&p2)), threshold) -} - -// GetCollisionRec - Get collision rectangle for two rectangles collision -func GetCollisionRec(rec1 Rectangle, rec2 Rectangle) Rectangle { - var rec Rectangle - getCollisionRec(uintptr(unsafe.Pointer(&rec)), uintptr(unsafe.Pointer(&rec1)), uintptr(unsafe.Pointer(&rec2))) - return rec -} - -// LoadImage - Load image from file into CPU memory (RAM) -func LoadImage(fileName string) *Image { - var img Image - loadImage(uintptr(unsafe.Pointer(&img)), fileName) - return &img -} - -// LoadImageRaw - Load image from RAW file data -func LoadImageRaw(fileName string, width int32, height int32, format PixelFormat, headerSize int32) *Image { - var img Image - loadImageRaw(uintptr(unsafe.Pointer(&img)), fileName, width, height, int32(format), headerSize) - return &img -} - -// LoadImageAnim - Load image sequence from file (frames appended to image.data) -func LoadImageAnim(fileName string, frames *int32) *Image { - var img Image - loadImageAnim(uintptr(unsafe.Pointer(&img)), fileName, frames) - return &img -} - -// LoadImageAnimFromMemory - Load image sequence from memory buffer -func LoadImageAnimFromMemory(fileType string, fileData []byte, dataSize int32, frames *int32) *Image { - var img Image - loadImageAnimFromMemory(uintptr(unsafe.Pointer(&img)), fileType, fileData, dataSize, frames) - return &img -} - -// LoadImageFromMemory - Load image from memory buffer, fileType refers to extension: i.e. '.png' -func LoadImageFromMemory(fileType string, fileData []byte, dataSize int32) *Image { - var img Image - loadImageFromMemory(uintptr(unsafe.Pointer(&img)), fileType, fileData, dataSize) - return &img -} - -// LoadImageFromTexture - Load image from GPU texture data -func LoadImageFromTexture(texture Texture2D) *Image { - var img Image - loadImageFromTexture(uintptr(unsafe.Pointer(&img)), uintptr(unsafe.Pointer(&texture))) - return &img -} - -// LoadImageFromScreen - Load image from screen buffer and (screenshot) -func LoadImageFromScreen() *Image { - var img Image - loadImageFromScreen(uintptr(unsafe.Pointer(&img))) - return &img -} - -// IsImageValid - Check if an image is valid (data and parameters) -func IsImageValid(image *Image) bool { - return isImageValid(uintptr(unsafe.Pointer(image))) -} - -// UnloadImage - Unload image from CPU memory (RAM) -func UnloadImage(image *Image) { - unloadImage(uintptr(unsafe.Pointer(image))) -} - -// ExportImage - Export image data to file, returns true on success -func ExportImage(image Image, fileName string) bool { - return exportImage(uintptr(unsafe.Pointer(&image)), fileName) -} - -// ExportImageToMemory - Export image to memory buffer -func ExportImageToMemory(image Image, fileType string) []byte { - var fileSize int32 - ret := exportImageToMemory(uintptr(unsafe.Pointer(&image)), fileType, &fileSize) - return unsafe.Slice(ret, fileSize) -} - -// GenImageColor - Generate image: plain color -func GenImageColor(width int, height int, col color.RGBA) *Image { - var image Image - genImageColor(uintptr(unsafe.Pointer(&image)), int32(width), int32(height), *(*uintptr)(unsafe.Pointer(&col))) - return &image -} - -// GenImageGradientLinear - Generate image: linear gradient, direction in degrees [0..360], 0=Vertical gradient -func GenImageGradientLinear(width int, height int, direction int, start color.RGBA, end color.RGBA) *Image { - var image Image - genImageGradientLinear(uintptr(unsafe.Pointer(&image)), int32(width), int32(height), int32(direction), *(*uintptr)(unsafe.Pointer(&start)), *(*uintptr)(unsafe.Pointer(&end))) - return &image -} - -// GenImageGradientRadial - Generate image: radial gradient -func GenImageGradientRadial(width int, height int, density float32, inner color.RGBA, outer color.RGBA) *Image { - var image Image - genImageGradientRadial(uintptr(unsafe.Pointer(&image)), int32(width), int32(height), density, *(*uintptr)(unsafe.Pointer(&inner)), *(*uintptr)(unsafe.Pointer(&outer))) - return &image -} - -// GenImageGradientSquare - Generate image: square gradient -func GenImageGradientSquare(width int, height int, density float32, inner color.RGBA, outer color.RGBA) *Image { - var image Image - genImageGradientSquare(uintptr(unsafe.Pointer(&image)), int32(width), int32(height), density, *(*uintptr)(unsafe.Pointer(&inner)), *(*uintptr)(unsafe.Pointer(&outer))) - return &image -} - -// GenImageChecked - Generate image: checked -func GenImageChecked(width int, height int, checksX int, checksY int, col1 color.RGBA, col2 color.RGBA) *Image { - var image Image - genImageChecked(uintptr(unsafe.Pointer(&image)), int32(width), int32(height), int32(checksX), int32(checksY), *(*uintptr)(unsafe.Pointer(&col1)), *(*uintptr)(unsafe.Pointer(&col2))) - return &image -} - -// GenImageWhiteNoise - Generate image: white noise -func GenImageWhiteNoise(width int, height int, factor float32) *Image { - var image Image - genImageWhiteNoise(uintptr(unsafe.Pointer(&image)), int32(width), int32(height), factor) - return &image -} - -// GenImagePerlinNoise - Generate image: perlin noise -func GenImagePerlinNoise(width int, height int, offsetX int32, offsetY int32, scale float32) *Image { - var image Image - genImagePerlinNoise(uintptr(unsafe.Pointer(&image)), int32(width), int32(height), offsetX, offsetY, scale) - return &image -} - -// GenImageCellular - Generate image: cellular algorithm, bigger tileSize means bigger cells -func GenImageCellular(width int, height int, tileSize int) *Image { - var image Image - genImageCellular(uintptr(unsafe.Pointer(&image)), int32(width), int32(height), int32(tileSize)) - return &image -} - -// GenImageText - Generate image: grayscale image from text data -func GenImageText(width int, height int, text string) Image { - var image Image - genImageText(uintptr(unsafe.Pointer(&image)), int32(width), int32(height), text) - return image -} - -// ImageCopy - Create an image duplicate (useful for transformations) -func ImageCopy(image *Image) *Image { - var retImage Image - imageCopy(uintptr(unsafe.Pointer(&retImage)), uintptr(unsafe.Pointer(image))) - return &retImage -} - -// ImageFromImage - Create an image from another image piece -func ImageFromImage(image Image, rec Rectangle) Image { - var retImage Image - imageFromImage(uintptr(unsafe.Pointer(&retImage)), uintptr(unsafe.Pointer(&image)), uintptr(unsafe.Pointer(&rec))) - return retImage -} - -// ImageFromChannel - Create an image from a selected channel of another image (GRAYSCALE) -func ImageFromChannel(image Image, selectedChannel int32) Image { - var retImage Image - imageFromChannel(uintptr(unsafe.Pointer(&retImage)), uintptr(unsafe.Pointer(&image)), selectedChannel) - return retImage -} - -// ImageText - Create an image from text (default font) -func ImageText(text string, fontSize int32, col color.RGBA) Image { - var retImage Image - imageText(uintptr(unsafe.Pointer(&retImage)), text, fontSize, *(*uintptr)(unsafe.Pointer(&col))) - return retImage -} - -// ImageTextEx - Create an image from text (custom sprite font) -func ImageTextEx(font Font, text string, fontSize float32, spacing float32, tint color.RGBA) Image { - var retImage Image - imageTextEx(uintptr(unsafe.Pointer(&retImage)), uintptr(unsafe.Pointer(&font)), text, fontSize, spacing, *(*uintptr)(unsafe.Pointer(&tint))) - return retImage -} - -// ImageFormat - Convert image data to desired format -func ImageFormat(image *Image, newFormat PixelFormat) { - imageFormat(image, int32(newFormat)) -} - -// ImageToPOT - Convert image to POT (power-of-two) -func ImageToPOT(image *Image, fill color.RGBA) { - imageToPOT(image, *(*uintptr)(unsafe.Pointer(&fill))) -} - -// ImageCrop - Crop an image to a defined rectangle -func ImageCrop(image *Image, crop Rectangle) { - imageCrop(image, uintptr(unsafe.Pointer(&crop))) -} - -// ImageAlphaCrop - Crop image depending on alpha value -func ImageAlphaCrop(image *Image, threshold float32) { - imageAlphaCrop(image, threshold) -} - -// ImageAlphaClear - Clear alpha channel to desired color -func ImageAlphaClear(image *Image, col color.RGBA, threshold float32) { - imageAlphaClear(image, *(*uintptr)(unsafe.Pointer(&col)), threshold) -} - -// ImageAlphaMask - Apply alpha mask to image -func ImageAlphaMask(image *Image, alphaMask *Image) { - imageAlphaMask(image, uintptr(unsafe.Pointer(alphaMask))) -} - -// ImageAlphaPremultiply - Premultiply alpha channel -func ImageAlphaPremultiply(image *Image) { - imageAlphaPremultiply(image) -} - -// ImageBlurGaussian - Apply Gaussian blur using a box blur approximation -func ImageBlurGaussian(image *Image, blurSize int32) { - imageBlurGaussian(image, blurSize) -} - -// ImageKernelConvolution - Apply custom square convolution kernel to image -func ImageKernelConvolution(image *Image, kernel []float32) { - imageKernelConvolution(image, kernel, int32(len(kernel))) -} - -// ImageResize - Resize image (Bicubic scaling algorithm) -func ImageResize(image *Image, newWidth int32, newHeight int32) { - imageResize(image, newWidth, newHeight) -} - -// ImageResizeNN - Resize image (Nearest-Neighbor scaling algorithm) -func ImageResizeNN(image *Image, newWidth int32, newHeight int32) { - imageResizeNN(image, newWidth, newHeight) -} - -// ImageResizeCanvas - Resize canvas and fill with color -func ImageResizeCanvas(image *Image, newWidth int32, newHeight int32, offsetX int32, offsetY int32, fill color.RGBA) { - imageResizeCanvas(image, newWidth, newHeight, offsetX, offsetY, *(*uintptr)(unsafe.Pointer(&fill))) -} - -// ImageMipmaps - Compute all mipmap levels for a provided image -func ImageMipmaps(image *Image) { - imageMipmaps(image) -} - -// ImageDither - Dither image data to 16bpp or lower (Floyd-Steinberg dithering) -func ImageDither(image *Image, rBpp int32, gBpp int32, bBpp int32, aBpp int32) { - imageDither(image, rBpp, gBpp, bBpp, aBpp) -} - -// ImageFlipVertical - Flip image vertically -func ImageFlipVertical(image *Image) { - imageFlipVertical(image) -} - -// ImageFlipHorizontal - Flip image horizontally -func ImageFlipHorizontal(image *Image) { - imageFlipHorizontal(image) -} - -// ImageRotate - Rotate image by input angle in degrees (-359 to 359) -func ImageRotate(image *Image, degrees int32) { - imageRotate(image, degrees) -} - -// ImageRotateCW - Rotate image clockwise 90deg -func ImageRotateCW(image *Image) { - imageRotateCW(image) -} - -// ImageRotateCCW - Rotate image counter-clockwise 90deg -func ImageRotateCCW(image *Image) { - imageRotateCCW(image) -} - -// ImageColorTint - Modify image color: tint -func ImageColorTint(image *Image, col color.RGBA) { - imageColorTint(image, *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageColorInvert - Modify image color: invert -func ImageColorInvert(image *Image) { - imageColorInvert(image) -} - -// ImageColorGrayscale - Modify image color: grayscale -func ImageColorGrayscale(image *Image) { - imageColorGrayscale(image) -} - -// ImageColorContrast - Modify image color: contrast (-100 to 100) -func ImageColorContrast(image *Image, contrast float32) { - imageColorContrast(image, contrast) -} - -// ImageColorBrightness - Modify image color: brightness (-255 to 255) -func ImageColorBrightness(image *Image, brightness int32) { - imageColorBrightness(image, brightness) -} - -// ImageColorReplace - Modify image color: replace color -func ImageColorReplace(image *Image, col color.RGBA, replace color.RGBA) { - imageColorReplace(image, *(*uintptr)(unsafe.Pointer(&col)), *(*uintptr)(unsafe.Pointer(&replace))) -} - -// LoadImageColors - Load color data from image as a Color array (RGBA - 32bit) -// -// NOTE: Memory allocated should be freed using UnloadImageColors() -func LoadImageColors(image *Image) []color.RGBA { - ret := loadImageColors(uintptr(unsafe.Pointer(image))) - return unsafe.Slice(ret, image.Width*image.Height) -} - -// LoadImagePalette - Load colors palette from image as a Color array (RGBA - 32bit) -// -// NOTE: Memory allocated should be freed using UnloadImagePalette() -func LoadImagePalette(image Image, maxPaletteSize int32) []color.RGBA { - var colorCount int32 - ret := loadImagePalette(uintptr(unsafe.Pointer(&image)), maxPaletteSize, &colorCount) - return unsafe.Slice(ret, colorCount) -} - -// UnloadImageColors - Unload color data loaded with LoadImageColors() -func UnloadImageColors(colors []color.RGBA) { - unloadImageColors(unsafe.SliceData(colors)) -} - -// UnloadImagePalette - Unload colors palette loaded with LoadImagePalette() -func UnloadImagePalette(colors []color.RGBA) { - unloadImagePalette(unsafe.SliceData(colors)) -} - -// GetImageAlphaBorder - Get image alpha border rectangle -func GetImageAlphaBorder(image Image, threshold float32) Rectangle { - var rec Rectangle - getImageAlphaBorder(uintptr(unsafe.Pointer(&rec)), uintptr(unsafe.Pointer(&image)), threshold) - return rec -} - -// GetImageColor - Get image pixel color at (x, y) position -func GetImageColor(image Image, x int32, y int32) color.RGBA { - ret := getImageColor(uintptr(unsafe.Pointer(&image)), x, y) - return *(*color.RGBA)(unsafe.Pointer(&ret)) -} - -// ImageClearBackground - Clear image background with given color -func ImageClearBackground(dst *Image, col color.RGBA) { - imageClearBackground(dst, *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawPixel - Draw pixel within an image -func ImageDrawPixel(dst *Image, posX int32, posY int32, col color.RGBA) { - imageDrawPixel(dst, posX, posY, *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawPixelV - Draw pixel within an image (Vector version) -func ImageDrawPixelV(dst *Image, position Vector2, col color.RGBA) { - imageDrawPixelV(dst, *(*uintptr)(unsafe.Pointer(&position)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawLine - Draw line within an image -func ImageDrawLine(dst *Image, startPosX int32, startPosY int32, endPosX int32, endPosY int32, col color.RGBA) { - imageDrawLine(dst, startPosX, startPosY, endPosX, endPosY, *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawLineV - Draw line within an image (Vector version) -func ImageDrawLineV(dst *Image, start, end Vector2, col color.RGBA) { - imageDrawLineV(dst, *(*uintptr)(unsafe.Pointer(&start)), *(*uintptr)(unsafe.Pointer(&end)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawLineEx - Draw a line defining thickness within an image -func ImageDrawLineEx(dst *Image, start, end Vector2, thick int32, col color.RGBA) { - imageDrawLineEx(dst, *(*uintptr)(unsafe.Pointer(&start)), *(*uintptr)(unsafe.Pointer(&end)), thick, *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawCircle - Draw a filled circle within an image -func ImageDrawCircle(dst *Image, centerX int32, centerY int32, radius int32, col color.RGBA) { - imageDrawCircle(dst, centerX, centerY, radius, *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawCircleV - Draw a filled circle within an image (Vector version) -func ImageDrawCircleV(dst *Image, center Vector2, radius int32, col color.RGBA) { - imageDrawCircleV(dst, *(*uintptr)(unsafe.Pointer(¢er)), radius, *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawCircleLines - Draw circle outline within an image -func ImageDrawCircleLines(dst *Image, centerX int32, centerY int32, radius int32, col color.RGBA) { - imageDrawCircleLines(dst, centerX, centerY, radius, *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawCircleLinesV - Draw circle outline within an image (Vector version) -func ImageDrawCircleLinesV(dst *Image, center Vector2, radius int32, col color.RGBA) { - imageDrawCircleLinesV(dst, *(*uintptr)(unsafe.Pointer(¢er)), radius, *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawRectangle - Draw rectangle within an image -func ImageDrawRectangle(dst *Image, posX int32, posY int32, width int32, height int32, col color.RGBA) { - imageDrawRectangle(dst, posX, posY, width, height, *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawRectangleV - Draw rectangle within an image (Vector version) -func ImageDrawRectangleV(dst *Image, position Vector2, size Vector2, col color.RGBA) { - imageDrawRectangleV(dst, *(*uintptr)(unsafe.Pointer(&position)), *(*uintptr)(unsafe.Pointer(&size)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawRectangleRec - Draw rectangle within an image -func ImageDrawRectangleRec(dst *Image, rec Rectangle, col color.RGBA) { - imageDrawRectangleRec(dst, uintptr(unsafe.Pointer(&rec)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawRectangleLines - Draw rectangle lines within an image -func ImageDrawRectangleLines(dst *Image, rec Rectangle, thick int, col color.RGBA) { - imageDrawRectangleLines(dst, uintptr(unsafe.Pointer(&rec)), int32(thick), *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawTriangle - Draw triangle within an image -func ImageDrawTriangle(dst *Image, v1, v2, v3 Vector2, col color.RGBA) { - imageDrawTriangle(dst, *(*uintptr)(unsafe.Pointer(&v1)), *(*uintptr)(unsafe.Pointer(&v2)), *(*uintptr)(unsafe.Pointer(&v3)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawTriangleEx - Draw triangle with interpolated colors within an image -func ImageDrawTriangleEx(dst *Image, v1, v2, v3 Vector2, c1, c2, c3 color.RGBA) { - imageDrawTriangleEx(dst, *(*uintptr)(unsafe.Pointer(&v1)), *(*uintptr)(unsafe.Pointer(&v2)), *(*uintptr)(unsafe.Pointer(&v3)), *(*uintptr)(unsafe.Pointer(&c1)), *(*uintptr)(unsafe.Pointer(&c2)), *(*uintptr)(unsafe.Pointer(&c3))) -} - -// ImageDrawTriangleLines - Draw triangle outline within an image -func ImageDrawTriangleLines(dst *Image, v1, v2, v3 Vector2, col color.RGBA) { - imageDrawTriangleLines(dst, *(*uintptr)(unsafe.Pointer(&v1)), *(*uintptr)(unsafe.Pointer(&v2)), *(*uintptr)(unsafe.Pointer(&v3)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawTriangleFan - Draw a triangle fan defined by points within an image (first vertex is the center) -func ImageDrawTriangleFan(dst *Image, points []Vector2, col color.RGBA) { - pointCount := int32(len(points)) - imageDrawTriangleFan(dst, (unsafe.SliceData(points)), pointCount, *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDrawTriangleStrip - Draw a triangle strip defined by points within an image -func ImageDrawTriangleStrip(dst *Image, points []Vector2, col color.RGBA) { - pointCount := int32(len(points)) - imageDrawTriangleStrip(dst, (unsafe.SliceData(points)), pointCount, *(*uintptr)(unsafe.Pointer(&col))) -} - -// ImageDraw - Draw a source image within a destination image (tint applied to source) -func ImageDraw(dst *Image, src *Image, srcRec Rectangle, dstRec Rectangle, tint color.RGBA) { - imageDraw(dst, uintptr(unsafe.Pointer(src)), uintptr(unsafe.Pointer(&srcRec)), uintptr(unsafe.Pointer(&dstRec)), *(*uintptr)(unsafe.Pointer(&tint))) -} - -// ImageDrawText - Draw text (using default font) within an image (destination) -func ImageDrawText(dst *Image, posX int32, posY int32, text string, fontSize int32, col color.RGBA) { - imageDrawText(dst, text, posX, posY, fontSize, *(*uintptr)(unsafe.Pointer(&col))) - -} - -// ImageDrawTextEx - Draw text (custom sprite font) within an image (destination) -func ImageDrawTextEx(dst *Image, position Vector2, font Font, text string, fontSize float32, spacing float32, tint color.RGBA) { - imageDrawTextEx(dst, uintptr(unsafe.Pointer(&font)), text, *(*uintptr)(unsafe.Pointer(&position)), fontSize, spacing, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// LoadTexture - Load texture from file into GPU memory (VRAM) -func LoadTexture(fileName string) Texture2D { - var texture Texture2D - loadTexture(uintptr(unsafe.Pointer(&texture)), fileName) - return texture -} - -// LoadTextureFromImage - Load texture from image data -func LoadTextureFromImage(image *Image) Texture2D { - var texture Texture2D - loadTextureFromImage(uintptr(unsafe.Pointer(&texture)), uintptr(unsafe.Pointer(image))) - return texture -} - -// LoadTextureCubemap - Load cubemap from image, multiple image cubemap layouts supported -func LoadTextureCubemap(image *Image, layout int32) Texture2D { - var texture Texture2D - loadTextureCubemap(uintptr(unsafe.Pointer(&texture)), uintptr(unsafe.Pointer(image)), layout) - return texture -} - -// LoadRenderTexture - Load texture for rendering (framebuffer) -func LoadRenderTexture(width int32, height int32) RenderTexture2D { - var texture RenderTexture2D - loadRenderTexture(uintptr(unsafe.Pointer(&texture)), width, height) - return texture -} - -// IsTextureValid - Check if a texture is valid (loaded in GPU) -func IsTextureValid(texture Texture2D) bool { - return isTextureValid(uintptr(unsafe.Pointer(&texture))) -} - -// UnloadTexture - Unload texture from GPU memory (VRAM) -func UnloadTexture(texture Texture2D) { - unloadTexture(uintptr(unsafe.Pointer(&texture))) -} - -// IsRenderTextureValid - Check if a render texture is valid (loaded in GPU) -func IsRenderTextureValid(target RenderTexture2D) bool { - return isRenderTextureValid(uintptr(unsafe.Pointer(&target))) -} - -// UnloadRenderTexture - Unload render texture from GPU memory (VRAM) -func UnloadRenderTexture(target RenderTexture2D) { - unloadRenderTexture(uintptr(unsafe.Pointer(&target))) -} - -// UpdateTexture - Update GPU texture with new data -func UpdateTexture(texture Texture2D, pixels []color.RGBA) { - updateTexture(uintptr(unsafe.Pointer(&texture)), unsafe.SliceData(pixels)) -} - -// UpdateTextureRec - Update GPU texture rectangle with new data -func UpdateTextureRec(texture Texture2D, rec Rectangle, pixels []color.RGBA) { - updateTextureRec(uintptr(unsafe.Pointer(&texture)), uintptr(unsafe.Pointer(&rec)), unsafe.SliceData(pixels)) -} - -// GenTextureMipmaps - Generate GPU mipmaps for a texture -func GenTextureMipmaps(texture *Texture2D) { - genTextureMipmaps(texture) -} - -// SetTextureFilter - Set texture scaling filter mode -func SetTextureFilter(texture Texture2D, filter TextureFilterMode) { - setTextureFilter(uintptr(unsafe.Pointer(&texture)), int32(filter)) -} - -// SetTextureWrap - Set texture wrapping mode -func SetTextureWrap(texture Texture2D, wrap TextureWrapMode) { - setTextureWrap(uintptr(unsafe.Pointer(&texture)), int32(wrap)) -} - -// DrawTexture - Draw a Texture2D -func DrawTexture(texture Texture2D, posX int32, posY int32, tint color.RGBA) { - drawTexture(uintptr(unsafe.Pointer(&texture)), posX, posY, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawTextureV - Draw a Texture2D with position defined as Vector2 -func DrawTextureV(texture Texture2D, position Vector2, tint color.RGBA) { - drawTextureV(uintptr(unsafe.Pointer(&texture)), *(*uintptr)(unsafe.Pointer(&position)), *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawTextureEx - Draw a Texture2D with extended parameters -func DrawTextureEx(texture Texture2D, position Vector2, rotation float32, scale float32, tint color.RGBA) { - drawTextureEx(uintptr(unsafe.Pointer(&texture)), *(*uintptr)(unsafe.Pointer(&position)), rotation, scale, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawTextureRec - Draw a part of a texture defined by a rectangle -func DrawTextureRec(texture Texture2D, source Rectangle, position Vector2, tint color.RGBA) { - drawTextureRec(uintptr(unsafe.Pointer(&texture)), uintptr(unsafe.Pointer(&source)), *(*uintptr)(unsafe.Pointer(&position)), *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawTexturePro - Draw a part of a texture defined by a rectangle with 'pro' parameters -func DrawTexturePro(texture Texture2D, source Rectangle, dest Rectangle, origin Vector2, rotation float32, tint color.RGBA) { - drawTexturePro(uintptr(unsafe.Pointer(&texture)), uintptr(unsafe.Pointer(&source)), uintptr(unsafe.Pointer(&dest)), *(*uintptr)(unsafe.Pointer(&origin)), rotation, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawTextureNPatch - Draws a texture (or part of it) that stretches or shrinks nicely -func DrawTextureNPatch(texture Texture2D, nPatchInfo NPatchInfo, dest Rectangle, origin Vector2, rotation float32, tint color.RGBA) { - drawTextureNPatch(uintptr(unsafe.Pointer(&texture)), uintptr(unsafe.Pointer(&nPatchInfo)), uintptr(unsafe.Pointer(&dest)), *(*uintptr)(unsafe.Pointer(&origin)), rotation, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// Fade - Get color with alpha applied, alpha goes from 0.0f to 1.0f -func Fade(col color.RGBA, alpha float32) color.RGBA { - ret := fade(*(*uintptr)(unsafe.Pointer(&col)), alpha) - return *(*color.RGBA)(unsafe.Pointer(&ret)) -} - -// ColorToInt - Get hexadecimal value for a Color (0xRRGGBBAA) -func ColorToInt(col color.RGBA) int32 { - return colorToInt(*(*uintptr)(unsafe.Pointer(&col))) -} - -// ColorNormalize - Get Color normalized as float [0..1] -func ColorNormalize(col color.RGBA) Vector4 { - var vector4 Vector4 - colorNormalize(uintptr(unsafe.Pointer(&vector4)), *(*uintptr)(unsafe.Pointer(&col))) - return vector4 -} - -// ColorFromNormalized - Get Color from normalized values [0..1] -func ColorFromNormalized(normalized Vector4) color.RGBA { - ret := colorFromNormalized(uintptr(unsafe.Pointer(&normalized))) - return *(*color.RGBA)(unsafe.Pointer(&ret)) -} - -// ColorToHSV - Get HSV values for a Color, hue [0..360], saturation/value [0..1] -func ColorToHSV(col color.RGBA) Vector3 { - var vector3 Vector3 - colorToHSV(uintptr(unsafe.Pointer(&vector3)), *(*uintptr)(unsafe.Pointer(&col))) - return vector3 -} - -// ColorFromHSV - Get a Color from HSV values, hue [0..360], saturation/value [0..1] -func ColorFromHSV(hue float32, saturation float32, value float32) color.RGBA { - ret := colorFromHSV(hue, saturation, value) - return *(*color.RGBA)(unsafe.Pointer(&ret)) -} - -// ColorTint - Get color multiplied with another color -func ColorTint(col color.RGBA, tint color.RGBA) color.RGBA { - ret := colorTint(*(*uintptr)(unsafe.Pointer(&col)), *(*uintptr)(unsafe.Pointer(&tint))) - return *(*color.RGBA)(unsafe.Pointer(&ret)) -} - -// ColorBrightness - Get color with brightness correction, brightness factor goes from -1.0f to 1.0f -func ColorBrightness(col color.RGBA, factor float32) color.RGBA { - ret := colorBrightness(*(*uintptr)(unsafe.Pointer(&col)), factor) - return *(*color.RGBA)(unsafe.Pointer(&ret)) -} - -// ColorContrast - Get color with contrast correction, contrast values between -1.0f and 1.0f -func ColorContrast(col color.RGBA, contrast float32) color.RGBA { - ret := colorContrast(*(*uintptr)(unsafe.Pointer(&col)), contrast) - return *(*color.RGBA)(unsafe.Pointer(&ret)) -} - -// ColorAlpha - Get color with alpha applied, alpha goes from 0.0f to 1.0f -func ColorAlpha(col color.RGBA, alpha float32) color.RGBA { - ret := colorAlpha(*(*uintptr)(unsafe.Pointer(&col)), alpha) - return *(*color.RGBA)(unsafe.Pointer(&ret)) -} - -// ColorAlphaBlend - Get src alpha-blended into dst color with tint -func ColorAlphaBlend(dst color.RGBA, src color.RGBA, tint color.RGBA) color.RGBA { - ret := colorAlphaBlend(*(*uintptr)(unsafe.Pointer(&dst)), *(*uintptr)(unsafe.Pointer(&src)), *(*uintptr)(unsafe.Pointer(&tint))) - return *(*color.RGBA)(unsafe.Pointer(&ret)) -} - -// ColorLerp - Get color lerp interpolation between two colors, factor [0.0f..1.0f] -func ColorLerp(col1, col2 color.RGBA, factor float32) color.RGBA { - ret := colorLerp(*(*uintptr)(unsafe.Pointer(&col1)), *(*uintptr)(unsafe.Pointer(&col2)), factor) - return *(*color.RGBA)(unsafe.Pointer(&ret)) -} - -// GetColor - Get Color structure from hexadecimal value -func GetColor(hexValue uint) color.RGBA { - ret := getColor(uint32(hexValue)) - return *(*color.RGBA)(unsafe.Pointer(&ret)) -} - -// GetPixelColor - Get Color from a source pixel pointer of certain format -func GetPixelColor(srcPtr unsafe.Pointer, format int32) color.RGBA { - ret := getPixelColor(srcPtr, format) - return *(*color.RGBA)(unsafe.Pointer(&ret)) -} - -// SetPixelColor - Set color formatted into destination pixel pointer -func SetPixelColor(dstPtr unsafe.Pointer, col color.RGBA, format int32) { - setPixelColor(dstPtr, *(*uintptr)(unsafe.Pointer(&col)), format) -} - -// GetPixelDataSize - Get pixel data size in bytes for certain format -func GetPixelDataSize(width int32, height int32, format int32) int32 { - return getPixelDataSize(width, height, format) -} - -// GetFontDefault - Get the default Font -func GetFontDefault() Font { - var font Font - getFontDefault(uintptr(unsafe.Pointer(&font))) - return font -} - -// LoadFont - Load font from file into GPU memory (VRAM) -func LoadFont(fileName string) Font { - var font Font - loadFont(uintptr(unsafe.Pointer(&font)), fileName) - return font -} - - -// LoadFontFromImage - Load font from Image (XNA style) -func LoadFontFromImage(image Image, key color.RGBA, firstChar rune) Font { - var font Font - loadFontFromImage(uintptr(unsafe.Pointer(&font)), uintptr(unsafe.Pointer(&image)), *(*uintptr)(unsafe.Pointer(&key)), firstChar) - return font -} - -// LoadFontFromMemory - Load font from memory buffer, fileType refers to extension: i.e. '.ttf' -func LoadFontFromMemory(fileType string, fileData []byte, fontSize int32, codepoints []rune) Font { - var font Font - dataSize := int32(len(fileData)) - codepointCount := int32(len(codepoints)) - loadFontFromMemory(uintptr(unsafe.Pointer(&font)), fileType, fileData, dataSize, fontSize, codepoints, codepointCount) - return font -} - -// IsFontValid - Check if a font is valid (font data loaded, WARNING: GPU texture not checked) -func IsFontValid(font Font) bool { - return isFontValid(uintptr(unsafe.Pointer(&font))) -} - -// LoadFontData - Load font data for further use -func LoadFontData(fileData []byte, fontSize int32, codepoints []rune, codepointCount, typ int32) []GlyphInfo { - dataSize := int32(len(fileData)) - // In case no chars count provided, default to 95 - if codepointCount <= 0 { - codepointCount = 95 - } - ret := loadFontData(fileData, dataSize, fontSize, codepoints, codepointCount, typ) - return unsafe.Slice(ret, codepointCount) -} - -// GenImageFontAtlas - Generate image font atlas using chars info -func GenImageFontAtlas(glyphs []GlyphInfo, glyphRecs []*Rectangle, fontSize int32, padding int32, packMethod int32) Image { - var image Image - glyphCount := int32(len(glyphs)) - genImageFontAtlas(uintptr(unsafe.Pointer(&image)), unsafe.SliceData(glyphs), glyphRecs, glyphCount, fontSize, padding, packMethod) - return image -} - -// UnloadFontData - Unload font chars info data (RAM) -func UnloadFontData(glyphs []GlyphInfo) { - glyphCount := int32(len(glyphs)) - unloadFontData(unsafe.SliceData(glyphs), glyphCount) -} - -// UnloadFont - Unload font from GPU memory (VRAM) -func UnloadFont(font Font) { - unloadFont(uintptr(unsafe.Pointer(&font))) -} - -// DrawFPS - Draw current FPS -func DrawFPS(posX int32, posY int32) { - drawFPS(posX, posY) -} - -// DrawText - Draw text (using default font) -func DrawText(text string, posX int32, posY int32, fontSize int32, col color.RGBA) { - drawText(text, posX, posY, fontSize, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawTextEx - Draw text using font and additional parameters -func DrawTextEx(font Font, text string, position Vector2, fontSize float32, spacing float32, tint color.RGBA) { - drawTextEx(uintptr(unsafe.Pointer(&font)), text, *(*uintptr)(unsafe.Pointer(&position)), fontSize, spacing, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawTextPro - Draw text using Font and pro parameters (rotation) -func DrawTextPro(font Font, text string, position Vector2, origin Vector2, rotation float32, fontSize float32, spacing float32, tint color.RGBA) { - drawTextPro(uintptr(unsafe.Pointer(&font)), text, *(*uintptr)(unsafe.Pointer(&position)), *(*uintptr)(unsafe.Pointer(&origin)), rotation, fontSize, spacing, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawTextCodepoint - Draw one character (codepoint) -func DrawTextCodepoint(font Font, codepoint rune, position Vector2, fontSize float32, tint color.RGBA) { - drawTextCodepoint(uintptr(unsafe.Pointer(&font)), codepoint, *(*uintptr)(unsafe.Pointer(&position)), fontSize, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawTextCodepoints - Draw multiple character (codepoint) -func DrawTextCodepoints(font Font, codepoints []rune, position Vector2, fontSize float32, spacing float32, tint color.RGBA) { - codepointCount := int32(len(codepoints)) - drawTextCodepoints(uintptr(unsafe.Pointer(&font)), codepoints, codepointCount, *(*uintptr)(unsafe.Pointer(&position)), fontSize, spacing, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// SetTextLineSpacing - Set vertical line spacing when drawing with line-breaks -func SetTextLineSpacing(spacing int) { - setTextLineSpacing(int32(spacing)) -} - -// MeasureText - Measure string width for default font -func MeasureText(text string, fontSize int32) int32 { - return measureText(text, fontSize) -} - -// MeasureTextEx - Measure string size for Font -func MeasureTextEx(font Font, text string, fontSize float32, spacing float32) Vector2 { - ret := measureTextEx(uintptr(unsafe.Pointer(&font)), text, fontSize, spacing) - return *(*Vector2)(unsafe.Pointer(&ret)) -} - -// GetGlyphIndex - Get glyph index position in font for a codepoint (unicode character), fallback to '?' if not found -func GetGlyphIndex(font Font, codepoint rune) int32 { - return getGlyphIndex(uintptr(unsafe.Pointer(&font)), codepoint) -} - -// GetGlyphInfo - Get glyph font info data for a codepoint (unicode character), fallback to '?' if not found -func GetGlyphInfo(font Font, codepoint rune) GlyphInfo { - var glyphInfo GlyphInfo - getGlyphInfo(uintptr(unsafe.Pointer(&glyphInfo)), uintptr(unsafe.Pointer(&font)), codepoint) - return glyphInfo -} - -// GetGlyphAtlasRec - Get glyph rectangle in font atlas for a codepoint (unicode character), fallback to '?' if not found -func GetGlyphAtlasRec(font Font, codepoint rune) Rectangle { - var rec Rectangle - getGlyphAtlasRec(uintptr(unsafe.Pointer(&rec)), uintptr(unsafe.Pointer(&font)), codepoint) - return rec -} - -// DrawLine3D - Draw a line in 3D world space -func DrawLine3D(startPos Vector3, endPos Vector3, col color.RGBA) { - drawLine3D(uintptr(unsafe.Pointer(&startPos)), uintptr(unsafe.Pointer(&endPos)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawPoint3D - Draw a point in 3D space, actually a small line -func DrawPoint3D(position Vector3, col color.RGBA) { - drawPoint3D(uintptr(unsafe.Pointer(&position)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCircle3D - Draw a circle in 3D world space -func DrawCircle3D(center Vector3, radius float32, rotationAxis Vector3, rotationAngle float32, col color.RGBA) { - drawCircle3D(uintptr(unsafe.Pointer(¢er)), radius, uintptr(unsafe.Pointer(&rotationAxis)), rotationAngle, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawTriangle3D - Draw a color-filled triangle (vertex in counter-clockwise order!) -func DrawTriangle3D(v1 Vector3, v2 Vector3, v3 Vector3, col color.RGBA) { - drawTriangle3D(uintptr(unsafe.Pointer(&v1)), uintptr(unsafe.Pointer(&v2)), uintptr(unsafe.Pointer(&v3)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawTriangleStrip3D - Draw a triangle strip defined by points -func DrawTriangleStrip3D(points []Vector3, col color.RGBA) { - pointCount := int32(len(points)) - drawTriangleStrip3D(unsafe.SliceData(points), pointCount, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCube - Draw cube -func DrawCube(position Vector3, width float32, height float32, length float32, col color.RGBA) { - drawCube(uintptr(unsafe.Pointer(&position)), width, height, length, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCubeV - Draw cube (Vector version) -func DrawCubeV(position Vector3, size Vector3, col color.RGBA) { - drawCubeV(uintptr(unsafe.Pointer(&position)), uintptr(unsafe.Pointer(&size)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCubeWires - Draw cube wires -func DrawCubeWires(position Vector3, width float32, height float32, length float32, col color.RGBA) { - drawCubeWires(uintptr(unsafe.Pointer(&position)), width, height, length, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCubeWiresV - Draw cube wires (Vector version) -func DrawCubeWiresV(position Vector3, size Vector3, col color.RGBA) { - drawCubeWiresV(uintptr(unsafe.Pointer(&position)), uintptr(unsafe.Pointer(&size)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawSphere - Draw sphere -func DrawSphere(centerPos Vector3, radius float32, col color.RGBA) { - drawSphere(uintptr(unsafe.Pointer(¢erPos)), radius, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawSphereEx - Draw sphere with extended parameters -func DrawSphereEx(centerPos Vector3, radius float32, rings int32, slices int32, col color.RGBA) { - drawSphereEx(uintptr(unsafe.Pointer(¢erPos)), radius, rings, slices, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawSphereWires - Draw sphere wires -func DrawSphereWires(centerPos Vector3, radius float32, rings int32, slices int32, col color.RGBA) { - drawSphereWires(uintptr(unsafe.Pointer(¢erPos)), radius, rings, slices, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCylinder - Draw a cylinder/cone -func DrawCylinder(position Vector3, radiusTop float32, radiusBottom float32, height float32, slices int32, col color.RGBA) { - drawCylinder(uintptr(unsafe.Pointer(&position)), radiusTop, radiusBottom, height, slices, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCylinderEx - Draw a cylinder with base at startPos and top at endPos -func DrawCylinderEx(startPos Vector3, endPos Vector3, startRadius float32, endRadius float32, sides int32, col color.RGBA) { - drawCylinderEx(uintptr(unsafe.Pointer(&startPos)), uintptr(unsafe.Pointer(&endPos)), startRadius, endRadius, sides, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCylinderWires - Draw a cylinder/cone wires -func DrawCylinderWires(position Vector3, radiusTop float32, radiusBottom float32, height float32, slices int32, col color.RGBA) { - drawCylinderWires(uintptr(unsafe.Pointer(&position)), radiusTop, radiusBottom, height, slices, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCylinderWiresEx - Draw a cylinder wires with base at startPos and top at endPos -func DrawCylinderWiresEx(startPos Vector3, endPos Vector3, startRadius float32, endRadius float32, sides int32, col color.RGBA) { - drawCylinderWiresEx(uintptr(unsafe.Pointer(&startPos)), uintptr(unsafe.Pointer(&endPos)), startRadius, endRadius, sides, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCapsule - Draw a capsule with the center of its sphere caps at startPos and endPos -func DrawCapsule(startPos Vector3, endPos Vector3, radius float32, slices int32, rings int32, col color.RGBA) { - drawCapsule(uintptr(unsafe.Pointer(&startPos)), uintptr(unsafe.Pointer(&endPos)), radius, slices, rings, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawCapsuleWires - Draw capsule wireframe with the center of its sphere caps at startPos and endPos -func DrawCapsuleWires(startPos Vector3, endPos Vector3, radius float32, slices int32, rings int32, col color.RGBA) { - drawCapsuleWires(uintptr(unsafe.Pointer(&startPos)), uintptr(unsafe.Pointer(&endPos)), radius, slices, rings, *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawPlane - Draw a plane XZ -func DrawPlane(centerPos Vector3, size Vector2, col color.RGBA) { - drawPlane(uintptr(unsafe.Pointer(¢erPos)), *(*uintptr)(unsafe.Pointer(&size)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawRay - Draw a ray line -func DrawRay(ray Ray, col color.RGBA) { - drawRay(uintptr(unsafe.Pointer(&ray)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawGrid - Draw a grid (centered at (0, 0, 0)) -func DrawGrid(slices int32, spacing float32) { - drawGrid(slices, spacing) -} - -// LoadModel - Load model from files (meshes and materials) -func LoadModel(fileName string) Model { - var model Model - loadModel(uintptr(unsafe.Pointer(&model)), fileName) - return model -} - -// LoadModelFromMesh - Load model from generated mesh (default material) -func LoadModelFromMesh(mesh Mesh) Model { - var model Model - loadModelFromMesh(uintptr(unsafe.Pointer(&model)), uintptr(unsafe.Pointer(&mesh))) - return model -} - -// IsModelValid - Check if a model is valid (loaded in GPU, VAO/VBOs) -func IsModelValid(model Model) bool { - return isModelValid(uintptr(unsafe.Pointer(&model))) -} - -// UnloadModel - Unload model (including meshes) from memory (RAM and/or VRAM) -func UnloadModel(model Model) { - unloadModel(uintptr(unsafe.Pointer(&model))) -} - -// GetModelBoundingBox - Compute model bounding box limits (considers all meshes) -func GetModelBoundingBox(model Model) BoundingBox { - var boundingBox BoundingBox - getModelBoundingBox(uintptr(unsafe.Pointer(&boundingBox)), uintptr(unsafe.Pointer(&model))) - return boundingBox -} - -// DrawModel - Draw a model (with texture if set) -func DrawModel(model Model, position Vector3, scale float32, tint color.RGBA) { - drawModel(uintptr(unsafe.Pointer(&model)), uintptr(unsafe.Pointer(&position)), scale, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawModelEx - Draw a model with extended parameters -func DrawModelEx(model Model, position Vector3, rotationAxis Vector3, rotationAngle float32, scale Vector3, tint color.RGBA) { - drawModelEx(uintptr(unsafe.Pointer(&model)), uintptr(unsafe.Pointer(&position)), uintptr(unsafe.Pointer(&rotationAxis)), rotationAngle, uintptr(unsafe.Pointer(&scale)), *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawModelWires - Draw a model wires (with texture if set) -func DrawModelWires(model Model, position Vector3, scale float32, tint color.RGBA) { - drawModelWires(uintptr(unsafe.Pointer(&model)), uintptr(unsafe.Pointer(&position)), scale, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawModelWiresEx - Draw a model wires (with texture if set) with extended parameters -func DrawModelWiresEx(model Model, position Vector3, rotationAxis Vector3, rotationAngle float32, scale Vector3, tint color.RGBA) { - drawModelWiresEx(uintptr(unsafe.Pointer(&model)), uintptr(unsafe.Pointer(&position)), uintptr(unsafe.Pointer(&rotationAxis)), rotationAngle, uintptr(unsafe.Pointer(&scale)), *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawModelPoints - Draw a model as points -func DrawModelPoints(model Model, position Vector3, scale float32, tint color.RGBA) { - drawModelPoints(uintptr(unsafe.Pointer(&model)), uintptr(unsafe.Pointer(&position)), scale, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawModelPointsEx - Draw a model as points with extended parameters -func DrawModelPointsEx(model Model, position Vector3, rotationAxis Vector3, rotationAngle float32, scale Vector3, tint color.RGBA) { - drawModelPointsEx(uintptr(unsafe.Pointer(&model)), uintptr(unsafe.Pointer(&position)), uintptr(unsafe.Pointer(&rotationAxis)), rotationAngle, uintptr(unsafe.Pointer(&scale)), *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawBoundingBox - Draw bounding box (wires) -func DrawBoundingBox(box BoundingBox, col color.RGBA) { - drawBoundingBox(uintptr(unsafe.Pointer(&box)), *(*uintptr)(unsafe.Pointer(&col))) -} - -// DrawBillboard - Draw a billboard texture -func DrawBillboard(camera Camera, texture Texture2D, position Vector3, scale float32, tint color.RGBA) { - drawBillboard(uintptr(unsafe.Pointer(&camera)), uintptr(unsafe.Pointer(&texture)), uintptr(unsafe.Pointer(&position)), scale, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawBillboardRec - Draw a billboard texture defined by source -func DrawBillboardRec(camera Camera, texture Texture2D, source Rectangle, position Vector3, size Vector2, tint color.RGBA) { - drawBillboardRec(uintptr(unsafe.Pointer(&camera)), uintptr(unsafe.Pointer(&texture)), uintptr(unsafe.Pointer(&source)), uintptr(unsafe.Pointer(&position)), *(*uintptr)(unsafe.Pointer(&size)), *(*uintptr)(unsafe.Pointer(&tint))) -} - -// DrawBillboardPro - Draw a billboard texture defined by source and rotation -func DrawBillboardPro(camera Camera, texture Texture2D, source Rectangle, position Vector3, up Vector3, size Vector2, origin Vector2, rotation float32, tint color.RGBA) { - drawBillboardPro(uintptr(unsafe.Pointer(&camera)), uintptr(unsafe.Pointer(&texture)), uintptr(unsafe.Pointer(&source)), uintptr(unsafe.Pointer(&position)), uintptr(unsafe.Pointer(&up)), *(*uintptr)(unsafe.Pointer(&size)), *(*uintptr)(unsafe.Pointer(&origin)), rotation, *(*uintptr)(unsafe.Pointer(&tint))) -} - -// UploadMesh - Upload mesh vertex data in GPU and provide VAO/VBO ids -func UploadMesh(mesh *Mesh, dynamic bool) { - uploadMesh(mesh, dynamic) -} - -// UpdateMeshBuffer - Update mesh vertex data in GPU for a specific buffer index -func UpdateMeshBuffer(mesh Mesh, index int32, data []byte, offset int) { - dataSize := int32(len(data)) - updateMeshBuffer(uintptr(unsafe.Pointer(&mesh)), index, data, dataSize, int32(offset)) -} - -// UnloadMesh - Unload mesh data from CPU and GPU -func UnloadMesh(mesh *Mesh) { - unloadMesh(uintptr(unsafe.Pointer(mesh))) -} - -// DrawMesh - Draw a 3d mesh with material and transform -func DrawMesh(mesh Mesh, material Material, transform Matrix) { - drawMesh(uintptr(unsafe.Pointer(&mesh)), uintptr(unsafe.Pointer(&material)), uintptr(unsafe.Pointer(&transform))) -} - -// DrawMeshInstanced - Draw multiple mesh instances with material and different transforms -func DrawMeshInstanced(mesh Mesh, material Material, transforms []Matrix, instances int32) { - drawMeshInstanced(uintptr(unsafe.Pointer(&mesh)), uintptr(unsafe.Pointer(&material)), transforms, instances) -} - -// ExportMesh - Export mesh data to file, returns true on success -func ExportMesh(mesh Mesh, fileName string) bool { - return exportMesh(uintptr(unsafe.Pointer(&mesh)), fileName) -} - -// GetMeshBoundingBox - Compute mesh bounding box limits -func GetMeshBoundingBox(mesh Mesh) BoundingBox { - var boundingBox BoundingBox - getMeshBoundingBox(uintptr(unsafe.Pointer(&boundingBox)), uintptr(unsafe.Pointer(&mesh))) - return boundingBox -} - -// GenMeshTangents - Compute mesh tangents -func GenMeshTangents(mesh *Mesh) { - genMeshTangents(mesh) -} - -// GenMeshPoly - Generate polygonal mesh -func GenMeshPoly(sides int, radius float32) Mesh { - var mesh Mesh - genMeshPoly(uintptr(unsafe.Pointer(&mesh)), int32(sides), radius) - return mesh -} - -// GenMeshPlane - Generate plane mesh (with subdivisions) -func GenMeshPlane(width float32, length float32, resX int, resZ int) Mesh { - var mesh Mesh - genMeshPlane(uintptr(unsafe.Pointer(&mesh)), width, length, int32(resX), int32(resZ)) - return mesh -} - -// GenMeshCube - Generate cuboid mesh -func GenMeshCube(width float32, height float32, length float32) Mesh { - var mesh Mesh - genMeshCube(uintptr(unsafe.Pointer(&mesh)), width, height, length) - return mesh -} - -// GenMeshSphere - Generate sphere mesh (standard sphere) -func GenMeshSphere(radius float32, rings int, slices int) Mesh { - var mesh Mesh - genMeshSphere(uintptr(unsafe.Pointer(&mesh)), radius, int32(rings), int32(slices)) - return mesh -} - -// GenMeshHemiSphere - Generate half-sphere mesh (no bottom cap) -func GenMeshHemiSphere(radius float32, rings int, slices int) Mesh { - var mesh Mesh - genMeshHemiSphere(uintptr(unsafe.Pointer(&mesh)), radius, int32(rings), int32(slices)) - return mesh -} - -// GenMeshCylinder - Generate cylinder mesh -func GenMeshCylinder(radius float32, height float32, slices int) Mesh { - var mesh Mesh - genMeshCylinder(uintptr(unsafe.Pointer(&mesh)), radius, height, int32(slices)) - return mesh -} - -// GenMeshCone - Generate cone/pyramid mesh -func GenMeshCone(radius float32, height float32, slices int) Mesh { - var mesh Mesh - genMeshCone(uintptr(unsafe.Pointer(&mesh)), radius, height, int32(slices)) - return mesh -} - -// GenMeshTorus - Generate torus mesh -func GenMeshTorus(radius float32, size float32, radSeg int, sides int) Mesh { - var mesh Mesh - genMeshTorus(uintptr(unsafe.Pointer(&mesh)), radius, size, int32(radSeg), int32(sides)) - return mesh -} - -// GenMeshKnot - Generate trefoil knot mesh -func GenMeshKnot(radius float32, size float32, radSeg int, sides int) Mesh { - var mesh Mesh - genMeshKnot(uintptr(unsafe.Pointer(&mesh)), radius, size, int32(radSeg), int32(sides)) - return mesh -} - -// GenMeshHeightmap - Generate heightmap mesh from image data -func GenMeshHeightmap(heightmap Image, size Vector3) Mesh { - var mesh Mesh - genMeshHeightmap(uintptr(unsafe.Pointer(&mesh)), uintptr(unsafe.Pointer(&heightmap)), uintptr(unsafe.Pointer(&size))) - return mesh -} - -// GenMeshCubicmap - Generate cubes-based map mesh from image data -func GenMeshCubicmap(cubicmap Image, cubeSize Vector3) Mesh { - var mesh Mesh - genMeshCubicmap(uintptr(unsafe.Pointer(&mesh)), uintptr(unsafe.Pointer(&cubicmap)), uintptr(unsafe.Pointer(&cubeSize))) - return mesh -} - -// LoadMaterials - Load materials from model file -func LoadMaterials(fileName string) []Material { - var materialCount int32 - ret := loadMaterials(fileName, &materialCount) - return unsafe.Slice(ret, materialCount) -} - -// LoadMaterialDefault - Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) -func LoadMaterialDefault() Material { - var material Material - loadMaterialDefault(uintptr(unsafe.Pointer(&material))) - return material -} - -// IsMaterialValid - Check if a material is valid (shader assigned, map textures loaded in GPU) -func IsMaterialValid(material Material) bool { - return isMaterialValid(uintptr(unsafe.Pointer(&material))) -} - -// UnloadMaterial - Unload material from GPU memory (VRAM) -func UnloadMaterial(material Material) { - unloadMaterial(uintptr(unsafe.Pointer(&material))) -} - -// SetMaterialTexture - Set texture for a material map type (MATERIAL_MAP_DIFFUSE, MATERIAL_MAP_SPECULAR...) -func SetMaterialTexture(material *Material, mapType int32, texture Texture2D) { - setMaterialTexture(material, mapType, uintptr(unsafe.Pointer(&texture))) -} - -// SetModelMeshMaterial - Set material for a mesh -func SetModelMeshMaterial(model *Model, meshId int32, materialId int32) { - setModelMeshMaterial(model, meshId, materialId) -} - -// LoadModelAnimations - Load model animations from file -func LoadModelAnimations(fileName string) []ModelAnimation { - var animCount int32 - ret := loadModelAnimations(fileName, &animCount) - return unsafe.Slice(ret, animCount) -} - -// UpdateModelAnimation - Update model animation pose (CPU) -func UpdateModelAnimation(model Model, anim ModelAnimation, frame int32) { - updateModelAnimation(uintptr(unsafe.Pointer(&model)), uintptr(unsafe.Pointer(&anim)), frame) -} - -// UpdateModelAnimationBones - Update model animation mesh bone matrices (GPU skinning) -func UpdateModelAnimationBones(model Model, anim ModelAnimation, frame int32) { - updateModelAnimationBones(uintptr(unsafe.Pointer(&model)), uintptr(unsafe.Pointer(&anim)), frame) -} - -// UnloadModelAnimation - Unload animation data -func UnloadModelAnimation(anim ModelAnimation) { - unloadModelAnimation(uintptr(unsafe.Pointer(&anim))) -} - -// UnloadModelAnimations - Unload animation array data -func UnloadModelAnimations(animations []ModelAnimation) { - animCount := int32(len(animations)) - unloadModelAnimations(unsafe.SliceData(animations), animCount) -} - -// IsModelAnimationValid - Check model animation skeleton match -func IsModelAnimationValid(model Model, anim ModelAnimation) bool { - return isModelAnimationValid(uintptr(unsafe.Pointer(&model)), uintptr(unsafe.Pointer(&anim))) -} - -// CheckCollisionSpheres - Check collision between two spheres -func CheckCollisionSpheres(center1 Vector3, radius1 float32, center2 Vector3, radius2 float32) bool { - return checkCollisionSpheres(uintptr(unsafe.Pointer(¢er1)), radius1, uintptr(unsafe.Pointer(¢er2)), radius2) -} - -// CheckCollisionBoxes - Check collision between two bounding boxes -func CheckCollisionBoxes(box1 BoundingBox, box2 BoundingBox) bool { - return checkCollisionBoxes(uintptr(unsafe.Pointer(&box1)), uintptr(unsafe.Pointer(&box2))) -} - -// CheckCollisionBoxSphere - Check collision between box and sphere -func CheckCollisionBoxSphere(box BoundingBox, center Vector3, radius float32) bool { - return checkCollisionBoxSphere(uintptr(unsafe.Pointer(&box)), uintptr(unsafe.Pointer(¢er)), radius) -} - -// GetRayCollisionSphere - Get collision info between ray and sphere -func GetRayCollisionSphere(ray Ray, center Vector3, radius float32) RayCollision { - var rayCollision RayCollision - getRayCollisionSphere(uintptr(unsafe.Pointer(&rayCollision)), uintptr(unsafe.Pointer(&ray)), uintptr(unsafe.Pointer(¢er)), radius) - return rayCollision -} - -// GetRayCollisionBox - Get collision info between ray and box -func GetRayCollisionBox(ray Ray, box BoundingBox) RayCollision { - var rayCollision RayCollision - getRayCollisionBox(uintptr(unsafe.Pointer(&rayCollision)), uintptr(unsafe.Pointer(&ray)), uintptr(unsafe.Pointer(&box))) - return rayCollision -} - -// GetRayCollisionMesh - Get collision info between ray and mesh -func GetRayCollisionMesh(ray Ray, mesh Mesh, transform Matrix) RayCollision { - var rayCollision RayCollision - getRayCollisionMesh(uintptr(unsafe.Pointer(&rayCollision)), uintptr(unsafe.Pointer(&ray)), uintptr(unsafe.Pointer(&mesh)), uintptr(unsafe.Pointer(&transform))) - return rayCollision -} - -// GetRayCollisionTriangle - Get collision info between ray and triangle -func GetRayCollisionTriangle(ray Ray, p1 Vector3, p2 Vector3, p3 Vector3) RayCollision { - var rayCollision RayCollision - getRayCollisionTriangle(uintptr(unsafe.Pointer(&rayCollision)), uintptr(unsafe.Pointer(&ray)), uintptr(unsafe.Pointer(&p1)), uintptr(unsafe.Pointer(&p2)), uintptr(unsafe.Pointer(&p3))) - return rayCollision -} - -// GetRayCollisionQuad - Get collision info between ray and quad -func GetRayCollisionQuad(ray Ray, p1 Vector3, p2 Vector3, p3 Vector3, p4 Vector3) RayCollision { - var rayCollision RayCollision - getRayCollisionQuad(uintptr(unsafe.Pointer(&rayCollision)), uintptr(unsafe.Pointer(&ray)), uintptr(unsafe.Pointer(&p1)), uintptr(unsafe.Pointer(&p2)), uintptr(unsafe.Pointer(&p3)), uintptr(unsafe.Pointer(&p4))) - return rayCollision -} - -// InitAudioDevice - Initialize audio device and context -func InitAudioDevice() { - initAudioDevice() -} - -// CloseAudioDevice - Close the audio device and context -func CloseAudioDevice() { - closeAudioDevice() -} - -// IsAudioDeviceReady - Check if audio device has been initialized successfully -func IsAudioDeviceReady() bool { - return isAudioDeviceReady() -} - -// SetMasterVolume - Set master volume (listener) -func SetMasterVolume(volume float32) { - setMasterVolume(volume) -} - -// GetMasterVolume - Get master volume (listener) -func GetMasterVolume() float32 { - return getMasterVolume() -} - -// LoadWave - Load wave data from file -func LoadWave(fileName string) Wave { - var wave Wave - loadWave(uintptr(unsafe.Pointer(&wave)), fileName) - return wave -} - -// LoadWaveFromMemory - Load wave from memory buffer, fileType refers to extension: i.e. '.wav' -func LoadWaveFromMemory(fileType string, fileData []byte, dataSize int32) Wave { - var wave Wave - loadWaveFromMemory(uintptr(unsafe.Pointer(&wave)), fileType, fileData, dataSize) - return wave -} - -// IsWaveValid - Checks if wave data is valid (data loaded and parameters) -func IsWaveValid(wave Wave) bool { - return isWaveValid(uintptr(unsafe.Pointer(&wave))) -} - -// LoadSound - Load sound from file -func LoadSound(fileName string) Sound { - var sound Sound - loadSound(uintptr(unsafe.Pointer(&sound)), fileName) - return sound -} - -// LoadSoundFromWave - Load sound from wave data -func LoadSoundFromWave(wave Wave) Sound { - var sound Sound - loadSoundFromWave(uintptr(unsafe.Pointer(&sound)), uintptr(unsafe.Pointer(&wave))) - return sound -} - -// LoadSoundAlias - Create a new sound that shares the same sample data as the source sound, does not own the sound data -func LoadSoundAlias(source Sound) Sound { - var sound Sound - loadSoundAlias(uintptr(unsafe.Pointer(&sound)), uintptr(unsafe.Pointer(&source))) - return sound -} - -// IsSoundValid - Checks if a sound is valid (data loaded and buffers initialized) -func IsSoundValid(sound Sound) bool { - return isSoundValid(uintptr(unsafe.Pointer(&sound))) -} - -// UpdateSound - Update sound buffer with new data -func UpdateSound(sound Sound, data []byte, sampleCount int32) { - updateSound(uintptr(unsafe.Pointer(&sound)), data, sampleCount) -} - -// UnloadWave - Unload wave data -func UnloadWave(wave Wave) { - unloadWave(uintptr(unsafe.Pointer(&wave))) -} - -// UnloadSound - Unload sound -func UnloadSound(sound Sound) { - unloadSound(uintptr(unsafe.Pointer(&sound))) -} - -// UnloadSoundAlias - Unload a sound alias (does not deallocate sample data) -func UnloadSoundAlias(alias Sound) { - unloadSoundAlias(uintptr(unsafe.Pointer(&alias))) -} - -// ExportWave - Export wave data to file, returns true on success -func ExportWave(wave Wave, fileName string) bool { - return exportWave(uintptr(unsafe.Pointer(&wave)), fileName) -} - -// PlaySound - Play a sound -func PlaySound(sound Sound) { - playSound(uintptr(unsafe.Pointer(&sound))) -} - -// StopSound - Stop playing a sound -func StopSound(sound Sound) { - stopSound(uintptr(unsafe.Pointer(&sound))) -} - -// PauseSound - Pause a sound -func PauseSound(sound Sound) { - pauseSound(uintptr(unsafe.Pointer(&sound))) -} - -// ResumeSound - Resume a paused sound -func ResumeSound(sound Sound) { - resumeSound(uintptr(unsafe.Pointer(&sound))) -} - -// IsSoundPlaying - Check if a sound is currently playing -func IsSoundPlaying(sound Sound) bool { - return isSoundPlaying(uintptr(unsafe.Pointer(&sound))) -} - -// SetSoundVolume - Set volume for a sound (1.0 is max level) -func SetSoundVolume(sound Sound, volume float32) { - setSoundVolume(uintptr(unsafe.Pointer(&sound)), volume) -} - -// SetSoundPitch - Set pitch for a sound (1.0 is base level) -func SetSoundPitch(sound Sound, pitch float32) { - setSoundPitch(uintptr(unsafe.Pointer(&sound)), pitch) -} - -// SetSoundPan - Set pan for a sound (0.5 is center) -func SetSoundPan(sound Sound, pan float32) { - setSoundPan(uintptr(unsafe.Pointer(&sound)), pan) -} - -// WaveCopy - Copy a wave to a new wave -func WaveCopy(wave Wave) Wave { - var copy Wave - waveCopy(uintptr(unsafe.Pointer(©)), uintptr(unsafe.Pointer(&wave))) - return copy -} - -// WaveCrop - Crop a wave to defined frames range -func WaveCrop(wave *Wave, initFrame int32, finalFrame int32) { - waveCrop(wave, initFrame, finalFrame) -} - -// WaveFormat - Convert wave data to desired format -func WaveFormat(wave *Wave, sampleRate int32, sampleSize int32, channels int32) { - waveFormat(wave, sampleRate, sampleRate, channels) -} - -// LoadWaveSamples - Load samples data from wave as a 32bit float data array -func LoadWaveSamples(wave Wave) []float32 { - ret := loadWaveSamples(uintptr(unsafe.Pointer(&wave))) - return unsafe.Slice(ret, wave.FrameCount*wave.Channels) -} - -// UnloadWaveSamples - Unload samples data loaded with LoadWaveSamples() -func UnloadWaveSamples(samples []float32) { - unloadWaveSamples(samples) -} - -// LoadMusicStream - Load music stream from file -func LoadMusicStream(fileName string) Music { - var music Music - loadMusicStream(uintptr(unsafe.Pointer(&music)), fileName) - return music -} - -// LoadMusicStreamFromMemory - Load music stream from data -func LoadMusicStreamFromMemory(fileType string, data []byte, dataSize int32) Music { - var music Music - loadMusicStreamFromMemory(uintptr(unsafe.Pointer(&music)), fileType, data, dataSize) - return music -} - -// IsMusicValid - Checks if a music stream is valid (context and buffers initialized) -func IsMusicValid(music Music) bool { - return isMusicValid(uintptr(unsafe.Pointer(&music))) -} - -// UnloadMusicStream - Unload music stream -func UnloadMusicStream(music Music) { - unloadMusicStream(uintptr(unsafe.Pointer(&music))) -} - -// PlayMusicStream - Start music playing -func PlayMusicStream(music Music) { - playMusicStream(uintptr(unsafe.Pointer(&music))) -} - -// IsMusicStreamPlaying - Check if music is playing -func IsMusicStreamPlaying(music Music) bool { - return isMusicStreamPlaying(uintptr(unsafe.Pointer(&music))) -} - -// UpdateMusicStream - Updates buffers for music streaming -func UpdateMusicStream(music Music) { - updateMusicStream(uintptr(unsafe.Pointer(&music))) -} - -// StopMusicStream - Stop music playing -func StopMusicStream(music Music) { - stopMusicStream(uintptr(unsafe.Pointer(&music))) -} - -// PauseMusicStream - Pause music playing -func PauseMusicStream(music Music) { - pauseMusicStream(uintptr(unsafe.Pointer(&music))) -} - -// ResumeMusicStream - Resume playing paused music -func ResumeMusicStream(music Music) { - resumeMusicStream(uintptr(unsafe.Pointer(&music))) -} - -// SeekMusicStream - Seek music to a position (in seconds) -func SeekMusicStream(music Music, position float32) { - seekMusicStream(uintptr(unsafe.Pointer(&music)), position) -} - -// SetMusicVolume - Set volume for music (1.0 is max level) -func SetMusicVolume(music Music, volume float32) { - setMusicVolume(uintptr(unsafe.Pointer(&music)), volume) -} - -// SetMusicPitch - Set pitch for a music (1.0 is base level) -func SetMusicPitch(music Music, pitch float32) { - setMusicPitch(uintptr(unsafe.Pointer(&music)), pitch) -} - -// SetMusicPan - Set pan for a music (0.5 is center) -func SetMusicPan(music Music, pan float32) { - setMusicPan(uintptr(unsafe.Pointer(&music)), pan) -} - -// GetMusicTimeLength - Get music time length (in seconds) -func GetMusicTimeLength(music Music) float32 { - return getMusicTimeLength(uintptr(unsafe.Pointer(&music))) -} - -// GetMusicTimePlayed - Get current music time played (in seconds) -func GetMusicTimePlayed(music Music) float32 { - return getMusicTimePlayed(uintptr(unsafe.Pointer(&music))) -} - -// LoadAudioStream - Load audio stream (to stream raw audio pcm data) -func LoadAudioStream(sampleRate uint32, sampleSize uint32, channels uint32) AudioStream { - var audioStream AudioStream - loadAudioStream(uintptr(unsafe.Pointer(&audioStream)), sampleRate, sampleSize, channels) - return audioStream -} - -// IsAudioStreamValid - Checks if an audio stream is valid (buffers initialized) -func IsAudioStreamValid(stream AudioStream) bool { - return isAudioStreamValid(uintptr(unsafe.Pointer(&stream))) -} - -// UnloadAudioStream - Unload audio stream and free memory -func UnloadAudioStream(stream AudioStream) { - unloadAudioStream(uintptr(unsafe.Pointer(&stream))) -} - -// UpdateAudioStream - Update audio stream buffers with data -func UpdateAudioStream(stream AudioStream, data []float32) { - frameCount := int32(len(data)) - updateAudioStream(uintptr(unsafe.Pointer(&stream)), data, frameCount) -} - -// IsAudioStreamProcessed - Check if any audio stream buffers requires refill -func IsAudioStreamProcessed(stream AudioStream) bool { - return isAudioStreamProcessed(uintptr(unsafe.Pointer(&stream))) -} - -// PlayAudioStream - Play audio stream -func PlayAudioStream(stream AudioStream) { - playAudioStream(uintptr(unsafe.Pointer(&stream))) -} - -// PauseAudioStream - Pause audio stream -func PauseAudioStream(stream AudioStream) { - pauseAudioStream(uintptr(unsafe.Pointer(&stream))) -} - -// ResumeAudioStream - Resume audio stream -func ResumeAudioStream(stream AudioStream) { - resumeAudioStream(uintptr(unsafe.Pointer(&stream))) -} - -// IsAudioStreamPlaying - Check if audio stream is playing -func IsAudioStreamPlaying(stream AudioStream) bool { - return isAudioStreamPlaying(uintptr(unsafe.Pointer(&stream))) -} - -// StopAudioStream - Stop audio stream -func StopAudioStream(stream AudioStream) { - stopAudioStream(uintptr(unsafe.Pointer(&stream))) -} - -// SetAudioStreamVolume - Set volume for audio stream (1.0 is max level) -func SetAudioStreamVolume(stream AudioStream, volume float32) { - setAudioStreamVolume(uintptr(unsafe.Pointer(&stream)), volume) -} - -// SetAudioStreamPitch - Set pitch for audio stream (1.0 is base level) -func SetAudioStreamPitch(stream AudioStream, pitch float32) { - setAudioStreamPitch(uintptr(unsafe.Pointer(&stream)), pitch) -} - -// SetAudioStreamPan - Set pan for audio stream (0.5 is centered) -func SetAudioStreamPan(stream AudioStream, pan float32) { - setAudioStreamPan(uintptr(unsafe.Pointer(&stream)), pan) -} - -// SetAudioStreamBufferSizeDefault - Default size for new audio streams -func SetAudioStreamBufferSizeDefault(size int32) { - setAudioStreamBufferSizeDefault(size) -} - -// SetAudioStreamCallback - Audio thread callback to request new data -func SetAudioStreamCallback(stream AudioStream, callback AudioCallback) { - fn := purego.NewCallback(func(bufferData unsafe.Pointer, frames int32) uintptr { - callback(unsafe.Slice((*float32)(bufferData), frames), int(frames)) - return 0 - }) - setAudioStreamCallback(uintptr(unsafe.Pointer(&stream)), fn) -} - -// AttachAudioStreamProcessor - Attach audio stream processor to stream, receives the samples as s -func AttachAudioStreamProcessor(stream AudioStream, processor AudioCallback) { - fn := purego.NewCallback(func(bufferData unsafe.Pointer, frames int32) uintptr { - processor(unsafe.Slice((*float32)(bufferData), frames), int(frames)) - return 0 - }) - ptr := uintptr(reflect.ValueOf(processor).UnsafePointer()) - audioCallbacks[ptr] = fn - attachAudioStreamProcessor(uintptr(unsafe.Pointer(&stream)), fn) -} - -// DetachAudioStreamProcessor - Detach audio stream processor from stream -func DetachAudioStreamProcessor(stream AudioStream, processor AudioCallback) { - ptr := uintptr(reflect.ValueOf(processor).UnsafePointer()) - fn := audioCallbacks[ptr] - detachAudioStreamProcessor(uintptr(unsafe.Pointer(&stream)), fn) -} - -// AttachAudioMixedProcessor - Attach audio stream processor to the entire audio pipeline, receives the samples as s -func AttachAudioMixedProcessor(processor AudioCallback) { - fn := purego.NewCallback(func(bufferData unsafe.Pointer, frames int32) uintptr { - processor(unsafe.Slice((*float32)(bufferData), frames), int(frames)) - return 0 - }) - ptr := uintptr(reflect.ValueOf(processor).UnsafePointer()) - audioCallbacks[ptr] = fn - attachAudioMixedProcessor(fn) -} - -// DetachAudioMixedProcessor - Detach audio stream processor from the entire audio pipeline -func DetachAudioMixedProcessor(processor AudioCallback) { - ptr := uintptr(reflect.ValueOf(processor).UnsafePointer()) - fn := audioCallbacks[ptr] - detachAudioMixedProcessor(fn) -} - -// SetCallbackFunc - Sets callback function -func SetCallbackFunc(func()) { -} - -// NewImageFromImage - Returns new Image from Go image.Image -func NewImageFromImage(img image.Image) *Image { - size := img.Bounds().Size() - - ret := GenImageColor(size.X, size.Y, White) - - for y := 0; y < size.Y; y++ { - for x := 0; x < size.X; x++ { - col := img.At(x, y) - r, g, b, a := col.RGBA() - rcolor := NewColor(uint8(r>>8), uint8(g>>8), uint8(b>>8), uint8(a>>8)) - ImageDrawPixel(ret, int32(x), int32(y), rcolor) - } - } - - return ret -} - -// ToImage converts a Image to Go image.Image -func (i *Image) ToImage() image.Image { - img := image.NewRGBA(image.Rect(0, 0, int(i.Width), int(i.Height))) - - // Get pixel data from image (RGBA 32bit) - ret := LoadImageColors(i) - pixels := (*[1 << 24]uint8)(unsafe.Pointer(unsafe.SliceData(ret)))[0 : i.Width*i.Height*4] - - img.Pix = pixels - - return img -} - -// OpenAsset - Open asset -func OpenAsset(name string) (Asset, error) { - f, err := os.Open(name) - if err != nil { - return nil, err - } - return f, nil -} - -// HomeDir - Returns user home directory -// NOTE: On Android this returns internal data path and must be called after InitWindow -func HomeDir() string { - if homeDir, err := os.UserHomeDir(); err == nil { - return homeDir - } - return "" -} diff --git a/wakatime.log b/wakatime.log deleted file mode 100644 index 7b4a839..0000000 --- a/wakatime.log +++ /dev/null @@ -1,65 +0,0 @@ -Command line interface used by all WakaTime text editor plugins. - -Usage: - wakatime-cli [flags] - -Flags: - --ai-line-changes int Optional number of lines added or removed by AI since last heartbeat in the current file. - --alternate-branch string Optional alternate branch name. Auto-detected branch takes priority. - --alternate-language string Optional alternate language name. Auto-detected language takes priority. - --alternate-project string Optional alternate project name. Auto-detected project takes priority. - --api-url string API base url used when sending heartbeats and fetching code stats. Defaults to https://api.wakatime.com/api/v1/. - --category string Category of this heartbeat activity. Can be "coding", "ai coding", "building", "indexing", "debugging", "learning", "notes", "meeting", "planning", "researching", "communicating", "supporting", "advising", "running tests", "writing tests", "manual testing", "writing docs", "code reviewing", "browsing", "translating", or "designing". Defaults to "coding". - --config string Optional config file. Defaults to '~/.wakatime.cfg'. - --config-read string Prints value for the given config key, then exits. - --config-section string Optional config section when reading or writing a config key. Defaults to [settings]. (default "settings") - --config-write stringToString Writes value to a config key, then exits. Expects two arguments, key and value. (default []) - --cursorpos int Optional cursor position in the current file. - --disable-offline Disables offline time logging instead of queuing logged time. - --entity string Absolute path to file for the heartbeat. Can also be a url, domain or app when --entity-type is not file. - --entity-type string Entity type for this heartbeat. Can be "file", "domain", "url", or "app". Defaults to "file". - --exclude strings Filename patterns to exclude from logging. POSIX regex syntax. Can be used more than once. - --exclude-unknown-project When set, any activity where the project cannot be detected will be ignored. - --extra-heartbeats Reads extra heartbeats from STDIN as a JSON array until EOF. - --file-experts Prints the top developer within a team for the given entity, then exits. - --guess-language Enable detecting language from file contents. - --heartbeat-rate-limit-seconds int Only sync heartbeats to the API once per these seconds, instead saving to the offline db. Defaults to 120. Use zero to disable. (default 120) - -h, --help help for wakatime-cli - --hide-branch-names string Obfuscate branch names. Will not send revision control branch names to api. - --hide-file-names string Obfuscate filenames. Will not send file names to api. - --hide-project-folder When set, send the file's path relative to the project folder. For ex: /User/me/projects/bar/src/file.ts is sent as src/file.ts so the server never sees the full path. When the project folder cannot be detected, only the file name is sent. For ex: file.ts. - --hide-project-names string Obfuscate project names. When a project folder is detected instead of using the folder name as the project, a .wakatime-project file is created with a random project name. - --hostname string Optional name of local machine. Defaults to local machine name read from system. - --human-line-changes int Optional number of lines added or removed by humans since last heartbeat in the current file. - --include strings Filename patterns to log. When used in combination with --exclude, files matching include will still be logged. POSIX regex syntax. Can be used more than once. - --include-only-with-project-file Disables tracking folders unless they contain a .wakatime-project file. Defaults to false. - --internal-config string Optional internal config file. Defaults to '~/.wakatime/wakatime-internal.cfg'. - --is-unsaved-entity Normally files that don't exist on disk are skipped and not tracked. When this option is present, the main heartbeat file will be tracked even if it doesn't exist. To set this flag on extra heartbeats, use the 'is_unsaved_entity' json key. - --key string Your wakatime api key; uses api_key from ~/.wakatime.cfg by default. - --language string Optional language name. If valid, takes priority over auto-detected language. - --lineno int Optional line number. This is the current line being edited. - --lines-in-file int Optional lines in the file. Normally, this is detected automatically but can be provided manually for performance, accuracy, or when using --local-file. - --local-file string Absolute path to local file for the heartbeat. When --entity is a remote file, this local file will be used for stats and just the value of --entity is sent with the heartbeat. - --log-file string Optional log file. Defaults to '~/.wakatime/wakatime.log'. - --log-to-stdout If enabled, logs will go to stdout. Will overwrite logfile configs. - --metrics When set, collects metrics usage in '~/.wakatime/metrics' folder. Defaults to false. - --no-ssl-verify Disables SSL certificate verification for HTTPS requests. By default, SSL certificates are verified. - --offline-count Prints the number of heartbeats in the offline db, then exits. - --output string Format output. Can be "text", "json" or "raw-json". Defaults to "text". - --plugin string Optional text editor plugin name and version for User-Agent header. - --print-offline-heartbeats int Prints offline heartbeats to stdout. (default 10) - --project string Override auto-detected project. Use --alternate-project to supply a fallback project if one can't be auto-detected. - --project-folder string Optional workspace path. Usually used when hiding the project folder, or when a project root folder can't be auto detected. - --proxy string Optional proxy configuration. Supports HTTPS SOCKS and NTLM proxies. For example: 'https://user:pass@host:port' or 'socks5://user:pass@host:port' or 'domain\user:pass' - --send-diagnostics-on-errors When --verbose or debug enabled, also sends diagnostics on any error not just crashes. - --ssl-certs-file string Override the bundled CA certs file. By default, uses system ca certs. - --sync-offline-activity int Amount of offline activity to sync from your local ~/.wakatime/offline_heartbeats.bdb bolt file to your WakaTime Dashboard before exiting. Can be zero or a positive integer. Defaults to 1000, meaning after sending a heartbeat while online, all queued offline heartbeats are sent to WakaTime API, up to a limit of 1000. Zero syncs all offline heartbeats. Can be used without --entity to only sync offline activity without generating new heartbeats. (default 1000) - --time float Optional floating-point unix epoch timestamp. Uses current time by default. - --timeout int Number of seconds to wait when sending heartbeats to api. Defaults to 120 seconds. (default 120) - --today Prints dashboard time for today, then exits. - --today-goal string Prints time for the given goal id today, then exits Visit wakatime.com/api/v1/users/current/goals to find your goal id. - --today-hide-categories string When optionally included with --today, causes output to show total code time today without categories. Defaults to false. - --verbose Turns on debug messages in log file, and sends diagnostics if a crash occurs. - --version Prints the wakatime-cli version number, then exits. - --write When set, tells api this heartbeat was triggered from writing to a file. - From 0ac9e310b29d12e53bdacc9db948a64c97028aac Mon Sep 17 00:00:00 2001 From: BrownNPC Date: Sat, 31 Jan 2026 14:05:23 +0500 Subject: [PATCH 09/12] working on codegen --- testdata/api/rlapi.go | 35 ++- testdata/codegen.go | 40 +++- testdata/go.mod | 3 + testdata/rl/.gitkeep | 0 testdata/rl/structs_gen_unformatted.go | 304 +++++++++++++++++++++++++ testdata/rl/wasm.go | 152 +++++++++++++ testdata/templates/structs.go.gotmpl | 19 ++ testdata/templates/templates.go | 13 ++ 8 files changed, 560 insertions(+), 6 deletions(-) create mode 100644 testdata/go.mod create mode 100644 testdata/rl/.gitkeep create mode 100644 testdata/rl/structs_gen_unformatted.go create mode 100644 testdata/rl/wasm.go create mode 100644 testdata/templates/structs.go.gotmpl create mode 100644 testdata/templates/templates.go diff --git a/testdata/api/rlapi.go b/testdata/api/rlapi.go index a16b779..f8e7ccf 100644 --- a/testdata/api/rlapi.go +++ b/testdata/api/rlapi.go @@ -12,14 +12,16 @@ var rlApiJson []byte func init() { err := json.Unmarshal(rlApiJson, &Api) - panic(err) + if err != nil { + panic(err) + } } type RlDefine struct { - Name string `json:"name"` - Type string `json:"type"` - Value string `json:"value"` - Description string `json:"description"` + Name string `json:"name"` + Type string `json:"type"` + Value StringyValue `json:"value"` + Description string `json:"description"` } type RlField struct { Type string `json:"type"` @@ -70,3 +72,26 @@ type RlApi struct { Callbacks []RlCallback `json:"callbacks"` Functions []RlFunction `json:"functions"` } +type StringyValue string + +func (s *StringyValue) UnmarshalJSON(b []byte) error { + // null + if string(b) == "null" { + *s = "" + return nil + } + + // quoted string + if len(b) > 0 && b[0] == '"' { + var v string + if err := json.Unmarshal(b, &v); err != nil { + return err + } + *s = StringyValue(v) + return nil + } + + // number / bare token → keep textual form + *s = StringyValue(b) + return nil +} diff --git a/testdata/codegen.go b/testdata/codegen.go index 6a3f65e..37e5eb8 100644 --- a/testdata/codegen.go +++ b/testdata/codegen.go @@ -1,6 +1,44 @@ package main -import "./api" +import ( + "bytes" + "codegen/api" + "codegen/templates" + _ "embed" + "go/format" + "os" +) + +//go:embed templates/structs.go.gotmpl +var structsTempl string + +type Model struct { + BuildTags string + Imports []string + Structs []api.RlStruct +} func main() { + m := Model{ + BuildTags: "", + Imports: []string{}, + Structs: api.Api.Structs, + } + structs := templates.LoadTemplate(structsTempl, "structs") + + var buf bytes.Buffer + if err := structs.Execute(&buf, m); err != nil { + panic(err) + } + if err := os.WriteFile("rl/structs_gen_unformatted.go", buf.Bytes(), 0644); err != nil { + panic(err) + } + + formatted, err := format.Source(buf.Bytes()) + if err != nil { + panic(err) + } + if err := os.WriteFile("rl/structs_gen.go", formatted, 0644); err != nil { + panic(err) + } } diff --git a/testdata/go.mod b/testdata/go.mod new file mode 100644 index 0000000..ad9a9fc --- /dev/null +++ b/testdata/go.mod @@ -0,0 +1,3 @@ +module codegen + +go 1.25.6 diff --git a/testdata/rl/.gitkeep b/testdata/rl/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/testdata/rl/structs_gen_unformatted.go b/testdata/rl/structs_gen_unformatted.go new file mode 100644 index 0000000..8507aa8 --- /dev/null +++ b/testdata/rl/structs_gen_unformatted.go @@ -0,0 +1,304 @@ +// go:build +package rl + +/* Vector2, 2 components */ +type Vector2 struct { + x float // Vector x component + y float // Vector y component +} + +/* Vector3, 3 components */ +type Vector3 struct { + x float // Vector x component + y float // Vector y component + z float // Vector z component +} + +/* Vector4, 4 components */ +type Vector4 struct { + x float // Vector x component + y float // Vector y component + z float // Vector z component + w float // Vector w component +} + +/* Matrix, 4x4 components, column major, OpenGL style, right-handed */ +type Matrix struct { + m0 float // Matrix first row (4 components) + m4 float // Matrix first row (4 components) + m8 float // Matrix first row (4 components) + m12 float // Matrix first row (4 components) + m1 float // Matrix second row (4 components) + m5 float // Matrix second row (4 components) + m9 float // Matrix second row (4 components) + m13 float // Matrix second row (4 components) + m2 float // Matrix third row (4 components) + m6 float // Matrix third row (4 components) + m10 float // Matrix third row (4 components) + m14 float // Matrix third row (4 components) + m3 float // Matrix fourth row (4 components) + m7 float // Matrix fourth row (4 components) + m11 float // Matrix fourth row (4 components) + m15 float // Matrix fourth row (4 components) +} + +/* Color, 4 components, R8G8B8A8 (32bit) */ +type Color struct { + r unsigned char // Color red value + g unsigned char // Color green value + b unsigned char // Color blue value + a unsigned char // Color alpha value +} + +/* Rectangle, 4 components */ +type Rectangle struct { + x float // Rectangle top-left corner position x + y float // Rectangle top-left corner position y + width float // Rectangle width + height float // Rectangle height +} + +/* Image, pixel data stored in CPU memory (RAM) */ +type Image struct { + data void * // Image raw data + width int // Image base width + height int // Image base height + mipmaps int // Mipmap levels, 1 by default + format int // Data format (PixelFormat type) +} + +/* Texture, tex data stored in GPU memory (VRAM) */ +type Texture struct { + id unsigned int // OpenGL texture id + width int // Texture base width + height int // Texture base height + mipmaps int // Mipmap levels, 1 by default + format int // Data format (PixelFormat type) +} + +/* RenderTexture, fbo for texture rendering */ +type RenderTexture struct { + id unsigned int // OpenGL framebuffer object id + texture Texture // Color buffer attachment texture + depth Texture // Depth buffer attachment texture +} + +/* NPatchInfo, n-patch layout info */ +type NPatchInfo struct { + source Rectangle // Texture source rectangle + left int // Left border offset + top int // Top border offset + right int // Right border offset + bottom int // Bottom border offset + layout int // Layout of the n-patch: 3x3, 1x3 or 3x1 +} + +/* GlyphInfo, font characters glyphs info */ +type GlyphInfo struct { + value int // Character value (Unicode) + offsetX int // Character offset X when drawing + offsetY int // Character offset Y when drawing + advanceX int // Character advance position X + image Image // Character image data +} + +/* Font, font texture and GlyphInfo array data */ +type Font struct { + baseSize int // Base size (default chars height) + glyphCount int // Number of glyph characters + glyphPadding int // Padding around the glyph characters + texture Texture2D // Texture atlas containing the glyphs + recs Rectangle * // Rectangles in texture for the glyphs + glyphs GlyphInfo * // Glyphs info data +} + +/* Camera, defines position/orientation in 3d space */ +type Camera3D struct { + position Vector3 // Camera position + target Vector3 // Camera target it looks-at + up Vector3 // Camera up vector (rotation over its axis) + fovy float // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane height in world units in orthographic + projection int // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC +} + +/* Camera2D, defines position/orientation in 2d space */ +type Camera2D struct { + offset Vector2 // Camera offset (screen space offset from window origin) + target Vector2 // Camera target (world space target point that is mapped to screen space offset) + rotation float // Camera rotation in degrees (pivots around target) + zoom float // Camera zoom (scaling around target), must not be set to 0, set to 1.0f for no scale +} + +/* Mesh, vertex data and vao/vbo */ +type Mesh struct { + vertexCount int // Number of vertices stored in arrays + triangleCount int // Number of triangles stored (indexed or not) + vertices float * // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) + texcoords float * // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) + texcoords2 float * // Vertex texture second coordinates (UV - 2 components per vertex) (shader-location = 5) + normals float * // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) + tangents float * // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) + colors unsigned char * // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) + indices unsigned short * // Vertex indices (in case vertex data comes indexed) + animVertices float * // Animated vertex positions (after bones transformations) + animNormals float * // Animated normals (after bones transformations) + boneIds unsigned char * // Vertex bone ids, max 255 bone ids, up to 4 bones influence by vertex (skinning) (shader-location = 6) + boneWeights float * // Vertex bone weight, up to 4 bones influence by vertex (skinning) (shader-location = 7) + boneMatrices Matrix * // Bones animated transformation matrices + boneCount int // Number of bones + vaoId unsigned int // OpenGL Vertex Array Object id + vboId unsigned int * // OpenGL Vertex Buffer Objects id (default vertex data) +} + +/* Shader */ +type Shader struct { + id unsigned int // Shader program id + locs int * // Shader locations array (RL_MAX_SHADER_LOCATIONS) +} + +/* MaterialMap */ +type MaterialMap struct { + texture Texture2D // Material map texture + color Color // Material map color + value float // Material map value +} + +/* Material, includes shader and maps */ +type Material struct { + shader Shader // Material shader + maps MaterialMap * // Material maps array (MAX_MATERIAL_MAPS) + params float[4] // Material generic parameters (if required) +} + +/* Transform, vertex transformation data */ +type Transform struct { + translation Vector3 // Translation + rotation Quaternion // Rotation + scale Vector3 // Scale +} + +/* Bone, skeletal animation bone */ +type BoneInfo struct { + name char[32] // Bone name + parent int // Bone parent +} + +/* Model, meshes, materials and animation data */ +type Model struct { + transform Matrix // Local transform matrix + meshCount int // Number of meshes + materialCount int // Number of materials + meshes Mesh * // Meshes array + materials Material * // Materials array + meshMaterial int * // Mesh material number + boneCount int // Number of bones + bones BoneInfo * // Bones information (skeleton) + bindPose Transform * // Bones base transformation (pose) +} + +/* ModelAnimation */ +type ModelAnimation struct { + boneCount int // Number of bones + frameCount int // Number of animation frames + bones BoneInfo * // Bones information (skeleton) + framePoses Transform ** // Poses array by frame + name char[32] // Animation name +} + +/* Ray, ray for raycasting */ +type Ray struct { + position Vector3 // Ray position (origin) + direction Vector3 // Ray direction (normalized) +} + +/* RayCollision, ray hit information */ +type RayCollision struct { + hit bool // Did the ray hit something? + distance float // Distance to the nearest hit + point Vector3 // Point of the nearest hit + normal Vector3 // Surface normal of hit +} + +/* BoundingBox */ +type BoundingBox struct { + min Vector3 // Minimum vertex box-corner + max Vector3 // Maximum vertex box-corner +} + +/* Wave, audio wave data */ +type Wave struct { + frameCount unsigned int // Total number of frames (considering channels) + sampleRate unsigned int // Frequency (samples per second) + sampleSize unsigned int // Bit depth (bits per sample): 8, 16, 32 (24 not supported) + channels unsigned int // Number of channels (1-mono, 2-stereo, ...) + data void * // Buffer data pointer +} + +/* AudioStream, custom audio stream */ +type AudioStream struct { + buffer rAudioBuffer * // Pointer to internal data used by the audio system + processor rAudioProcessor * // Pointer to internal data processor, useful for audio effects + sampleRate unsigned int // Frequency (samples per second) + sampleSize unsigned int // Bit depth (bits per sample): 8, 16, 32 (24 not supported) + channels unsigned int // Number of channels (1-mono, 2-stereo, ...) +} + +/* Sound */ +type Sound struct { + stream AudioStream // Audio stream + frameCount unsigned int // Total number of frames (considering channels) +} + +/* Music, audio stream, anything longer than ~10 seconds should be streamed */ +type Music struct { + stream AudioStream // Audio stream + frameCount unsigned int // Total number of frames (considering channels) + looping bool // Music looping enable + ctxType int // Type of music context (audio filetype) + ctxData void * // Audio context data, depends on type +} + +/* VrDeviceInfo, Head-Mounted-Display device parameters */ +type VrDeviceInfo struct { + hResolution int // Horizontal resolution in pixels + vResolution int // Vertical resolution in pixels + hScreenSize float // Horizontal size in meters + vScreenSize float // Vertical size in meters + eyeToScreenDistance float // Distance between eye and display in meters + lensSeparationDistance float // Lens separation distance in meters + interpupillaryDistance float // IPD (distance between pupils) in meters + lensDistortionValues float[4] // Lens distortion constant parameters + chromaAbCorrection float[4] // Chromatic aberration correction parameters +} + +/* VrStereoConfig, VR stereo rendering configuration for simulator */ +type VrStereoConfig struct { + projection Matrix[2] // VR projection matrices (per eye) + viewOffset Matrix[2] // VR view offset matrices (per eye) + leftLensCenter float[2] // VR left lens center + rightLensCenter float[2] // VR right lens center + leftScreenCenter float[2] // VR left screen center + rightScreenCenter float[2] // VR right screen center + scale float[2] // VR distortion scale + scaleIn float[2] // VR distortion scale in +} + +/* File path list */ +type FilePathList struct { + count unsigned int // Filepaths entries count + paths char ** // Filepaths entries +} + +/* Automation event */ +type AutomationEvent struct { + frame unsigned int // Event frame + type unsigned int // Event type (AutomationEventType) + params int[4] // Event parameters (if required) +} + +/* Automation event list */ +type AutomationEventList struct { + capacity unsigned int // Events max entries (MAX_AUTOMATION_EVENTS) + count unsigned int // Events entries count + events AutomationEvent * // Events entries +} diff --git a/testdata/rl/wasm.go b/testdata/rl/wasm.go new file mode 100644 index 0000000..7a37731 --- /dev/null +++ b/testdata/rl/wasm.go @@ -0,0 +1,152 @@ + +//go:build js + +package rl + +import ( + "syscall/js" + "unsafe" +) + +// cptr is a pointer to raylib wasm memory +type cptr = uint32 + +// Allocates memory on raylib heap +// +//go:wasmimport raylib _malloc +//go:noescape +func malloc(size cptr) cptr + +// malloc the size of V +func mallocV[T any](V T) (cptr, func()) { + ptr := malloc(sizeof(V)) + return ptr, func() { free(ptr) } +} + +// free memory allocated on raylib heap +// +//go:wasmimport raylib _free +//go:noescape +func free(cptr) + +// _copyToC copies a Go type/struct to C memory. Useful for copying slices and structs. +// +// Destination C array must have enough space. +// +// NOTE: Value must be a type, it cannot be a slice. +// To pass a slice, use [unsafe.SliceData] +// +//go:wasmimport gojs CopyToC +//go:noescape +func _copyToC(Value unsafe.Pointer, srcSize, dstCptr cptr) + +// copies C memory to a Go pointer. Useful for copying C structs into Go structs +// +// example usage: +// +// type Person struct{ +// Age int32 +// } +// +// var cPtrToPersonInCHeap cptr = ... +// +// var p Person +// CopyToGo(unsafe.Pointer(&p),unsafe.SizeOf(p),cPtrToPersonInCHeap) +// +// p.Age == (whatever it was in C) +// +//go:wasmimport gojs CopyToGo +//go:noescape +func _copyToGo(dstGoPtr unsafe.Pointer, size cptr, src cptr) + +// Copies the src value to the dst cptr +func copyToC[T any](src *T, dst cptr) { + size := sizeof(src) + _copyToC(unsafe.Pointer(src), size, dst) +} + +// The alocated C string lives on the raylib heap and must be free()'d +// +//go:wasmimport gojs CStringFromGoString +//go:noescape +func cString(string) cptr + +// Scan for null terminator and return length excluding the null terminator. +// +//go:wasmimport gojs CStringGetLength +//go:noescape +func _cStringGetLength(cstr cptr) cptr + +// Copies a C string to Go memory without freeing the C string. +func goString(cstr cptr) string { + size := _cStringGetLength(cstr) + dstStr := make([]byte, size) + copySliceToGo(cstr, dstStr) + return string(dstStr) +} + +// copyValueToC copies a value to C and returns a pointer to it. +// +// NOTE: Value cannot be a slice. For a slice, use [copySliceToC] +func copyValueToC[T any](srcValue T) (cptr, func()) { + size := sizeof(srcValue) + dst := malloc(size) + copyToC(&srcValue, dst) + return dst, func() { free(dst) } +} + +// copySliceToC allocates a copy of a slice in C memory and returns a cptr to it. +// +// NOTE: Value MUST be a slice +func copySliceToC[Slice ~[]E, E any](s Slice) (cptr, func()) { + // size of the slice's underlying array in bytes + sliceSize := cptr(unsafe.Sizeof(s[0])) * cptr(len(s)) + // allocate C array to hold Value + dstCptr := malloc(sliceSize) + // copy underlying array memory to C + _copyToC(unsafe.Pointer(unsafe.SliceData(s)), sliceSize, dstCptr) + return dstCptr, func() { free(dstCptr) } +} + +// copyValueToGo copies a value from C memory to Go memory. +// Useful for copying structs +// +// NOTE: Slices are not supported. Use [copySliceToGo] +func copyValueToGo[T any](src cptr, dst *T) { + size := sizeof(*dst) + _copyToGo(unsafe.Pointer(dst), size, src) +} + +// copySliceToGo copies a C array into a Go Slice. +// +// It copies bytes to the underlying array of the slice. +func copySliceToGo[Slice ~[]E, E any](src cptr, dst Slice) { + // size of underlying array + var occupiedSize = len(dst) + if occupiedSize == 0 { + occupiedSize = cap(dst) + } + size := cptr(unsafe.Sizeof(dst[0])) * cptr(occupiedSize) + dstPtr := unsafe.SliceData(dst) + _copyToGo(unsafe.Pointer(dstPtr), size, src) +} + +//go:wasmimport gojs Alert +//go:noescape +func alert(string) + +// Use this instead of a for loop on web platform +// Everything that you would do inside the for-loop must be done inside UpdateAndDrawFrame +func SetMain(UpdateAndDrawFrame func()) { + var updateLoop js.Func + updateLoop = js.FuncOf(func(this js.Value, args []js.Value) any { + UpdateAndDrawFrame() + js.Global().Call("requestAnimationFrame", updateLoop) + return nil + }) + js.Global().Call("requestAnimationFrame", updateLoop) + select {} +} + +// return sizeof of v in bytes +func sizeof[T any](v T) cptr { return cptr(unsafe.Sizeof(v)) } diff --git a/testdata/templates/structs.go.gotmpl b/testdata/templates/structs.go.gotmpl new file mode 100644 index 0000000..607d2c7 --- /dev/null +++ b/testdata/templates/structs.go.gotmpl @@ -0,0 +1,19 @@ +{{- $root := . -}} + +//go:build {{.BuildTags}} +package rl + +{{- range .Imports }} +import {{ . }} +{{- end }} + +{{- range .Structs}} + +/* {{ .Description}} */ +type {{ .Name}} struct { + {{- range .Fields }} + {{ .Name }} {{ .Type }} // {{.Description}} + {{- end }} +} + +{{- end}} diff --git a/testdata/templates/templates.go b/testdata/templates/templates.go new file mode 100644 index 0000000..606411b --- /dev/null +++ b/testdata/templates/templates.go @@ -0,0 +1,13 @@ +package templates + +import ( + _ "embed" + "text/template" +) + +// LoadTemplate takes in a gotempl as a string and a name for the template. +// It panics if template could not be parsed. +func LoadTemplate(templ, name string) *template.Template { + return template.Must(template.New(name). + Parse(templ)) +} From 916679b9a85894d5dd8f9caae05956000f92adeb Mon Sep 17 00:00:00 2001 From: BrownNPC Date: Sun, 1 Feb 2026 08:30:18 +0500 Subject: [PATCH 10/12] structs translated --- testdata/api/publicNameString.go | 21 ++ testdata/api/rlapi.go | 29 +-- testdata/api/rltype.go | 41 +++ testdata/api/stringyvalue.go | 27 ++ testdata/codegen.go | 33 ++- testdata/rl/go.mod | 4 + testdata/rl/structs_gen_unformatted.go | 337 +++++++++++++------------ testdata/rl/wasm.go | 1 - testdata/templates/structs.go.gotmpl | 3 + 9 files changed, 293 insertions(+), 203 deletions(-) create mode 100644 testdata/api/publicNameString.go create mode 100644 testdata/api/rltype.go create mode 100644 testdata/api/stringyvalue.go create mode 100644 testdata/rl/go.mod diff --git a/testdata/api/publicNameString.go b/testdata/api/publicNameString.go new file mode 100644 index 0000000..0e9f70d --- /dev/null +++ b/testdata/api/publicNameString.go @@ -0,0 +1,21 @@ +package api + +import ( + "encoding/json" + "strings" +) + +// PublicName just sets the first character as uppercase. Used for making struct members public. +type PublicName string + +func (s *PublicName) UnmarshalJSON(b []byte) error { + var v string + if err := json.Unmarshal(b, &v); err != nil { + return err + } + firstChar := string(v[0]) + firstChar =strings.ToUpper(firstChar) + theRest := string(v[1:]) + *s = PublicName(firstChar + theRest) + return nil +} diff --git a/testdata/api/rlapi.go b/testdata/api/rlapi.go index f8e7ccf..382c146 100644 --- a/testdata/api/rlapi.go +++ b/testdata/api/rlapi.go @@ -24,9 +24,9 @@ type RlDefine struct { Description string `json:"description"` } type RlField struct { - Type string `json:"type"` - Name string `json:"name"` - Description string `json:"description"` + Type RlType `json:"type"` + Name PublicName `json:"name"` + Description string `json:"description"` } type RlStruct struct { Name string `json:"name"` @@ -72,26 +72,3 @@ type RlApi struct { Callbacks []RlCallback `json:"callbacks"` Functions []RlFunction `json:"functions"` } -type StringyValue string - -func (s *StringyValue) UnmarshalJSON(b []byte) error { - // null - if string(b) == "null" { - *s = "" - return nil - } - - // quoted string - if len(b) > 0 && b[0] == '"' { - var v string - if err := json.Unmarshal(b, &v); err != nil { - return err - } - *s = StringyValue(v) - return nil - } - - // number / bare token → keep textual form - *s = StringyValue(b) - return nil -} diff --git a/testdata/api/rltype.go b/testdata/api/rltype.go new file mode 100644 index 0000000..996d035 --- /dev/null +++ b/testdata/api/rltype.go @@ -0,0 +1,41 @@ +package api + +import ( + "encoding/json" + "slices" +) + +// RlType converts a C type to Go +type RlType string + +func (s *RlType) UnmarshalJSON(b []byte) error { + var v string + if err := json.Unmarshal(b, &v); err != nil { + return err + } + *s = RlType(GoTypeFromC(v)) + return nil +} +func GoTypeFromC(t string) string { + oneToOneTypes := map[string]string{ + "char": "byte", + "float": "float32", + "unsigned char": "byte", + "unsigned int": "uint32", + "int": "int32", + } + if mapping, ok := oneToOneTypes[t]; ok { + return mapping + } + runed := []rune(t) + if runed[len(runed)-1] == '*' { + return "cptr" + } + if index := slices.Index(runed, '['); index >= 0 { + arraySize := runed[index:] + arrayType := runed[:index] + arrayType = []rune(GoTypeFromC(string(arrayType))) + return string(arraySize) + string(arrayType) + } + return t +} diff --git a/testdata/api/stringyvalue.go b/testdata/api/stringyvalue.go new file mode 100644 index 0000000..1efef57 --- /dev/null +++ b/testdata/api/stringyvalue.go @@ -0,0 +1,27 @@ +package api + +import "encoding/json" + +type StringyValue string + +func (s *StringyValue) UnmarshalJSON(b []byte) error { + // null + if string(b) == "null" { + *s = "" + return nil + } + + // quoted string + if len(b) > 0 && b[0] == '"' { + var v string + if err := json.Unmarshal(b, &v); err != nil { + return err + } + *s = StringyValue(v) + return nil + } + + // number / bare token → keep textual form + *s = StringyValue(b) + return nil +} diff --git a/testdata/codegen.go b/testdata/codegen.go index 37e5eb8..6240176 100644 --- a/testdata/codegen.go +++ b/testdata/codegen.go @@ -5,7 +5,6 @@ import ( "codegen/api" "codegen/templates" _ "embed" - "go/format" "os" ) @@ -19,26 +18,42 @@ type Model struct { } func main() { + + // recordedTypes := map[string]struct{}{} + + // for _, s := range api.Api.Structs { + // for _, t := range s.Fields { + // if _, ok := recordedTypes[t.Type]; !ok { + // recordedTypes[t.Type] = struct{}{} + // fmt.Println(t.Type) + // } + // } + // } + m := Model{ - BuildTags: "", + BuildTags: "js", Imports: []string{}, Structs: api.Api.Structs, } structs := templates.LoadTemplate(structsTempl, "structs") var buf bytes.Buffer + if err := structs.Execute(&buf, m); err != nil { panic(err) } + if err := os.WriteFile("rl/structs_gen_unformatted.go", buf.Bytes(), 0644); err != nil { panic(err) } - formatted, err := format.Source(buf.Bytes()) - if err != nil { - panic(err) - } - if err := os.WriteFile("rl/structs_gen.go", formatted, 0644); err != nil { - panic(err) - } + // formatted, err := format.Source(buf.Bytes()) + + // if err != nil { + // panic(err) + // } + + // if err := os.WriteFile("rl/structs_gen.go", formatted, 0644); err != nil { + // panic(err) + // } } diff --git a/testdata/rl/go.mod b/testdata/rl/go.mod new file mode 100644 index 0000000..2556a58 --- /dev/null +++ b/testdata/rl/go.mod @@ -0,0 +1,4 @@ +module rl + +go 1.25.6 + diff --git a/testdata/rl/structs_gen_unformatted.go b/testdata/rl/structs_gen_unformatted.go index 8507aa8..d86eb88 100644 --- a/testdata/rl/structs_gen_unformatted.go +++ b/testdata/rl/structs_gen_unformatted.go @@ -1,304 +1,307 @@ -// go:build +// AUTOGENERATED FILE. DO NOT EDIT + +//go:build js + package rl /* Vector2, 2 components */ type Vector2 struct { - x float // Vector x component - y float // Vector y component + X float32 // Vector x component + Y float32 // Vector y component } /* Vector3, 3 components */ type Vector3 struct { - x float // Vector x component - y float // Vector y component - z float // Vector z component + X float32 // Vector x component + Y float32 // Vector y component + Z float32 // Vector z component } /* Vector4, 4 components */ type Vector4 struct { - x float // Vector x component - y float // Vector y component - z float // Vector z component - w float // Vector w component + X float32 // Vector x component + Y float32 // Vector y component + Z float32 // Vector z component + W float32 // Vector w component } /* Matrix, 4x4 components, column major, OpenGL style, right-handed */ type Matrix struct { - m0 float // Matrix first row (4 components) - m4 float // Matrix first row (4 components) - m8 float // Matrix first row (4 components) - m12 float // Matrix first row (4 components) - m1 float // Matrix second row (4 components) - m5 float // Matrix second row (4 components) - m9 float // Matrix second row (4 components) - m13 float // Matrix second row (4 components) - m2 float // Matrix third row (4 components) - m6 float // Matrix third row (4 components) - m10 float // Matrix third row (4 components) - m14 float // Matrix third row (4 components) - m3 float // Matrix fourth row (4 components) - m7 float // Matrix fourth row (4 components) - m11 float // Matrix fourth row (4 components) - m15 float // Matrix fourth row (4 components) + M0 float32 // Matrix first row (4 components) + M4 float32 // Matrix first row (4 components) + M8 float32 // Matrix first row (4 components) + M12 float32 // Matrix first row (4 components) + M1 float32 // Matrix second row (4 components) + M5 float32 // Matrix second row (4 components) + M9 float32 // Matrix second row (4 components) + M13 float32 // Matrix second row (4 components) + M2 float32 // Matrix third row (4 components) + M6 float32 // Matrix third row (4 components) + M10 float32 // Matrix third row (4 components) + M14 float32 // Matrix third row (4 components) + M3 float32 // Matrix fourth row (4 components) + M7 float32 // Matrix fourth row (4 components) + M11 float32 // Matrix fourth row (4 components) + M15 float32 // Matrix fourth row (4 components) } /* Color, 4 components, R8G8B8A8 (32bit) */ type Color struct { - r unsigned char // Color red value - g unsigned char // Color green value - b unsigned char // Color blue value - a unsigned char // Color alpha value + R byte // Color red value + G byte // Color green value + B byte // Color blue value + A byte // Color alpha value } /* Rectangle, 4 components */ type Rectangle struct { - x float // Rectangle top-left corner position x - y float // Rectangle top-left corner position y - width float // Rectangle width - height float // Rectangle height + X float32 // Rectangle top-left corner position x + Y float32 // Rectangle top-left corner position y + Width float32 // Rectangle width + Height float32 // Rectangle height } /* Image, pixel data stored in CPU memory (RAM) */ type Image struct { - data void * // Image raw data - width int // Image base width - height int // Image base height - mipmaps int // Mipmap levels, 1 by default - format int // Data format (PixelFormat type) + Data cptr // Image raw data + Width int32 // Image base width + Height int32 // Image base height + Mipmaps int32 // Mipmap levels, 1 by default + Format int32 // Data format (PixelFormat type) } /* Texture, tex data stored in GPU memory (VRAM) */ type Texture struct { - id unsigned int // OpenGL texture id - width int // Texture base width - height int // Texture base height - mipmaps int // Mipmap levels, 1 by default - format int // Data format (PixelFormat type) + Id uint32 // OpenGL texture id + Width int32 // Texture base width + Height int32 // Texture base height + Mipmaps int32 // Mipmap levels, 1 by default + Format int32 // Data format (PixelFormat type) } /* RenderTexture, fbo for texture rendering */ type RenderTexture struct { - id unsigned int // OpenGL framebuffer object id - texture Texture // Color buffer attachment texture - depth Texture // Depth buffer attachment texture + Id uint32 // OpenGL framebuffer object id + Texture Texture // Color buffer attachment texture + Depth Texture // Depth buffer attachment texture } /* NPatchInfo, n-patch layout info */ type NPatchInfo struct { - source Rectangle // Texture source rectangle - left int // Left border offset - top int // Top border offset - right int // Right border offset - bottom int // Bottom border offset - layout int // Layout of the n-patch: 3x3, 1x3 or 3x1 + Source Rectangle // Texture source rectangle + Left int32 // Left border offset + Top int32 // Top border offset + Right int32 // Right border offset + Bottom int32 // Bottom border offset + Layout int32 // Layout of the n-patch: 3x3, 1x3 or 3x1 } /* GlyphInfo, font characters glyphs info */ type GlyphInfo struct { - value int // Character value (Unicode) - offsetX int // Character offset X when drawing - offsetY int // Character offset Y when drawing - advanceX int // Character advance position X - image Image // Character image data + Value int32 // Character value (Unicode) + OffsetX int32 // Character offset X when drawing + OffsetY int32 // Character offset Y when drawing + AdvanceX int32 // Character advance position X + Image Image // Character image data } /* Font, font texture and GlyphInfo array data */ type Font struct { - baseSize int // Base size (default chars height) - glyphCount int // Number of glyph characters - glyphPadding int // Padding around the glyph characters - texture Texture2D // Texture atlas containing the glyphs - recs Rectangle * // Rectangles in texture for the glyphs - glyphs GlyphInfo * // Glyphs info data + BaseSize int32 // Base size (default chars height) + GlyphCount int32 // Number of glyph characters + GlyphPadding int32 // Padding around the glyph characters + Texture Texture2D // Texture atlas containing the glyphs + Recs cptr // Rectangles in texture for the glyphs + Glyphs cptr // Glyphs info data } /* Camera, defines position/orientation in 3d space */ type Camera3D struct { - position Vector3 // Camera position - target Vector3 // Camera target it looks-at - up Vector3 // Camera up vector (rotation over its axis) - fovy float // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane height in world units in orthographic - projection int // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC + Position Vector3 // Camera position + Target Vector3 // Camera target it looks-at + Up Vector3 // Camera up vector (rotation over its axis) + Fovy float32 // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane height in world units in orthographic + Projection int32 // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC } /* Camera2D, defines position/orientation in 2d space */ type Camera2D struct { - offset Vector2 // Camera offset (screen space offset from window origin) - target Vector2 // Camera target (world space target point that is mapped to screen space offset) - rotation float // Camera rotation in degrees (pivots around target) - zoom float // Camera zoom (scaling around target), must not be set to 0, set to 1.0f for no scale + Offset Vector2 // Camera offset (screen space offset from window origin) + Target Vector2 // Camera target (world space target point that is mapped to screen space offset) + Rotation float32 // Camera rotation in degrees (pivots around target) + Zoom float32 // Camera zoom (scaling around target), must not be set to 0, set to 1.0f for no scale } /* Mesh, vertex data and vao/vbo */ type Mesh struct { - vertexCount int // Number of vertices stored in arrays - triangleCount int // Number of triangles stored (indexed or not) - vertices float * // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) - texcoords float * // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) - texcoords2 float * // Vertex texture second coordinates (UV - 2 components per vertex) (shader-location = 5) - normals float * // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) - tangents float * // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) - colors unsigned char * // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) - indices unsigned short * // Vertex indices (in case vertex data comes indexed) - animVertices float * // Animated vertex positions (after bones transformations) - animNormals float * // Animated normals (after bones transformations) - boneIds unsigned char * // Vertex bone ids, max 255 bone ids, up to 4 bones influence by vertex (skinning) (shader-location = 6) - boneWeights float * // Vertex bone weight, up to 4 bones influence by vertex (skinning) (shader-location = 7) - boneMatrices Matrix * // Bones animated transformation matrices - boneCount int // Number of bones - vaoId unsigned int // OpenGL Vertex Array Object id - vboId unsigned int * // OpenGL Vertex Buffer Objects id (default vertex data) + VertexCount int32 // Number of vertices stored in arrays + TriangleCount int32 // Number of triangles stored (indexed or not) + Vertices cptr // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) + Texcoords cptr // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) + Texcoords2 cptr // Vertex texture second coordinates (UV - 2 components per vertex) (shader-location = 5) + Normals cptr // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) + Tangents cptr // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) + Colors cptr // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) + Indices cptr // Vertex indices (in case vertex data comes indexed) + AnimVertices cptr // Animated vertex positions (after bones transformations) + AnimNormals cptr // Animated normals (after bones transformations) + BoneIds cptr // Vertex bone ids, max 255 bone ids, up to 4 bones influence by vertex (skinning) (shader-location = 6) + BoneWeights cptr // Vertex bone weight, up to 4 bones influence by vertex (skinning) (shader-location = 7) + BoneMatrices cptr // Bones animated transformation matrices + BoneCount int32 // Number of bones + VaoId uint32 // OpenGL Vertex Array Object id + VboId cptr // OpenGL Vertex Buffer Objects id (default vertex data) } /* Shader */ type Shader struct { - id unsigned int // Shader program id - locs int * // Shader locations array (RL_MAX_SHADER_LOCATIONS) + Id uint32 // Shader program id + Locs cptr // Shader locations array (RL_MAX_SHADER_LOCATIONS) } /* MaterialMap */ type MaterialMap struct { - texture Texture2D // Material map texture - color Color // Material map color - value float // Material map value + Texture Texture2D // Material map texture + Color Color // Material map color + Value float32 // Material map value } /* Material, includes shader and maps */ type Material struct { - shader Shader // Material shader - maps MaterialMap * // Material maps array (MAX_MATERIAL_MAPS) - params float[4] // Material generic parameters (if required) + Shader Shader // Material shader + Maps cptr // Material maps array (MAX_MATERIAL_MAPS) + Params [4]float32 // Material generic parameters (if required) } /* Transform, vertex transformation data */ type Transform struct { - translation Vector3 // Translation - rotation Quaternion // Rotation - scale Vector3 // Scale + Translation Vector3 // Translation + Rotation Quaternion // Rotation + Scale Vector3 // Scale } /* Bone, skeletal animation bone */ type BoneInfo struct { - name char[32] // Bone name - parent int // Bone parent + Name [32]byte // Bone name + Parent int32 // Bone parent } /* Model, meshes, materials and animation data */ type Model struct { - transform Matrix // Local transform matrix - meshCount int // Number of meshes - materialCount int // Number of materials - meshes Mesh * // Meshes array - materials Material * // Materials array - meshMaterial int * // Mesh material number - boneCount int // Number of bones - bones BoneInfo * // Bones information (skeleton) - bindPose Transform * // Bones base transformation (pose) + Transform Matrix // Local transform matrix + MeshCount int32 // Number of meshes + MaterialCount int32 // Number of materials + Meshes cptr // Meshes array + Materials cptr // Materials array + MeshMaterial cptr // Mesh material number + BoneCount int32 // Number of bones + Bones cptr // Bones information (skeleton) + BindPose cptr // Bones base transformation (pose) } /* ModelAnimation */ type ModelAnimation struct { - boneCount int // Number of bones - frameCount int // Number of animation frames - bones BoneInfo * // Bones information (skeleton) - framePoses Transform ** // Poses array by frame - name char[32] // Animation name + BoneCount int32 // Number of bones + FrameCount int32 // Number of animation frames + Bones cptr // Bones information (skeleton) + FramePoses cptr // Poses array by frame + Name [32]byte // Animation name } /* Ray, ray for raycasting */ type Ray struct { - position Vector3 // Ray position (origin) - direction Vector3 // Ray direction (normalized) + Position Vector3 // Ray position (origin) + Direction Vector3 // Ray direction (normalized) } /* RayCollision, ray hit information */ type RayCollision struct { - hit bool // Did the ray hit something? - distance float // Distance to the nearest hit - point Vector3 // Point of the nearest hit - normal Vector3 // Surface normal of hit + Hit bool // Did the ray hit something? + Distance float32 // Distance to the nearest hit + Point Vector3 // Point of the nearest hit + Normal Vector3 // Surface normal of hit } /* BoundingBox */ type BoundingBox struct { - min Vector3 // Minimum vertex box-corner - max Vector3 // Maximum vertex box-corner + Min Vector3 // Minimum vertex box-corner + Max Vector3 // Maximum vertex box-corner } /* Wave, audio wave data */ type Wave struct { - frameCount unsigned int // Total number of frames (considering channels) - sampleRate unsigned int // Frequency (samples per second) - sampleSize unsigned int // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - channels unsigned int // Number of channels (1-mono, 2-stereo, ...) - data void * // Buffer data pointer + FrameCount uint32 // Total number of frames (considering channels) + SampleRate uint32 // Frequency (samples per second) + SampleSize uint32 // Bit depth (bits per sample): 8, 16, 32 (24 not supported) + Channels uint32 // Number of channels (1-mono, 2-stereo, ...) + Data cptr // Buffer data pointer } /* AudioStream, custom audio stream */ type AudioStream struct { - buffer rAudioBuffer * // Pointer to internal data used by the audio system - processor rAudioProcessor * // Pointer to internal data processor, useful for audio effects - sampleRate unsigned int // Frequency (samples per second) - sampleSize unsigned int // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - channels unsigned int // Number of channels (1-mono, 2-stereo, ...) + Buffer cptr // Pointer to internal data used by the audio system + Processor cptr // Pointer to internal data processor, useful for audio effects + SampleRate uint32 // Frequency (samples per second) + SampleSize uint32 // Bit depth (bits per sample): 8, 16, 32 (24 not supported) + Channels uint32 // Number of channels (1-mono, 2-stereo, ...) } /* Sound */ type Sound struct { - stream AudioStream // Audio stream - frameCount unsigned int // Total number of frames (considering channels) + Stream AudioStream // Audio stream + FrameCount uint32 // Total number of frames (considering channels) } /* Music, audio stream, anything longer than ~10 seconds should be streamed */ type Music struct { - stream AudioStream // Audio stream - frameCount unsigned int // Total number of frames (considering channels) - looping bool // Music looping enable - ctxType int // Type of music context (audio filetype) - ctxData void * // Audio context data, depends on type + Stream AudioStream // Audio stream + FrameCount uint32 // Total number of frames (considering channels) + Looping bool // Music looping enable + CtxType int32 // Type of music context (audio filetype) + CtxData cptr // Audio context data, depends on type } /* VrDeviceInfo, Head-Mounted-Display device parameters */ type VrDeviceInfo struct { - hResolution int // Horizontal resolution in pixels - vResolution int // Vertical resolution in pixels - hScreenSize float // Horizontal size in meters - vScreenSize float // Vertical size in meters - eyeToScreenDistance float // Distance between eye and display in meters - lensSeparationDistance float // Lens separation distance in meters - interpupillaryDistance float // IPD (distance between pupils) in meters - lensDistortionValues float[4] // Lens distortion constant parameters - chromaAbCorrection float[4] // Chromatic aberration correction parameters + HResolution int32 // Horizontal resolution in pixels + VResolution int32 // Vertical resolution in pixels + HScreenSize float32 // Horizontal size in meters + VScreenSize float32 // Vertical size in meters + EyeToScreenDistance float32 // Distance between eye and display in meters + LensSeparationDistance float32 // Lens separation distance in meters + InterpupillaryDistance float32 // IPD (distance between pupils) in meters + LensDistortionValues [4]float32 // Lens distortion constant parameters + ChromaAbCorrection [4]float32 // Chromatic aberration correction parameters } /* VrStereoConfig, VR stereo rendering configuration for simulator */ type VrStereoConfig struct { - projection Matrix[2] // VR projection matrices (per eye) - viewOffset Matrix[2] // VR view offset matrices (per eye) - leftLensCenter float[2] // VR left lens center - rightLensCenter float[2] // VR right lens center - leftScreenCenter float[2] // VR left screen center - rightScreenCenter float[2] // VR right screen center - scale float[2] // VR distortion scale - scaleIn float[2] // VR distortion scale in + Projection [2]Matrix // VR projection matrices (per eye) + ViewOffset [2]Matrix // VR view offset matrices (per eye) + LeftLensCenter [2]float32 // VR left lens center + RightLensCenter [2]float32 // VR right lens center + LeftScreenCenter [2]float32 // VR left screen center + RightScreenCenter [2]float32 // VR right screen center + Scale [2]float32 // VR distortion scale + ScaleIn [2]float32 // VR distortion scale in } /* File path list */ type FilePathList struct { - count unsigned int // Filepaths entries count - paths char ** // Filepaths entries + Count uint32 // Filepaths entries count + Paths cptr // Filepaths entries } /* Automation event */ type AutomationEvent struct { - frame unsigned int // Event frame - type unsigned int // Event type (AutomationEventType) - params int[4] // Event parameters (if required) + Frame uint32 // Event frame + Type uint32 // Event type (AutomationEventType) + Params [4]int32 // Event parameters (if required) } /* Automation event list */ type AutomationEventList struct { - capacity unsigned int // Events max entries (MAX_AUTOMATION_EVENTS) - count unsigned int // Events entries count - events AutomationEvent * // Events entries + Capacity uint32 // Events max entries (MAX_AUTOMATION_EVENTS) + Count uint32 // Events entries count + Events cptr // Events entries } diff --git a/testdata/rl/wasm.go b/testdata/rl/wasm.go index 7a37731..2a43f3d 100644 --- a/testdata/rl/wasm.go +++ b/testdata/rl/wasm.go @@ -1,4 +1,3 @@ - //go:build js package rl diff --git a/testdata/templates/structs.go.gotmpl b/testdata/templates/structs.go.gotmpl index 607d2c7..87829b5 100644 --- a/testdata/templates/structs.go.gotmpl +++ b/testdata/templates/structs.go.gotmpl @@ -1,6 +1,9 @@ {{- $root := . -}} +// AUTOGENERATED FILE. DO NOT EDIT +{{if .BuildTags}} //go:build {{.BuildTags}} +{{end}} package rl {{- range .Imports }} From 566e4f7ccddd31505915e09c4bfe09456ffd1c16 Mon Sep 17 00:00:00 2001 From: BrownNPC Date: Sat, 7 Feb 2026 11:06:47 +0500 Subject: [PATCH 11/12] generate enums --- testdata/api/rlapi.go | 32 ++ testdata/codegen.go | 57 +- testdata/rl/defines_gen_unformatted.go | 114 ++++ testdata/rl/enums_gen_unformatted.go | 741 +++++++++++++++++++++++++ testdata/rl/structs_gen_unformatted.go | 332 +++++------ testdata/templates/defines.go.gotmpl | 30 + testdata/templates/enums.go.gotmpl | 23 + testdata/templates/structs.go.gotmpl | 2 +- testdata/templates/templates.go | 8 + 9 files changed, 1163 insertions(+), 176 deletions(-) create mode 100644 testdata/rl/defines_gen_unformatted.go create mode 100644 testdata/rl/enums_gen_unformatted.go create mode 100644 testdata/templates/defines.go.gotmpl create mode 100644 testdata/templates/enums.go.gotmpl diff --git a/testdata/api/rlapi.go b/testdata/api/rlapi.go index 382c146..05eebec 100644 --- a/testdata/api/rlapi.go +++ b/testdata/api/rlapi.go @@ -3,6 +3,9 @@ package api import ( _ "embed" "encoding/json" + "fmt" + "slices" + "strings" ) var Api RlApi @@ -23,6 +26,35 @@ type RlDefine struct { Value StringyValue `json:"value"` Description string `json:"description"` } + +func FixDefines(defs []RlDefine) []RlDefine { + defs = slices.Clone(defs) + for i, d := range defs { + def := &defs[i] + switch d.Type { + case "STRING": + def.Value = "\"" + def.Value + "\"" + case "FLOAT_MATH": + def.Value = StringyValue(strings.ReplaceAll(string(def.Value), "f", "")) + case "COLOR": + v := strings.ReplaceAll(string(def.Value), "CLITERAL(Color)", "") + def.Value = StringyValue(v) + case "UNKNOWN": + switch def.Name { + case "GetMouseRay": + def.Value = StringyValue(fmt.Sprintf("var %s = %s", def.Name, def.Value)) + case "RLAPI": + *def = RlDefine{} + default: + def.Value = StringyValue( + fmt.Sprintf("const %v = %v", def.Name, def.Value), + ) + } + } + } + return defs +} + type RlField struct { Type RlType `json:"type"` Name PublicName `json:"name"` diff --git a/testdata/codegen.go b/testdata/codegen.go index 6240176..355d14d 100644 --- a/testdata/codegen.go +++ b/testdata/codegen.go @@ -6,15 +6,25 @@ import ( "codegen/templates" _ "embed" "os" + "slices" + "text/template" ) //go:embed templates/structs.go.gotmpl var structsTempl string +//go:embed templates/defines.go.gotmpl +var definesTempl string + +//go:embed templates/enums.go.gotmpl +var enumsTempl string + type Model struct { BuildTags string Imports []string Structs []api.RlStruct + Defines []api.RlDefine + Enums []api.RlEnum } func main() { @@ -34,17 +44,46 @@ func main() { BuildTags: "js", Imports: []string{}, Structs: api.Api.Structs, + Defines: api.FixDefines(api.Api.Defines), + Enums: api.Api.Enums, } - structs := templates.LoadTemplate(structsTempl, "structs") - - var buf bytes.Buffer - - if err := structs.Execute(&buf, m); err != nil { - panic(err) + { + structs := templates.LoadTemplate(structsTempl, "structs") + var buf bytes.Buffer + if err := structs.Execute(&buf, m); err != nil { + panic(err) + } + if err := os.WriteFile("rl/structs_gen_unformatted.go", buf.Bytes(), 0644); err != nil { + panic(err) + } } - - if err := os.WriteFile("rl/structs_gen_unformatted.go", buf.Bytes(), 0644); err != nil { - panic(err) + { + defines := templates.LoadTemplateFuncs(definesTempl, "defines", + template.FuncMap{ + "eq": func(a, b any) bool { return a == b }, + "contains": func(a any, b ...any) bool { return slices.Contains(b, a) }, + }) + var buf bytes.Buffer + if err := defines.Execute(&buf, m); err != nil { + panic(err) + } + if err := os.WriteFile("rl/defines_gen_unformatted.go", buf.Bytes(), 0644); err != nil { + panic(err) + } + } + { + enums := templates.LoadTemplateFuncs(enumsTempl, "enums", + template.FuncMap{ + "eq": func(a, b any) bool { return a == b }, + "contains": func(a any, b ...any) bool { return slices.Contains(b, a) }, + }) + var buf bytes.Buffer + if err := enums.Execute(&buf, m); err != nil { + panic(err) + } + if err := os.WriteFile("rl/enums_gen_unformatted.go", buf.Bytes(), 0644); err != nil { + panic(err) + } } // formatted, err := format.Source(buf.Bytes()) diff --git a/testdata/rl/defines_gen_unformatted.go b/testdata/rl/defines_gen_unformatted.go new file mode 100644 index 0000000..02c50f1 --- /dev/null +++ b/testdata/rl/defines_gen_unformatted.go @@ -0,0 +1,114 @@ +// AUTOGENERATED FILE. DO NOT EDIT + +//go:build js + +package rl + +const RAYLIB_VERSION_MAJOR = 5 + +const RAYLIB_VERSION_MINOR = 6 + +const RAYLIB_VERSION_PATCH = 0 + +const RAYLIB_VERSION = "5.6-dev" + +const PI = 3.14159265358979323846 + +const DEG2RAD = (PI / 180.0) + +const RAD2DEG = (180.0 / PI) + +// Light Gray +var LIGHTGRAY = Color{200, 200, 200, 255} + +// Gray +var GRAY = Color{130, 130, 130, 255} + +// Dark Gray +var DARKGRAY = Color{80, 80, 80, 255} + +// Yellow +var YELLOW = Color{253, 249, 0, 255} + +// Gold +var GOLD = Color{255, 203, 0, 255} + +// Orange +var ORANGE = Color{255, 161, 0, 255} + +// Pink +var PINK = Color{255, 109, 194, 255} + +// Red +var RED = Color{230, 41, 55, 255} + +// Maroon +var MAROON = Color{190, 33, 55, 255} + +// Green +var GREEN = Color{0, 228, 48, 255} + +// Lime +var LIME = Color{0, 158, 47, 255} + +// Dark Green +var DARKGREEN = Color{0, 117, 44, 255} + +// Sky Blue +var SKYBLUE = Color{102, 191, 255, 255} + +// Blue +var BLUE = Color{0, 121, 241, 255} + +// Dark Blue +var DARKBLUE = Color{0, 82, 172, 255} + +// Purple +var PURPLE = Color{200, 122, 255, 255} + +// Violet +var VIOLET = Color{135, 60, 190, 255} + +// Dark Purple +var DARKPURPLE = Color{112, 31, 126, 255} + +// Beige +var BEIGE = Color{211, 176, 131, 255} + +// Brown +var BROWN = Color{127, 106, 79, 255} + +// Dark Brown +var DARKBROWN = Color{76, 63, 47, 255} + +// White +var WHITE = Color{255, 255, 255, 255} + +// Black +var BLACK = Color{0, 0, 0, 255} + +// Blank (Transparent) +var BLANK = Color{0, 0, 0, 0} + +// Magenta +var MAGENTA = Color{255, 0, 255, 255} + +// My own White (raylib logo) +var RAYWHITE = Color{245, 245, 245, 255} + +const MOUSE_LEFT_BUTTON = MOUSE_BUTTON_LEFT + +const MOUSE_RIGHT_BUTTON = MOUSE_BUTTON_RIGHT + +const MOUSE_MIDDLE_BUTTON = MOUSE_BUTTON_MIDDLE + +const MATERIAL_MAP_DIFFUSE = MATERIAL_MAP_ALBEDO + +const MATERIAL_MAP_SPECULAR = MATERIAL_MAP_METALNESS + +const SHADER_LOC_MAP_DIFFUSE = SHADER_LOC_MAP_ALBEDO + +const SHADER_LOC_MAP_SPECULAR = SHADER_LOC_MAP_METALNESS + +// Compatibility hack for previous raylib versions +var GetMouseRay = GetScreenToWorldRay diff --git a/testdata/rl/enums_gen_unformatted.go b/testdata/rl/enums_gen_unformatted.go new file mode 100644 index 0000000..2d3ff1e --- /dev/null +++ b/testdata/rl/enums_gen_unformatted.go @@ -0,0 +1,741 @@ +// AUTOGENERATED FILE. DO NOT EDIT + +//go:build js + +package rl + +// System/Window config flags +type ConfigFlags = int32 + +const ( + // Set to try enabling V-Sync on GPU + FLAG_VSYNC_HINT = 64 + // Set to run program in fullscreen + FLAG_FULLSCREEN_MODE = 2 + // Set to allow resizable window + FLAG_WINDOW_RESIZABLE = 4 + // Set to disable window decoration (frame and buttons) + FLAG_WINDOW_UNDECORATED = 8 + // Set to hide window + FLAG_WINDOW_HIDDEN = 128 + // Set to minimize window (iconify) + FLAG_WINDOW_MINIMIZED = 512 + // Set to maximize window (expanded to monitor) + FLAG_WINDOW_MAXIMIZED = 1024 + // Set to window non focused + FLAG_WINDOW_UNFOCUSED = 2048 + // Set to window always on top + FLAG_WINDOW_TOPMOST = 4096 + // Set to allow windows running while minimized + FLAG_WINDOW_ALWAYS_RUN = 256 + // Set to allow transparent framebuffer + FLAG_WINDOW_TRANSPARENT = 16 + // Set to support HighDPI + FLAG_WINDOW_HIGHDPI = 8192 + // Set to support mouse passthrough, only supported when FLAG_WINDOW_UNDECORATED + FLAG_WINDOW_MOUSE_PASSTHROUGH = 16384 + // Set to run program in borderless windowed mode + FLAG_BORDERLESS_WINDOWED_MODE = 32768 + // Set to try enabling MSAA 4X + FLAG_MSAA_4X_HINT = 32 + // Set to try enabling interlaced video format (for V3D) + FLAG_INTERLACED_HINT = 65536 +) + +// Trace log level +type TraceLogLevel = int32 + +const ( + // Display all logs + LOG_ALL = 0 + // Trace logging, intended for internal use only + LOG_TRACE = 1 + // Debug logging, used for internal debugging, it should be disabled on release builds + LOG_DEBUG = 2 + // Info logging, used for program execution info + LOG_INFO = 3 + // Warning logging, used on recoverable failures + LOG_WARNING = 4 + // Error logging, used on unrecoverable failures + LOG_ERROR = 5 + // Fatal logging, used to abort program: exit(EXIT_FAILURE) + LOG_FATAL = 6 + // Disable logging + LOG_NONE = 7 +) + +// Keyboard keys (US keyboard layout) +type KeyboardKey = int32 + +const ( + // Key: NULL, used for no key pressed + KEY_NULL = 0 + // Key: ' + KEY_APOSTROPHE = 39 + // Key: , + KEY_COMMA = 44 + // Key: - + KEY_MINUS = 45 + // Key: . + KEY_PERIOD = 46 + // Key: / + KEY_SLASH = 47 + // Key: 0 + KEY_ZERO = 48 + // Key: 1 + KEY_ONE = 49 + // Key: 2 + KEY_TWO = 50 + // Key: 3 + KEY_THREE = 51 + // Key: 4 + KEY_FOUR = 52 + // Key: 5 + KEY_FIVE = 53 + // Key: 6 + KEY_SIX = 54 + // Key: 7 + KEY_SEVEN = 55 + // Key: 8 + KEY_EIGHT = 56 + // Key: 9 + KEY_NINE = 57 + // Key: ; + KEY_SEMICOLON = 59 + // Key: = + KEY_EQUAL = 61 + // Key: A | a + KEY_A = 65 + // Key: B | b + KEY_B = 66 + // Key: C | c + KEY_C = 67 + // Key: D | d + KEY_D = 68 + // Key: E | e + KEY_E = 69 + // Key: F | f + KEY_F = 70 + // Key: G | g + KEY_G = 71 + // Key: H | h + KEY_H = 72 + // Key: I | i + KEY_I = 73 + // Key: J | j + KEY_J = 74 + // Key: K | k + KEY_K = 75 + // Key: L | l + KEY_L = 76 + // Key: M | m + KEY_M = 77 + // Key: N | n + KEY_N = 78 + // Key: O | o + KEY_O = 79 + // Key: P | p + KEY_P = 80 + // Key: Q | q + KEY_Q = 81 + // Key: R | r + KEY_R = 82 + // Key: S | s + KEY_S = 83 + // Key: T | t + KEY_T = 84 + // Key: U | u + KEY_U = 85 + // Key: V | v + KEY_V = 86 + // Key: W | w + KEY_W = 87 + // Key: X | x + KEY_X = 88 + // Key: Y | y + KEY_Y = 89 + // Key: Z | z + KEY_Z = 90 + // Key: [ + KEY_LEFT_BRACKET = 91 + // Key: '\' + KEY_BACKSLASH = 92 + // Key: ] + KEY_RIGHT_BRACKET = 93 + // Key: ` + KEY_GRAVE = 96 + // Key: Space + KEY_SPACE = 32 + // Key: Esc + KEY_ESCAPE = 256 + // Key: Enter + KEY_ENTER = 257 + // Key: Tab + KEY_TAB = 258 + // Key: Backspace + KEY_BACKSPACE = 259 + // Key: Ins + KEY_INSERT = 260 + // Key: Del + KEY_DELETE = 261 + // Key: Cursor right + KEY_RIGHT = 262 + // Key: Cursor left + KEY_LEFT = 263 + // Key: Cursor down + KEY_DOWN = 264 + // Key: Cursor up + KEY_UP = 265 + // Key: Page up + KEY_PAGE_UP = 266 + // Key: Page down + KEY_PAGE_DOWN = 267 + // Key: Home + KEY_HOME = 268 + // Key: End + KEY_END = 269 + // Key: Caps lock + KEY_CAPS_LOCK = 280 + // Key: Scroll down + KEY_SCROLL_LOCK = 281 + // Key: Num lock + KEY_NUM_LOCK = 282 + // Key: Print screen + KEY_PRINT_SCREEN = 283 + // Key: Pause + KEY_PAUSE = 284 + // Key: F1 + KEY_F1 = 290 + // Key: F2 + KEY_F2 = 291 + // Key: F3 + KEY_F3 = 292 + // Key: F4 + KEY_F4 = 293 + // Key: F5 + KEY_F5 = 294 + // Key: F6 + KEY_F6 = 295 + // Key: F7 + KEY_F7 = 296 + // Key: F8 + KEY_F8 = 297 + // Key: F9 + KEY_F9 = 298 + // Key: F10 + KEY_F10 = 299 + // Key: F11 + KEY_F11 = 300 + // Key: F12 + KEY_F12 = 301 + // Key: Shift left + KEY_LEFT_SHIFT = 340 + // Key: Control left + KEY_LEFT_CONTROL = 341 + // Key: Alt left + KEY_LEFT_ALT = 342 + // Key: Super left + KEY_LEFT_SUPER = 343 + // Key: Shift right + KEY_RIGHT_SHIFT = 344 + // Key: Control right + KEY_RIGHT_CONTROL = 345 + // Key: Alt right + KEY_RIGHT_ALT = 346 + // Key: Super right + KEY_RIGHT_SUPER = 347 + // Key: KB menu + KEY_KB_MENU = 348 + // Key: Keypad 0 + KEY_KP_0 = 320 + // Key: Keypad 1 + KEY_KP_1 = 321 + // Key: Keypad 2 + KEY_KP_2 = 322 + // Key: Keypad 3 + KEY_KP_3 = 323 + // Key: Keypad 4 + KEY_KP_4 = 324 + // Key: Keypad 5 + KEY_KP_5 = 325 + // Key: Keypad 6 + KEY_KP_6 = 326 + // Key: Keypad 7 + KEY_KP_7 = 327 + // Key: Keypad 8 + KEY_KP_8 = 328 + // Key: Keypad 9 + KEY_KP_9 = 329 + // Key: Keypad . + KEY_KP_DECIMAL = 330 + // Key: Keypad / + KEY_KP_DIVIDE = 331 + // Key: Keypad * + KEY_KP_MULTIPLY = 332 + // Key: Keypad - + KEY_KP_SUBTRACT = 333 + // Key: Keypad + + KEY_KP_ADD = 334 + // Key: Keypad Enter + KEY_KP_ENTER = 335 + // Key: Keypad = + KEY_KP_EQUAL = 336 + // Key: Android back button + KEY_BACK = 4 + // Key: Android menu button + KEY_MENU = 5 + // Key: Android volume up button + KEY_VOLUME_UP = 24 + // Key: Android volume down button + KEY_VOLUME_DOWN = 25 +) + +// Mouse buttons +type MouseButton = int32 + +const ( + // Mouse button left + MOUSE_BUTTON_LEFT = 0 + // Mouse button right + MOUSE_BUTTON_RIGHT = 1 + // Mouse button middle (pressed wheel) + MOUSE_BUTTON_MIDDLE = 2 + // Mouse button side (advanced mouse device) + MOUSE_BUTTON_SIDE = 3 + // Mouse button extra (advanced mouse device) + MOUSE_BUTTON_EXTRA = 4 + // Mouse button forward (advanced mouse device) + MOUSE_BUTTON_FORWARD = 5 + // Mouse button back (advanced mouse device) + MOUSE_BUTTON_BACK = 6 +) + +// Mouse cursor +type MouseCursor = int32 + +const ( + // Default pointer shape + MOUSE_CURSOR_DEFAULT = 0 + // Arrow shape + MOUSE_CURSOR_ARROW = 1 + // Text writing cursor shape + MOUSE_CURSOR_IBEAM = 2 + // Cross shape + MOUSE_CURSOR_CROSSHAIR = 3 + // Pointing hand cursor + MOUSE_CURSOR_POINTING_HAND = 4 + // Horizontal resize/move arrow shape + MOUSE_CURSOR_RESIZE_EW = 5 + // Vertical resize/move arrow shape + MOUSE_CURSOR_RESIZE_NS = 6 + // Top-left to bottom-right diagonal resize/move arrow shape + MOUSE_CURSOR_RESIZE_NWSE = 7 + // The top-right to bottom-left diagonal resize/move arrow shape + MOUSE_CURSOR_RESIZE_NESW = 8 + // The omnidirectional resize/move cursor shape + MOUSE_CURSOR_RESIZE_ALL = 9 + // The operation-not-allowed shape + MOUSE_CURSOR_NOT_ALLOWED = 10 +) + +// Gamepad buttons +type GamepadButton = int32 + +const ( + // Unknown button, just for error checking + GAMEPAD_BUTTON_UNKNOWN = 0 + // Gamepad left DPAD up button + GAMEPAD_BUTTON_LEFT_FACE_UP = 1 + // Gamepad left DPAD right button + GAMEPAD_BUTTON_LEFT_FACE_RIGHT = 2 + // Gamepad left DPAD down button + GAMEPAD_BUTTON_LEFT_FACE_DOWN = 3 + // Gamepad left DPAD left button + GAMEPAD_BUTTON_LEFT_FACE_LEFT = 4 + // Gamepad right button up (i.e. PS3: Triangle, Xbox: Y) + GAMEPAD_BUTTON_RIGHT_FACE_UP = 5 + // Gamepad right button right (i.e. PS3: Circle, Xbox: B) + GAMEPAD_BUTTON_RIGHT_FACE_RIGHT = 6 + // Gamepad right button down (i.e. PS3: Cross, Xbox: A) + GAMEPAD_BUTTON_RIGHT_FACE_DOWN = 7 + // Gamepad right button left (i.e. PS3: Square, Xbox: X) + GAMEPAD_BUTTON_RIGHT_FACE_LEFT = 8 + // Gamepad top/back trigger left (first), it could be a trailing button + GAMEPAD_BUTTON_LEFT_TRIGGER_1 = 9 + // Gamepad top/back trigger left (second), it could be a trailing button + GAMEPAD_BUTTON_LEFT_TRIGGER_2 = 10 + // Gamepad top/back trigger right (first), it could be a trailing button + GAMEPAD_BUTTON_RIGHT_TRIGGER_1 = 11 + // Gamepad top/back trigger right (second), it could be a trailing button + GAMEPAD_BUTTON_RIGHT_TRIGGER_2 = 12 + // Gamepad center buttons, left one (i.e. PS3: Select) + GAMEPAD_BUTTON_MIDDLE_LEFT = 13 + // Gamepad center buttons, middle one (i.e. PS3: PS, Xbox: XBOX) + GAMEPAD_BUTTON_MIDDLE = 14 + // Gamepad center buttons, right one (i.e. PS3: Start) + GAMEPAD_BUTTON_MIDDLE_RIGHT = 15 + // Gamepad joystick pressed button left + GAMEPAD_BUTTON_LEFT_THUMB = 16 + // Gamepad joystick pressed button right + GAMEPAD_BUTTON_RIGHT_THUMB = 17 +) + +// Gamepad axes +type GamepadAxis = int32 + +const ( + // Gamepad left stick X axis + GAMEPAD_AXIS_LEFT_X = 0 + // Gamepad left stick Y axis + GAMEPAD_AXIS_LEFT_Y = 1 + // Gamepad right stick X axis + GAMEPAD_AXIS_RIGHT_X = 2 + // Gamepad right stick Y axis + GAMEPAD_AXIS_RIGHT_Y = 3 + // Gamepad back trigger left, pressure level: [1..-1] + GAMEPAD_AXIS_LEFT_TRIGGER = 4 + // Gamepad back trigger right, pressure level: [1..-1] + GAMEPAD_AXIS_RIGHT_TRIGGER = 5 +) + +// Material map index +type MaterialMapIndex = int32 + +const ( + // Albedo material (same as: MATERIAL_MAP_DIFFUSE) + MATERIAL_MAP_ALBEDO = 0 + // Metalness material (same as: MATERIAL_MAP_SPECULAR) + MATERIAL_MAP_METALNESS = 1 + // Normal material + MATERIAL_MAP_NORMAL = 2 + // Roughness material + MATERIAL_MAP_ROUGHNESS = 3 + // Ambient occlusion material + MATERIAL_MAP_OCCLUSION = 4 + // Emission material + MATERIAL_MAP_EMISSION = 5 + // Heightmap material + MATERIAL_MAP_HEIGHT = 6 + // Cubemap material (NOTE: Uses GL_TEXTURE_CUBE_MAP) + MATERIAL_MAP_CUBEMAP = 7 + // Irradiance material (NOTE: Uses GL_TEXTURE_CUBE_MAP) + MATERIAL_MAP_IRRADIANCE = 8 + // Prefilter material (NOTE: Uses GL_TEXTURE_CUBE_MAP) + MATERIAL_MAP_PREFILTER = 9 + // Brdf material + MATERIAL_MAP_BRDF = 10 +) + +// Shader location index +type ShaderLocationIndex = int32 + +const ( + // Shader location: vertex attribute: position + SHADER_LOC_VERTEX_POSITION = 0 + // Shader location: vertex attribute: texcoord01 + SHADER_LOC_VERTEX_TEXCOORD01 = 1 + // Shader location: vertex attribute: texcoord02 + SHADER_LOC_VERTEX_TEXCOORD02 = 2 + // Shader location: vertex attribute: normal + SHADER_LOC_VERTEX_NORMAL = 3 + // Shader location: vertex attribute: tangent + SHADER_LOC_VERTEX_TANGENT = 4 + // Shader location: vertex attribute: color + SHADER_LOC_VERTEX_COLOR = 5 + // Shader location: matrix uniform: model-view-projection + SHADER_LOC_MATRIX_MVP = 6 + // Shader location: matrix uniform: view (camera transform) + SHADER_LOC_MATRIX_VIEW = 7 + // Shader location: matrix uniform: projection + SHADER_LOC_MATRIX_PROJECTION = 8 + // Shader location: matrix uniform: model (transform) + SHADER_LOC_MATRIX_MODEL = 9 + // Shader location: matrix uniform: normal + SHADER_LOC_MATRIX_NORMAL = 10 + // Shader location: vector uniform: view + SHADER_LOC_VECTOR_VIEW = 11 + // Shader location: vector uniform: diffuse color + SHADER_LOC_COLOR_DIFFUSE = 12 + // Shader location: vector uniform: specular color + SHADER_LOC_COLOR_SPECULAR = 13 + // Shader location: vector uniform: ambient color + SHADER_LOC_COLOR_AMBIENT = 14 + // Shader location: sampler2d texture: albedo (same as: SHADER_LOC_MAP_DIFFUSE) + SHADER_LOC_MAP_ALBEDO = 15 + // Shader location: sampler2d texture: metalness (same as: SHADER_LOC_MAP_SPECULAR) + SHADER_LOC_MAP_METALNESS = 16 + // Shader location: sampler2d texture: normal + SHADER_LOC_MAP_NORMAL = 17 + // Shader location: sampler2d texture: roughness + SHADER_LOC_MAP_ROUGHNESS = 18 + // Shader location: sampler2d texture: occlusion + SHADER_LOC_MAP_OCCLUSION = 19 + // Shader location: sampler2d texture: emission + SHADER_LOC_MAP_EMISSION = 20 + // Shader location: sampler2d texture: height + SHADER_LOC_MAP_HEIGHT = 21 + // Shader location: samplerCube texture: cubemap + SHADER_LOC_MAP_CUBEMAP = 22 + // Shader location: samplerCube texture: irradiance + SHADER_LOC_MAP_IRRADIANCE = 23 + // Shader location: samplerCube texture: prefilter + SHADER_LOC_MAP_PREFILTER = 24 + // Shader location: sampler2d texture: brdf + SHADER_LOC_MAP_BRDF = 25 + // Shader location: vertex attribute: boneIds + SHADER_LOC_VERTEX_BONEIDS = 26 + // Shader location: vertex attribute: boneWeights + SHADER_LOC_VERTEX_BONEWEIGHTS = 27 + // Shader location: array of matrices uniform: boneMatrices + SHADER_LOC_BONE_MATRICES = 28 + // Shader location: vertex attribute: instanceTransform + SHADER_LOC_VERTEX_INSTANCE_TX = 29 +) + +// Shader uniform data type +type ShaderUniformDataType = int32 + +const ( + // Shader uniform type: float + SHADER_UNIFORM_FLOAT = 0 + // Shader uniform type: vec2 (2 float) + SHADER_UNIFORM_VEC2 = 1 + // Shader uniform type: vec3 (3 float) + SHADER_UNIFORM_VEC3 = 2 + // Shader uniform type: vec4 (4 float) + SHADER_UNIFORM_VEC4 = 3 + // Shader uniform type: int + SHADER_UNIFORM_INT = 4 + // Shader uniform type: ivec2 (2 int) + SHADER_UNIFORM_IVEC2 = 5 + // Shader uniform type: ivec3 (3 int) + SHADER_UNIFORM_IVEC3 = 6 + // Shader uniform type: ivec4 (4 int) + SHADER_UNIFORM_IVEC4 = 7 + // Shader uniform type: unsigned int + SHADER_UNIFORM_UINT = 8 + // Shader uniform type: uivec2 (2 unsigned int) + SHADER_UNIFORM_UIVEC2 = 9 + // Shader uniform type: uivec3 (3 unsigned int) + SHADER_UNIFORM_UIVEC3 = 10 + // Shader uniform type: uivec4 (4 unsigned int) + SHADER_UNIFORM_UIVEC4 = 11 + // Shader uniform type: sampler2d + SHADER_UNIFORM_SAMPLER2D = 12 +) + +// Shader attribute data types +type ShaderAttributeDataType = int32 + +const ( + // Shader attribute type: float + SHADER_ATTRIB_FLOAT = 0 + // Shader attribute type: vec2 (2 float) + SHADER_ATTRIB_VEC2 = 1 + // Shader attribute type: vec3 (3 float) + SHADER_ATTRIB_VEC3 = 2 + // Shader attribute type: vec4 (4 float) + SHADER_ATTRIB_VEC4 = 3 +) + +// Pixel formats +type PixelFormat = int32 + +const ( + // 8 bit per pixel (no alpha) + PIXELFORMAT_UNCOMPRESSED_GRAYSCALE = 1 + // 8*2 bpp (2 channels) + PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA = 2 + // 16 bpp + PIXELFORMAT_UNCOMPRESSED_R5G6B5 = 3 + // 24 bpp + PIXELFORMAT_UNCOMPRESSED_R8G8B8 = 4 + // 16 bpp (1 bit alpha) + PIXELFORMAT_UNCOMPRESSED_R5G5B5A1 = 5 + // 16 bpp (4 bit alpha) + PIXELFORMAT_UNCOMPRESSED_R4G4B4A4 = 6 + // 32 bpp + PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 = 7 + // 32 bpp (1 channel - float) + PIXELFORMAT_UNCOMPRESSED_R32 = 8 + // 32*3 bpp (3 channels - float) + PIXELFORMAT_UNCOMPRESSED_R32G32B32 = 9 + // 32*4 bpp (4 channels - float) + PIXELFORMAT_UNCOMPRESSED_R32G32B32A32 = 10 + // 16 bpp (1 channel - half float) + PIXELFORMAT_UNCOMPRESSED_R16 = 11 + // 16*3 bpp (3 channels - half float) + PIXELFORMAT_UNCOMPRESSED_R16G16B16 = 12 + // 16*4 bpp (4 channels - half float) + PIXELFORMAT_UNCOMPRESSED_R16G16B16A16 = 13 + // 4 bpp (no alpha) + PIXELFORMAT_COMPRESSED_DXT1_RGB = 14 + // 4 bpp (1 bit alpha) + PIXELFORMAT_COMPRESSED_DXT1_RGBA = 15 + // 8 bpp + PIXELFORMAT_COMPRESSED_DXT3_RGBA = 16 + // 8 bpp + PIXELFORMAT_COMPRESSED_DXT5_RGBA = 17 + // 4 bpp + PIXELFORMAT_COMPRESSED_ETC1_RGB = 18 + // 4 bpp + PIXELFORMAT_COMPRESSED_ETC2_RGB = 19 + // 8 bpp + PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA = 20 + // 4 bpp + PIXELFORMAT_COMPRESSED_PVRT_RGB = 21 + // 4 bpp + PIXELFORMAT_COMPRESSED_PVRT_RGBA = 22 + // 8 bpp + PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA = 23 + // 2 bpp + PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA = 24 +) + +// Texture parameters: filter mode +type TextureFilter = int32 + +const ( + // No filter, just pixel approximation + TEXTURE_FILTER_POINT = 0 + // Linear filtering + TEXTURE_FILTER_BILINEAR = 1 + // Trilinear filtering (linear with mipmaps) + TEXTURE_FILTER_TRILINEAR = 2 + // Anisotropic filtering 4x + TEXTURE_FILTER_ANISOTROPIC_4X = 3 + // Anisotropic filtering 8x + TEXTURE_FILTER_ANISOTROPIC_8X = 4 + // Anisotropic filtering 16x + TEXTURE_FILTER_ANISOTROPIC_16X = 5 +) + +// Texture parameters: wrap mode +type TextureWrap = int32 + +const ( + // Repeats texture in tiled mode + TEXTURE_WRAP_REPEAT = 0 + // Clamps texture to edge pixel in tiled mode + TEXTURE_WRAP_CLAMP = 1 + // Mirrors and repeats the texture in tiled mode + TEXTURE_WRAP_MIRROR_REPEAT = 2 + // Mirrors and clamps to border the texture in tiled mode + TEXTURE_WRAP_MIRROR_CLAMP = 3 +) + +// Cubemap layouts +type CubemapLayout = int32 + +const ( + // Automatically detect layout type + CUBEMAP_LAYOUT_AUTO_DETECT = 0 + // Layout is defined by a vertical line with faces + CUBEMAP_LAYOUT_LINE_VERTICAL = 1 + // Layout is defined by a horizontal line with faces + CUBEMAP_LAYOUT_LINE_HORIZONTAL = 2 + // Layout is defined by a 3x4 cross with cubemap faces + CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR = 3 + // Layout is defined by a 4x3 cross with cubemap faces + CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE = 4 +) + +// Font type, defines generation method +type FontType = int32 + +const ( + // Default font generation, anti-aliased + FONT_DEFAULT = 0 + // Bitmap font generation, no anti-aliasing + FONT_BITMAP = 1 + // SDF font generation, requires external shader + FONT_SDF = 2 +) + +// Color blending modes (pre-defined) +type BlendMode = int32 + +const ( + // Blend textures considering alpha (default) + BLEND_ALPHA = 0 + // Blend textures adding colors + BLEND_ADDITIVE = 1 + // Blend textures multiplying colors + BLEND_MULTIPLIED = 2 + // Blend textures adding colors (alternative) + BLEND_ADD_COLORS = 3 + // Blend textures subtracting colors (alternative) + BLEND_SUBTRACT_COLORS = 4 + // Blend premultiplied textures considering alpha + BLEND_ALPHA_PREMULTIPLY = 5 + // Blend textures using custom src/dst factors (use rlSetBlendFactors()) + BLEND_CUSTOM = 6 + // Blend textures using custom rgb/alpha separate src/dst factors (use rlSetBlendFactorsSeparate()) + BLEND_CUSTOM_SEPARATE = 7 +) + +// Gesture +type Gesture = int32 + +const ( + // No gesture + GESTURE_NONE = 0 + // Tap gesture + GESTURE_TAP = 1 + // Double tap gesture + GESTURE_DOUBLETAP = 2 + // Hold gesture + GESTURE_HOLD = 4 + // Drag gesture + GESTURE_DRAG = 8 + // Swipe right gesture + GESTURE_SWIPE_RIGHT = 16 + // Swipe left gesture + GESTURE_SWIPE_LEFT = 32 + // Swipe up gesture + GESTURE_SWIPE_UP = 64 + // Swipe down gesture + GESTURE_SWIPE_DOWN = 128 + // Pinch in gesture + GESTURE_PINCH_IN = 256 + // Pinch out gesture + GESTURE_PINCH_OUT = 512 +) + +// Camera system modes +type CameraMode = int32 + +const ( + // Camera custom, controlled by user (UpdateCamera() does nothing) + CAMERA_CUSTOM = 0 + // Camera free mode + CAMERA_FREE = 1 + // Camera orbital, around target, zoom supported + CAMERA_ORBITAL = 2 + // Camera first person + CAMERA_FIRST_PERSON = 3 + // Camera third person + CAMERA_THIRD_PERSON = 4 +) + +// Camera projection +type CameraProjection = int32 + +const ( + // Perspective projection + CAMERA_PERSPECTIVE = 0 + // Orthographic projection + CAMERA_ORTHOGRAPHIC = 1 +) + +// N-patch layout +type NPatchLayout = int32 + +const ( + // Npatch layout: 3x3 tiles + NPATCH_NINE_PATCH = 0 + // Npatch layout: 1x3 tiles + NPATCH_THREE_PATCH_VERTICAL = 1 + // Npatch layout: 3x1 tiles + NPATCH_THREE_PATCH_HORIZONTAL = 2 +) diff --git a/testdata/rl/structs_gen_unformatted.go b/testdata/rl/structs_gen_unformatted.go index d86eb88..1d2e2ac 100644 --- a/testdata/rl/structs_gen_unformatted.go +++ b/testdata/rl/structs_gen_unformatted.go @@ -4,20 +4,20 @@ package rl -/* Vector2, 2 components */ +// Vector2, 2 components type Vector2 struct { X float32 // Vector x component Y float32 // Vector y component } -/* Vector3, 3 components */ +// Vector3, 3 components type Vector3 struct { X float32 // Vector x component Y float32 // Vector y component Z float32 // Vector z component } -/* Vector4, 4 components */ +// Vector4, 4 components type Vector4 struct { X float32 // Vector x component Y float32 // Vector y component @@ -25,27 +25,27 @@ type Vector4 struct { W float32 // Vector w component } -/* Matrix, 4x4 components, column major, OpenGL style, right-handed */ +// Matrix, 4x4 components, column major, OpenGL style, right-handed type Matrix struct { - M0 float32 // Matrix first row (4 components) - M4 float32 // Matrix first row (4 components) - M8 float32 // Matrix first row (4 components) + M0 float32 // Matrix first row (4 components) + M4 float32 // Matrix first row (4 components) + M8 float32 // Matrix first row (4 components) M12 float32 // Matrix first row (4 components) - M1 float32 // Matrix second row (4 components) - M5 float32 // Matrix second row (4 components) - M9 float32 // Matrix second row (4 components) + M1 float32 // Matrix second row (4 components) + M5 float32 // Matrix second row (4 components) + M9 float32 // Matrix second row (4 components) M13 float32 // Matrix second row (4 components) - M2 float32 // Matrix third row (4 components) - M6 float32 // Matrix third row (4 components) + M2 float32 // Matrix third row (4 components) + M6 float32 // Matrix third row (4 components) M10 float32 // Matrix third row (4 components) M14 float32 // Matrix third row (4 components) - M3 float32 // Matrix fourth row (4 components) - M7 float32 // Matrix fourth row (4 components) + M3 float32 // Matrix fourth row (4 components) + M7 float32 // Matrix fourth row (4 components) M11 float32 // Matrix fourth row (4 components) M15 float32 // Matrix fourth row (4 components) } -/* Color, 4 components, R8G8B8A8 (32bit) */ +// Color, 4 components, R8G8B8A8 (32bit) type Color struct { R byte // Color red value G byte // Color green value @@ -53,255 +53,255 @@ type Color struct { A byte // Color alpha value } -/* Rectangle, 4 components */ +// Rectangle, 4 components type Rectangle struct { - X float32 // Rectangle top-left corner position x - Y float32 // Rectangle top-left corner position y - Width float32 // Rectangle width + X float32 // Rectangle top-left corner position x + Y float32 // Rectangle top-left corner position y + Width float32 // Rectangle width Height float32 // Rectangle height } -/* Image, pixel data stored in CPU memory (RAM) */ +// Image, pixel data stored in CPU memory (RAM) type Image struct { - Data cptr // Image raw data - Width int32 // Image base width - Height int32 // Image base height + Data cptr // Image raw data + Width int32 // Image base width + Height int32 // Image base height Mipmaps int32 // Mipmap levels, 1 by default - Format int32 // Data format (PixelFormat type) + Format int32 // Data format (PixelFormat type) } -/* Texture, tex data stored in GPU memory (VRAM) */ +// Texture, tex data stored in GPU memory (VRAM) type Texture struct { - Id uint32 // OpenGL texture id - Width int32 // Texture base width - Height int32 // Texture base height - Mipmaps int32 // Mipmap levels, 1 by default - Format int32 // Data format (PixelFormat type) + Id uint32 // OpenGL texture id + Width int32 // Texture base width + Height int32 // Texture base height + Mipmaps int32 // Mipmap levels, 1 by default + Format int32 // Data format (PixelFormat type) } -/* RenderTexture, fbo for texture rendering */ +// RenderTexture, fbo for texture rendering type RenderTexture struct { - Id uint32 // OpenGL framebuffer object id + Id uint32 // OpenGL framebuffer object id Texture Texture // Color buffer attachment texture - Depth Texture // Depth buffer attachment texture + Depth Texture // Depth buffer attachment texture } -/* NPatchInfo, n-patch layout info */ +// NPatchInfo, n-patch layout info type NPatchInfo struct { Source Rectangle // Texture source rectangle - Left int32 // Left border offset - Top int32 // Top border offset - Right int32 // Right border offset - Bottom int32 // Bottom border offset - Layout int32 // Layout of the n-patch: 3x3, 1x3 or 3x1 + Left int32 // Left border offset + Top int32 // Top border offset + Right int32 // Right border offset + Bottom int32 // Bottom border offset + Layout int32 // Layout of the n-patch: 3x3, 1x3 or 3x1 } -/* GlyphInfo, font characters glyphs info */ +// GlyphInfo, font characters glyphs info type GlyphInfo struct { - Value int32 // Character value (Unicode) - OffsetX int32 // Character offset X when drawing - OffsetY int32 // Character offset Y when drawing + Value int32 // Character value (Unicode) + OffsetX int32 // Character offset X when drawing + OffsetY int32 // Character offset Y when drawing AdvanceX int32 // Character advance position X - Image Image // Character image data + Image Image // Character image data } -/* Font, font texture and GlyphInfo array data */ +// Font, font texture and GlyphInfo array data type Font struct { - BaseSize int32 // Base size (default chars height) - GlyphCount int32 // Number of glyph characters - GlyphPadding int32 // Padding around the glyph characters - Texture Texture2D // Texture atlas containing the glyphs - Recs cptr // Rectangles in texture for the glyphs - Glyphs cptr // Glyphs info data + BaseSize int32 // Base size (default chars height) + GlyphCount int32 // Number of glyph characters + GlyphPadding int32 // Padding around the glyph characters + Texture Texture2D // Texture atlas containing the glyphs + Recs cptr // Rectangles in texture for the glyphs + Glyphs cptr // Glyphs info data } -/* Camera, defines position/orientation in 3d space */ +// Camera, defines position/orientation in 3d space type Camera3D struct { - Position Vector3 // Camera position - Target Vector3 // Camera target it looks-at - Up Vector3 // Camera up vector (rotation over its axis) - Fovy float32 // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane height in world units in orthographic - Projection int32 // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC + Position Vector3 // Camera position + Target Vector3 // Camera target it looks-at + Up Vector3 // Camera up vector (rotation over its axis) + Fovy float32 // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane height in world units in orthographic + Projection int32 // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC } -/* Camera2D, defines position/orientation in 2d space */ +// Camera2D, defines position/orientation in 2d space type Camera2D struct { - Offset Vector2 // Camera offset (screen space offset from window origin) - Target Vector2 // Camera target (world space target point that is mapped to screen space offset) + Offset Vector2 // Camera offset (screen space offset from window origin) + Target Vector2 // Camera target (world space target point that is mapped to screen space offset) Rotation float32 // Camera rotation in degrees (pivots around target) - Zoom float32 // Camera zoom (scaling around target), must not be set to 0, set to 1.0f for no scale + Zoom float32 // Camera zoom (scaling around target), must not be set to 0, set to 1.0f for no scale } -/* Mesh, vertex data and vao/vbo */ +// Mesh, vertex data and vao/vbo type Mesh struct { - VertexCount int32 // Number of vertices stored in arrays - TriangleCount int32 // Number of triangles stored (indexed or not) - Vertices cptr // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) - Texcoords cptr // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) - Texcoords2 cptr // Vertex texture second coordinates (UV - 2 components per vertex) (shader-location = 5) - Normals cptr // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) - Tangents cptr // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) - Colors cptr // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) - Indices cptr // Vertex indices (in case vertex data comes indexed) - AnimVertices cptr // Animated vertex positions (after bones transformations) - AnimNormals cptr // Animated normals (after bones transformations) - BoneIds cptr // Vertex bone ids, max 255 bone ids, up to 4 bones influence by vertex (skinning) (shader-location = 6) - BoneWeights cptr // Vertex bone weight, up to 4 bones influence by vertex (skinning) (shader-location = 7) - BoneMatrices cptr // Bones animated transformation matrices - BoneCount int32 // Number of bones - VaoId uint32 // OpenGL Vertex Array Object id - VboId cptr // OpenGL Vertex Buffer Objects id (default vertex data) -} - -/* Shader */ + VertexCount int32 // Number of vertices stored in arrays + TriangleCount int32 // Number of triangles stored (indexed or not) + Vertices cptr // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) + Texcoords cptr // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) + Texcoords2 cptr // Vertex texture second coordinates (UV - 2 components per vertex) (shader-location = 5) + Normals cptr // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) + Tangents cptr // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) + Colors cptr // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) + Indices cptr // Vertex indices (in case vertex data comes indexed) + AnimVertices cptr // Animated vertex positions (after bones transformations) + AnimNormals cptr // Animated normals (after bones transformations) + BoneIds cptr // Vertex bone ids, max 255 bone ids, up to 4 bones influence by vertex (skinning) (shader-location = 6) + BoneWeights cptr // Vertex bone weight, up to 4 bones influence by vertex (skinning) (shader-location = 7) + BoneMatrices cptr // Bones animated transformation matrices + BoneCount int32 // Number of bones + VaoId uint32 // OpenGL Vertex Array Object id + VboId cptr // OpenGL Vertex Buffer Objects id (default vertex data) +} + +// Shader type Shader struct { - Id uint32 // Shader program id - Locs cptr // Shader locations array (RL_MAX_SHADER_LOCATIONS) + Id uint32 // Shader program id + Locs cptr // Shader locations array (RL_MAX_SHADER_LOCATIONS) } -/* MaterialMap */ +// MaterialMap type MaterialMap struct { Texture Texture2D // Material map texture - Color Color // Material map color - Value float32 // Material map value + Color Color // Material map color + Value float32 // Material map value } -/* Material, includes shader and maps */ +// Material, includes shader and maps type Material struct { - Shader Shader // Material shader - Maps cptr // Material maps array (MAX_MATERIAL_MAPS) + Shader Shader // Material shader + Maps cptr // Material maps array (MAX_MATERIAL_MAPS) Params [4]float32 // Material generic parameters (if required) } -/* Transform, vertex transformation data */ +// Transform, vertex transformation data type Transform struct { - Translation Vector3 // Translation - Rotation Quaternion // Rotation - Scale Vector3 // Scale + Translation Vector3 // Translation + Rotation Quaternion // Rotation + Scale Vector3 // Scale } -/* Bone, skeletal animation bone */ +// Bone, skeletal animation bone type BoneInfo struct { - Name [32]byte // Bone name - Parent int32 // Bone parent + Name [32]byte // Bone name + Parent int32 // Bone parent } -/* Model, meshes, materials and animation data */ +// Model, meshes, materials and animation data type Model struct { - Transform Matrix // Local transform matrix - MeshCount int32 // Number of meshes - MaterialCount int32 // Number of materials - Meshes cptr // Meshes array - Materials cptr // Materials array - MeshMaterial cptr // Mesh material number - BoneCount int32 // Number of bones - Bones cptr // Bones information (skeleton) - BindPose cptr // Bones base transformation (pose) -} - -/* ModelAnimation */ + Transform Matrix // Local transform matrix + MeshCount int32 // Number of meshes + MaterialCount int32 // Number of materials + Meshes cptr // Meshes array + Materials cptr // Materials array + MeshMaterial cptr // Mesh material number + BoneCount int32 // Number of bones + Bones cptr // Bones information (skeleton) + BindPose cptr // Bones base transformation (pose) +} + +// ModelAnimation type ModelAnimation struct { - BoneCount int32 // Number of bones - FrameCount int32 // Number of animation frames - Bones cptr // Bones information (skeleton) - FramePoses cptr // Poses array by frame - Name [32]byte // Animation name + BoneCount int32 // Number of bones + FrameCount int32 // Number of animation frames + Bones cptr // Bones information (skeleton) + FramePoses cptr // Poses array by frame + Name [32]byte // Animation name } -/* Ray, ray for raycasting */ +// Ray, ray for raycasting type Ray struct { - Position Vector3 // Ray position (origin) + Position Vector3 // Ray position (origin) Direction Vector3 // Ray direction (normalized) } -/* RayCollision, ray hit information */ +// RayCollision, ray hit information type RayCollision struct { - Hit bool // Did the ray hit something? + Hit bool // Did the ray hit something? Distance float32 // Distance to the nearest hit - Point Vector3 // Point of the nearest hit - Normal Vector3 // Surface normal of hit + Point Vector3 // Point of the nearest hit + Normal Vector3 // Surface normal of hit } -/* BoundingBox */ +// BoundingBox type BoundingBox struct { Min Vector3 // Minimum vertex box-corner Max Vector3 // Maximum vertex box-corner } -/* Wave, audio wave data */ +// Wave, audio wave data type Wave struct { FrameCount uint32 // Total number of frames (considering channels) SampleRate uint32 // Frequency (samples per second) SampleSize uint32 // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - Channels uint32 // Number of channels (1-mono, 2-stereo, ...) - Data cptr // Buffer data pointer + Channels uint32 // Number of channels (1-mono, 2-stereo, ...) + Data cptr // Buffer data pointer } -/* AudioStream, custom audio stream */ +// AudioStream, custom audio stream type AudioStream struct { - Buffer cptr // Pointer to internal data used by the audio system - Processor cptr // Pointer to internal data processor, useful for audio effects + Buffer cptr // Pointer to internal data used by the audio system + Processor cptr // Pointer to internal data processor, useful for audio effects SampleRate uint32 // Frequency (samples per second) SampleSize uint32 // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - Channels uint32 // Number of channels (1-mono, 2-stereo, ...) + Channels uint32 // Number of channels (1-mono, 2-stereo, ...) } -/* Sound */ +// Sound type Sound struct { - Stream AudioStream // Audio stream - FrameCount uint32 // Total number of frames (considering channels) + Stream AudioStream // Audio stream + FrameCount uint32 // Total number of frames (considering channels) } -/* Music, audio stream, anything longer than ~10 seconds should be streamed */ +// Music, audio stream, anything longer than ~10 seconds should be streamed type Music struct { - Stream AudioStream // Audio stream - FrameCount uint32 // Total number of frames (considering channels) - Looping bool // Music looping enable - CtxType int32 // Type of music context (audio filetype) - CtxData cptr // Audio context data, depends on type + Stream AudioStream // Audio stream + FrameCount uint32 // Total number of frames (considering channels) + Looping bool // Music looping enable + CtxType int32 // Type of music context (audio filetype) + CtxData cptr // Audio context data, depends on type } -/* VrDeviceInfo, Head-Mounted-Display device parameters */ +// VrDeviceInfo, Head-Mounted-Display device parameters type VrDeviceInfo struct { - HResolution int32 // Horizontal resolution in pixels - VResolution int32 // Vertical resolution in pixels - HScreenSize float32 // Horizontal size in meters - VScreenSize float32 // Vertical size in meters - EyeToScreenDistance float32 // Distance between eye and display in meters - LensSeparationDistance float32 // Lens separation distance in meters - InterpupillaryDistance float32 // IPD (distance between pupils) in meters - LensDistortionValues [4]float32 // Lens distortion constant parameters - ChromaAbCorrection [4]float32 // Chromatic aberration correction parameters -} - -/* VrStereoConfig, VR stereo rendering configuration for simulator */ + HResolution int32 // Horizontal resolution in pixels + VResolution int32 // Vertical resolution in pixels + HScreenSize float32 // Horizontal size in meters + VScreenSize float32 // Vertical size in meters + EyeToScreenDistance float32 // Distance between eye and display in meters + LensSeparationDistance float32 // Lens separation distance in meters + InterpupillaryDistance float32 // IPD (distance between pupils) in meters + LensDistortionValues [4]float32 // Lens distortion constant parameters + ChromaAbCorrection [4]float32 // Chromatic aberration correction parameters +} + +// VrStereoConfig, VR stereo rendering configuration for simulator type VrStereoConfig struct { - Projection [2]Matrix // VR projection matrices (per eye) - ViewOffset [2]Matrix // VR view offset matrices (per eye) - LeftLensCenter [2]float32 // VR left lens center - RightLensCenter [2]float32 // VR right lens center - LeftScreenCenter [2]float32 // VR left screen center + Projection [2]Matrix // VR projection matrices (per eye) + ViewOffset [2]Matrix // VR view offset matrices (per eye) + LeftLensCenter [2]float32 // VR left lens center + RightLensCenter [2]float32 // VR right lens center + LeftScreenCenter [2]float32 // VR left screen center RightScreenCenter [2]float32 // VR right screen center - Scale [2]float32 // VR distortion scale - ScaleIn [2]float32 // VR distortion scale in + Scale [2]float32 // VR distortion scale + ScaleIn [2]float32 // VR distortion scale in } -/* File path list */ +// File path list type FilePathList struct { Count uint32 // Filepaths entries count - Paths cptr // Filepaths entries + Paths cptr // Filepaths entries } -/* Automation event */ +// Automation event type AutomationEvent struct { - Frame uint32 // Event frame - Type uint32 // Event type (AutomationEventType) + Frame uint32 // Event frame + Type uint32 // Event type (AutomationEventType) Params [4]int32 // Event parameters (if required) } -/* Automation event list */ +// Automation event list type AutomationEventList struct { Capacity uint32 // Events max entries (MAX_AUTOMATION_EVENTS) - Count uint32 // Events entries count - Events cptr // Events entries + Count uint32 // Events entries count + Events cptr // Events entries } diff --git a/testdata/templates/defines.go.gotmpl b/testdata/templates/defines.go.gotmpl new file mode 100644 index 0000000..fc10382 --- /dev/null +++ b/testdata/templates/defines.go.gotmpl @@ -0,0 +1,30 @@ +{{- $root := . -}} + +// AUTOGENERATED FILE. DO NOT EDIT +{{if .BuildTags}} +//go:build {{.BuildTags}} +{{end}} +package rl + +{{- range .Imports }} +import {{ . }} +{{- end }} + + +{{- range .Defines}} +{{if contains .Type "INT" "FLOAT" "FLOAT_MATH" "STRING" }} + {{if .Description}} + // {{- .Description}} + {{- end}} + const {{.Name}} = {{.Value}} +{{- end}} +{{if contains .Type "COLOR"}} + //{{- .Description}} + var {{.Name}} = Color{{.Value}} +{{- end}} + +{{if contains .Type "UNKNOWN"}} + // {{- .Description}} + {{.Value}} +{{- end}} +{{- end}} diff --git a/testdata/templates/enums.go.gotmpl b/testdata/templates/enums.go.gotmpl new file mode 100644 index 0000000..f06dd4b --- /dev/null +++ b/testdata/templates/enums.go.gotmpl @@ -0,0 +1,23 @@ + +{{- $root := . -}} + +// AUTOGENERATED FILE. DO NOT EDIT +{{if .BuildTags}} +//go:build {{.BuildTags}} +{{end}} +package rl + +{{- range .Imports }} +import {{ . }} +{{- end }} + +{{- range .Enums}} +// {{ .Description}} +type {{ .Name}} = int32 +const ( + {{- range .Values}} + // {{.Description}} + {{.Name}} = {{.Value}} + {{- end}} +) +{{- end}} diff --git a/testdata/templates/structs.go.gotmpl b/testdata/templates/structs.go.gotmpl index 87829b5..46f641b 100644 --- a/testdata/templates/structs.go.gotmpl +++ b/testdata/templates/structs.go.gotmpl @@ -12,7 +12,7 @@ import {{ . }} {{- range .Structs}} -/* {{ .Description}} */ +// {{ .Description}} type {{ .Name}} struct { {{- range .Fields }} {{ .Name }} {{ .Type }} // {{.Description}} diff --git a/testdata/templates/templates.go b/testdata/templates/templates.go index 606411b..f24e9bc 100644 --- a/testdata/templates/templates.go +++ b/testdata/templates/templates.go @@ -11,3 +11,11 @@ func LoadTemplate(templ, name string) *template.Template { return template.Must(template.New(name). Parse(templ)) } + +// LoadTemplate takes in a gotempl as a string and a name for the template. +// It panics if template could not be parsed. +func LoadTemplateFuncs(templ, name string, funcs template.FuncMap) *template.Template { + return template.Must(template.New(name). + Funcs(funcs). + Parse(templ)) +} From ddba0806ff801ab14c1dff8c7d9f6bbf00a76397 Mon Sep 17 00:00:00 2001 From: BrownNPC Date: Sun, 8 Feb 2026 04:43:13 +0500 Subject: [PATCH 12/12] generate all types. TODO: generate function bindings --- testdata/api/publicNameString.go | 21 - testdata/api/rlapi.go | 36 +- testdata/api/rltype.go | 41 -- testdata/api/stringyvalue.go | 1 + testdata/codegen.go | 84 +-- testdata/go.mod | 2 + testdata/go.sum | 2 + testdata/rl/aliases_gen_formatted.go | 20 + testdata/rl/defines_gen_formatted.go | 121 ++++ testdata/rl/defines_gen_unformatted.go | 114 ---- ..._unformatted.go => enums_gen_formatted.go} | 610 +++++++++--------- testdata/rl/structs_gen_formatted.go | 307 +++++++++ testdata/rl/structs_gen_unformatted.go | 307 --------- testdata/templates/aliases.go.gotmpl | 16 + testdata/templates/defines.go.gotmpl | 2 +- testdata/templates/templates.go | 36 ++ testdata/util.go | 104 +++ 17 files changed, 939 insertions(+), 885 deletions(-) delete mode 100644 testdata/api/publicNameString.go delete mode 100644 testdata/api/rltype.go create mode 100644 testdata/go.sum create mode 100644 testdata/rl/aliases_gen_formatted.go create mode 100644 testdata/rl/defines_gen_formatted.go delete mode 100644 testdata/rl/defines_gen_unformatted.go rename testdata/rl/{enums_gen_unformatted.go => enums_gen_formatted.go} (59%) create mode 100644 testdata/rl/structs_gen_formatted.go delete mode 100644 testdata/rl/structs_gen_unformatted.go create mode 100644 testdata/templates/aliases.go.gotmpl create mode 100644 testdata/util.go diff --git a/testdata/api/publicNameString.go b/testdata/api/publicNameString.go deleted file mode 100644 index 0e9f70d..0000000 --- a/testdata/api/publicNameString.go +++ /dev/null @@ -1,21 +0,0 @@ -package api - -import ( - "encoding/json" - "strings" -) - -// PublicName just sets the first character as uppercase. Used for making struct members public. -type PublicName string - -func (s *PublicName) UnmarshalJSON(b []byte) error { - var v string - if err := json.Unmarshal(b, &v); err != nil { - return err - } - firstChar := string(v[0]) - firstChar =strings.ToUpper(firstChar) - theRest := string(v[1:]) - *s = PublicName(firstChar + theRest) - return nil -} diff --git a/testdata/api/rlapi.go b/testdata/api/rlapi.go index 05eebec..be1fefd 100644 --- a/testdata/api/rlapi.go +++ b/testdata/api/rlapi.go @@ -3,9 +3,6 @@ package api import ( _ "embed" "encoding/json" - "fmt" - "slices" - "strings" ) var Api RlApi @@ -27,38 +24,11 @@ type RlDefine struct { Description string `json:"description"` } -func FixDefines(defs []RlDefine) []RlDefine { - defs = slices.Clone(defs) - for i, d := range defs { - def := &defs[i] - switch d.Type { - case "STRING": - def.Value = "\"" + def.Value + "\"" - case "FLOAT_MATH": - def.Value = StringyValue(strings.ReplaceAll(string(def.Value), "f", "")) - case "COLOR": - v := strings.ReplaceAll(string(def.Value), "CLITERAL(Color)", "") - def.Value = StringyValue(v) - case "UNKNOWN": - switch def.Name { - case "GetMouseRay": - def.Value = StringyValue(fmt.Sprintf("var %s = %s", def.Name, def.Value)) - case "RLAPI": - *def = RlDefine{} - default: - def.Value = StringyValue( - fmt.Sprintf("const %v = %v", def.Name, def.Value), - ) - } - } - } - return defs -} type RlField struct { - Type RlType `json:"type"` - Name PublicName `json:"name"` - Description string `json:"description"` + Type string `json:"type"` + Name string `json:"name"` + Description string `json:"description"` } type RlStruct struct { Name string `json:"name"` diff --git a/testdata/api/rltype.go b/testdata/api/rltype.go deleted file mode 100644 index 996d035..0000000 --- a/testdata/api/rltype.go +++ /dev/null @@ -1,41 +0,0 @@ -package api - -import ( - "encoding/json" - "slices" -) - -// RlType converts a C type to Go -type RlType string - -func (s *RlType) UnmarshalJSON(b []byte) error { - var v string - if err := json.Unmarshal(b, &v); err != nil { - return err - } - *s = RlType(GoTypeFromC(v)) - return nil -} -func GoTypeFromC(t string) string { - oneToOneTypes := map[string]string{ - "char": "byte", - "float": "float32", - "unsigned char": "byte", - "unsigned int": "uint32", - "int": "int32", - } - if mapping, ok := oneToOneTypes[t]; ok { - return mapping - } - runed := []rune(t) - if runed[len(runed)-1] == '*' { - return "cptr" - } - if index := slices.Index(runed, '['); index >= 0 { - arraySize := runed[index:] - arrayType := runed[:index] - arrayType = []rune(GoTypeFromC(string(arrayType))) - return string(arraySize) + string(arrayType) - } - return t -} diff --git a/testdata/api/stringyvalue.go b/testdata/api/stringyvalue.go index 1efef57..4176fec 100644 --- a/testdata/api/stringyvalue.go +++ b/testdata/api/stringyvalue.go @@ -4,6 +4,7 @@ import "encoding/json" type StringyValue string +// convert the json type to a string. func (s *StringyValue) UnmarshalJSON(b []byte) error { // null if string(b) == "null" { diff --git a/testdata/codegen.go b/testdata/codegen.go index 355d14d..1fe6a80 100644 --- a/testdata/codegen.go +++ b/testdata/codegen.go @@ -1,11 +1,9 @@ package main import ( - "bytes" "codegen/api" "codegen/templates" _ "embed" - "os" "slices" "text/template" ) @@ -19,80 +17,40 @@ var definesTempl string //go:embed templates/enums.go.gotmpl var enumsTempl string +//go:embed templates/aliases.go.gotmpl +var aliasesTempl string + type Model struct { BuildTags string Imports []string Structs []api.RlStruct Defines []api.RlDefine Enums []api.RlEnum + Aliases []api.RlAlias } func main() { - - // recordedTypes := map[string]struct{}{} - - // for _, s := range api.Api.Structs { - // for _, t := range s.Fields { - // if _, ok := recordedTypes[t.Type]; !ok { - // recordedTypes[t.Type] = struct{}{} - // fmt.Println(t.Type) - // } - // } - // } - m := Model{ BuildTags: "js", Imports: []string{}, - Structs: api.Api.Structs, - Defines: api.FixDefines(api.Api.Defines), - Enums: api.Api.Enums, + Structs: slices.Clone(api.Api.Structs), + // C #define macros need special parsing. And Names need to be PascalCase. + Defines: ParseDefines(api.Api.Defines), + Enums: slices.Clone(api.Api.Enums), + Aliases: slices.Clone(api.Api.Aliases), } - { - structs := templates.LoadTemplate(structsTempl, "structs") - var buf bytes.Buffer - if err := structs.Execute(&buf, m); err != nil { - panic(err) - } - if err := os.WriteFile("rl/structs_gen_unformatted.go", buf.Bytes(), 0644); err != nil { - panic(err) - } + // convert C types to Go and use PascalCase for field names. + for _, s := range m.Structs { + ProcessStructFields(s.Fields) } - { - defines := templates.LoadTemplateFuncs(definesTempl, "defines", - template.FuncMap{ - "eq": func(a, b any) bool { return a == b }, - "contains": func(a any, b ...any) bool { return slices.Contains(b, a) }, - }) - var buf bytes.Buffer - if err := defines.Execute(&buf, m); err != nil { - panic(err) - } - if err := os.WriteFile("rl/defines_gen_unformatted.go", buf.Bytes(), 0644); err != nil { - panic(err) - } + // Use PascalCase for enum names. + PascalCaseEnums(m.Enums) + funcs := template.FuncMap{ + "eq": func(a, b any) bool { return a == b }, + "contains": func(a any, b ...any) bool { return slices.Contains(b, a) }, } - { - enums := templates.LoadTemplateFuncs(enumsTempl, "enums", - template.FuncMap{ - "eq": func(a, b any) bool { return a == b }, - "contains": func(a any, b ...any) bool { return slices.Contains(b, a) }, - }) - var buf bytes.Buffer - if err := enums.Execute(&buf, m); err != nil { - panic(err) - } - if err := os.WriteFile("rl/enums_gen_unformatted.go", buf.Bytes(), 0644); err != nil { - panic(err) - } - } - - // formatted, err := format.Source(buf.Bytes()) - - // if err != nil { - // panic(err) - // } - - // if err := os.WriteFile("rl/structs_gen.go", formatted, 0644); err != nil { - // panic(err) - // } + templates.GenerateCodeFormatted(m, structsTempl, "structs", nil) + templates.GenerateCodeFormatted(m, enumsTempl, "enums", nil) + templates.GenerateCodeFormatted(m, definesTempl, "defines", funcs) + templates.GenerateCodeFormatted(m, aliasesTempl, "aliases", funcs) } diff --git a/testdata/go.mod b/testdata/go.mod index ad9a9fc..ce211ca 100644 --- a/testdata/go.mod +++ b/testdata/go.mod @@ -1,3 +1,5 @@ module codegen go 1.25.6 + +require github.com/iancoleman/strcase v0.3.0 // indirect diff --git a/testdata/go.sum b/testdata/go.sum new file mode 100644 index 0000000..6261b6a --- /dev/null +++ b/testdata/go.sum @@ -0,0 +1,2 @@ +github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= +github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= diff --git a/testdata/rl/aliases_gen_formatted.go b/testdata/rl/aliases_gen_formatted.go new file mode 100644 index 0000000..85f4693 --- /dev/null +++ b/testdata/rl/aliases_gen_formatted.go @@ -0,0 +1,20 @@ +// AUTOGENERATED FILE. DO NOT EDIT + +//go:build js + +package rl + +// Quaternion, 4 components (Vector4 alias) +type Quaternion = Vector4 + +// Texture2D, same as Texture +type Texture2D = Texture + +// TextureCubemap, same as Texture +type TextureCubemap = Texture + +// RenderTexture2D, same as RenderTexture +type RenderTexture2D = RenderTexture + +// Camera type fallback, defaults to Camera3D +type Camera = Camera3D diff --git a/testdata/rl/defines_gen_formatted.go b/testdata/rl/defines_gen_formatted.go new file mode 100644 index 0000000..de37abb --- /dev/null +++ b/testdata/rl/defines_gen_formatted.go @@ -0,0 +1,121 @@ +// AUTOGENERATED FILE. DO NOT EDIT + +//go:build js + +package rl + +const RaylibVersionMajor = 5 + +const RaylibVersionMinor = 6 + +const RaylibVersionPatch = 0 + +const RaylibVersion = "5.6-dev" + +const Pi = 3.14159265358979323846 + +const Deg2Rad = (Pi / 180.0) + +const Rad2Deg = (180.0 / Pi) + +//Light Gray +var Lightgray = Color{200, 200, 200, 255} + +//Gray +var Gray = Color{130, 130, 130, 255} + +//Dark Gray +var Darkgray = Color{80, 80, 80, 255} + +//Yellow +var Yellow = Color{253, 249, 0, 255} + +//Gold +var Gold = Color{255, 203, 0, 255} + +//Orange +var Orange = Color{255, 161, 0, 255} + +//Pink +var Pink = Color{255, 109, 194, 255} + +//Red +var Red = Color{230, 41, 55, 255} + +//Maroon +var Maroon = Color{190, 33, 55, 255} + +//Green +var Green = Color{0, 228, 48, 255} + +//Lime +var Lime = Color{0, 158, 47, 255} + +//Dark Green +var Darkgreen = Color{0, 117, 44, 255} + +//Sky Blue +var Skyblue = Color{102, 191, 255, 255} + +//Blue +var Blue = Color{0, 121, 241, 255} + +//Dark Blue +var Darkblue = Color{0, 82, 172, 255} + +//Purple +var Purple = Color{200, 122, 255, 255} + +//Violet +var Violet = Color{135, 60, 190, 255} + +//Dark Purple +var Darkpurple = Color{112, 31, 126, 255} + +//Beige +var Beige = Color{211, 176, 131, 255} + +//Brown +var Brown = Color{127, 106, 79, 255} + +//Dark Brown +var Darkbrown = Color{76, 63, 47, 255} + +//White +var White = Color{255, 255, 255, 255} + +//Black +var Black = Color{0, 0, 0, 255} + +//Blank (Transparent) +var Blank = Color{0, 0, 0, 0} + +//Magenta +var Magenta = Color{255, 0, 255, 255} + +//My own White (raylib logo) +var Raywhite = Color{245, 245, 245, 255} + +// +const MouseLeftButton = MOUSE_BUTTON_LEFT + +// +const MouseRightButton = MOUSE_BUTTON_RIGHT + +// +const MouseMiddleButton = MOUSE_BUTTON_MIDDLE + +// +const MaterialMapDiffuse = MATERIAL_MAP_ALBEDO + +// +const MaterialMapSpecular = MATERIAL_MAP_METALNESS + +// +const ShaderLocMapDiffuse = SHADER_LOC_MAP_ALBEDO + +// +const ShaderLocMapSpecular = SHADER_LOC_MAP_METALNESS + +//Compatibility hack for previous raylib versions +var GetMouseRay = GetScreenToWorldRay diff --git a/testdata/rl/defines_gen_unformatted.go b/testdata/rl/defines_gen_unformatted.go deleted file mode 100644 index 02c50f1..0000000 --- a/testdata/rl/defines_gen_unformatted.go +++ /dev/null @@ -1,114 +0,0 @@ -// AUTOGENERATED FILE. DO NOT EDIT - -//go:build js - -package rl - -const RAYLIB_VERSION_MAJOR = 5 - -const RAYLIB_VERSION_MINOR = 6 - -const RAYLIB_VERSION_PATCH = 0 - -const RAYLIB_VERSION = "5.6-dev" - -const PI = 3.14159265358979323846 - -const DEG2RAD = (PI / 180.0) - -const RAD2DEG = (180.0 / PI) - -// Light Gray -var LIGHTGRAY = Color{200, 200, 200, 255} - -// Gray -var GRAY = Color{130, 130, 130, 255} - -// Dark Gray -var DARKGRAY = Color{80, 80, 80, 255} - -// Yellow -var YELLOW = Color{253, 249, 0, 255} - -// Gold -var GOLD = Color{255, 203, 0, 255} - -// Orange -var ORANGE = Color{255, 161, 0, 255} - -// Pink -var PINK = Color{255, 109, 194, 255} - -// Red -var RED = Color{230, 41, 55, 255} - -// Maroon -var MAROON = Color{190, 33, 55, 255} - -// Green -var GREEN = Color{0, 228, 48, 255} - -// Lime -var LIME = Color{0, 158, 47, 255} - -// Dark Green -var DARKGREEN = Color{0, 117, 44, 255} - -// Sky Blue -var SKYBLUE = Color{102, 191, 255, 255} - -// Blue -var BLUE = Color{0, 121, 241, 255} - -// Dark Blue -var DARKBLUE = Color{0, 82, 172, 255} - -// Purple -var PURPLE = Color{200, 122, 255, 255} - -// Violet -var VIOLET = Color{135, 60, 190, 255} - -// Dark Purple -var DARKPURPLE = Color{112, 31, 126, 255} - -// Beige -var BEIGE = Color{211, 176, 131, 255} - -// Brown -var BROWN = Color{127, 106, 79, 255} - -// Dark Brown -var DARKBROWN = Color{76, 63, 47, 255} - -// White -var WHITE = Color{255, 255, 255, 255} - -// Black -var BLACK = Color{0, 0, 0, 255} - -// Blank (Transparent) -var BLANK = Color{0, 0, 0, 0} - -// Magenta -var MAGENTA = Color{255, 0, 255, 255} - -// My own White (raylib logo) -var RAYWHITE = Color{245, 245, 245, 255} - -const MOUSE_LEFT_BUTTON = MOUSE_BUTTON_LEFT - -const MOUSE_RIGHT_BUTTON = MOUSE_BUTTON_RIGHT - -const MOUSE_MIDDLE_BUTTON = MOUSE_BUTTON_MIDDLE - -const MATERIAL_MAP_DIFFUSE = MATERIAL_MAP_ALBEDO - -const MATERIAL_MAP_SPECULAR = MATERIAL_MAP_METALNESS - -const SHADER_LOC_MAP_DIFFUSE = SHADER_LOC_MAP_ALBEDO - -const SHADER_LOC_MAP_SPECULAR = SHADER_LOC_MAP_METALNESS - -// Compatibility hack for previous raylib versions -var GetMouseRay = GetScreenToWorldRay diff --git a/testdata/rl/enums_gen_unformatted.go b/testdata/rl/enums_gen_formatted.go similarity index 59% rename from testdata/rl/enums_gen_unformatted.go rename to testdata/rl/enums_gen_formatted.go index 2d3ff1e..303b8d2 100644 --- a/testdata/rl/enums_gen_unformatted.go +++ b/testdata/rl/enums_gen_formatted.go @@ -9,37 +9,37 @@ type ConfigFlags = int32 const ( // Set to try enabling V-Sync on GPU - FLAG_VSYNC_HINT = 64 + FlagVsyncHint = 64 // Set to run program in fullscreen - FLAG_FULLSCREEN_MODE = 2 + FlagFullscreenMode = 2 // Set to allow resizable window - FLAG_WINDOW_RESIZABLE = 4 + FlagWindowResizable = 4 // Set to disable window decoration (frame and buttons) - FLAG_WINDOW_UNDECORATED = 8 + FlagWindowUndecorated = 8 // Set to hide window - FLAG_WINDOW_HIDDEN = 128 + FlagWindowHidden = 128 // Set to minimize window (iconify) - FLAG_WINDOW_MINIMIZED = 512 + FlagWindowMinimized = 512 // Set to maximize window (expanded to monitor) - FLAG_WINDOW_MAXIMIZED = 1024 + FlagWindowMaximized = 1024 // Set to window non focused - FLAG_WINDOW_UNFOCUSED = 2048 + FlagWindowUnfocused = 2048 // Set to window always on top - FLAG_WINDOW_TOPMOST = 4096 + FlagWindowTopmost = 4096 // Set to allow windows running while minimized - FLAG_WINDOW_ALWAYS_RUN = 256 + FlagWindowAlwaysRun = 256 // Set to allow transparent framebuffer - FLAG_WINDOW_TRANSPARENT = 16 + FlagWindowTransparent = 16 // Set to support HighDPI - FLAG_WINDOW_HIGHDPI = 8192 + FlagWindowHighdpi = 8192 // Set to support mouse passthrough, only supported when FLAG_WINDOW_UNDECORATED - FLAG_WINDOW_MOUSE_PASSTHROUGH = 16384 + FlagWindowMousePassthrough = 16384 // Set to run program in borderless windowed mode - FLAG_BORDERLESS_WINDOWED_MODE = 32768 + FlagBorderlessWindowedMode = 32768 // Set to try enabling MSAA 4X - FLAG_MSAA_4X_HINT = 32 + FlagMsaa4XHint = 32 // Set to try enabling interlaced video format (for V3D) - FLAG_INTERLACED_HINT = 65536 + FlagInterlacedHint = 65536 ) // Trace log level @@ -47,21 +47,21 @@ type TraceLogLevel = int32 const ( // Display all logs - LOG_ALL = 0 + LogAll = 0 // Trace logging, intended for internal use only - LOG_TRACE = 1 + LogTrace = 1 // Debug logging, used for internal debugging, it should be disabled on release builds - LOG_DEBUG = 2 + LogDebug = 2 // Info logging, used for program execution info - LOG_INFO = 3 + LogInfo = 3 // Warning logging, used on recoverable failures - LOG_WARNING = 4 + LogWarning = 4 // Error logging, used on unrecoverable failures - LOG_ERROR = 5 + LogError = 5 // Fatal logging, used to abort program: exit(EXIT_FAILURE) - LOG_FATAL = 6 + LogFatal = 6 // Disable logging - LOG_NONE = 7 + LogNone = 7 ) // Keyboard keys (US keyboard layout) @@ -69,225 +69,225 @@ type KeyboardKey = int32 const ( // Key: NULL, used for no key pressed - KEY_NULL = 0 + KeyNull = 0 // Key: ' - KEY_APOSTROPHE = 39 + KeyApostrophe = 39 // Key: , - KEY_COMMA = 44 + KeyComma = 44 // Key: - - KEY_MINUS = 45 + KeyMinus = 45 // Key: . - KEY_PERIOD = 46 + KeyPeriod = 46 // Key: / - KEY_SLASH = 47 + KeySlash = 47 // Key: 0 - KEY_ZERO = 48 + KeyZero = 48 // Key: 1 - KEY_ONE = 49 + KeyOne = 49 // Key: 2 - KEY_TWO = 50 + KeyTwo = 50 // Key: 3 - KEY_THREE = 51 + KeyThree = 51 // Key: 4 - KEY_FOUR = 52 + KeyFour = 52 // Key: 5 - KEY_FIVE = 53 + KeyFive = 53 // Key: 6 - KEY_SIX = 54 + KeySix = 54 // Key: 7 - KEY_SEVEN = 55 + KeySeven = 55 // Key: 8 - KEY_EIGHT = 56 + KeyEight = 56 // Key: 9 - KEY_NINE = 57 + KeyNine = 57 // Key: ; - KEY_SEMICOLON = 59 + KeySemicolon = 59 // Key: = - KEY_EQUAL = 61 + KeyEqual = 61 // Key: A | a - KEY_A = 65 + KeyA = 65 // Key: B | b - KEY_B = 66 + KeyB = 66 // Key: C | c - KEY_C = 67 + KeyC = 67 // Key: D | d - KEY_D = 68 + KeyD = 68 // Key: E | e - KEY_E = 69 + KeyE = 69 // Key: F | f - KEY_F = 70 + KeyF = 70 // Key: G | g - KEY_G = 71 + KeyG = 71 // Key: H | h - KEY_H = 72 + KeyH = 72 // Key: I | i - KEY_I = 73 + KeyI = 73 // Key: J | j - KEY_J = 74 + KeyJ = 74 // Key: K | k - KEY_K = 75 + KeyK = 75 // Key: L | l - KEY_L = 76 + KeyL = 76 // Key: M | m - KEY_M = 77 + KeyM = 77 // Key: N | n - KEY_N = 78 + KeyN = 78 // Key: O | o - KEY_O = 79 + KeyO = 79 // Key: P | p - KEY_P = 80 + KeyP = 80 // Key: Q | q - KEY_Q = 81 + KeyQ = 81 // Key: R | r - KEY_R = 82 + KeyR = 82 // Key: S | s - KEY_S = 83 + KeyS = 83 // Key: T | t - KEY_T = 84 + KeyT = 84 // Key: U | u - KEY_U = 85 + KeyU = 85 // Key: V | v - KEY_V = 86 + KeyV = 86 // Key: W | w - KEY_W = 87 + KeyW = 87 // Key: X | x - KEY_X = 88 + KeyX = 88 // Key: Y | y - KEY_Y = 89 + KeyY = 89 // Key: Z | z - KEY_Z = 90 + KeyZ = 90 // Key: [ - KEY_LEFT_BRACKET = 91 + KeyLeftBracket = 91 // Key: '\' - KEY_BACKSLASH = 92 + KeyBackslash = 92 // Key: ] - KEY_RIGHT_BRACKET = 93 + KeyRightBracket = 93 // Key: ` - KEY_GRAVE = 96 + KeyGrave = 96 // Key: Space - KEY_SPACE = 32 + KeySpace = 32 // Key: Esc - KEY_ESCAPE = 256 + KeyEscape = 256 // Key: Enter - KEY_ENTER = 257 + KeyEnter = 257 // Key: Tab - KEY_TAB = 258 + KeyTab = 258 // Key: Backspace - KEY_BACKSPACE = 259 + KeyBackspace = 259 // Key: Ins - KEY_INSERT = 260 + KeyInsert = 260 // Key: Del - KEY_DELETE = 261 + KeyDelete = 261 // Key: Cursor right - KEY_RIGHT = 262 + KeyRight = 262 // Key: Cursor left - KEY_LEFT = 263 + KeyLeft = 263 // Key: Cursor down - KEY_DOWN = 264 + KeyDown = 264 // Key: Cursor up - KEY_UP = 265 + KeyUp = 265 // Key: Page up - KEY_PAGE_UP = 266 + KeyPageUp = 266 // Key: Page down - KEY_PAGE_DOWN = 267 + KeyPageDown = 267 // Key: Home - KEY_HOME = 268 + KeyHome = 268 // Key: End - KEY_END = 269 + KeyEnd = 269 // Key: Caps lock - KEY_CAPS_LOCK = 280 + KeyCapsLock = 280 // Key: Scroll down - KEY_SCROLL_LOCK = 281 + KeyScrollLock = 281 // Key: Num lock - KEY_NUM_LOCK = 282 + KeyNumLock = 282 // Key: Print screen - KEY_PRINT_SCREEN = 283 + KeyPrintScreen = 283 // Key: Pause - KEY_PAUSE = 284 + KeyPause = 284 // Key: F1 - KEY_F1 = 290 + KeyF1 = 290 // Key: F2 - KEY_F2 = 291 + KeyF2 = 291 // Key: F3 - KEY_F3 = 292 + KeyF3 = 292 // Key: F4 - KEY_F4 = 293 + KeyF4 = 293 // Key: F5 - KEY_F5 = 294 + KeyF5 = 294 // Key: F6 - KEY_F6 = 295 + KeyF6 = 295 // Key: F7 - KEY_F7 = 296 + KeyF7 = 296 // Key: F8 - KEY_F8 = 297 + KeyF8 = 297 // Key: F9 - KEY_F9 = 298 + KeyF9 = 298 // Key: F10 - KEY_F10 = 299 + KeyF10 = 299 // Key: F11 - KEY_F11 = 300 + KeyF11 = 300 // Key: F12 - KEY_F12 = 301 + KeyF12 = 301 // Key: Shift left - KEY_LEFT_SHIFT = 340 + KeyLeftShift = 340 // Key: Control left - KEY_LEFT_CONTROL = 341 + KeyLeftControl = 341 // Key: Alt left - KEY_LEFT_ALT = 342 + KeyLeftAlt = 342 // Key: Super left - KEY_LEFT_SUPER = 343 + KeyLeftSuper = 343 // Key: Shift right - KEY_RIGHT_SHIFT = 344 + KeyRightShift = 344 // Key: Control right - KEY_RIGHT_CONTROL = 345 + KeyRightControl = 345 // Key: Alt right - KEY_RIGHT_ALT = 346 + KeyRightAlt = 346 // Key: Super right - KEY_RIGHT_SUPER = 347 + KeyRightSuper = 347 // Key: KB menu - KEY_KB_MENU = 348 + KeyKbMenu = 348 // Key: Keypad 0 - KEY_KP_0 = 320 + KeyKp0 = 320 // Key: Keypad 1 - KEY_KP_1 = 321 + KeyKp1 = 321 // Key: Keypad 2 - KEY_KP_2 = 322 + KeyKp2 = 322 // Key: Keypad 3 - KEY_KP_3 = 323 + KeyKp3 = 323 // Key: Keypad 4 - KEY_KP_4 = 324 + KeyKp4 = 324 // Key: Keypad 5 - KEY_KP_5 = 325 + KeyKp5 = 325 // Key: Keypad 6 - KEY_KP_6 = 326 + KeyKp6 = 326 // Key: Keypad 7 - KEY_KP_7 = 327 + KeyKp7 = 327 // Key: Keypad 8 - KEY_KP_8 = 328 + KeyKp8 = 328 // Key: Keypad 9 - KEY_KP_9 = 329 + KeyKp9 = 329 // Key: Keypad . - KEY_KP_DECIMAL = 330 + KeyKpDecimal = 330 // Key: Keypad / - KEY_KP_DIVIDE = 331 + KeyKpDivide = 331 // Key: Keypad * - KEY_KP_MULTIPLY = 332 + KeyKpMultiply = 332 // Key: Keypad - - KEY_KP_SUBTRACT = 333 + KeyKpSubtract = 333 // Key: Keypad + - KEY_KP_ADD = 334 + KeyKpAdd = 334 // Key: Keypad Enter - KEY_KP_ENTER = 335 + KeyKpEnter = 335 // Key: Keypad = - KEY_KP_EQUAL = 336 + KeyKpEqual = 336 // Key: Android back button - KEY_BACK = 4 + KeyBack = 4 // Key: Android menu button - KEY_MENU = 5 + KeyMenu = 5 // Key: Android volume up button - KEY_VOLUME_UP = 24 + KeyVolumeUp = 24 // Key: Android volume down button - KEY_VOLUME_DOWN = 25 + KeyVolumeDown = 25 ) // Mouse buttons @@ -295,19 +295,19 @@ type MouseButton = int32 const ( // Mouse button left - MOUSE_BUTTON_LEFT = 0 + MouseButtonLeft = 0 // Mouse button right - MOUSE_BUTTON_RIGHT = 1 + MouseButtonRight = 1 // Mouse button middle (pressed wheel) - MOUSE_BUTTON_MIDDLE = 2 + MouseButtonMiddle = 2 // Mouse button side (advanced mouse device) - MOUSE_BUTTON_SIDE = 3 + MouseButtonSide = 3 // Mouse button extra (advanced mouse device) - MOUSE_BUTTON_EXTRA = 4 + MouseButtonExtra = 4 // Mouse button forward (advanced mouse device) - MOUSE_BUTTON_FORWARD = 5 + MouseButtonForward = 5 // Mouse button back (advanced mouse device) - MOUSE_BUTTON_BACK = 6 + MouseButtonBack = 6 ) // Mouse cursor @@ -315,27 +315,27 @@ type MouseCursor = int32 const ( // Default pointer shape - MOUSE_CURSOR_DEFAULT = 0 + MouseCursorDefault = 0 // Arrow shape - MOUSE_CURSOR_ARROW = 1 + MouseCursorArrow = 1 // Text writing cursor shape - MOUSE_CURSOR_IBEAM = 2 + MouseCursorIbeam = 2 // Cross shape - MOUSE_CURSOR_CROSSHAIR = 3 + MouseCursorCrosshair = 3 // Pointing hand cursor - MOUSE_CURSOR_POINTING_HAND = 4 + MouseCursorPointingHand = 4 // Horizontal resize/move arrow shape - MOUSE_CURSOR_RESIZE_EW = 5 + MouseCursorResizeEw = 5 // Vertical resize/move arrow shape - MOUSE_CURSOR_RESIZE_NS = 6 + MouseCursorResizeNs = 6 // Top-left to bottom-right diagonal resize/move arrow shape - MOUSE_CURSOR_RESIZE_NWSE = 7 + MouseCursorResizeNwse = 7 // The top-right to bottom-left diagonal resize/move arrow shape - MOUSE_CURSOR_RESIZE_NESW = 8 + MouseCursorResizeNesw = 8 // The omnidirectional resize/move cursor shape - MOUSE_CURSOR_RESIZE_ALL = 9 + MouseCursorResizeAll = 9 // The operation-not-allowed shape - MOUSE_CURSOR_NOT_ALLOWED = 10 + MouseCursorNotAllowed = 10 ) // Gamepad buttons @@ -343,41 +343,41 @@ type GamepadButton = int32 const ( // Unknown button, just for error checking - GAMEPAD_BUTTON_UNKNOWN = 0 + GamepadButtonUnknown = 0 // Gamepad left DPAD up button - GAMEPAD_BUTTON_LEFT_FACE_UP = 1 + GamepadButtonLeftFaceUp = 1 // Gamepad left DPAD right button - GAMEPAD_BUTTON_LEFT_FACE_RIGHT = 2 + GamepadButtonLeftFaceRight = 2 // Gamepad left DPAD down button - GAMEPAD_BUTTON_LEFT_FACE_DOWN = 3 + GamepadButtonLeftFaceDown = 3 // Gamepad left DPAD left button - GAMEPAD_BUTTON_LEFT_FACE_LEFT = 4 + GamepadButtonLeftFaceLeft = 4 // Gamepad right button up (i.e. PS3: Triangle, Xbox: Y) - GAMEPAD_BUTTON_RIGHT_FACE_UP = 5 + GamepadButtonRightFaceUp = 5 // Gamepad right button right (i.e. PS3: Circle, Xbox: B) - GAMEPAD_BUTTON_RIGHT_FACE_RIGHT = 6 + GamepadButtonRightFaceRight = 6 // Gamepad right button down (i.e. PS3: Cross, Xbox: A) - GAMEPAD_BUTTON_RIGHT_FACE_DOWN = 7 + GamepadButtonRightFaceDown = 7 // Gamepad right button left (i.e. PS3: Square, Xbox: X) - GAMEPAD_BUTTON_RIGHT_FACE_LEFT = 8 + GamepadButtonRightFaceLeft = 8 // Gamepad top/back trigger left (first), it could be a trailing button - GAMEPAD_BUTTON_LEFT_TRIGGER_1 = 9 + GamepadButtonLeftTrigger1 = 9 // Gamepad top/back trigger left (second), it could be a trailing button - GAMEPAD_BUTTON_LEFT_TRIGGER_2 = 10 + GamepadButtonLeftTrigger2 = 10 // Gamepad top/back trigger right (first), it could be a trailing button - GAMEPAD_BUTTON_RIGHT_TRIGGER_1 = 11 + GamepadButtonRightTrigger1 = 11 // Gamepad top/back trigger right (second), it could be a trailing button - GAMEPAD_BUTTON_RIGHT_TRIGGER_2 = 12 + GamepadButtonRightTrigger2 = 12 // Gamepad center buttons, left one (i.e. PS3: Select) - GAMEPAD_BUTTON_MIDDLE_LEFT = 13 + GamepadButtonMiddleLeft = 13 // Gamepad center buttons, middle one (i.e. PS3: PS, Xbox: XBOX) - GAMEPAD_BUTTON_MIDDLE = 14 + GamepadButtonMiddle = 14 // Gamepad center buttons, right one (i.e. PS3: Start) - GAMEPAD_BUTTON_MIDDLE_RIGHT = 15 + GamepadButtonMiddleRight = 15 // Gamepad joystick pressed button left - GAMEPAD_BUTTON_LEFT_THUMB = 16 + GamepadButtonLeftThumb = 16 // Gamepad joystick pressed button right - GAMEPAD_BUTTON_RIGHT_THUMB = 17 + GamepadButtonRightThumb = 17 ) // Gamepad axes @@ -385,17 +385,17 @@ type GamepadAxis = int32 const ( // Gamepad left stick X axis - GAMEPAD_AXIS_LEFT_X = 0 + GamepadAxisLeftX = 0 // Gamepad left stick Y axis - GAMEPAD_AXIS_LEFT_Y = 1 + GamepadAxisLeftY = 1 // Gamepad right stick X axis - GAMEPAD_AXIS_RIGHT_X = 2 + GamepadAxisRightX = 2 // Gamepad right stick Y axis - GAMEPAD_AXIS_RIGHT_Y = 3 + GamepadAxisRightY = 3 // Gamepad back trigger left, pressure level: [1..-1] - GAMEPAD_AXIS_LEFT_TRIGGER = 4 + GamepadAxisLeftTrigger = 4 // Gamepad back trigger right, pressure level: [1..-1] - GAMEPAD_AXIS_RIGHT_TRIGGER = 5 + GamepadAxisRightTrigger = 5 ) // Material map index @@ -403,27 +403,27 @@ type MaterialMapIndex = int32 const ( // Albedo material (same as: MATERIAL_MAP_DIFFUSE) - MATERIAL_MAP_ALBEDO = 0 + MaterialMapAlbedo = 0 // Metalness material (same as: MATERIAL_MAP_SPECULAR) - MATERIAL_MAP_METALNESS = 1 + MaterialMapMetalness = 1 // Normal material - MATERIAL_MAP_NORMAL = 2 + MaterialMapNormal = 2 // Roughness material - MATERIAL_MAP_ROUGHNESS = 3 + MaterialMapRoughness = 3 // Ambient occlusion material - MATERIAL_MAP_OCCLUSION = 4 + MaterialMapOcclusion = 4 // Emission material - MATERIAL_MAP_EMISSION = 5 + MaterialMapEmission = 5 // Heightmap material - MATERIAL_MAP_HEIGHT = 6 + MaterialMapHeight = 6 // Cubemap material (NOTE: Uses GL_TEXTURE_CUBE_MAP) - MATERIAL_MAP_CUBEMAP = 7 + MaterialMapCubemap = 7 // Irradiance material (NOTE: Uses GL_TEXTURE_CUBE_MAP) - MATERIAL_MAP_IRRADIANCE = 8 + MaterialMapIrradiance = 8 // Prefilter material (NOTE: Uses GL_TEXTURE_CUBE_MAP) - MATERIAL_MAP_PREFILTER = 9 + MaterialMapPrefilter = 9 // Brdf material - MATERIAL_MAP_BRDF = 10 + MaterialMapBrdf = 10 ) // Shader location index @@ -431,65 +431,65 @@ type ShaderLocationIndex = int32 const ( // Shader location: vertex attribute: position - SHADER_LOC_VERTEX_POSITION = 0 + ShaderLocVertexPosition = 0 // Shader location: vertex attribute: texcoord01 - SHADER_LOC_VERTEX_TEXCOORD01 = 1 + ShaderLocVertexTexcoord01 = 1 // Shader location: vertex attribute: texcoord02 - SHADER_LOC_VERTEX_TEXCOORD02 = 2 + ShaderLocVertexTexcoord02 = 2 // Shader location: vertex attribute: normal - SHADER_LOC_VERTEX_NORMAL = 3 + ShaderLocVertexNormal = 3 // Shader location: vertex attribute: tangent - SHADER_LOC_VERTEX_TANGENT = 4 + ShaderLocVertexTangent = 4 // Shader location: vertex attribute: color - SHADER_LOC_VERTEX_COLOR = 5 + ShaderLocVertexColor = 5 // Shader location: matrix uniform: model-view-projection - SHADER_LOC_MATRIX_MVP = 6 + ShaderLocMatrixMvp = 6 // Shader location: matrix uniform: view (camera transform) - SHADER_LOC_MATRIX_VIEW = 7 + ShaderLocMatrixView = 7 // Shader location: matrix uniform: projection - SHADER_LOC_MATRIX_PROJECTION = 8 + ShaderLocMatrixProjection = 8 // Shader location: matrix uniform: model (transform) - SHADER_LOC_MATRIX_MODEL = 9 + ShaderLocMatrixModel = 9 // Shader location: matrix uniform: normal - SHADER_LOC_MATRIX_NORMAL = 10 + ShaderLocMatrixNormal = 10 // Shader location: vector uniform: view - SHADER_LOC_VECTOR_VIEW = 11 + ShaderLocVectorView = 11 // Shader location: vector uniform: diffuse color - SHADER_LOC_COLOR_DIFFUSE = 12 + ShaderLocColorDiffuse = 12 // Shader location: vector uniform: specular color - SHADER_LOC_COLOR_SPECULAR = 13 + ShaderLocColorSpecular = 13 // Shader location: vector uniform: ambient color - SHADER_LOC_COLOR_AMBIENT = 14 + ShaderLocColorAmbient = 14 // Shader location: sampler2d texture: albedo (same as: SHADER_LOC_MAP_DIFFUSE) - SHADER_LOC_MAP_ALBEDO = 15 + ShaderLocMapAlbedo = 15 // Shader location: sampler2d texture: metalness (same as: SHADER_LOC_MAP_SPECULAR) - SHADER_LOC_MAP_METALNESS = 16 + ShaderLocMapMetalness = 16 // Shader location: sampler2d texture: normal - SHADER_LOC_MAP_NORMAL = 17 + ShaderLocMapNormal = 17 // Shader location: sampler2d texture: roughness - SHADER_LOC_MAP_ROUGHNESS = 18 + ShaderLocMapRoughness = 18 // Shader location: sampler2d texture: occlusion - SHADER_LOC_MAP_OCCLUSION = 19 + ShaderLocMapOcclusion = 19 // Shader location: sampler2d texture: emission - SHADER_LOC_MAP_EMISSION = 20 + ShaderLocMapEmission = 20 // Shader location: sampler2d texture: height - SHADER_LOC_MAP_HEIGHT = 21 + ShaderLocMapHeight = 21 // Shader location: samplerCube texture: cubemap - SHADER_LOC_MAP_CUBEMAP = 22 + ShaderLocMapCubemap = 22 // Shader location: samplerCube texture: irradiance - SHADER_LOC_MAP_IRRADIANCE = 23 + ShaderLocMapIrradiance = 23 // Shader location: samplerCube texture: prefilter - SHADER_LOC_MAP_PREFILTER = 24 + ShaderLocMapPrefilter = 24 // Shader location: sampler2d texture: brdf - SHADER_LOC_MAP_BRDF = 25 + ShaderLocMapBrdf = 25 // Shader location: vertex attribute: boneIds - SHADER_LOC_VERTEX_BONEIDS = 26 + ShaderLocVertexBoneids = 26 // Shader location: vertex attribute: boneWeights - SHADER_LOC_VERTEX_BONEWEIGHTS = 27 + ShaderLocVertexBoneweights = 27 // Shader location: array of matrices uniform: boneMatrices - SHADER_LOC_BONE_MATRICES = 28 + ShaderLocBoneMatrices = 28 // Shader location: vertex attribute: instanceTransform - SHADER_LOC_VERTEX_INSTANCE_TX = 29 + ShaderLocVertexInstanceTx = 29 ) // Shader uniform data type @@ -497,31 +497,31 @@ type ShaderUniformDataType = int32 const ( // Shader uniform type: float - SHADER_UNIFORM_FLOAT = 0 + ShaderUniformFloat = 0 // Shader uniform type: vec2 (2 float) - SHADER_UNIFORM_VEC2 = 1 + ShaderUniformVec2 = 1 // Shader uniform type: vec3 (3 float) - SHADER_UNIFORM_VEC3 = 2 + ShaderUniformVec3 = 2 // Shader uniform type: vec4 (4 float) - SHADER_UNIFORM_VEC4 = 3 + ShaderUniformVec4 = 3 // Shader uniform type: int - SHADER_UNIFORM_INT = 4 + ShaderUniformInt = 4 // Shader uniform type: ivec2 (2 int) - SHADER_UNIFORM_IVEC2 = 5 + ShaderUniformIvec2 = 5 // Shader uniform type: ivec3 (3 int) - SHADER_UNIFORM_IVEC3 = 6 + ShaderUniformIvec3 = 6 // Shader uniform type: ivec4 (4 int) - SHADER_UNIFORM_IVEC4 = 7 + ShaderUniformIvec4 = 7 // Shader uniform type: unsigned int - SHADER_UNIFORM_UINT = 8 + ShaderUniformUint = 8 // Shader uniform type: uivec2 (2 unsigned int) - SHADER_UNIFORM_UIVEC2 = 9 + ShaderUniformUivec2 = 9 // Shader uniform type: uivec3 (3 unsigned int) - SHADER_UNIFORM_UIVEC3 = 10 + ShaderUniformUivec3 = 10 // Shader uniform type: uivec4 (4 unsigned int) - SHADER_UNIFORM_UIVEC4 = 11 + ShaderUniformUivec4 = 11 // Shader uniform type: sampler2d - SHADER_UNIFORM_SAMPLER2D = 12 + ShaderUniformSampler2D = 12 ) // Shader attribute data types @@ -529,13 +529,13 @@ type ShaderAttributeDataType = int32 const ( // Shader attribute type: float - SHADER_ATTRIB_FLOAT = 0 + ShaderAttribFloat = 0 // Shader attribute type: vec2 (2 float) - SHADER_ATTRIB_VEC2 = 1 + ShaderAttribVec2 = 1 // Shader attribute type: vec3 (3 float) - SHADER_ATTRIB_VEC3 = 2 + ShaderAttribVec3 = 2 // Shader attribute type: vec4 (4 float) - SHADER_ATTRIB_VEC4 = 3 + ShaderAttribVec4 = 3 ) // Pixel formats @@ -543,53 +543,53 @@ type PixelFormat = int32 const ( // 8 bit per pixel (no alpha) - PIXELFORMAT_UNCOMPRESSED_GRAYSCALE = 1 + PixelformatUncompressedGrayscale = 1 // 8*2 bpp (2 channels) - PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA = 2 + PixelformatUncompressedGrayAlpha = 2 // 16 bpp - PIXELFORMAT_UNCOMPRESSED_R5G6B5 = 3 + PixelformatUncompressedR5G6B5 = 3 // 24 bpp - PIXELFORMAT_UNCOMPRESSED_R8G8B8 = 4 + PixelformatUncompressedR8G8B8 = 4 // 16 bpp (1 bit alpha) - PIXELFORMAT_UNCOMPRESSED_R5G5B5A1 = 5 + PixelformatUncompressedR5G5B5A1 = 5 // 16 bpp (4 bit alpha) - PIXELFORMAT_UNCOMPRESSED_R4G4B4A4 = 6 + PixelformatUncompressedR4G4B4A4 = 6 // 32 bpp - PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 = 7 + PixelformatUncompressedR8G8B8A8 = 7 // 32 bpp (1 channel - float) - PIXELFORMAT_UNCOMPRESSED_R32 = 8 + PixelformatUncompressedR32 = 8 // 32*3 bpp (3 channels - float) - PIXELFORMAT_UNCOMPRESSED_R32G32B32 = 9 + PixelformatUncompressedR32G32B32 = 9 // 32*4 bpp (4 channels - float) - PIXELFORMAT_UNCOMPRESSED_R32G32B32A32 = 10 + PixelformatUncompressedR32G32B32A32 = 10 // 16 bpp (1 channel - half float) - PIXELFORMAT_UNCOMPRESSED_R16 = 11 + PixelformatUncompressedR16 = 11 // 16*3 bpp (3 channels - half float) - PIXELFORMAT_UNCOMPRESSED_R16G16B16 = 12 + PixelformatUncompressedR16G16B16 = 12 // 16*4 bpp (4 channels - half float) - PIXELFORMAT_UNCOMPRESSED_R16G16B16A16 = 13 + PixelformatUncompressedR16G16B16A16 = 13 // 4 bpp (no alpha) - PIXELFORMAT_COMPRESSED_DXT1_RGB = 14 + PixelformatCompressedDxt1Rgb = 14 // 4 bpp (1 bit alpha) - PIXELFORMAT_COMPRESSED_DXT1_RGBA = 15 + PixelformatCompressedDxt1Rgba = 15 // 8 bpp - PIXELFORMAT_COMPRESSED_DXT3_RGBA = 16 + PixelformatCompressedDxt3Rgba = 16 // 8 bpp - PIXELFORMAT_COMPRESSED_DXT5_RGBA = 17 + PixelformatCompressedDxt5Rgba = 17 // 4 bpp - PIXELFORMAT_COMPRESSED_ETC1_RGB = 18 + PixelformatCompressedEtc1Rgb = 18 // 4 bpp - PIXELFORMAT_COMPRESSED_ETC2_RGB = 19 + PixelformatCompressedEtc2Rgb = 19 // 8 bpp - PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA = 20 + PixelformatCompressedEtc2EacRgba = 20 // 4 bpp - PIXELFORMAT_COMPRESSED_PVRT_RGB = 21 + PixelformatCompressedPvrtRgb = 21 // 4 bpp - PIXELFORMAT_COMPRESSED_PVRT_RGBA = 22 + PixelformatCompressedPvrtRgba = 22 // 8 bpp - PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA = 23 + PixelformatCompressedAstc4X4Rgba = 23 // 2 bpp - PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA = 24 + PixelformatCompressedAstc8X8Rgba = 24 ) // Texture parameters: filter mode @@ -597,17 +597,17 @@ type TextureFilter = int32 const ( // No filter, just pixel approximation - TEXTURE_FILTER_POINT = 0 + TextureFilterPoint = 0 // Linear filtering - TEXTURE_FILTER_BILINEAR = 1 + TextureFilterBilinear = 1 // Trilinear filtering (linear with mipmaps) - TEXTURE_FILTER_TRILINEAR = 2 + TextureFilterTrilinear = 2 // Anisotropic filtering 4x - TEXTURE_FILTER_ANISOTROPIC_4X = 3 + TextureFilterAnisotropic4X = 3 // Anisotropic filtering 8x - TEXTURE_FILTER_ANISOTROPIC_8X = 4 + TextureFilterAnisotropic8X = 4 // Anisotropic filtering 16x - TEXTURE_FILTER_ANISOTROPIC_16X = 5 + TextureFilterAnisotropic16X = 5 ) // Texture parameters: wrap mode @@ -615,13 +615,13 @@ type TextureWrap = int32 const ( // Repeats texture in tiled mode - TEXTURE_WRAP_REPEAT = 0 + TextureWrapRepeat = 0 // Clamps texture to edge pixel in tiled mode - TEXTURE_WRAP_CLAMP = 1 + TextureWrapClamp = 1 // Mirrors and repeats the texture in tiled mode - TEXTURE_WRAP_MIRROR_REPEAT = 2 + TextureWrapMirrorRepeat = 2 // Mirrors and clamps to border the texture in tiled mode - TEXTURE_WRAP_MIRROR_CLAMP = 3 + TextureWrapMirrorClamp = 3 ) // Cubemap layouts @@ -629,15 +629,15 @@ type CubemapLayout = int32 const ( // Automatically detect layout type - CUBEMAP_LAYOUT_AUTO_DETECT = 0 + CubemapLayoutAutoDetect = 0 // Layout is defined by a vertical line with faces - CUBEMAP_LAYOUT_LINE_VERTICAL = 1 + CubemapLayoutLineVertical = 1 // Layout is defined by a horizontal line with faces - CUBEMAP_LAYOUT_LINE_HORIZONTAL = 2 + CubemapLayoutLineHorizontal = 2 // Layout is defined by a 3x4 cross with cubemap faces - CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR = 3 + CubemapLayoutCrossThreeByFour = 3 // Layout is defined by a 4x3 cross with cubemap faces - CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE = 4 + CubemapLayoutCrossFourByThree = 4 ) // Font type, defines generation method @@ -645,11 +645,11 @@ type FontType = int32 const ( // Default font generation, anti-aliased - FONT_DEFAULT = 0 + FontDefault = 0 // Bitmap font generation, no anti-aliasing - FONT_BITMAP = 1 + FontBitmap = 1 // SDF font generation, requires external shader - FONT_SDF = 2 + FontSdf = 2 ) // Color blending modes (pre-defined) @@ -657,21 +657,21 @@ type BlendMode = int32 const ( // Blend textures considering alpha (default) - BLEND_ALPHA = 0 + BlendAlpha = 0 // Blend textures adding colors - BLEND_ADDITIVE = 1 + BlendAdditive = 1 // Blend textures multiplying colors - BLEND_MULTIPLIED = 2 + BlendMultiplied = 2 // Blend textures adding colors (alternative) - BLEND_ADD_COLORS = 3 + BlendAddColors = 3 // Blend textures subtracting colors (alternative) - BLEND_SUBTRACT_COLORS = 4 + BlendSubtractColors = 4 // Blend premultiplied textures considering alpha - BLEND_ALPHA_PREMULTIPLY = 5 + BlendAlphaPremultiply = 5 // Blend textures using custom src/dst factors (use rlSetBlendFactors()) - BLEND_CUSTOM = 6 + BlendCustom = 6 // Blend textures using custom rgb/alpha separate src/dst factors (use rlSetBlendFactorsSeparate()) - BLEND_CUSTOM_SEPARATE = 7 + BlendCustomSeparate = 7 ) // Gesture @@ -679,27 +679,27 @@ type Gesture = int32 const ( // No gesture - GESTURE_NONE = 0 + GestureNone = 0 // Tap gesture - GESTURE_TAP = 1 + GestureTap = 1 // Double tap gesture - GESTURE_DOUBLETAP = 2 + GestureDoubletap = 2 // Hold gesture - GESTURE_HOLD = 4 + GestureHold = 4 // Drag gesture - GESTURE_DRAG = 8 + GestureDrag = 8 // Swipe right gesture - GESTURE_SWIPE_RIGHT = 16 + GestureSwipeRight = 16 // Swipe left gesture - GESTURE_SWIPE_LEFT = 32 + GestureSwipeLeft = 32 // Swipe up gesture - GESTURE_SWIPE_UP = 64 + GestureSwipeUp = 64 // Swipe down gesture - GESTURE_SWIPE_DOWN = 128 + GestureSwipeDown = 128 // Pinch in gesture - GESTURE_PINCH_IN = 256 + GesturePinchIn = 256 // Pinch out gesture - GESTURE_PINCH_OUT = 512 + GesturePinchOut = 512 ) // Camera system modes @@ -707,15 +707,15 @@ type CameraMode = int32 const ( // Camera custom, controlled by user (UpdateCamera() does nothing) - CAMERA_CUSTOM = 0 + CameraCustom = 0 // Camera free mode - CAMERA_FREE = 1 + CameraFree = 1 // Camera orbital, around target, zoom supported - CAMERA_ORBITAL = 2 + CameraOrbital = 2 // Camera first person - CAMERA_FIRST_PERSON = 3 + CameraFirstPerson = 3 // Camera third person - CAMERA_THIRD_PERSON = 4 + CameraThirdPerson = 4 ) // Camera projection @@ -723,9 +723,9 @@ type CameraProjection = int32 const ( // Perspective projection - CAMERA_PERSPECTIVE = 0 + CameraPerspective = 0 // Orthographic projection - CAMERA_ORTHOGRAPHIC = 1 + CameraOrthographic = 1 ) // N-patch layout @@ -733,9 +733,9 @@ type NPatchLayout = int32 const ( // Npatch layout: 3x3 tiles - NPATCH_NINE_PATCH = 0 + NpatchNinePatch = 0 // Npatch layout: 1x3 tiles - NPATCH_THREE_PATCH_VERTICAL = 1 + NpatchThreePatchVertical = 1 // Npatch layout: 3x1 tiles - NPATCH_THREE_PATCH_HORIZONTAL = 2 + NpatchThreePatchHorizontal = 2 ) diff --git a/testdata/rl/structs_gen_formatted.go b/testdata/rl/structs_gen_formatted.go new file mode 100644 index 0000000..a10fb6d --- /dev/null +++ b/testdata/rl/structs_gen_formatted.go @@ -0,0 +1,307 @@ +// AUTOGENERATED FILE. DO NOT EDIT + +//go:build js + +package rl + +// Vector2, 2 components +type Vector2 struct { + X float32 // Vector x component + Y float32 // Vector y component +} + +// Vector3, 3 components +type Vector3 struct { + X float32 // Vector x component + Y float32 // Vector y component + Z float32 // Vector z component +} + +// Vector4, 4 components +type Vector4 struct { + X float32 // Vector x component + Y float32 // Vector y component + Z float32 // Vector z component + W float32 // Vector w component +} + +// Matrix, 4x4 components, column major, OpenGL style, right-handed +type Matrix struct { + M0 float32 // Matrix first row (4 components) + M4 float32 // Matrix first row (4 components) + M8 float32 // Matrix first row (4 components) + M12 float32 // Matrix first row (4 components) + M1 float32 // Matrix second row (4 components) + M5 float32 // Matrix second row (4 components) + M9 float32 // Matrix second row (4 components) + M13 float32 // Matrix second row (4 components) + M2 float32 // Matrix third row (4 components) + M6 float32 // Matrix third row (4 components) + M10 float32 // Matrix third row (4 components) + M14 float32 // Matrix third row (4 components) + M3 float32 // Matrix fourth row (4 components) + M7 float32 // Matrix fourth row (4 components) + M11 float32 // Matrix fourth row (4 components) + M15 float32 // Matrix fourth row (4 components) +} + +// Color, 4 components, R8G8B8A8 (32bit) +type Color struct { + R byte // Color red value + G byte // Color green value + B byte // Color blue value + A byte // Color alpha value +} + +// Rectangle, 4 components +type Rectangle struct { + X float32 // Rectangle top-left corner position x + Y float32 // Rectangle top-left corner position y + Width float32 // Rectangle width + Height float32 // Rectangle height +} + +// Image, pixel data stored in CPU memory (RAM) +type Image struct { + Data cptr // Image raw data + Width int32 // Image base width + Height int32 // Image base height + Mipmaps int32 // Mipmap levels, 1 by default + Format int32 // Data format (PixelFormat type) +} + +// Texture, tex data stored in GPU memory (VRAM) +type Texture struct { + Id uint32 // OpenGL texture id + Width int32 // Texture base width + Height int32 // Texture base height + Mipmaps int32 // Mipmap levels, 1 by default + Format int32 // Data format (PixelFormat type) +} + +// RenderTexture, fbo for texture rendering +type RenderTexture struct { + Id uint32 // OpenGL framebuffer object id + Texture Texture // Color buffer attachment texture + Depth Texture // Depth buffer attachment texture +} + +// NPatchInfo, n-patch layout info +type NPatchInfo struct { + Source Rectangle // Texture source rectangle + Left int32 // Left border offset + Top int32 // Top border offset + Right int32 // Right border offset + Bottom int32 // Bottom border offset + Layout int32 // Layout of the n-patch: 3x3, 1x3 or 3x1 +} + +// GlyphInfo, font characters glyphs info +type GlyphInfo struct { + Value int32 // Character value (Unicode) + OffsetX int32 // Character offset X when drawing + OffsetY int32 // Character offset Y when drawing + AdvanceX int32 // Character advance position X + Image Image // Character image data +} + +// Font, font texture and GlyphInfo array data +type Font struct { + BaseSize int32 // Base size (default chars height) + GlyphCount int32 // Number of glyph characters + GlyphPadding int32 // Padding around the glyph characters + Texture Texture2D // Texture atlas containing the glyphs + Recs cptr // Rectangles in texture for the glyphs + Glyphs cptr // Glyphs info data +} + +// Camera, defines position/orientation in 3d space +type Camera3D struct { + Position Vector3 // Camera position + Target Vector3 // Camera target it looks-at + Up Vector3 // Camera up vector (rotation over its axis) + Fovy float32 // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane height in world units in orthographic + Projection int32 // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC +} + +// Camera2D, defines position/orientation in 2d space +type Camera2D struct { + Offset Vector2 // Camera offset (screen space offset from window origin) + Target Vector2 // Camera target (world space target point that is mapped to screen space offset) + Rotation float32 // Camera rotation in degrees (pivots around target) + Zoom float32 // Camera zoom (scaling around target), must not be set to 0, set to 1.0f for no scale +} + +// Mesh, vertex data and vao/vbo +type Mesh struct { + VertexCount int32 // Number of vertices stored in arrays + TriangleCount int32 // Number of triangles stored (indexed or not) + Vertices cptr // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) + Texcoords cptr // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) + Texcoords2 cptr // Vertex texture second coordinates (UV - 2 components per vertex) (shader-location = 5) + Normals cptr // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) + Tangents cptr // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) + Colors cptr // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) + Indices cptr // Vertex indices (in case vertex data comes indexed) + AnimVertices cptr // Animated vertex positions (after bones transformations) + AnimNormals cptr // Animated normals (after bones transformations) + BoneIds cptr // Vertex bone ids, max 255 bone ids, up to 4 bones influence by vertex (skinning) (shader-location = 6) + BoneWeights cptr // Vertex bone weight, up to 4 bones influence by vertex (skinning) (shader-location = 7) + BoneMatrices cptr // Bones animated transformation matrices + BoneCount int32 // Number of bones + VaoId uint32 // OpenGL Vertex Array Object id + VboId cptr // OpenGL Vertex Buffer Objects id (default vertex data) +} + +// Shader +type Shader struct { + Id uint32 // Shader program id + Locs cptr // Shader locations array (RL_MAX_SHADER_LOCATIONS) +} + +// MaterialMap +type MaterialMap struct { + Texture Texture2D // Material map texture + Color Color // Material map color + Value float32 // Material map value +} + +// Material, includes shader and maps +type Material struct { + Shader Shader // Material shader + Maps cptr // Material maps array (MAX_MATERIAL_MAPS) + Params [4]float32 // Material generic parameters (if required) +} + +// Transform, vertex transformation data +type Transform struct { + Translation Vector3 // Translation + Rotation Quaternion // Rotation + Scale Vector3 // Scale +} + +// Bone, skeletal animation bone +type BoneInfo struct { + Name [32]byte // Bone name + Parent int32 // Bone parent +} + +// Model, meshes, materials and animation data +type Model struct { + Transform Matrix // Local transform matrix + MeshCount int32 // Number of meshes + MaterialCount int32 // Number of materials + Meshes cptr // Meshes array + Materials cptr // Materials array + MeshMaterial cptr // Mesh material number + BoneCount int32 // Number of bones + Bones cptr // Bones information (skeleton) + BindPose cptr // Bones base transformation (pose) +} + +// ModelAnimation +type ModelAnimation struct { + BoneCount int32 // Number of bones + FrameCount int32 // Number of animation frames + Bones cptr // Bones information (skeleton) + FramePoses cptr // Poses array by frame + Name [32]byte // Animation name +} + +// Ray, ray for raycasting +type Ray struct { + Position Vector3 // Ray position (origin) + Direction Vector3 // Ray direction (normalized) +} + +// RayCollision, ray hit information +type RayCollision struct { + Hit bool // Did the ray hit something? + Distance float32 // Distance to the nearest hit + Point Vector3 // Point of the nearest hit + Normal Vector3 // Surface normal of hit +} + +// BoundingBox +type BoundingBox struct { + Min Vector3 // Minimum vertex box-corner + Max Vector3 // Maximum vertex box-corner +} + +// Wave, audio wave data +type Wave struct { + FrameCount uint32 // Total number of frames (considering channels) + SampleRate uint32 // Frequency (samples per second) + SampleSize uint32 // Bit depth (bits per sample): 8, 16, 32 (24 not supported) + Channels uint32 // Number of channels (1-mono, 2-stereo, ...) + Data cptr // Buffer data pointer +} + +// AudioStream, custom audio stream +type AudioStream struct { + Buffer cptr // Pointer to internal data used by the audio system + Processor cptr // Pointer to internal data processor, useful for audio effects + SampleRate uint32 // Frequency (samples per second) + SampleSize uint32 // Bit depth (bits per sample): 8, 16, 32 (24 not supported) + Channels uint32 // Number of channels (1-mono, 2-stereo, ...) +} + +// Sound +type Sound struct { + Stream AudioStream // Audio stream + FrameCount uint32 // Total number of frames (considering channels) +} + +// Music, audio stream, anything longer than ~10 seconds should be streamed +type Music struct { + Stream AudioStream // Audio stream + FrameCount uint32 // Total number of frames (considering channels) + Looping bool // Music looping enable + CtxType int32 // Type of music context (audio filetype) + CtxData cptr // Audio context data, depends on type +} + +// VrDeviceInfo, Head-Mounted-Display device parameters +type VrDeviceInfo struct { + HResolution int32 // Horizontal resolution in pixels + VResolution int32 // Vertical resolution in pixels + HScreenSize float32 // Horizontal size in meters + VScreenSize float32 // Vertical size in meters + EyeToScreenDistance float32 // Distance between eye and display in meters + LensSeparationDistance float32 // Lens separation distance in meters + InterpupillaryDistance float32 // IPD (distance between pupils) in meters + LensDistortionValues [4]float32 // Lens distortion constant parameters + ChromaAbCorrection [4]float32 // Chromatic aberration correction parameters +} + +// VrStereoConfig, VR stereo rendering configuration for simulator +type VrStereoConfig struct { + Projection [2]Matrix // VR projection matrices (per eye) + ViewOffset [2]Matrix // VR view offset matrices (per eye) + LeftLensCenter [2]float32 // VR left lens center + RightLensCenter [2]float32 // VR right lens center + LeftScreenCenter [2]float32 // VR left screen center + RightScreenCenter [2]float32 // VR right screen center + Scale [2]float32 // VR distortion scale + ScaleIn [2]float32 // VR distortion scale in +} + +// File path list +type FilePathList struct { + Count uint32 // Filepaths entries count + Paths cptr // Filepaths entries +} + +// Automation event +type AutomationEvent struct { + Frame uint32 // Event frame + Type uint32 // Event type (AutomationEventType) + Params [4]int32 // Event parameters (if required) +} + +// Automation event list +type AutomationEventList struct { + Capacity uint32 // Events max entries (MAX_AUTOMATION_EVENTS) + Count uint32 // Events entries count + Events cptr // Events entries +} diff --git a/testdata/rl/structs_gen_unformatted.go b/testdata/rl/structs_gen_unformatted.go deleted file mode 100644 index 1d2e2ac..0000000 --- a/testdata/rl/structs_gen_unformatted.go +++ /dev/null @@ -1,307 +0,0 @@ -// AUTOGENERATED FILE. DO NOT EDIT - -//go:build js - -package rl - -// Vector2, 2 components -type Vector2 struct { - X float32 // Vector x component - Y float32 // Vector y component -} - -// Vector3, 3 components -type Vector3 struct { - X float32 // Vector x component - Y float32 // Vector y component - Z float32 // Vector z component -} - -// Vector4, 4 components -type Vector4 struct { - X float32 // Vector x component - Y float32 // Vector y component - Z float32 // Vector z component - W float32 // Vector w component -} - -// Matrix, 4x4 components, column major, OpenGL style, right-handed -type Matrix struct { - M0 float32 // Matrix first row (4 components) - M4 float32 // Matrix first row (4 components) - M8 float32 // Matrix first row (4 components) - M12 float32 // Matrix first row (4 components) - M1 float32 // Matrix second row (4 components) - M5 float32 // Matrix second row (4 components) - M9 float32 // Matrix second row (4 components) - M13 float32 // Matrix second row (4 components) - M2 float32 // Matrix third row (4 components) - M6 float32 // Matrix third row (4 components) - M10 float32 // Matrix third row (4 components) - M14 float32 // Matrix third row (4 components) - M3 float32 // Matrix fourth row (4 components) - M7 float32 // Matrix fourth row (4 components) - M11 float32 // Matrix fourth row (4 components) - M15 float32 // Matrix fourth row (4 components) -} - -// Color, 4 components, R8G8B8A8 (32bit) -type Color struct { - R byte // Color red value - G byte // Color green value - B byte // Color blue value - A byte // Color alpha value -} - -// Rectangle, 4 components -type Rectangle struct { - X float32 // Rectangle top-left corner position x - Y float32 // Rectangle top-left corner position y - Width float32 // Rectangle width - Height float32 // Rectangle height -} - -// Image, pixel data stored in CPU memory (RAM) -type Image struct { - Data cptr // Image raw data - Width int32 // Image base width - Height int32 // Image base height - Mipmaps int32 // Mipmap levels, 1 by default - Format int32 // Data format (PixelFormat type) -} - -// Texture, tex data stored in GPU memory (VRAM) -type Texture struct { - Id uint32 // OpenGL texture id - Width int32 // Texture base width - Height int32 // Texture base height - Mipmaps int32 // Mipmap levels, 1 by default - Format int32 // Data format (PixelFormat type) -} - -// RenderTexture, fbo for texture rendering -type RenderTexture struct { - Id uint32 // OpenGL framebuffer object id - Texture Texture // Color buffer attachment texture - Depth Texture // Depth buffer attachment texture -} - -// NPatchInfo, n-patch layout info -type NPatchInfo struct { - Source Rectangle // Texture source rectangle - Left int32 // Left border offset - Top int32 // Top border offset - Right int32 // Right border offset - Bottom int32 // Bottom border offset - Layout int32 // Layout of the n-patch: 3x3, 1x3 or 3x1 -} - -// GlyphInfo, font characters glyphs info -type GlyphInfo struct { - Value int32 // Character value (Unicode) - OffsetX int32 // Character offset X when drawing - OffsetY int32 // Character offset Y when drawing - AdvanceX int32 // Character advance position X - Image Image // Character image data -} - -// Font, font texture and GlyphInfo array data -type Font struct { - BaseSize int32 // Base size (default chars height) - GlyphCount int32 // Number of glyph characters - GlyphPadding int32 // Padding around the glyph characters - Texture Texture2D // Texture atlas containing the glyphs - Recs cptr // Rectangles in texture for the glyphs - Glyphs cptr // Glyphs info data -} - -// Camera, defines position/orientation in 3d space -type Camera3D struct { - Position Vector3 // Camera position - Target Vector3 // Camera target it looks-at - Up Vector3 // Camera up vector (rotation over its axis) - Fovy float32 // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane height in world units in orthographic - Projection int32 // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC -} - -// Camera2D, defines position/orientation in 2d space -type Camera2D struct { - Offset Vector2 // Camera offset (screen space offset from window origin) - Target Vector2 // Camera target (world space target point that is mapped to screen space offset) - Rotation float32 // Camera rotation in degrees (pivots around target) - Zoom float32 // Camera zoom (scaling around target), must not be set to 0, set to 1.0f for no scale -} - -// Mesh, vertex data and vao/vbo -type Mesh struct { - VertexCount int32 // Number of vertices stored in arrays - TriangleCount int32 // Number of triangles stored (indexed or not) - Vertices cptr // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) - Texcoords cptr // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) - Texcoords2 cptr // Vertex texture second coordinates (UV - 2 components per vertex) (shader-location = 5) - Normals cptr // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) - Tangents cptr // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) - Colors cptr // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) - Indices cptr // Vertex indices (in case vertex data comes indexed) - AnimVertices cptr // Animated vertex positions (after bones transformations) - AnimNormals cptr // Animated normals (after bones transformations) - BoneIds cptr // Vertex bone ids, max 255 bone ids, up to 4 bones influence by vertex (skinning) (shader-location = 6) - BoneWeights cptr // Vertex bone weight, up to 4 bones influence by vertex (skinning) (shader-location = 7) - BoneMatrices cptr // Bones animated transformation matrices - BoneCount int32 // Number of bones - VaoId uint32 // OpenGL Vertex Array Object id - VboId cptr // OpenGL Vertex Buffer Objects id (default vertex data) -} - -// Shader -type Shader struct { - Id uint32 // Shader program id - Locs cptr // Shader locations array (RL_MAX_SHADER_LOCATIONS) -} - -// MaterialMap -type MaterialMap struct { - Texture Texture2D // Material map texture - Color Color // Material map color - Value float32 // Material map value -} - -// Material, includes shader and maps -type Material struct { - Shader Shader // Material shader - Maps cptr // Material maps array (MAX_MATERIAL_MAPS) - Params [4]float32 // Material generic parameters (if required) -} - -// Transform, vertex transformation data -type Transform struct { - Translation Vector3 // Translation - Rotation Quaternion // Rotation - Scale Vector3 // Scale -} - -// Bone, skeletal animation bone -type BoneInfo struct { - Name [32]byte // Bone name - Parent int32 // Bone parent -} - -// Model, meshes, materials and animation data -type Model struct { - Transform Matrix // Local transform matrix - MeshCount int32 // Number of meshes - MaterialCount int32 // Number of materials - Meshes cptr // Meshes array - Materials cptr // Materials array - MeshMaterial cptr // Mesh material number - BoneCount int32 // Number of bones - Bones cptr // Bones information (skeleton) - BindPose cptr // Bones base transformation (pose) -} - -// ModelAnimation -type ModelAnimation struct { - BoneCount int32 // Number of bones - FrameCount int32 // Number of animation frames - Bones cptr // Bones information (skeleton) - FramePoses cptr // Poses array by frame - Name [32]byte // Animation name -} - -// Ray, ray for raycasting -type Ray struct { - Position Vector3 // Ray position (origin) - Direction Vector3 // Ray direction (normalized) -} - -// RayCollision, ray hit information -type RayCollision struct { - Hit bool // Did the ray hit something? - Distance float32 // Distance to the nearest hit - Point Vector3 // Point of the nearest hit - Normal Vector3 // Surface normal of hit -} - -// BoundingBox -type BoundingBox struct { - Min Vector3 // Minimum vertex box-corner - Max Vector3 // Maximum vertex box-corner -} - -// Wave, audio wave data -type Wave struct { - FrameCount uint32 // Total number of frames (considering channels) - SampleRate uint32 // Frequency (samples per second) - SampleSize uint32 // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - Channels uint32 // Number of channels (1-mono, 2-stereo, ...) - Data cptr // Buffer data pointer -} - -// AudioStream, custom audio stream -type AudioStream struct { - Buffer cptr // Pointer to internal data used by the audio system - Processor cptr // Pointer to internal data processor, useful for audio effects - SampleRate uint32 // Frequency (samples per second) - SampleSize uint32 // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - Channels uint32 // Number of channels (1-mono, 2-stereo, ...) -} - -// Sound -type Sound struct { - Stream AudioStream // Audio stream - FrameCount uint32 // Total number of frames (considering channels) -} - -// Music, audio stream, anything longer than ~10 seconds should be streamed -type Music struct { - Stream AudioStream // Audio stream - FrameCount uint32 // Total number of frames (considering channels) - Looping bool // Music looping enable - CtxType int32 // Type of music context (audio filetype) - CtxData cptr // Audio context data, depends on type -} - -// VrDeviceInfo, Head-Mounted-Display device parameters -type VrDeviceInfo struct { - HResolution int32 // Horizontal resolution in pixels - VResolution int32 // Vertical resolution in pixels - HScreenSize float32 // Horizontal size in meters - VScreenSize float32 // Vertical size in meters - EyeToScreenDistance float32 // Distance between eye and display in meters - LensSeparationDistance float32 // Lens separation distance in meters - InterpupillaryDistance float32 // IPD (distance between pupils) in meters - LensDistortionValues [4]float32 // Lens distortion constant parameters - ChromaAbCorrection [4]float32 // Chromatic aberration correction parameters -} - -// VrStereoConfig, VR stereo rendering configuration for simulator -type VrStereoConfig struct { - Projection [2]Matrix // VR projection matrices (per eye) - ViewOffset [2]Matrix // VR view offset matrices (per eye) - LeftLensCenter [2]float32 // VR left lens center - RightLensCenter [2]float32 // VR right lens center - LeftScreenCenter [2]float32 // VR left screen center - RightScreenCenter [2]float32 // VR right screen center - Scale [2]float32 // VR distortion scale - ScaleIn [2]float32 // VR distortion scale in -} - -// File path list -type FilePathList struct { - Count uint32 // Filepaths entries count - Paths cptr // Filepaths entries -} - -// Automation event -type AutomationEvent struct { - Frame uint32 // Event frame - Type uint32 // Event type (AutomationEventType) - Params [4]int32 // Event parameters (if required) -} - -// Automation event list -type AutomationEventList struct { - Capacity uint32 // Events max entries (MAX_AUTOMATION_EVENTS) - Count uint32 // Events entries count - Events cptr // Events entries -} diff --git a/testdata/templates/aliases.go.gotmpl b/testdata/templates/aliases.go.gotmpl new file mode 100644 index 0000000..717f967 --- /dev/null +++ b/testdata/templates/aliases.go.gotmpl @@ -0,0 +1,16 @@ +{{- $root := . -}} + +// AUTOGENERATED FILE. DO NOT EDIT +{{if .BuildTags}} +//go:build {{.BuildTags}} +{{end}} +package rl + +{{- range .Imports }} +import {{ . }} +{{- end }} + +{{- range .Aliases}} +// {{ .Description}} +type {{ .Name}} = {{.Type}} +{{- end}} diff --git a/testdata/templates/defines.go.gotmpl b/testdata/templates/defines.go.gotmpl index fc10382..56513eb 100644 --- a/testdata/templates/defines.go.gotmpl +++ b/testdata/templates/defines.go.gotmpl @@ -20,7 +20,7 @@ import {{ . }} {{- end}} {{if contains .Type "COLOR"}} //{{- .Description}} - var {{.Name}} = Color{{.Value}} + var {{.Name}} = {{.Value}} {{- end}} {{if contains .Type "UNKNOWN"}} diff --git a/testdata/templates/templates.go b/testdata/templates/templates.go index f24e9bc..3600221 100644 --- a/testdata/templates/templates.go +++ b/testdata/templates/templates.go @@ -1,7 +1,11 @@ package templates import ( + "bytes" _ "embed" + "fmt" + "go/format" + "os" "text/template" ) @@ -19,3 +23,35 @@ func LoadTemplateFuncs(templ, name string, funcs template.FuncMap) *template.Tem Funcs(funcs). Parse(templ)) } + +// GenerateCode will generate the template using model. and write a file to disk in the format: +// rl/{name}_gen_unformatted.go +func GenerateCode(model any, templ string, name string, funcs template.FuncMap) { + structs := LoadTemplateFuncs(templ, name, funcs) + var buf bytes.Buffer + if err := structs.Execute(&buf, model); err != nil { + panic(err) + } + if err := os.WriteFile(fmt.Sprintf("rl/%s_gen_unformatted.go", name), buf.Bytes(), 0644); err != nil { + panic(err) + } +} + +// GenerateCode will generate the template using model. and write a file to disk in the format: +// rl/{name}_gen_formatted.go +func GenerateCodeFormatted(model any, templ string, name string, funcs template.FuncMap) { + structs := LoadTemplateFuncs(templ, name, funcs) + var buf bytes.Buffer + if err := structs.Execute(&buf, model); err != nil { + panic(err) + } + + formatted, err := format.Source(buf.Bytes()) + if err != nil { + panic(err) + } + + if err := os.WriteFile(fmt.Sprintf("rl/%s_gen_formatted.go", name), formatted, 0644); err != nil { + panic(err) + } +} diff --git a/testdata/util.go b/testdata/util.go new file mode 100644 index 0000000..6892bba --- /dev/null +++ b/testdata/util.go @@ -0,0 +1,104 @@ +package main + +import ( + "codegen/api" + "fmt" + "slices" + "strings" + + "github.com/iancoleman/strcase" +) + +// GoTypeFromC maps a C type to a Go type +func GoTypeFromC(t string) string { + oneToOneTypes := map[string]string{ + "char": "byte", + "float": "float32", + "unsigned char": "byte", + "unsigned int": "uint32", + "int": "int32", + } + if mapping, ok := oneToOneTypes[t]; ok { + return mapping + } + runed := []rune(t) + if runed[len(runed)-1] == '*' { + return "cptr" + } + if index := slices.Index(runed, '['); index >= 0 { + arraySize := runed[index:] + arrayType := runed[:index] + arrayType = []rune(GoTypeFromC(string(arrayType))) + return string(arraySize) + string(arrayType) + } + return t +} + +// ParseDefines prepares data for inserting into the template. +// Different C #define macros map to different Go constructs. +// +// It also makes the Name of the define PascalCase +// This function maps them to the proper Go constructs. +// See template templates/defines.go.gotmpl +func ParseDefines(defs []api.RlDefine) []api.RlDefine { + defs = slices.Clone(defs) + for i, d := range defs { + def := &defs[i] + // make name of defines PascalCase + def.Name = PascalCase(def.Name) + switch d.Type { + case "STRING": + // add quotes around value so the template can do const {{.Name}} = {{.Value}} + def.Value = "\"" + def.Value + "\"" + case "FLOAT_MATH": + // remove the trailing "f" from float values. + def.Value = api.StringyValue(strings.ReplaceAll(string(def.Value), "f", "")) + // make PI pascal case. + def.Value = api.StringyValue(strings.ReplaceAll(string(def.Value), "PI", "Pi")) + case "COLOR": + // turn CLITERAL(Color){ 200, 200, 200, 255 } into Color{ 200, 200, 200, 255 } + v := strings.ReplaceAll(string(def.Value), "CLITERAL(Color)", "Color") + def.Value = api.StringyValue(v) + case "UNKNOWN": + // Special cases need to be handled properly. + switch def.Name { + case "GetMouseRay": + def.Value = api.StringyValue(fmt.Sprintf("var %s = %s", def.Name, def.Value)) + case "Rlapi": + *def = api.RlDefine{} + default: + def.Value = api.StringyValue( + fmt.Sprintf("const %v = %v", def.Name, def.Value), + ) + } + } + } + return defs +} + +// Sets the Name field to PascaleCase. And converts type field to a Go type. +func ProcessStructFields(fields []api.RlField) { + for i := range fields { + f := &fields[i] + f.Name = PascalCase(f.Name) + f.Type = GoTypeFromC(f.Type) + } +} + +// Use for adding custom acronym mapping for PascalCase conversion. Eg. (DEG2RAD:Deg2Rad) +func RegisterPascalCaseAcronym(key, val string) { + strcase.ConfigureAcronym(key, val) +} + +func PascalCaseEnums(enums []api.RlEnum) { + for i := range enums { + enum := enums[i] + for i := range enum.Values { + v := &enum.Values[i] + v.Name = PascalCase(v.Name) + } + } +} + +// convert string to PascalCase +func PascalCase(v string) string { return strcase.ToCamel(v) }