From 449be4c4b781b342eb2f79ffa5cffb5e29ab18bc Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Sat, 24 Oct 2026 22:20:01 +0100 Subject: [PATCH] probe --- Makefile | 26 +- README.md | 62 ++ gen-hate-no-d.lua | 1267 +++++++++++++++++++++++-- hate-no-d.lua | 1396 +++++++++++++++++++++------- tests/cases/01_many_textures.lua | 46 + tests/cases/02_explicit.lua | 35 + tests/cases/03_borrowed.lua | 32 + tests/cases/04_model_from_mesh.lua | 45 + tests/cases/05_sound_alias.lua | 54 ++ tests/cases/06_teardown.lua | 52 ++ tests/cases/07_inout.lua | 37 + tests/cases/08_pins.lua | 62 ++ tests/cases/08b_views.lua | 36 + tests/cases/08c_font_atlas.lua | 36 + tests/cases/09_pointers.lua | 50 + tests/cases/10_ram.lua | 57 ++ tests/cases/11_strings.lua | 47 + tests/helpers.lua | 189 ++++ tests/run-valgrind.sh | 51 + tests/run.sh | 62 ++ tests/valgrind.supp | 15 + 21 files changed, 3252 insertions(+), 405 deletions(-) create mode 100644 tests/cases/01_many_textures.lua create mode 100644 tests/cases/02_explicit.lua create mode 100644 tests/cases/03_borrowed.lua create mode 100644 tests/cases/04_model_from_mesh.lua create mode 100644 tests/cases/05_sound_alias.lua create mode 100644 tests/cases/06_teardown.lua create mode 100644 tests/cases/07_inout.lua create mode 100644 tests/cases/08_pins.lua create mode 100644 tests/cases/08b_views.lua create mode 100644 tests/cases/08c_font_atlas.lua create mode 100644 tests/cases/09_pointers.lua create mode 100644 tests/cases/10_ram.lua create mode 100644 tests/cases/11_strings.lua create mode 100644 tests/helpers.lua create mode 100755 tests/run-valgrind.sh create mode 100755 tests/run.sh create mode 100644 tests/valgrind.supp diff --git a/Makefile b/Makefile index 05a24b7..658af09 100644 --- a/Makefile +++ b/Makefile @@ -32,6 +32,7 @@ API_DIR := $(BUILD_DIR)/api RLPARSER := $(BUILD_DIR)/rlparser RAYLIB_API := $(API_DIR)/raylib_api.lua BINDING := hate-no-d.lua +OWNERSHIP_SNAPSHOT := ownership.txt OBJ := $(BUILD_DIR)/hate-no-d.o BIN := hate-no-d @@ -257,6 +258,10 @@ help: @echo " make [all] CLI for the current platform + hate-no-d.lua" @echo " make bindings regenerate hate-no-d.lua only" @echo " make check-bindings verify hate-no-d.lua is reproducible and loads" + @echo " make test run the functional test matrix" + @echo " make check-valgrind run RAM-only tests under valgrind" + @echo " make ownership regenerate the ownership snapshot (ownership.txt)" + @echo " make check bindings + test matrix + valgrind" @echo " make print-config resolved configuration for the current target" @echo " make clean remove build/ and submodule build artifacts" @echo " make help this text" @@ -325,13 +330,29 @@ $(BINDING): gen-hate-no-d.lua $(API_DIR)/rlgl_api.lua $(API_DIR)/raymath_api.lua bindings: $(BINDING) -# Fail if regeneration is not byte-identical or the module does not load. +# Fail if regeneration is not byte-identical, the ownership classification +# changed, or the module does not load. check-bindings: $(BINDING) $(LUAJIT) gen-hate-no-d.lua --out=$(BUILD_DIR)/hate-no-d.lua.tmp $(GEN_FLAGS) cmp $(BINDING) $(BUILD_DIR)/hate-no-d.lua.tmp rm -f $(BUILD_DIR)/hate-no-d.lua.tmp + $(LUAJIT) gen-hate-no-d.lua --dump-ownership=$(BUILD_DIR)/ownership.txt $(GEN_FLAGS) + cmp $(OWNERSHIP_SNAPSHOT) $(BUILD_DIR)/ownership.txt $(LUAJIT) -e 'local M = dofile("$(BINDING)"); assert(type(M) == "table"); assert(type(M.GetMousePosition) == "function", "raylib"); assert(type(M.rlLoadIdentity) == "function", "rlgl"); assert(type(M.Vector2Add) == "function", "raymath"); print("bindings ok")' +# Regenerate the committed ownership classification snapshot. +ownership: + $(LUAJIT) gen-hate-no-d.lua --dump-ownership=$(OWNERSHIP_SNAPSHOT) $(GEN_FLAGS) + +test: $(LINK_TARGET) $(BINDING) + sh tests/run.sh + +check-valgrind: $(LINK_TARGET) $(BINDING) + sh tests/run-valgrind.sh + +check: all check-bindings test check-valgrind + @echo "check: ok" + # Resolved configuration for the current target; useful before a cross build. print-config: @echo "PLATFORM = $(PLATFORM)" @@ -366,4 +387,5 @@ clean: rm -f $(BINDING) rm -f hate-no-d.o # object from builds that predate the move into build/ -.PHONY: all clean print-config help bindings check-bindings +.PHONY: all clean print-config help bindings check-bindings \ + test check check-valgrind ownership diff --git a/README.md b/README.md index dbcdc96..9970853 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,68 @@ hate-no-d.exe quick-start.lua `hate-no-d.lua` is the generated raylib/rlgl/raymath binding; release archives ship it next to the binary. +## Resource ownership + +Every `Load*`/`Gen*` result that raylib hands to the caller is owned by the Lua +value you get back. hate-no-d attaches a finalizer to the underlying cdata, so +dropping the last reference is enough: + +```lua +local tex = hnd.LoadTexture("sprite.png") -- armed +tex = nil +collectgarbage() -- raylib UnloadTexture() runs here +``` + +This covers textures, render textures, shaders, meshes, models, materials, +fonts, waves, sounds, music streams, audio streams, images, automation event +lists, directory listings, VR stereo configs, and the raw-pointer loaders +(`LoadImageColors`, `LoadImagePalette`, `LoadFontData`, `LoadMaterials`, +`LoadModelAnimations`, `LoadRandomSequence`, `LoadWaveSamples`, +`LoadCodepoints`, `LoadTextLines`, `LoadFileData`, `CompressData`, +`DecompressData`, `DecodeDataBase64`, `ExportImageToMemory`, `MemAlloc`, and +rlgl's pixel readers). + +- **Readiness gates.** A finalizer never touches a dead subsystem. GPU releases + only run while a window is alive, audio releases only while the audio device + is alive, and anything still armed when a window is closed or recreated is + skipped rather than freed. `InitWindow`/`CloseWindow` bump an internal GPU + generation so stale handles are never unloaded against a new context. +- **`Unload*` is explicit and idempotent.** `hnd.UnloadImage(img)` frees + immediately, zeroes the struct, and is safe to call again. It also cancels + the finalizer, so a resource is never released twice. `M._ownership` exposes + `armed`/`released`/`skipped`/`errors` counters (mostly useful for tests). +- **Array loaders return their count.** Functions that fill a C `int *` count + out-parameter (`LoadImagePalette`, `LoadFontData`, `LoadMaterials`, + `LoadModelAnimations`, `LoadTextLines`, `LoadFileData`, `CompressData`, + `DecompressData`, `DecodeDataBase64`, `ExportImageToMemory`) now return + `pointer, count`. Passing a cdata still fills it, so existing code keeps + working; the extra return value is safe to ignore. +- **Views are never freed.** Values that alias raylib-owned memory are plain + copies: `font.texture`, `rt.texture`, `rt.depth`, `model.meshes[i]`, + `model.materials[i]`, `GetGlyphInfo()`, `GetFontDefault()`, + `GetShapesTexture()`, and `LoadDroppedFiles()`. Keep the owner alive while you + use a view — `GetGlyphInfo()`'s `image.data` points into the font. +- **Materials are special.** `UnloadMaterial`/the material finalizer free only + the `maps` array, never the shader or textures it references (those may be + shared). Textures assigned with `SetMaterialTexture` are pinned for the + lifetime of the material; `SetShapesTexture` pins the shapes texture, and + unloading that texture restores the previous one. +- **Mesh ownership transfers.** `LoadModelFromMesh(mesh)` consumes the mesh — + the model frees it. Calling `UnloadMesh` on the consumed handle is a no-op. + `LoadSoundAlias(src)` keeps `src` alive until the alias is released, and + `LoadMusicStreamFromMemory` keeps its buffer alive. +- **Raw memory.** `MemAlloc`/`MemRealloc` results are GC-managed; `MemFree` + cancels the finalizer before freeing, so explicit frees are safe. + `M.C` is the raw `ffi` namespace: calls made through it are unmanaged. +- **Process exit.** The CLI runs finalizers on normal exit (it calls + `lua_close`). `os.exit()` skips them; use `os.exit(code, true)` if you need + them to run. + +The ownership classification is exhaustive: the generator refuses to emit a +binding if any function's return shape is unclassified, and `make check-bindings` +diffs `ownership.txt` against the current raylib API. `make check` runs the test +suite (including a valgrind pass over the RAM-only cases). + ## Building Precompiled builds can be found on the [releases page](https://git.pbento.pt/pedro-bento/hate-no-d/releases). diff --git a/gen-hate-no-d.lua b/gen-hate-no-d.lua index acf304b..63a5cfe 100644 --- a/gen-hate-no-d.lua +++ b/gen-hate-no-d.lua @@ -36,8 +36,10 @@ local CFG = { rlgl = "build/api/rlgl_api.lua", raymath = "build/api/raymath_api.lua", out = "hate-no-d.lua", + out_explicit = false, use_rlgl = true, use_raymath = true, + dump_ownership = false, -- false | true (stdout) | path } local USAGE = [[ @@ -47,6 +49,8 @@ usage: luajit gen-hate-no-d.lua [options] --raylib=PATH raylib parser table (default: build/api/raylib_api.lua) --rlgl=PATH rlgl parser table (default: build/api/rlgl_api.lua) --raymath=PATH raymath parser table(default: build/api/raymath_api.lua) + --dump-ownership[=PATH] + write the ownership map to PATH (default: stdout) --no-rlgl skip rlgl --no-raymath skip raymath -h, --help this text @@ -63,17 +67,22 @@ end for i = 1, #arg do local a = arg[i] - local key, value = a:match("^%-%-([%w]+)=(.*)$") + local key, value = a:match("^%-%-([%w%-]+)=(.*)$") if key == "out" then CFG.out = value + CFG.out_explicit = true elseif key == "raylib" then CFG.raylib = value elseif key == "rlgl" then CFG.rlgl = value elseif key == "raymath" then CFG.raymath = value + elseif key == "dump-ownership" then + CFG.dump_ownership = (value ~= "") and value or true elseif key then die("unknown option --%s", key) + elseif a == "--dump-ownership" then + CFG.dump_ownership = true elseif a == "--no-rlgl" then CFG.use_rlgl = false elseif a == "--no-raymath" then @@ -133,6 +142,17 @@ if CFG.use_raymath then end end +local function find_define(data, name) + for _, d in ipairs(data.defines or {}) do + if d.name == name then + return d.value + end + end + return nil +end + +local version = tostring(find_define(raylib_api, "RAYLIB_VERSION") or "unknown") + ---------------------------------------------------------------------------- -- type model ---------------------------------------------------------------------------- @@ -514,18 +534,484 @@ local function ann_field(ftype) end -- Struct pointers that are genuinely in/out: the caller passes the handle and --- gets the (possibly mutated) handle back. +-- gets the (possibly mutated) handle back. Owned types are mutated in place +-- (address-of); the rest go through a one-element array copy. local OUT_STRUCT = { Image = true, Texture2D = true, Mesh = true, Wave = true, Material = true, Model = true, RenderTexture2D = true, Camera = true, AutomationEventList = true, } +-- Struct-pointer params that are not in/out: pass them through (optionally +-- converting a Lua table) instead of copying one element. +local INOUT_EXCLUDE = { + SetWindowIcons = true, +} + -- Functions whose struct-pointer parameters are pure outputs. Those params are -- optional on the Lua side and become extra return values. local OUT_OVERRIDES = { MatrixDecompose = { 2, 3, 4 }, } +---------------------------------------------------------------------------- +-- ownership classification (issue #4) +-- +-- Every function's return shape must land in exactly one bucket, or generation +-- dies. That is the guarantee: a raylib bump that adds an asset type or an +-- array loader cannot silently leak. +---------------------------------------------------------------------------- + +-- Resolve struct aliases to the canonical type (Texture2D -> Texture, ...). +local function canon(base) + local seen = {} + while ALIASES[base] and not seen[base] do + seen[base] = true + local target = ALIASES[base].target or ALIASES[base].type + base = parse_type(target).base + end + return base +end + +-- Struct values that own memory. `kind` gates the release on device readiness, +-- `release` is the C unloader (checked against the API tables). +local OWNED = { + Image = { kind = "ram", release = "UnloadImage" }, + Texture = { kind = "gpu", release = "UnloadTexture" }, + RenderTexture = { kind = "gpu", release = "UnloadRenderTexture" }, + Shader = { kind = "gpu", release = "UnloadShader" }, + Mesh = { kind = "gpu", release = "UnloadMesh" }, + Model = { kind = "gpu", release = "UnloadModel" }, + Material = { kind = "gpu", release = "UnloadMaterial" }, -- maps only, see _release_Material + Font = { kind = "gpu", release = "UnloadFont" }, + Wave = { kind = "ram", release = "UnloadWave" }, + Sound = { kind = "audio", release = "UnloadSound" }, + Music = { kind = "audio", release = "UnloadMusicStream" }, + AudioStream = { kind = "audio", release = "UnloadAudioStream" }, + AutomationEventList = { kind = "ram", release = "UnloadAutomationEventList" }, + FilePathList = { kind = "ram", release = "UnloadDirectoryFiles" }, + VrStereoConfig = { kind = "gpu", release = "UnloadVrStereoConfig" }, +} + +-- Struct returns that own no memory at all. +local VALUE_ONLY = { + Vector2 = true, Vector3 = true, Vector4 = true, Matrix = true, + float16 = true, float3 = true, + Color = true, Rectangle = true, Ray = true, BoundingBox = true, + RayCollision = true, + GlyphInfo = true, -- GlyphInfo.image aliases the font; never armed +} + +-- Struct returns owned elsewhere (raylib globals, or a view of another owner). +local BORROWED = { + GetShapesTexture = true, + GetFontDefault = true, + LoadDroppedFiles = true, -- aliases CORE.Window.dropFilepaths + GetGlyphInfo = true, -- GlyphInfo.image.data aliases the font's glyph array +} + +-- Pointer/array returns that must be freed by the caller. +local OWNED_POINTER = { + LoadImageColors = { kind = "ram", release = "UnloadImageColors" }, + LoadImagePalette = { kind = "ram", release = "UnloadImagePalette", count = "colorCount" }, + LoadFontData = { kind = "ram", release = "UnloadFontData", count = "glyphCount" }, + -- raylib has no UnloadMaterials(): free every material's maps, then the array. + LoadMaterials = { kind = "ram", release = "UnloadMaterial", count = "materialCount", + per_item = true, free = "MemFree" }, + LoadModelAnimations = { kind = "ram", release = "UnloadModelAnimations", count = "animCount", + init_count = true }, + LoadRandomSequence = { kind = "ram", release = "UnloadRandomSequence" }, + LoadWaveSamples = { kind = "ram", release = "UnloadWaveSamples" }, + LoadCodepoints = { kind = "ram", release = "UnloadCodepoints", count = "count" }, + LoadTextLines = { kind = "ram", release = "UnloadTextLines", count = "count" }, + LoadFileData = { kind = "ram", release = "UnloadFileData", count = "dataSize" }, + CompressData = { kind = "ram", release = "MemFree", count = "compDataSize" }, + DecompressData = { kind = "ram", release = "MemFree", count = "dataSize" }, + DecodeDataBase64 = { kind = "ram", release = "MemFree", count = "outputSize" }, + ExportImageToMemory = { kind = "ram", release = "MemFree", count = "fileSize" }, + MemAlloc = { kind = "ram", release = "MemFree" }, + MemRealloc = { kind = "ram", release = "MemFree" }, + rlReadScreenPixels = { kind = "ram", release = "MemFree" }, + rlReadTexturePixels = { kind = "ram", release = "MemFree" }, + rlLoadRenderBatch = { kind = "gpu", release = "rlUnloadRenderBatch" }, +} + +-- Pointer returns that must never be freed (raylib static buffers). +local BORROWED_STATIC = { + ComputeMD5 = true, ComputeSHA1 = true, ComputeSHA256 = true, -- static unsigned int[4] + GetWindowHandle = true, rlGetProcAddress = true, rlGetShaderLocsDefault = true, + TextSplit = true, -- static char* buffers +} + +-- char* returns that must be copied, then freed. +local OWNED_STRING = { + LoadFileText = "UnloadFileText", + LoadUTF8 = "UnloadUTF8", + EncodeDataBase64 = "MemFree", + TextReplaceAlloc = "MemFree", + TextReplaceBetweenAlloc = "MemFree", + TextInsertAlloc = "MemFree", +} + +-- char* returns owned by raylib / static: copy only. +local BORROWED_STRING = { + CodepointToUTF8 = true, GetApplicationDirectory = true, GetClipboardText = true, + GetDirectoryPath = true, GetFileExtension = true, GetFileName = true, + GetFileNameWithoutExt = true, GetGamepadName = true, GetKeyName = true, + GetMonitorName = true, GetPrevDirectoryPath = true, GetTextBetween = true, + GetWorkingDirectory = true, TextFormat = true, TextInsert = true, + TextJoin = true, TextRemoveSpaces = true, TextReplace = true, + TextReplaceBetween = true, TextSubtext = true, TextToCamel = true, + TextToLower = true, TextToPascal = true, TextToSnake = true, TextToUpper = true, + rlGetPixelFormatName = true, +} + +-- Pointer returns that are genuinely inert handles (none today). A new raylib +-- pointer return must be listed here, in OWNED_POINTER or in BORROWED_STATIC. +local NON_OWNING = {} + +-- Functions that move ownership of a parameter to their return value. +local CONSUMES = { + LoadModelFromMesh = { param = "mesh", type = "Mesh", valid_field = "meshCount" }, +} + +-- Functions that retain a parameter: it becomes a finalizer upvalue. +local KEEPS = { + LoadSoundAlias = { keep = "source", own = "SoundAlias", release = "UnloadSoundAlias" }, + LoadMusicStreamFromMemory = { keep = "data", own = "Music" }, +} + +-- Owner variants that are not plain struct types. +local EXTRA_OWNERS = { + -- LoadSoundAlias shares the sample data with its source, so it must NOT be + -- released with UnloadSound. + SoundAlias = { kind = "audio", release = "UnloadSoundAlias", valid = "Sound" }, +} + +-- Window instance counter: finalizers armed under an older GPU generation +-- refuse to run, because the GL context (and its ids) is gone. +local POST_CALL = { + -- A new or destroyed GL context invalidates every pin: keeping them would + -- both point at dead ids and keep the pinned Lua objects alive forever. + InitWindow = "_gpu_gen = _gpu_gen + 1; _st.gen = _gpu_gen; _fin_cache = {}; _pins.shapes = nil; _pins.shapes_prev = nil; _pins.material = {}; _pins.auto = nil", + CloseWindow = "_gpu_gen = _gpu_gen + 1; _st.gen = _gpu_gen; _fin_cache = {}; _pins.shapes = nil; _pins.shapes_prev = nil; _pins.material = {}; _pins.auto = nil", +} + +-- Extra doc lines for wrappers whose lifetime contract is easy to get wrong. +local EXTRA_DOC = { + GetGlyphInfo = "NOTE: the returned GlyphInfo.image.data aliases the font's glyph array; keep the font alive while using it.", + GetShapesTexture = "NOTE: this is a view; the texture is owned by raylib.", + GetFontDefault = "NOTE: this is a view; raylib owns the default font.", + LoadDroppedFiles = "NOTE: this is a view of raylib's internal dropped-file state.", +} + +-- Functions emitted by hand (signature or lifetime differs from the C shape). +local SPECIAL = { + TextFormat = true, + TraceLog = true, + CodepointToUTF8 = true, + GenImageFontAtlas = true, + LoadModelFromMesh = true, + LoadSoundAlias = true, + LoadMusicStreamFromMemory = true, + SetShapesTexture = true, + SetMaterialTexture = true, + SetAutomationEventList = true, + SetWindowIcons = true, + MemAlloc = true, + MemRealloc = true, + MemFree = true, +} + +local INOUT_ALLOW = { Camera = true } + +-- Small validity predicates: a failed load must not be armed. +local VALID = { + Image = "x.data ~= nil", + Texture = "x.id ~= 0", + RenderTexture = "x.id ~= 0", + Shader = "x.id ~= 0", + Font = "x.texture.id ~= 0", + Wave = "x.data ~= nil", + Sound = "x.stream.buffer ~= nil", + Music = "x.stream.buffer ~= nil", + AudioStream = "x.buffer ~= nil", + AutomationEventList = "x.events ~= nil", + FilePathList = "x.paths ~= nil", + Model = "x.meshCount > 0", +} + +local funcs_by_name = {} +for _, f in ipairs(FUNCS) do + funcs_by_name[f.name] = f +end + +local function has_func(name) + local f = funcs_by_name[name] + return f ~= nil and not is_skipped(f) +end + +-- Buckets: owned | value | borrowed | owned_pointer | borrowed_static | +-- owned_string | borrowed_string | non_owning +local CLASS = {} + +local function classify(f) + local name = f.name + local ret = parse_type(f.returnType) + + if ret.base == "char" and ret.ptr == 1 then + if OWNED_STRING[name] then + return { bucket = "owned_string", release = OWNED_STRING[name], kind = "ram" } + end + if BORROWED_STRING[name] then + return { bucket = "borrowed_string" } + end + return nil, string.format("unclassified char* return %s", name) + end + + if ret.ptr > 0 then + local op = OWNED_POINTER[name] + if op then + return { + bucket = "owned_pointer", type = canon(ret.base), kind = op.kind, + release = op.release, count = op.count, init_count = op.init_count, + per_item = op.per_item, free = op.free, + } + end + if BORROWED_STATIC[name] then + return { bucket = "borrowed_static" } + end + if NON_OWNING[name] then + return { bucket = "non_owning" } + end + return nil, string.format("unclassified pointer return %s -> %s", name, norm(f.returnType)) + end + + if ret.base == "void" then + return { bucket = "non_owning" } + end + + if is_structish(ret.base) then + local c = canon(ret.base) + -- BORROWED wins over OWNED: that is the override mechanism for raylib + -- globals that have an owned type (GetFontDefault, LoadDroppedFiles). + if BORROWED[name] then + return { bucket = "borrowed", type = c } + end + if OWNED[c] then + return { bucket = "owned", type = c, kind = OWNED[c].kind, release = OWNED[c].release } + end + local op = OWNED_POINTER[name] + if op then + -- value structs with an unload function (rlLoadRenderBatch) + return { bucket = "owned_pointer", type = c, kind = op.kind, release = op.release } + end + if VALUE_ONLY[c] then + return { bucket = "value", type = c } + end + return nil, string.format("unclassified struct return %s -> %s", name, c) + end + + return { bucket = "non_owning" } +end + +local function validate_ownership() + local errors = {} + local function bad(fmt, ...) + errors[#errors + 1] = string.format(fmt, ...) + end + local function need_func(name, where) + if not has_func(name) then + bad("%s: %s is not an API function", where, tostring(name)) + end + end + local function need_struct(name, where) + if not STRUCTS[name] then + bad("%s: %s is not an API struct", where, tostring(name)) + end + end + + -- Total classification: every emitted function lands in exactly one bucket. + for _, f in ipairs(FUNCS) do + if not is_skipped(f) then + local cls, err = classify(f) + if cls then + CLASS[f.name] = cls + else + bad("%s", err) + end + end + end + + for t, o in pairs(OWNED) do + need_struct(t, "OWNED") + need_func(o.release, "OWNED." .. t) + if o.kind ~= "ram" and o.kind ~= "gpu" and o.kind ~= "audio" then + bad("OWNED.%s: bad kind %q", t, tostring(o.kind)) + end + if VALUE_ONLY[t] then + bad("%s is in both OWNED and VALUE_ONLY", t) + end + end + for t in pairs(VALUE_ONLY) do + need_struct(t, "VALUE_ONLY") + end + for fn in pairs(BORROWED) do + need_func(fn, "BORROWED") + if OWNED_POINTER[fn] or OWNED_STRING[fn] or CONSUMES[fn] or KEEPS[fn] then + bad("%s is in both BORROWED and an owning table", fn) + end + end + for fn in pairs(BORROWED_STATIC) do + need_func(fn, "BORROWED_STATIC") + end + for fn in pairs(BORROWED_STRING) do + need_func(fn, "BORROWED_STRING") + end + for fn, release in pairs(OWNED_STRING) do + need_func(fn, "OWNED_STRING") + need_func(release, "OWNED_STRING." .. fn) + end + for fn, o in pairs(OWNED_POINTER) do + need_func(fn, "OWNED_POINTER") + need_func(o.release, "OWNED_POINTER." .. fn) + if o.free then + need_func(o.free, "OWNED_POINTER." .. fn .. ".free") + end + if o.count then + local found = false + for _, p in ipairs(params_of(funcs_by_name[fn])) do + if p.name == o.count then + found = true + local pt = parse_type(p.type) + if pt.ptr ~= 1 or not INTEGER[pt.base] then + bad("OWNED_POINTER.%s.count %s is not an integer out-param", fn, o.count) + end + end + end + if not found then + bad("OWNED_POINTER.%s.count %s is not a parameter", fn, o.count) + end + end + end + for fn in pairs(NON_OWNING) do + need_func(fn, "NON_OWNING") + end + for fn, c in pairs(CONSUMES) do + need_func(fn, "CONSUMES") + local found = false + for _, p in ipairs(params_of(funcs_by_name[fn])) do + if p.name == c.param then + found = true + if canon(parse_type(p.type).base) ~= c.type then + bad("CONSUMES.%s.param %s is not a %s", fn, c.param, c.type) + end + end + end + if not found then + bad("CONSUMES.%s.param %s is not a parameter", fn, c.param) + end + end + for fn, k in pairs(KEEPS) do + need_func(fn, "KEEPS") + if k.release then + need_func(k.release, "KEEPS." .. fn) + end + if not OWNED[k.own] and not EXTRA_OWNERS[k.own] then + bad("KEEPS.%s.own %s is not an owned type", fn, tostring(k.own)) + end + local found = false + for _, p in ipairs(params_of(funcs_by_name[fn])) do + if p.name == k.keep then + found = true + end + end + if not found then + bad("KEEPS.%s.keep %s is not a parameter", fn, k.keep) + end + end + for fn in pairs(POST_CALL) do + need_func(fn, "POST_CALL") + end + for fn in pairs(SPECIAL) do + need_func(fn, "SPECIAL") + end + + -- In/out struct params must be owned types (or an explicit exception). + for t in pairs(OUT_STRUCT) do + if not OWNED[canon(t)] and not INOUT_ALLOW[t] then + bad("OUT_STRUCT.%s is not an owned type", t) + end + end + + if #errors > 0 then + for _, e in ipairs(errors) do + io.stderr:write("gen-hate-no-d: ownership: " .. e .. "\n") + end + die("%d ownership classification error(s)", #errors) + end +end + +validate_ownership() + +-- Counts for the summary line and the ownership map. +local function ownership_summary() + local n = { + owned = 0, value = 0, borrowed = 0, owned_pointer = 0, + borrowed_static = 0, owned_string = 0, borrowed_string = 0, non_owning = 0, + } + for _, f in ipairs(FUNCS) do + local cls = CLASS[f.name] + if cls then + n[cls.bucket] = n[cls.bucket] + 1 + end + end + return n +end + +local function ownership_map() + local lines = {} + local fmt = "%-6s %-36s %-16s %-5s %s" + local types = {} + for t in pairs(OWNED) do + types[#types + 1] = t + end + table.sort(types) + for _, t in ipairs(types) do + lines[#lines + 1] = string.format(fmt, "struct", t, "owned", OWNED[t].kind, OWNED[t].release) + end + local values = {} + for t in pairs(VALUE_ONLY) do + values[#values + 1] = t + end + table.sort(values) + for _, t in ipairs(values) do + lines[#lines + 1] = string.format(fmt, "struct", t, "value", "-", "-") + end + for _, f in ipairs(FUNCS) do + local cls = CLASS[f.name] + if cls then + lines[#lines + 1] = string.format(fmt, "func", f.name, cls.bucket, + cls.kind or "-", cls.release or "-") + end + end + table.sort(lines) + local header = { + "# hate-no-d ownership map", + "# raylib " .. version, + "# class: owned | value | borrowed | owned_pointer | borrowed_static |" .. + " owned_string | borrowed_string | non_owning", + } + local all = {} + for _, h in ipairs(header) do + all[#all + 1] = h + end + for _, l in ipairs(lines) do + all[#all + 1] = l + end + return table.concat(all, "\n") .. "\n" +end + + local function ann_param(p, is_out) local pt = parse_type(p.type) if pt.base == "..." then @@ -594,6 +1080,9 @@ local function out_params(f) end return out end + if INOUT_EXCLUDE[f.name] then + return out + end local params = params_of(f) for i, p in ipairs(params) do local pt = parse_type(p.type) @@ -666,18 +1155,6 @@ local function clean_description(s) return s end -local version = "unknown" -local function find_define(data, name) - for _, d in ipairs(data.defines or {}) do - if d.name == name then - return d.value - end - end - return nil -end - -version = tostring(find_define(raylib_api, "RAYLIB_VERSION") or "unknown") - w("--[[") w(" hate-no-d.lua - generated by gen-hate-no-d.lua, do not edit.") w("") @@ -796,6 +1273,382 @@ w(" return a") w("end") w("") +---------------------------------------------------------------------------- +-- ownership runtime (emitted only when at least one owned type exists) +---------------------------------------------------------------------------- + +local function emit_ownership_preamble() + local owned_types = {} + for t in pairs(OWNED) do + owned_types[#owned_types + 1] = t + end + table.sort(owned_types) + + local extra_types = {} + for t in pairs(EXTRA_OWNERS) do + extra_types[#extra_types + 1] = t + end + table.sort(extra_types) + + local ptr_loaders = {} + for fn in pairs(OWNED_POINTER) do + if not SPECIAL[fn] then + ptr_loaders[#ptr_loaders + 1] = fn + end + end + table.sort(ptr_loaders) + + w("-- ---------------------------------------------------------------------------") + w("-- Resource ownership") + w("--") + w("-- Owned struct values returned by raylib are armed with an FFI finalizer that") + w("-- calls the matching Unload* function. The finalizer only runs while the") + w("-- device it needs is still up, and GPU owners are pinned to the window") + w("-- generation they were created in. M.C stays raw: nothing is armed for direct") + w("-- ffi.C calls. See 'Resource ownership' in README.md.") + w("--") + w("-- One finalizer slot per cdata: a second ffi.gc() replaces the first. Never") + w("-- arm views/reference cdata (model.meshes[i], rt.texture, ...): only values") + w("-- that came straight out of a C return are owned.") + w("-- ---------------------------------------------------------------------------") + w("---@class raylib.ownership_stats") + w("---@field armed integer resources handed to the GC with a finalizer") + w("---@field released integer finalizers that actually freed a resource") + w("---@field skipped integer finalizers that refused (device gone / stale generation)") + w("---@field errors integer finalizers whose release call raised") + w("---@field gen integer current GPU generation (window instance)") + w("---@field reset fun()") + w("M._ownership = { armed = 0, released = 0, skipped = 0, errors = 0, gen = 0 }") + w("local _st = M._ownership") + w("function _st.reset()") + w(" _st.armed, _st.released, _st.skipped, _st.errors = 0, 0, 0, 0") + w("end") + w("") + w("local _gpu_gen = 0") + w('local _dead = setmetatable({}, { __mode = "k" })') + w('local _attached = setmetatable({}, { __mode = "k" })') + w("local _fin_cache = {}") + w("") + w("local _pins = {") + w(" shapes = nil,") + w(" shapes_prev = nil,") + w(" auto = nil,") + w(" material = {},") + w("}") + w("") + w("local function _can_unload(kind)") + w(' if kind == "gpu" then return C.IsWindowReady() end') + w(' if kind == "audio" then return C.IsAudioDeviceReady() end') + w(" return true") + w("end") + w("") + w("-- `keep` is the release function's optional second argument (owned extras,") + w("-- retained buffers). It is also an upvalue here, which is what keeps it alive") + w("-- until this finalizer runs: weak tables are cleared before finalizers, so a") + w("-- weak map cannot be used for keep-alive.") + w("local function _fire(kind, gen, release, x, keep)") + w(' if kind == "gpu" and gen ~= _gpu_gen then') + w(" _st.skipped = _st.skipped + 1") + w(" return") + w(" end") + w(" if not _can_unload(kind) then") + w(" _st.skipped = _st.skipped + 1") + w(" return") + w(" end") + w(" local ok = pcall(release, x, keep)") + w(" if ok then _st.released = _st.released + 1 else _st.errors = _st.errors + 1 end") + w(" -- keep is referenced here so the closure retains it until finalization.") + w(" if keep ~= nil then keep = nil end") + w("end") + w("") + w("-- One finalizer closure per (release, generation), not per object.") + w("local function _finalizer(kind, gen, release)") + w(" local by_gen = _fin_cache[release]") + w(" if by_gen == nil then") + w(" by_gen = {}") + w(" _fin_cache[release] = by_gen") + w(" end") + w(" local fin = by_gen[gen]") + w(" if fin == nil then") + w(" fin = function(x) _fire(kind, gen, release, x, nil) end") + w(" by_gen[gen] = fin") + w(" end") + w(" return fin") + w("end") + w("") + w("local function _arm(kind, release, valid, x, keep)") + w(" if x == nil then return x end") + w(" if valid ~= nil and not valid(x) then return x end") + w(" -- Pointer cdata is keyed by address, and the allocator reuses addresses") + w(" -- after a free: a stale _dead entry must never suppress this allocation.") + w(" _dead[x] = nil") + w(" _st.armed = _st.armed + 1") + w(" local gen = _gpu_gen") + w(" if keep ~= nil then") + w(" return ffi.gc(x, function(y) _fire(kind, gen, release, y, keep) end)") + w(" end") + w(" return ffi.gc(x, _finalizer(kind, gen, release))") + w("end") + w("") + w("local function _free_attached(x)") + w(" local extra = _attached[x]") + w(" if extra == nil then return nil end") + w(" _attached[x] = nil") + w(" for i = 1, #extra do C.MemFree(extra[i]) end") + w(" return extra") + w("end") + w("") + w("-- Raw pointer release: MemAlloc/MemRealloc and the loaders that hand back") + w("-- RL_MALLOC'd buffers (MemFree is free()).") + w("local function _release_raw(p)") + w(" if p == nil or _dead[p] then return end") + w(" _dead[p] = true") + w(" C.MemFree(p)") + w("end") + w("") + + for _, t in ipairs(owned_types) do + local release = OWNED[t].release + if t == "Image" or t == "Font" then + w("local function _release_" .. t .. "(x, extra)") + w(" if _dead[x] then return end") + w(" _dead[x] = true") + w(" if extra == nil then extra = _attached[x] end") + w(" _attached[x] = nil") + w(" if extra ~= nil then") + w(" for i = 1, #extra do C.MemFree(extra[i]) end") + w(" end") + w(" C." .. release .. "(x)") + w(" ffi.fill(x, ffi.sizeof(x))") + w("end") + elseif t == "Texture" then + w("local function _release_Texture(x)") + w(" if _dead[x] then return end") + w(" _dead[x] = true") + w(" local prev = _pins.shapes_prev") + w(" if _pins.shapes ~= nil and _pins.shapes.id == x.id then") + w(" if prev ~= nil and prev.tex ~= nil and prev.tex.id ~= 0 and C.IsWindowReady() then") + w(" C.SetShapesTexture(prev.tex, prev.rec)") + w(" end") + w(" _pins.shapes = nil") + w(" _pins.shapes_prev = nil") + w(" end") + w(" C.UnloadTexture(x)") + w(" ffi.fill(x, ffi.sizeof(x))") + w("end") + elseif t == "Model" then + w("local function _release_Model(x)") + w(" if _dead[x] then return end") + w(" _dead[x] = true") + w(" if x.materials ~= nil then") + w(" for i = 0, x.materialCount - 1 do") + w(" local maps = x.materials[i].maps") + w(" if maps ~= nil then") + w(' _pins.material[tostring(ffi.cast("void *", maps))] = nil') + w(" end") + w(" end") + w(" end") + w(" C.UnloadModel(x)") + w(" ffi.fill(x, ffi.sizeof(x))") + w("end") + elseif t == "Material" then + w("-- UnloadMaterial() deletes the material's shader and map textures, which may") + w("-- be owned by separate Lua objects. The Material owner owns only its maps.") + w("local function _release_Material(x)") + w(" if _dead[x] then return end") + w(" _dead[x] = true") + w(" if x.maps ~= nil then") + w(' _pins.material[tostring(ffi.cast("void *", x.maps))] = nil') + w(" C.MemFree(x.maps)") + w(" end") + w(" ffi.fill(x, ffi.sizeof(x))") + w("end") + elseif t == "AutomationEventList" then + w("local function _release_AutomationEventList(x)") + w(" if _dead[x] then return end") + w(" _dead[x] = true") + w(" local pinned = _pins.auto") + w(" if pinned ~= nil and (pinned == x or (pinned.events ~= nil and pinned.events == x.events)) then") + w(" _pins.auto = nil") + w(" C.SetAutomationEventList(nil)") + w(" end") + w(" C.UnloadAutomationEventList(x)") + w(" ffi.fill(x, ffi.sizeof(x))") + w("end") + else + w("local function _release_" .. t .. "(x)") + w(" if _dead[x] then return end") + w(" _dead[x] = true") + w(" C." .. release .. "(x)") + w(" ffi.fill(x, ffi.sizeof(x))") + w("end") + end + w("") + end + + for _, t in ipairs(extra_types) do + local release = EXTRA_OWNERS[t].release + w("local function _release_" .. t .. "(x)") + w(" if _dead[x] then return end") + w(" _dead[x] = true") + w(" C." .. release .. "(x)") + w(" ffi.fill(x, ffi.sizeof(x))") + w("end") + w("") + end + + for _, fn in ipairs(ptr_loaders) do + local o = OWNED_POINTER[fn] + local relf = funcs_by_name[o.release] + local nparams = #params_of(relf) + if o.release == "MemFree" then + -- released through _release_raw + elseif o.per_item then + w("local function _release_" .. fn .. "(p, n)") + w(" if p == nil or _dead[p] then return end") + w(" _dead[p] = true") + w(" n = n or 0") + w(" for i = 0, n - 1 do C." .. o.release .. "(p[i]) end") + w(" C." .. (o.free or "MemFree") .. "(p)") + w("end") + w("") + else + w("local function _release_" .. fn .. "(p, n)") + w(" if p == nil or _dead[p] then return end") + w(" _dead[p] = true") + if nparams >= 2 then + w(" C." .. o.release .. "(p, n or 0)") + else + w(" C." .. o.release .. "(p)") + end + w("end") + w("") + end + end + + local valid_types = {} + for _, t in ipairs(owned_types) do + if VALID[t] then + valid_types[#valid_types + 1] = t + end + end + for _, t in ipairs(extra_types) do + local v = EXTRA_OWNERS[t].valid + if v and VALID[v] then + valid_types[#valid_types + 1] = t + end + end + table.sort(valid_types) + for _, t in ipairs(valid_types) do + local v = VALID[t] or VALID[EXTRA_OWNERS[t].valid] + w("local function _valid_" .. t .. "(x) return " .. v .. " end") + end + if #valid_types > 0 then + w("") + end + + local function owner_expr(t, keep) + local kind, release, valid + if OWNED[t] then + kind, release, valid = OWNED[t].kind, OWNED[t].release, VALID[t] + else + local e = EXTRA_OWNERS[t] + kind, release, valid = e.kind, e.release, VALID[e.valid] + end + local valid_arg = valid and ("_valid_" .. t) or "nil" + local args = "x" + if keep then + args = "x, keep" + end + return kind, release, valid_arg, args + end + + for _, t in ipairs(owned_types) do + local kind, release, valid_arg, args = owner_expr(t, false) + w("local function _own_" .. t .. "(" .. args .. ")") + w(' return _arm("' .. kind .. '", _release_' .. t .. ", " .. valid_arg .. ", x)") + w("end") + w("") + end + + -- keep variants: the retained object becomes a finalizer upvalue + local keep_types = {} + for _, k in pairs(KEEPS) do + if k.own then + keep_types[k.own] = true + end + end + local keep_order = {} + for t in pairs(keep_types) do + keep_order[#keep_order + 1] = t + end + table.sort(keep_order) + for _, t in ipairs(keep_order) do + local kind, release, valid_arg = owner_expr(t, true) + w("local function _own_" .. t .. "_keep(x, keep)") + w(' return _arm("' .. kind .. '", _release_' .. t .. ", " .. valid_arg .. ", x, keep)") + w("end") + w("") + end + + for _, fn in ipairs(ptr_loaders) do + local o = OWNED_POINTER[fn] + local has_count = o.count ~= nil + local sig = has_count and "p, n" or "p" + local release = (o.release == "MemFree") and "_release_raw" or ("_release_" .. fn) + w("local function _own_ptr_" .. fn .. "(" .. sig .. ")") + if has_count then + -- The count is needed by the release call (UnloadFontData, + -- UnloadMaterials, UnloadModelAnimations, UnloadTextLines) and doubles as + -- the keep-alive upvalue that makes the closure per-object. + w(' return _arm("' .. o.kind .. '", ' .. release .. ", nil, p, n)") + else + w(' return _arm("' .. o.kind .. '", ' .. release .. ", nil, p)") + end + w("end") + w("") + end + + w("local function _own_raw(p)") + w(' return _arm("ram", _release_raw, nil, p)') + w("end") + w("") + w("-- GenImageFontAtlas: the Rectangle* out-param belongs to the Image. The") + w("-- explicit-unload path finds it through _attached; the finalizer carries it") + w("-- as an upvalue (weak tables are cleared before finalizers run).") + w("local function _own_Image_extra(x, extra)") + w(" if extra == nil then return _own_Image(x) end") + w(" if x == nil or x.data == nil then") + w(" for i = 1, #extra do C.MemFree(extra[i]) end") + w(" return x") + w(" end") + w(" _attached[x] = extra") + w(" _st.armed = _st.armed + 1") + w(" local gen = _gpu_gen") + w(" return ffi.gc(x, function(y) _fire(\"ram\", gen, _release_Image, y, extra) end)") + w("end") + w("") + w("-- Ownership of a struct value moves to another object (LoadModelFromMesh):") + w("-- disarm it, mark it dead and zero it so a stale unload is a no-op.") + w("local function _consume(x)") + w(" if x == nil then return end") + w(" ffi.gc(x, nil)") + w(" _dead[x] = true") + w(" ffi.fill(x, ffi.sizeof(x))") + w("end") + w("") + w("local function _consume_ptr(p)") + w(" if p == nil then return end") + w(" ffi.gc(p, nil)") + w(" _dead[p] = true") + w("end") + w("") +end + +if next(OWNED) then + emit_ownership_preamble() +end + ---------------------------------------------------------------------------- -- constants ---------------------------------------------------------------------------- @@ -987,26 +1840,29 @@ local function lua_name(name) return name end -local RET_OWNER = { - LoadFileText = "UnloadFileText", - LoadUTF8 = "UnloadUTF8", - EncodeDataBase64 = "MemFree", - TextReplaceAlloc = "MemFree", - TextReplaceBetweenAlloc = "MemFree", - TextInsertAlloc = "MemFree", -} +-- Explicit unload functions: disarm the finalizer, then release through the +-- same idempotent helper the finalizer uses. +local RELEASE_OWNER = {} +for t, o in pairs(OWNED) do + RELEASE_OWNER[o.release] = t +end +for t, e in pairs(EXTRA_OWNERS) do + RELEASE_OWNER[e.release] = t +end -local SPECIAL = { - TextFormat = true, - TraceLog = true, - CodepointToUTF8 = true, -} +local POINTER_RELEASE = {} +for fn, o in pairs(OWNED_POINTER) do + if o.release ~= "MemFree" and not RELEASE_OWNER[o.release] then + POINTER_RELEASE[o.release] = fn + end +end local emitted_wrappers = 0 local function emit_special(f) + local desc = clean_description(f.description) if f.name == "TextFormat" then - w("---" .. (clean_description(f.description) or "Text formatting")) + w("---" .. (desc or "Text formatting")) w("---@param fmt string") w("---@param ... any") w("---@return string") @@ -1018,7 +1874,7 @@ local function emit_special(f) w("end") w("") elseif f.name == "TraceLog" then - w("---" .. (clean_description(f.description) or "Show trace log messages")) + w("---" .. (desc or "Show trace log messages")) w("---@param level integer") w("---@param fmt string") w("---@param ... any") @@ -1032,7 +1888,7 @@ local function emit_special(f) w("end") w("") elseif f.name == "CodepointToUTF8" then - w("---" .. (clean_description(f.description) or "Encode a codepoint")) + w("---" .. (desc or "Encode a codepoint")) w("---@param codepoint integer") w("---@return string|nil") w("function M.CodepointToUTF8(codepoint)") @@ -1042,6 +1898,151 @@ local function emit_special(f) w(" return ffi_string(p, size[0])") w("end") w("") + elseif f.name == "GenImageFontAtlas" then + w("---" .. (desc or "Generate image font atlas using chars info")) + w("---@param glyphs raylib.GlyphInfo[]|ffi.cdata*") + w("---@param glyphCount integer") + w("---@param fontSize integer") + w("---@param padding integer") + w("---@param packMethod integer") + w("---@return raylib.Image, ffi.cdata*") + w("-- NOTE: the Rectangle* out-param belongs to the returned Image and is") + w("-- released with it; the second result is a borrowed view.") + w("function M.GenImageFontAtlas(glyphs, glyphCount, fontSize, padding, packMethod)") + w(" local _a1") + w(' if type(glyphs) == "table" then _a1 = to_array("GlyphInfo", glyphs) else _a1 = glyphs end') + w(' local _recs = ffi.new("Rectangle *[1]")') + w(" local _img = C.GenImageFontAtlas(_a1, _recs, glyphCount, fontSize, padding, packMethod)") + w(" if _recs[0] == nil then") + w(" return _own_Image(_img), nil") + w(" end") + w(' return _own_Image_extra(_img, { ffi.cast("void *", _recs[0]) }), _recs[0]') + w("end") + w("") + elseif f.name == "LoadModelFromMesh" then + w("---" .. (desc or "Load model from generated mesh")) + w("---@param mesh raylib.Mesh") + w("---@return raylib.Model") + w("-- NOTE: the mesh's data becomes part of the model; the mesh is consumed") + w("-- (disarmed and zeroed), so a later UnloadMesh(mesh) is a no-op.") + w("function M.LoadModelFromMesh(mesh)") + w(" local _r = C.LoadModelFromMesh(mesh)") + w(" local _o = _own_Model(_r)") + w(" if _r.meshCount > 0 then _consume(mesh) end") + w(" return _o") + w("end") + w("") + elseif f.name == "LoadSoundAlias" then + w("---" .. (desc or "Load sound alias sharing same sample data")) + w("---@param source raylib.Sound") + w("---@return raylib.Sound") + w("-- NOTE: the alias shares the source's sample data; the source is kept") + w("-- alive until the alias is released, and the alias is released with") + w("-- UnloadSoundAlias (not UnloadSound).") + w("function M.LoadSoundAlias(source)") + w(" return _own_SoundAlias_keep(C.LoadSoundAlias(source), source)") + w("end") + w("") + elseif f.name == "LoadMusicStreamFromMemory" then + w("---" .. (desc or "Load music stream from data")) + w("---@param fileType string") + w("---@param data string|integer[]|ffi.cdata*") + w("---@param dataSize integer") + w("---@return raylib.Music") + w("-- NOTE: raylib retains the buffer; it is kept alive until the Music is") + w("-- released (a finalizer upvalue, not a weak map).") + w("function M.LoadMusicStreamFromMemory(fileType, data, dataSize)") + w(" local _a2") + w(' if type(data) == "string" then _a2 = ffi.cast("const unsigned char *", data)') + w(' elseif type(data) == "table" then _a2 = to_array("unsigned char", data)') + w(" else _a2 = data end") + w(" return _own_Music_keep(C.LoadMusicStreamFromMemory(fileType, _a2, dataSize), _a2)") + w("end") + w("") + elseif f.name == "SetShapesTexture" then + w("---" .. (desc or "Set texture and rectangle to be used on shapes drawing")) + w("---@param texture raylib.Texture2D") + w("---@param rec raylib.Rectangle|ffi.cdata*") + w("---@return nil") + w("function M.SetShapesTexture(texture, rec)") + w(' if type(rec) == "table" then rec = ffi.new("Rectangle", rec) end') + w(" if C.IsWindowReady() then") + w(" _pins.shapes_prev = { tex = C.GetShapesTexture(), rec = C.GetShapesTextureRectangle() }") + w(" end") + w(" _pins.shapes = texture") + w(" C.SetShapesTexture(texture, rec)") + w("end") + w("") + elseif f.name == "SetAutomationEventList" then + w("---" .. (desc or "Set automation event list to record to")) + w("---@param list? raylib.AutomationEventList") + w("---@return nil") + w("-- NOTE: raylib stores the pointer, so the list is pinned until it is") + w("-- unloaded or replaced (previously this passed a temporary array).") + w("function M.SetAutomationEventList(list)") + w(" if list == nil then") + w(" _pins.auto = nil") + w(" C.SetAutomationEventList(nil)") + w(" return") + w(" end") + w(" _pins.auto = list") + w(' C.SetAutomationEventList(ffi.cast("AutomationEventList *", list))') + w("end") + w("") + elseif f.name == "SetMaterialTexture" then + w("---" .. (desc or "Set texture for a material map type")) + w("---@param material raylib.Material") + w("---@param mapType integer") + w("---@param texture raylib.Texture2D") + w("---@return nil") + w("-- NOTE: the texture is pinned by the material's maps address (the material") + w("-- may be a reference cdata such as model.materials[i]).") + w("function M.SetMaterialTexture(material, mapType, texture)") + w(" if material.maps ~= nil then") + w(' _pins.material[tostring(ffi.cast("void *", material.maps))] = texture') + w(" end") + w(' C.SetMaterialTexture(ffi.cast("Material *", material), mapType, texture)') + w("end") + w("") + elseif f.name == "SetWindowIcons" then + w("---" .. (desc or "Set window icons")) + w("---@param images raylib.Image[]|ffi.cdata*") + w("---@param count integer") + w("---@return nil") + w("function M.SetWindowIcons(images, count)") + w(" local _a1") + w(' if type(images) == "table" then _a1 = to_array("Image", images) else _a1 = images end') + w(" C.SetWindowIcons(_a1, count)") + w("end") + w("") + elseif f.name == "MemAlloc" then + w("---" .. (desc or "Internal memory allocator")) + w("---@param size integer") + w("---@return ffi.cdata*") + w("function M.MemAlloc(size)") + w(" return _own_raw(C.MemAlloc(size))") + w("end") + w("") + elseif f.name == "MemRealloc" then + w("---" .. (desc or "Internal memory reallocator")) + w("---@param ptr ffi.cdata*") + w("---@param size integer") + w("---@return ffi.cdata*") + w("function M.MemRealloc(ptr, size)") + w(" _consume_ptr(ptr)") + w(" return _own_raw(C.MemRealloc(ptr, size))") + w("end") + w("") + elseif f.name == "MemFree" then + w("---" .. (desc or "Internal memory free")) + w("---@param ptr ffi.cdata*") + w("---@return nil") + w("function M.MemFree(ptr)") + w(" if ptr == nil then return end") + w(" ffi.gc(ptr, nil)") + w(" _release_raw(ptr)") + w("end") + w("") end emitted_wrappers = emitted_wrappers + 1 end @@ -1049,6 +2050,10 @@ end local function emit_function(f) local params = params_of(f) local outs = out_params(f) + local cls = CLASS[f.name] + if cls == nil then + die("no ownership classification for %s", f.name) + end local sig = {} local pre = {} @@ -1056,27 +2061,66 @@ local function emit_function(f) local arg_ann = {} local out_vars = {} local out_ann = {} + local arg_expr = {} + local raw_names = {} + + local ptr_info = OWNED_POINTER[f.name] + local count_idx = nil + if ptr_info and ptr_info.count and not SPECIAL[f.name] then + for i, p in ipairs(params) do + if p.name == ptr_info.count then + count_idx = i + end + end + end for i, p in ipairs(params) do local pt = parse_type(p.type) local name = lua_name(p.name) + raw_names[i] = name if pt.base == "..." then sig[#sig + 1] = "..." args[#args + 1] = "..." + arg_expr[i] = "..." arg_ann[#arg_ann + 1] = "---@param ... any" + elseif i == count_idx then + -- Optional count out-param: allocate it internally and hand the value + -- back as an extra return value. A caller-supplied cdata is filled too. + local var = "_n" .. i + pre[#pre + 1] = 'local ' .. var .. ' = ffi.new("' .. pt.base .. '[1]")' + if ptr_info.init_count then + pre[#pre + 1] = var .. "[0] = 0" + end + sig[#sig + 1] = name + args[#args + 1] = var + arg_expr[i] = var + arg_ann[#arg_ann + 1] = "---@param " .. name .. "? ffi.cdata*" elseif outs[i] then local var = "_o" .. i - if outs[i] == "inout" then + if outs[i] == "inout" and OWNED[canon(pt.base)] then + -- Mutate in place and return the same cdata: raylib's own Image* / + -- Mesh* contract. Copying here loses reallocations (double free). + arg_ann[#arg_ann + 1] = "---@param " .. name .. " raylib." .. pt.base + args[#args + 1] = 'ffi.cast("' .. pt.base .. ' *", ' .. name .. ')' + arg_expr[i] = name + out_vars[#out_vars + 1] = name + out_ann[#out_ann + 1] = "---@return raylib." .. pt.base + elseif outs[i] == "inout" then pre[#pre + 1] = 'local ' .. var .. ' = ffi.new("' .. pt.base .. '[1]", ' .. name .. ')' arg_ann[#arg_ann + 1] = "---@param " .. name .. " raylib." .. pt.base + args[#args + 1] = var + arg_expr[i] = var + out_vars[#out_vars + 1] = var .. "[0]" + out_ann[#out_ann + 1] = "---@return raylib." .. pt.base else pre[#pre + 1] = 'local ' .. var .. ' = ffi.new("' .. pt.base .. '[1]")' pre[#pre + 1] = "if " .. name .. " ~= nil then " .. var .. "[0] = " .. name .. " end" arg_ann[#arg_ann + 1] = "---@param " .. name .. "? raylib." .. pt.base + args[#args + 1] = var + arg_expr[i] = var + out_vars[#out_vars + 1] = var .. "[0]" + out_ann[#out_ann + 1] = "---@return raylib." .. pt.base end - args[#args + 1] = var - out_vars[#out_vars + 1] = var .. "[0]" - out_ann[#out_ann + 1] = "---@return raylib." .. pt.base sig[#sig + 1] = name else sig[#sig + 1] = name @@ -1086,6 +2130,7 @@ local function emit_function(f) local var = "_cb" .. i pre[#pre + 1] = "local " .. var .. ' = pin("' .. pt.base .. '", ' .. name .. ")" args[#args + 1] = var + arg_expr[i] = var else local conv = conversion_for(name, p.type, i) if conv then @@ -1093,8 +2138,10 @@ local function emit_function(f) pre[#pre + 1] = line end args[#args + 1] = conv.arg + arg_expr[i] = conv.arg else args[#args + 1] = name + arg_expr[i] = name end end end @@ -1104,6 +2151,9 @@ local function emit_function(f) if desc then w("---" .. desc) end + if EXTRA_DOC[f.name] then + w("---" .. EXTRA_DOC[f.name]) + end for _, line in ipairs(arg_ann) do w(line) end @@ -1111,12 +2161,49 @@ local function emit_function(f) for _, line in ipairs(out_ann) do w(line) end + elseif count_idx then + w("---@return ffi.cdata*, integer") elseif parse_type(f.returnType).base == "void" and parse_type(f.returnType).ptr == 0 then w("---@return nil") else w("---@return " .. ann_return(f.returnType)) end + -- Explicit unload: disarm, then release through the idempotent helper. + local owner = RELEASE_OWNER[f.name] + local powner = POINTER_RELEASE[f.name] + if owner or powner then + local first = raw_names[1] + w("function M." .. f.name .. "(" .. table.concat(sig, ", ") .. ")") + w(" if " .. first .. " == nil then return end") + w(" ffi.gc(" .. first .. ", nil)") + local kind = owner and + ((OWNED[owner] and OWNED[owner].kind) or + (EXTRA_OWNERS[owner] and EXTRA_OWNERS[owner].kind)) + -- Material/VrStereoConfig only free RAM (maps / nothing), so they must run + -- even after the GPU context is gone. + if (kind == "gpu" or kind == "audio") and + owner ~= "Material" and owner ~= "VrStereoConfig" then + w(' if not _can_unload("' .. kind .. '") then') + w(" _dead[" .. first .. "] = true") + w(" ffi.fill(" .. first .. ", ffi.sizeof(" .. first .. "))") + w(" return") + w(" end") + end + w(" if not _dead[" .. first .. "] then") + if owner then + w(" _release_" .. owner .. "(" .. first .. ")") + else + w(" _release_" .. powner .. "(" .. table.concat(raw_names, ", ") .. ")") + end + w(" _st.released = _st.released + 1") + w(" end") + w("end") + w("") + emitted_wrappers = emitted_wrappers + 1 + return + end + w("function M." .. f.name .. "(" .. table.concat(sig, ", ") .. ")") for _, line in ipairs(pre) do w(" " .. line) @@ -1124,23 +2211,65 @@ local function emit_function(f) local call = "C." .. f.name .. "(" .. table.concat(args, ", ") .. ")" local ret = parse_type(f.returnType) + local post = POST_CALL[f.name] if #out_vars > 0 then w(" " .. call) + if post then + w(" " .. post) + end w(" return " .. table.concat(out_vars, ", ")) elseif ret.base == "void" and ret.ptr == 0 then w(" " .. call) + if post then + w(" " .. post) + end elseif ret.base == "char" and ret.ptr == 1 then - local owner = RET_OWNER[f.name] w(" local _p = " .. call) w(" if _p == nil then") w(" return nil") w(" end") w(" local _s = ffi_string(_p)") - if owner then - w(" C." .. owner .. "(_p)") + if cls.bucket == "owned_string" then + w(" C." .. cls.release .. "(_p)") end w(" return _s") + elseif cls.bucket == "owned_pointer" then + if count_idx then + local cname = raw_names[count_idx] + local nvar = "_n" .. count_idx + w(" local _p = " .. call) + w(" local _c = " .. nvar .. "[0]") + w(" if " .. cname .. " ~= nil then " .. cname .. "[0] = _c end") + w(" return _own_ptr_" .. f.name .. "(_p, _c), _c") + else + w(" return _own_ptr_" .. f.name .. "(" .. call .. ")") + end + elseif cls.bucket == "owned" then + local consumes = CONSUMES[f.name] + local keeps = KEEPS[f.name] + if consumes then + local idx + for i, p in ipairs(params) do + if p.name == consumes.param then + idx = i + end + end + w(" local _r = " .. call) + w(" local _o = _own_" .. cls.type .. "(_r)") + w(" if _r." .. consumes.valid_field .. " > 0 then _consume(" .. raw_names[idx] .. ") end") + w(" return _o") + elseif keeps then + local idx + for i, p in ipairs(params) do + if p.name == keeps.keep then + idx = i + end + end + w(" return _own_" .. keeps.own .. "_keep(" .. call .. ", " .. arg_expr[idx] .. ")") + else + w(" return _own_" .. cls.type .. "(" .. call .. ")") + end else w(" return " .. call) end @@ -1165,26 +2294,54 @@ w("return M") -- write ---------------------------------------------------------------------------- -local text = table.concat(out, "\n") .. "\n" -local file, err = io.open(CFG.out, "wb") -if not file then - die("cannot write %s: %s", CFG.out, err) - return -end -file:write(text) -file:close() +-- A pure --dump-ownership run (no explicit --out) only produces the map; it +-- must not rewrite the binding as a side effect. +local write_binding = not (CFG.dump_ownership and not CFG.out_explicit) +if write_binding then + local text = table.concat(out, "\n") .. "\n" + local file, err = io.open(CFG.out, "wb") + if not file then + die("cannot write %s: %s", CFG.out, err) + return + end + file:write(text) + file:close() -local n_struct, n_alias, n_cb = 0, 0, 0 -for _, d in ipairs(ordered) do - if d.kind == "struct" then - n_struct = n_struct + 1 + local n_struct, n_alias, n_cb = 0, 0, 0 + for _, d in ipairs(ordered) do + if d.kind == "struct" then + n_struct = n_struct + 1 + else + n_alias = n_alias + 1 + end + end + for _ in pairs(CALLBACKS) do + n_cb = n_cb + 1 + end + io.stderr:write(string.format( + "gen-hate-no-d: wrote %s (%d functions, %d structs, %d aliases, %d callbacks, %d lines)\n", + CFG.out, emitted_wrappers, n_struct, n_alias, n_cb, #out)) +end + +if CFG.dump_ownership then + local map = ownership_map() + if CFG.dump_ownership == true then + io.write(map) else - n_alias = n_alias + 1 + local dump, derr = io.open(CFG.dump_ownership, "wb") + if not dump then + die("cannot write %s: %s", CFG.dump_ownership, derr) + return + end + dump:write(map) + dump:close() end end -for _ in pairs(CALLBACKS) do - n_cb = n_cb + 1 -end + +local counts = ownership_summary() io.stderr:write(string.format( - "gen-hate-no-d: wrote %s (%d functions, %d structs, %d aliases, %d callbacks, %d lines)\n", - CFG.out, emitted_wrappers, n_struct, n_alias, n_cb, #out)) + "gen-hate-no-d: ownership: %d owned-struct callsites, %d owned pointers, " .. + "%d owned strings, %d borrowed structs, %d borrowed statics, " .. + "%d borrowed strings, %d value structs, %d non-owning\n", + counts.owned, counts.owned_pointer, counts.owned_string, counts.borrowed, + counts.borrowed_static, counts.borrowed_string, counts.value, counts.non_owning)) diff --git a/hate-no-d.lua b/hate-no-d.lua index a544708..dbc1a2b 100644 --- a/hate-no-d.lua +++ b/hate-no-d.lua @@ -1317,6 +1317,514 @@ local function to_array(ct, t, n) return a end +-- --------------------------------------------------------------------------- +-- Resource ownership +-- +-- Owned struct values returned by raylib are armed with an FFI finalizer that +-- calls the matching Unload* function. The finalizer only runs while the +-- device it needs is still up, and GPU owners are pinned to the window +-- generation they were created in. M.C stays raw: nothing is armed for direct +-- ffi.C calls. See 'Resource ownership' in README.md. +-- +-- One finalizer slot per cdata: a second ffi.gc() replaces the first. Never +-- arm views/reference cdata (model.meshes[i], rt.texture, ...): only values +-- that came straight out of a C return are owned. +-- --------------------------------------------------------------------------- +---@class raylib.ownership_stats +---@field armed integer resources handed to the GC with a finalizer +---@field released integer finalizers that actually freed a resource +---@field skipped integer finalizers that refused (device gone / stale generation) +---@field errors integer finalizers whose release call raised +---@field gen integer current GPU generation (window instance) +---@field reset fun() +M._ownership = { armed = 0, released = 0, skipped = 0, errors = 0, gen = 0 } +local _st = M._ownership +function _st.reset() + _st.armed, _st.released, _st.skipped, _st.errors = 0, 0, 0, 0 +end + +local _gpu_gen = 0 +local _dead = setmetatable({}, { __mode = "k" }) +local _attached = setmetatable({}, { __mode = "k" }) +local _fin_cache = {} + +local _pins = { + shapes = nil, + shapes_prev = nil, + auto = nil, + material = {}, +} + +local function _can_unload(kind) + if kind == "gpu" then return C.IsWindowReady() end + if kind == "audio" then return C.IsAudioDeviceReady() end + return true +end + +-- `keep` is the release function's optional second argument (owned extras, +-- retained buffers). It is also an upvalue here, which is what keeps it alive +-- until this finalizer runs: weak tables are cleared before finalizers, so a +-- weak map cannot be used for keep-alive. +local function _fire(kind, gen, release, x, keep) + if kind == "gpu" and gen ~= _gpu_gen then + _st.skipped = _st.skipped + 1 + return + end + if not _can_unload(kind) then + _st.skipped = _st.skipped + 1 + return + end + local ok = pcall(release, x, keep) + if ok then _st.released = _st.released + 1 else _st.errors = _st.errors + 1 end + -- keep is referenced here so the closure retains it until finalization. + if keep ~= nil then keep = nil end +end + +-- One finalizer closure per (release, generation), not per object. +local function _finalizer(kind, gen, release) + local by_gen = _fin_cache[release] + if by_gen == nil then + by_gen = {} + _fin_cache[release] = by_gen + end + local fin = by_gen[gen] + if fin == nil then + fin = function(x) _fire(kind, gen, release, x, nil) end + by_gen[gen] = fin + end + return fin +end + +local function _arm(kind, release, valid, x, keep) + if x == nil then return x end + if valid ~= nil and not valid(x) then return x end + -- Pointer cdata is keyed by address, and the allocator reuses addresses + -- after a free: a stale _dead entry must never suppress this allocation. + _dead[x] = nil + _st.armed = _st.armed + 1 + local gen = _gpu_gen + if keep ~= nil then + return ffi.gc(x, function(y) _fire(kind, gen, release, y, keep) end) + end + return ffi.gc(x, _finalizer(kind, gen, release)) +end + +local function _free_attached(x) + local extra = _attached[x] + if extra == nil then return nil end + _attached[x] = nil + for i = 1, #extra do C.MemFree(extra[i]) end + return extra +end + +-- Raw pointer release: MemAlloc/MemRealloc and the loaders that hand back +-- RL_MALLOC'd buffers (MemFree is free()). +local function _release_raw(p) + if p == nil or _dead[p] then return end + _dead[p] = true + C.MemFree(p) +end + +local function _release_AudioStream(x) + if _dead[x] then return end + _dead[x] = true + C.UnloadAudioStream(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_AutomationEventList(x) + if _dead[x] then return end + _dead[x] = true + local pinned = _pins.auto + if pinned ~= nil and (pinned == x or (pinned.events ~= nil and pinned.events == x.events)) then + _pins.auto = nil + C.SetAutomationEventList(nil) + end + C.UnloadAutomationEventList(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_FilePathList(x) + if _dead[x] then return end + _dead[x] = true + C.UnloadDirectoryFiles(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_Font(x, extra) + if _dead[x] then return end + _dead[x] = true + if extra == nil then extra = _attached[x] end + _attached[x] = nil + if extra ~= nil then + for i = 1, #extra do C.MemFree(extra[i]) end + end + C.UnloadFont(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_Image(x, extra) + if _dead[x] then return end + _dead[x] = true + if extra == nil then extra = _attached[x] end + _attached[x] = nil + if extra ~= nil then + for i = 1, #extra do C.MemFree(extra[i]) end + end + C.UnloadImage(x) + ffi.fill(x, ffi.sizeof(x)) +end + +-- UnloadMaterial() deletes the material's shader and map textures, which may +-- be owned by separate Lua objects. The Material owner owns only its maps. +local function _release_Material(x) + if _dead[x] then return end + _dead[x] = true + if x.maps ~= nil then + _pins.material[tostring(ffi.cast("void *", x.maps))] = nil + C.MemFree(x.maps) + end + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_Mesh(x) + if _dead[x] then return end + _dead[x] = true + C.UnloadMesh(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_Model(x) + if _dead[x] then return end + _dead[x] = true + if x.materials ~= nil then + for i = 0, x.materialCount - 1 do + local maps = x.materials[i].maps + if maps ~= nil then + _pins.material[tostring(ffi.cast("void *", maps))] = nil + end + end + end + C.UnloadModel(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_Music(x) + if _dead[x] then return end + _dead[x] = true + C.UnloadMusicStream(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_RenderTexture(x) + if _dead[x] then return end + _dead[x] = true + C.UnloadRenderTexture(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_Shader(x) + if _dead[x] then return end + _dead[x] = true + C.UnloadShader(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_Sound(x) + if _dead[x] then return end + _dead[x] = true + C.UnloadSound(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_Texture(x) + if _dead[x] then return end + _dead[x] = true + local prev = _pins.shapes_prev + if _pins.shapes ~= nil and _pins.shapes.id == x.id then + if prev ~= nil and prev.tex ~= nil and prev.tex.id ~= 0 and C.IsWindowReady() then + C.SetShapesTexture(prev.tex, prev.rec) + end + _pins.shapes = nil + _pins.shapes_prev = nil + end + C.UnloadTexture(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_VrStereoConfig(x) + if _dead[x] then return end + _dead[x] = true + C.UnloadVrStereoConfig(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_Wave(x) + if _dead[x] then return end + _dead[x] = true + C.UnloadWave(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_SoundAlias(x) + if _dead[x] then return end + _dead[x] = true + C.UnloadSoundAlias(x) + ffi.fill(x, ffi.sizeof(x)) +end + +local function _release_LoadCodepoints(p, n) + if p == nil or _dead[p] then return end + _dead[p] = true + C.UnloadCodepoints(p) +end + +local function _release_LoadFileData(p, n) + if p == nil or _dead[p] then return end + _dead[p] = true + C.UnloadFileData(p) +end + +local function _release_LoadFontData(p, n) + if p == nil or _dead[p] then return end + _dead[p] = true + C.UnloadFontData(p, n or 0) +end + +local function _release_LoadImageColors(p, n) + if p == nil or _dead[p] then return end + _dead[p] = true + C.UnloadImageColors(p) +end + +local function _release_LoadImagePalette(p, n) + if p == nil or _dead[p] then return end + _dead[p] = true + C.UnloadImagePalette(p) +end + +local function _release_LoadMaterials(p, n) + if p == nil or _dead[p] then return end + _dead[p] = true + n = n or 0 + for i = 0, n - 1 do C.UnloadMaterial(p[i]) end + C.MemFree(p) +end + +local function _release_LoadModelAnimations(p, n) + if p == nil or _dead[p] then return end + _dead[p] = true + C.UnloadModelAnimations(p, n or 0) +end + +local function _release_LoadRandomSequence(p, n) + if p == nil or _dead[p] then return end + _dead[p] = true + C.UnloadRandomSequence(p) +end + +local function _release_LoadTextLines(p, n) + if p == nil or _dead[p] then return end + _dead[p] = true + C.UnloadTextLines(p, n or 0) +end + +local function _release_LoadWaveSamples(p, n) + if p == nil or _dead[p] then return end + _dead[p] = true + C.UnloadWaveSamples(p) +end + +local function _release_rlLoadRenderBatch(p, n) + if p == nil or _dead[p] then return end + _dead[p] = true + C.rlUnloadRenderBatch(p) +end + +local function _valid_AudioStream(x) return x.buffer ~= nil end +local function _valid_AutomationEventList(x) return x.events ~= nil end +local function _valid_FilePathList(x) return x.paths ~= nil end +local function _valid_Font(x) return x.texture.id ~= 0 end +local function _valid_Image(x) return x.data ~= nil end +local function _valid_Model(x) return x.meshCount > 0 end +local function _valid_Music(x) return x.stream.buffer ~= nil end +local function _valid_RenderTexture(x) return x.id ~= 0 end +local function _valid_Shader(x) return x.id ~= 0 end +local function _valid_Sound(x) return x.stream.buffer ~= nil end +local function _valid_SoundAlias(x) return x.stream.buffer ~= nil end +local function _valid_Texture(x) return x.id ~= 0 end +local function _valid_Wave(x) return x.data ~= nil end + +local function _own_AudioStream(x) + return _arm("audio", _release_AudioStream, _valid_AudioStream, x) +end + +local function _own_AutomationEventList(x) + return _arm("ram", _release_AutomationEventList, _valid_AutomationEventList, x) +end + +local function _own_FilePathList(x) + return _arm("ram", _release_FilePathList, _valid_FilePathList, x) +end + +local function _own_Font(x) + return _arm("gpu", _release_Font, _valid_Font, x) +end + +local function _own_Image(x) + return _arm("ram", _release_Image, _valid_Image, x) +end + +local function _own_Material(x) + return _arm("gpu", _release_Material, nil, x) +end + +local function _own_Mesh(x) + return _arm("gpu", _release_Mesh, nil, x) +end + +local function _own_Model(x) + return _arm("gpu", _release_Model, _valid_Model, x) +end + +local function _own_Music(x) + return _arm("audio", _release_Music, _valid_Music, x) +end + +local function _own_RenderTexture(x) + return _arm("gpu", _release_RenderTexture, _valid_RenderTexture, x) +end + +local function _own_Shader(x) + return _arm("gpu", _release_Shader, _valid_Shader, x) +end + +local function _own_Sound(x) + return _arm("audio", _release_Sound, _valid_Sound, x) +end + +local function _own_Texture(x) + return _arm("gpu", _release_Texture, _valid_Texture, x) +end + +local function _own_VrStereoConfig(x) + return _arm("gpu", _release_VrStereoConfig, nil, x) +end + +local function _own_Wave(x) + return _arm("ram", _release_Wave, _valid_Wave, x) +end + +local function _own_Music_keep(x, keep) + return _arm("audio", _release_Music, _valid_Music, x, keep) +end + +local function _own_SoundAlias_keep(x, keep) + return _arm("audio", _release_SoundAlias, _valid_SoundAlias, x, keep) +end + +local function _own_ptr_CompressData(p, n) + return _arm("ram", _release_raw, nil, p, n) +end + +local function _own_ptr_DecodeDataBase64(p, n) + return _arm("ram", _release_raw, nil, p, n) +end + +local function _own_ptr_DecompressData(p, n) + return _arm("ram", _release_raw, nil, p, n) +end + +local function _own_ptr_ExportImageToMemory(p, n) + return _arm("ram", _release_raw, nil, p, n) +end + +local function _own_ptr_LoadCodepoints(p, n) + return _arm("ram", _release_LoadCodepoints, nil, p, n) +end + +local function _own_ptr_LoadFileData(p, n) + return _arm("ram", _release_LoadFileData, nil, p, n) +end + +local function _own_ptr_LoadFontData(p, n) + return _arm("ram", _release_LoadFontData, nil, p, n) +end + +local function _own_ptr_LoadImageColors(p) + return _arm("ram", _release_LoadImageColors, nil, p) +end + +local function _own_ptr_LoadImagePalette(p, n) + return _arm("ram", _release_LoadImagePalette, nil, p, n) +end + +local function _own_ptr_LoadMaterials(p, n) + return _arm("ram", _release_LoadMaterials, nil, p, n) +end + +local function _own_ptr_LoadModelAnimations(p, n) + return _arm("ram", _release_LoadModelAnimations, nil, p, n) +end + +local function _own_ptr_LoadRandomSequence(p) + return _arm("ram", _release_LoadRandomSequence, nil, p) +end + +local function _own_ptr_LoadTextLines(p, n) + return _arm("ram", _release_LoadTextLines, nil, p, n) +end + +local function _own_ptr_LoadWaveSamples(p) + return _arm("ram", _release_LoadWaveSamples, nil, p) +end + +local function _own_ptr_rlLoadRenderBatch(p) + return _arm("gpu", _release_rlLoadRenderBatch, nil, p) +end + +local function _own_ptr_rlReadScreenPixels(p) + return _arm("ram", _release_raw, nil, p) +end + +local function _own_ptr_rlReadTexturePixels(p) + return _arm("ram", _release_raw, nil, p) +end + +local function _own_raw(p) + return _arm("ram", _release_raw, nil, p) +end + +-- GenImageFontAtlas: the Rectangle* out-param belongs to the Image. The +-- explicit-unload path finds it through _attached; the finalizer carries it +-- as an upvalue (weak tables are cleared before finalizers run). +local function _own_Image_extra(x, extra) + if extra == nil then return _own_Image(x) end + if x == nil or x.data == nil then + for i = 1, #extra do C.MemFree(extra[i]) end + return x + end + _attached[x] = extra + _st.armed = _st.armed + 1 + local gen = _gpu_gen + return ffi.gc(x, function(y) _fire("ram", gen, _release_Image, y, extra) end) +end + +-- Ownership of a struct value moves to another object (LoadModelFromMesh): +-- disarm it, mark it dead and zero it so a stale unload is a no-op. +local function _consume(x) + if x == nil then return end + ffi.gc(x, nil) + _dead[x] = true + ffi.fill(x, ffi.sizeof(x)) +end + +local function _consume_ptr(p) + if p == nil then return end + ffi.gc(p, nil) + _dead[p] = true +end + ---@enum raylib.ConfigFlags M.ConfigFlags = { FLAG_VSYNC_HINT = 64, @@ -3207,12 +3715,14 @@ M.RL_SHADER_LOC_MAP_SPECULAR = M.RL_SHADER_LOC_MAP_METALNESS ---@return nil function M.InitWindow(width, height, title) C.InitWindow(width, height, title) + _gpu_gen = _gpu_gen + 1; _st.gen = _gpu_gen; _fin_cache = {}; _pins.shapes = nil; _pins.shapes_prev = nil; _pins.material = {}; _pins.auto = nil end ---Close window and unload OpenGL context ---@return nil function M.CloseWindow() C.CloseWindow() + _gpu_gen = _gpu_gen + 1; _st.gen = _gpu_gen; _fin_cache = {}; _pins.shapes = nil; _pins.shapes_prev = nil; _pins.material = {}; _pins.auto = nil end ---Check if application should close (KEY_ESCAPE pressed or windows close icon clicked) @@ -3322,13 +3832,13 @@ function M.SetWindowIcon(image) end ---Set icon for window (multiple images, RGBA 32bit) ----@param images raylib.Image +---@param images raylib.Image[]|ffi.cdata* ---@param count integer ----@return raylib.Image +---@return nil function M.SetWindowIcons(images, count) - local _o1 = ffi.new("Image[1]", images) - C.SetWindowIcons(_o1, count) - return _o1[0] + local _a1 + if type(images) == "table" then _a1 = to_array("Image", images) else _a1 = images end + C.SetWindowIcons(_a1, count) end ---Set title for window @@ -3519,7 +4029,7 @@ end ---Get clipboard image content ---@return raylib.Image function M.GetClipboardImage() - return C.GetClipboardImage() + return _own_Image(C.GetClipboardImage()) end ---Enable waiting for events on EndDrawing(), no automatic event polling @@ -3687,14 +4197,19 @@ end ---@param device raylib.VrDeviceInfo ---@return raylib.VrStereoConfig function M.LoadVrStereoConfig(device) - return C.LoadVrStereoConfig(device) + return _own_VrStereoConfig(C.LoadVrStereoConfig(device)) end ---Unload VR stereo config ---@param config raylib.VrStereoConfig ---@return nil function M.UnloadVrStereoConfig(config) - C.UnloadVrStereoConfig(config) + if config == nil then return end + ffi.gc(config, nil) + if not _dead[config] then + _release_VrStereoConfig(config) + _st.released = _st.released + 1 + end end ---Load shader from files and bind default locations @@ -3702,7 +4217,7 @@ end ---@param fsFileName string ---@return raylib.Shader function M.LoadShader(vsFileName, fsFileName) - return C.LoadShader(vsFileName, fsFileName) + return _own_Shader(C.LoadShader(vsFileName, fsFileName)) end ---Load shader from code strings and bind default locations @@ -3710,7 +4225,7 @@ end ---@param fsCode string ---@return raylib.Shader function M.LoadShaderFromMemory(vsCode, fsCode) - return C.LoadShaderFromMemory(vsCode, fsCode) + return _own_Shader(C.LoadShaderFromMemory(vsCode, fsCode)) end ---Check if shader is valid (loaded on GPU) @@ -3785,7 +4300,17 @@ end ---@param shader raylib.Shader ---@return nil function M.UnloadShader(shader) - C.UnloadShader(shader) + if shader == nil then return end + ffi.gc(shader, nil) + if not _can_unload("gpu") then + _dead[shader] = true + ffi.fill(shader, ffi.sizeof(shader)) + return + end + if not _dead[shader] then + _release_Shader(shader) + _st.released = _st.released + 1 + end end ---Get a ray trace from screen position (i.e mouse) @@ -3919,14 +4444,19 @@ end ---@param max integer ---@return ffi.cdata* function M.LoadRandomSequence(count, min, max) - return C.LoadRandomSequence(count, min, max) + return _own_ptr_LoadRandomSequence(C.LoadRandomSequence(count, min, max)) end ---Unload random values sequence ---@param sequence ffi.cdata* ---@return nil function M.UnloadRandomSequence(sequence) - C.UnloadRandomSequence(sequence) + if sequence == nil then return end + ffi.gc(sequence, nil) + if not _dead[sequence] then + _release_LoadRandomSequence(sequence) + _st.released = _st.released + 1 + end end ---Takes a screenshot of current screen (filename extension defines format) @@ -3974,43 +4504,49 @@ end ---@param size integer ---@return ffi.cdata* function M.MemAlloc(size) - return C.MemAlloc(size) + return _own_raw(C.MemAlloc(size)) end ---Internal memory reallocator ----@param ptr ffi.cdata*|string +---@param ptr ffi.cdata* ---@param size integer ---@return ffi.cdata* function M.MemRealloc(ptr, size) - local _a1 - if type(ptr) == "string" then _a1 = ffi.cast("const void *", ptr) - else _a1 = ptr end - return C.MemRealloc(_a1, size) + _consume_ptr(ptr) + return _own_raw(C.MemRealloc(ptr, size)) end ---Internal memory free ----@param ptr ffi.cdata*|string +---@param ptr ffi.cdata* ---@return nil function M.MemFree(ptr) - local _a1 - if type(ptr) == "string" then _a1 = ffi.cast("const void *", ptr) - else _a1 = ptr end - C.MemFree(_a1) + if ptr == nil then return end + ffi.gc(ptr, nil) + _release_raw(ptr) end ---Load file data as byte array (read) ---@param fileName string ----@param dataSize ffi.cdata* ----@return ffi.cdata* +---@param dataSize? ffi.cdata* +---@return ffi.cdata*, integer function M.LoadFileData(fileName, dataSize) - return C.LoadFileData(fileName, dataSize) + local _n2 = ffi.new("int[1]") + local _p = C.LoadFileData(fileName, _n2) + local _c = _n2[0] + if dataSize ~= nil then dataSize[0] = _c end + return _own_ptr_LoadFileData(_p, _c), _c end ---Unload file data allocated by LoadFileData() ---@param data ffi.cdata* ---@return nil function M.UnloadFileData(data) - C.UnloadFileData(data) + if data == nil then return end + ffi.gc(data, nil) + if not _dead[data] then + _release_LoadFileData(data) + _st.released = _st.released + 1 + end end ---Save data to file from byte array (write), returns true on success @@ -4317,7 +4853,7 @@ end ---@param dirPath string ---@return raylib.FilePathList function M.LoadDirectoryFiles(dirPath) - return C.LoadDirectoryFiles(dirPath) + return _own_FilePathList(C.LoadDirectoryFiles(dirPath)) end ---Load directory filepaths with extension filtering and subdir scan; some filters available: '*.*','FILES*','DIRS*' @@ -4326,14 +4862,19 @@ end ---@param scanSubdirs boolean ---@return raylib.FilePathList function M.LoadDirectoryFilesEx(basePath, filter, scanSubdirs) - return C.LoadDirectoryFilesEx(basePath, filter, scanSubdirs) + return _own_FilePathList(C.LoadDirectoryFilesEx(basePath, filter, scanSubdirs)) end ---Unload filepaths ---@param files raylib.FilePathList ---@return nil function M.UnloadDirectoryFiles(files) - C.UnloadDirectoryFiles(files) + if files == nil then return end + ffi.gc(files, nil) + if not _dead[files] then + _release_FilePathList(files) + _st.released = _st.released + 1 + end end ---Check if file has been dropped into window @@ -4343,6 +4884,7 @@ function M.IsFileDropped() end ---Load dropped filepaths +---NOTE: this is a view of raylib's internal dropped-file state. ---@return raylib.FilePathList function M.LoadDroppedFiles() return C.LoadDroppedFiles() @@ -4374,27 +4916,35 @@ end ---Compress data (DEFLATE algorithm), memory must be MemFree() ---@param data string|integer[] ---@param dataSize integer ----@param compDataSize ffi.cdata* ----@return ffi.cdata* +---@param compDataSize? ffi.cdata* +---@return ffi.cdata*, integer function M.CompressData(data, dataSize, compDataSize) local _a1 if type(data) == "string" then _a1 = ffi.cast("const unsigned char *", data) elseif type(data) == "table" then _a1 = to_array("unsigned char", data) else _a1 = data end - return C.CompressData(_a1, dataSize, compDataSize) + local _n3 = ffi.new("int[1]") + local _p = C.CompressData(_a1, dataSize, _n3) + local _c = _n3[0] + if compDataSize ~= nil then compDataSize[0] = _c end + return _own_ptr_CompressData(_p, _c), _c end ---Decompress data (DEFLATE algorithm), memory must be MemFree() ---@param compData string|integer[] ---@param compDataSize integer ----@param dataSize ffi.cdata* ----@return ffi.cdata* +---@param dataSize? ffi.cdata* +---@return ffi.cdata*, integer function M.DecompressData(compData, compDataSize, dataSize) local _a1 if type(compData) == "string" then _a1 = ffi.cast("const unsigned char *", compData) elseif type(compData) == "table" then _a1 = to_array("unsigned char", compData) else _a1 = compData end - return C.DecompressData(_a1, compDataSize, dataSize) + local _n3 = ffi.new("int[1]") + local _p = C.DecompressData(_a1, compDataSize, _n3) + local _c = _n3[0] + if dataSize ~= nil then dataSize[0] = _c end + return _own_ptr_DecompressData(_p, _c), _c end ---Encode data to Base64 string (includes NULL terminator), memory must be MemFree() @@ -4418,10 +4968,14 @@ end ---Decode Base64 string (expected NULL terminated), memory must be MemFree() ---@param text string ----@param outputSize ffi.cdata* ----@return ffi.cdata* +---@param outputSize? ffi.cdata* +---@return ffi.cdata*, integer function M.DecodeDataBase64(text, outputSize) - return C.DecodeDataBase64(text, outputSize) + local _n2 = ffi.new("int[1]") + local _p = C.DecodeDataBase64(text, _n2) + local _c = _n2[0] + if outputSize ~= nil then outputSize[0] = _c end + return _own_ptr_DecodeDataBase64(_p, _c), _c end ---Compute CRC32 hash code @@ -4476,14 +5030,19 @@ end ---@param fileName string ---@return raylib.AutomationEventList function M.LoadAutomationEventList(fileName) - return C.LoadAutomationEventList(fileName) + return _own_AutomationEventList(C.LoadAutomationEventList(fileName)) end ---Unload automation events list from file ---@param list raylib.AutomationEventList ---@return nil function M.UnloadAutomationEventList(list) - C.UnloadAutomationEventList(list) + if list == nil then return end + ffi.gc(list, nil) + if not _dead[list] then + _release_AutomationEventList(list) + _st.released = _st.released + 1 + end end ---Export automation events list as text file @@ -4495,12 +5054,18 @@ function M.ExportAutomationEventList(list, fileName) end ---Set automation event list to record to ----@param list raylib.AutomationEventList ----@return raylib.AutomationEventList +---@param list? raylib.AutomationEventList +---@return nil +-- NOTE: raylib stores the pointer, so the list is pinned until it is +-- unloaded or replaced (previously this passed a temporary array). function M.SetAutomationEventList(list) - local _o1 = ffi.new("AutomationEventList[1]", list) - C.SetAutomationEventList(_o1) - return _o1[0] + if list == nil then + _pins.auto = nil + C.SetAutomationEventList(nil) + return + end + _pins.auto = list + C.SetAutomationEventList(ffi.cast("AutomationEventList *", list)) end ---Set automation event internal base frame to start recording @@ -4885,13 +5450,19 @@ end ---Set texture and rectangle to be used on shapes drawing ---@param texture raylib.Texture2D ----@param rec raylib.Rectangle +---@param rec raylib.Rectangle|ffi.cdata* ---@return nil function M.SetShapesTexture(texture, rec) + if type(rec) == "table" then rec = ffi.new("Rectangle", rec) end + if C.IsWindowReady() then + _pins.shapes_prev = { tex = C.GetShapesTexture(), rec = C.GetShapesTextureRectangle() } + end + _pins.shapes = texture C.SetShapesTexture(texture, rec) end ---Get texture that is used for shapes drawing +---NOTE: this is a view; the texture is owned by raylib. ---@return raylib.Texture2D function M.GetShapesTexture() return C.GetShapesTexture() @@ -5679,7 +6250,7 @@ end ---@param fileName string ---@return raylib.Image function M.LoadImage(fileName) - return C.LoadImage(fileName) + return _own_Image(C.LoadImage(fileName)) end ---Load image from RAW file data @@ -5690,7 +6261,7 @@ end ---@param headerSize integer ---@return raylib.Image function M.LoadImageRaw(fileName, width, height, format, headerSize) - return C.LoadImageRaw(fileName, width, height, format, headerSize) + return _own_Image(C.LoadImageRaw(fileName, width, height, format, headerSize)) end ---Load image sequence from file (frames appended to image.data) @@ -5698,7 +6269,7 @@ end ---@param frames ffi.cdata* ---@return raylib.Image function M.LoadImageAnim(fileName, frames) - return C.LoadImageAnim(fileName, frames) + return _own_Image(C.LoadImageAnim(fileName, frames)) end ---Load image sequence from memory buffer @@ -5712,7 +6283,7 @@ function M.LoadImageAnimFromMemory(fileType, fileData, dataSize, frames) if type(fileData) == "string" then _a2 = ffi.cast("const unsigned char *", fileData) elseif type(fileData) == "table" then _a2 = to_array("unsigned char", fileData) else _a2 = fileData end - return C.LoadImageAnimFromMemory(fileType, _a2, dataSize, frames) + return _own_Image(C.LoadImageAnimFromMemory(fileType, _a2, dataSize, frames)) end ---Load image from memory buffer, fileType refers to extension: i.e. '.png' @@ -5725,20 +6296,20 @@ function M.LoadImageFromMemory(fileType, fileData, dataSize) if type(fileData) == "string" then _a2 = ffi.cast("const unsigned char *", fileData) elseif type(fileData) == "table" then _a2 = to_array("unsigned char", fileData) else _a2 = fileData end - return C.LoadImageFromMemory(fileType, _a2, dataSize) + return _own_Image(C.LoadImageFromMemory(fileType, _a2, dataSize)) end ---Load image from GPU texture data ---@param texture raylib.Texture2D ---@return raylib.Image function M.LoadImageFromTexture(texture) - return C.LoadImageFromTexture(texture) + return _own_Image(C.LoadImageFromTexture(texture)) end ---Load image from screen buffer (screenshot) ---@return raylib.Image function M.LoadImageFromScreen() - return C.LoadImageFromScreen() + return _own_Image(C.LoadImageFromScreen()) end ---Check if an image is valid (data and parameters) @@ -5752,7 +6323,12 @@ end ---@param image raylib.Image ---@return nil function M.UnloadImage(image) - C.UnloadImage(image) + if image == nil then return end + ffi.gc(image, nil) + if not _dead[image] then + _release_Image(image) + _st.released = _st.released + 1 + end end ---Export image data to file, returns true on success @@ -5766,10 +6342,14 @@ end ---Export image to memory buffer, memory must be MemFree() ---@param image raylib.Image ---@param fileType string ----@param fileSize ffi.cdata* ----@return ffi.cdata* +---@param fileSize? ffi.cdata* +---@return ffi.cdata*, integer function M.ExportImageToMemory(image, fileType, fileSize) - return C.ExportImageToMemory(image, fileType, fileSize) + local _n3 = ffi.new("int[1]") + local _p = C.ExportImageToMemory(image, fileType, _n3) + local _c = _n3[0] + if fileSize ~= nil then fileSize[0] = _c end + return _own_ptr_ExportImageToMemory(_p, _c), _c end ---Export image as code file defining an array of bytes, returns true on success @@ -5786,7 +6366,7 @@ end ---@param color raylib.Color ---@return raylib.Image function M.GenImageColor(width, height, color) - return C.GenImageColor(width, height, color) + return _own_Image(C.GenImageColor(width, height, color)) end ---Generate image: linear gradient, direction in degrees [0..360], 0=Vertical gradient @@ -5797,7 +6377,7 @@ end ---@param end_ raylib.Color ---@return raylib.Image function M.GenImageGradientLinear(width, height, direction, start, end_) - return C.GenImageGradientLinear(width, height, direction, start, end_) + return _own_Image(C.GenImageGradientLinear(width, height, direction, start, end_)) end ---Generate image: radial gradient @@ -5808,7 +6388,7 @@ end ---@param outer raylib.Color ---@return raylib.Image function M.GenImageGradientRadial(width, height, density, inner, outer) - return C.GenImageGradientRadial(width, height, density, inner, outer) + return _own_Image(C.GenImageGradientRadial(width, height, density, inner, outer)) end ---Generate image: square gradient @@ -5819,7 +6399,7 @@ end ---@param outer raylib.Color ---@return raylib.Image function M.GenImageGradientSquare(width, height, density, inner, outer) - return C.GenImageGradientSquare(width, height, density, inner, outer) + return _own_Image(C.GenImageGradientSquare(width, height, density, inner, outer)) end ---Generate image: checked @@ -5831,7 +6411,7 @@ end ---@param col2 raylib.Color ---@return raylib.Image function M.GenImageChecked(width, height, checksX, checksY, col1, col2) - return C.GenImageChecked(width, height, checksX, checksY, col1, col2) + return _own_Image(C.GenImageChecked(width, height, checksX, checksY, col1, col2)) end ---Generate image: white noise @@ -5840,7 +6420,7 @@ end ---@param factor number ---@return raylib.Image function M.GenImageWhiteNoise(width, height, factor) - return C.GenImageWhiteNoise(width, height, factor) + return _own_Image(C.GenImageWhiteNoise(width, height, factor)) end ---Generate image: perlin noise @@ -5851,7 +6431,7 @@ end ---@param scale number ---@return raylib.Image function M.GenImagePerlinNoise(width, height, offsetX, offsetY, scale) - return C.GenImagePerlinNoise(width, height, offsetX, offsetY, scale) + return _own_Image(C.GenImagePerlinNoise(width, height, offsetX, offsetY, scale)) end ---Generate image: cellular algorithm, bigger tileSize means bigger cells @@ -5860,7 +6440,7 @@ end ---@param tileSize integer ---@return raylib.Image function M.GenImageCellular(width, height, tileSize) - return C.GenImageCellular(width, height, tileSize) + return _own_Image(C.GenImageCellular(width, height, tileSize)) end ---Generate image: grayscale image from text data @@ -5869,14 +6449,14 @@ end ---@param text string ---@return raylib.Image function M.GenImageText(width, height, text) - return C.GenImageText(width, height, text) + return _own_Image(C.GenImageText(width, height, text)) end ---Create an image duplicate (useful for transformations) ---@param image raylib.Image ---@return raylib.Image function M.ImageCopy(image) - return C.ImageCopy(image) + return _own_Image(C.ImageCopy(image)) end ---Create an image from another image piece @@ -5884,7 +6464,7 @@ end ---@param rec raylib.Rectangle ---@return raylib.Image function M.ImageFromImage(image, rec) - return C.ImageFromImage(image, rec) + return _own_Image(C.ImageFromImage(image, rec)) end ---Create an image from a selected channel of another image (GRAYSCALE) @@ -5892,7 +6472,7 @@ end ---@param selectedChannel integer ---@return raylib.Image function M.ImageFromChannel(image, selectedChannel) - return C.ImageFromChannel(image, selectedChannel) + return _own_Image(C.ImageFromChannel(image, selectedChannel)) end ---Create an image from text (default font) @@ -5901,7 +6481,7 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageText(text, fontSize, color) - return C.ImageText(text, fontSize, color) + return _own_Image(C.ImageText(text, fontSize, color)) end ---Create an image from text (custom sprite font) @@ -5912,7 +6492,7 @@ end ---@param tint raylib.Color ---@return raylib.Image function M.ImageTextEx(font, text, fontSize, spacing, tint) - return C.ImageTextEx(font, text, fontSize, spacing, tint) + return _own_Image(C.ImageTextEx(font, text, fontSize, spacing, tint)) end ---Convert image data to desired format @@ -5920,9 +6500,8 @@ end ---@param newFormat integer ---@return raylib.Image function M.ImageFormat(image, newFormat) - local _o1 = ffi.new("Image[1]", image) - C.ImageFormat(_o1, newFormat) - return _o1[0] + C.ImageFormat(ffi.cast("Image *", image), newFormat) + return image end ---Convert image to POT (power-of-two) @@ -5930,9 +6509,8 @@ end ---@param fill raylib.Color ---@return raylib.Image function M.ImageToPOT(image, fill) - local _o1 = ffi.new("Image[1]", image) - C.ImageToPOT(_o1, fill) - return _o1[0] + C.ImageToPOT(ffi.cast("Image *", image), fill) + return image end ---Crop an image to a defined rectangle @@ -5940,9 +6518,8 @@ end ---@param crop raylib.Rectangle ---@return raylib.Image function M.ImageCrop(image, crop) - local _o1 = ffi.new("Image[1]", image) - C.ImageCrop(_o1, crop) - return _o1[0] + C.ImageCrop(ffi.cast("Image *", image), crop) + return image end ---Crop image depending on alpha value @@ -5950,9 +6527,8 @@ end ---@param threshold number ---@return raylib.Image function M.ImageAlphaCrop(image, threshold) - local _o1 = ffi.new("Image[1]", image) - C.ImageAlphaCrop(_o1, threshold) - return _o1[0] + C.ImageAlphaCrop(ffi.cast("Image *", image), threshold) + return image end ---Clear alpha channel to desired color @@ -5961,9 +6537,8 @@ end ---@param threshold number ---@return raylib.Image function M.ImageAlphaClear(image, color, threshold) - local _o1 = ffi.new("Image[1]", image) - C.ImageAlphaClear(_o1, color, threshold) - return _o1[0] + C.ImageAlphaClear(ffi.cast("Image *", image), color, threshold) + return image end ---Apply alpha mask to image @@ -5971,18 +6546,16 @@ end ---@param alphaMask raylib.Image ---@return raylib.Image function M.ImageAlphaMask(image, alphaMask) - local _o1 = ffi.new("Image[1]", image) - C.ImageAlphaMask(_o1, alphaMask) - return _o1[0] + C.ImageAlphaMask(ffi.cast("Image *", image), alphaMask) + return image end ---Premultiply alpha channel ---@param image raylib.Image ---@return raylib.Image function M.ImageAlphaPremultiply(image) - local _o1 = ffi.new("Image[1]", image) - C.ImageAlphaPremultiply(_o1) - return _o1[0] + C.ImageAlphaPremultiply(ffi.cast("Image *", image)) + return image end ---Apply Gaussian blur using a box blur approximation @@ -5990,9 +6563,8 @@ end ---@param blurSize integer ---@return raylib.Image function M.ImageBlurGaussian(image, blurSize) - local _o1 = ffi.new("Image[1]", image) - C.ImageBlurGaussian(_o1, blurSize) - return _o1[0] + C.ImageBlurGaussian(ffi.cast("Image *", image), blurSize) + return image end ---Apply custom square convolution kernel to image @@ -6001,12 +6573,11 @@ end ---@param kernelSize integer ---@return raylib.Image function M.ImageKernelConvolution(image, kernel, kernelSize) - local _o1 = ffi.new("Image[1]", image) local _a2 if type(kernel) == "table" then _a2 = to_array("float", kernel) else _a2 = kernel end - C.ImageKernelConvolution(_o1, _a2, kernelSize) - return _o1[0] + C.ImageKernelConvolution(ffi.cast("Image *", image), _a2, kernelSize) + return image end ---Resize image (Bicubic scaling algorithm) @@ -6015,9 +6586,8 @@ end ---@param newHeight integer ---@return raylib.Image function M.ImageResize(image, newWidth, newHeight) - local _o1 = ffi.new("Image[1]", image) - C.ImageResize(_o1, newWidth, newHeight) - return _o1[0] + C.ImageResize(ffi.cast("Image *", image), newWidth, newHeight) + return image end ---Resize image (Nearest-Neighbor scaling algorithm) @@ -6026,9 +6596,8 @@ end ---@param newHeight integer ---@return raylib.Image function M.ImageResizeNN(image, newWidth, newHeight) - local _o1 = ffi.new("Image[1]", image) - C.ImageResizeNN(_o1, newWidth, newHeight) - return _o1[0] + C.ImageResizeNN(ffi.cast("Image *", image), newWidth, newHeight) + return image end ---Resize canvas and fill with color @@ -6040,18 +6609,16 @@ end ---@param fill raylib.Color ---@return raylib.Image function M.ImageResizeCanvas(image, newWidth, newHeight, offsetX, offsetY, fill) - local _o1 = ffi.new("Image[1]", image) - C.ImageResizeCanvas(_o1, newWidth, newHeight, offsetX, offsetY, fill) - return _o1[0] + C.ImageResizeCanvas(ffi.cast("Image *", image), newWidth, newHeight, offsetX, offsetY, fill) + return image end ---Compute all mipmap levels for a provided image ---@param image raylib.Image ---@return raylib.Image function M.ImageMipmaps(image) - local _o1 = ffi.new("Image[1]", image) - C.ImageMipmaps(_o1) - return _o1[0] + C.ImageMipmaps(ffi.cast("Image *", image)) + return image end ---Dither image data to 16bpp or lower (Floyd-Steinberg dithering) @@ -6062,27 +6629,24 @@ end ---@param aBpp integer ---@return raylib.Image function M.ImageDither(image, rBpp, gBpp, bBpp, aBpp) - local _o1 = ffi.new("Image[1]", image) - C.ImageDither(_o1, rBpp, gBpp, bBpp, aBpp) - return _o1[0] + C.ImageDither(ffi.cast("Image *", image), rBpp, gBpp, bBpp, aBpp) + return image end ---Flip image vertically ---@param image raylib.Image ---@return raylib.Image function M.ImageFlipVertical(image) - local _o1 = ffi.new("Image[1]", image) - C.ImageFlipVertical(_o1) - return _o1[0] + C.ImageFlipVertical(ffi.cast("Image *", image)) + return image end ---Flip image horizontally ---@param image raylib.Image ---@return raylib.Image function M.ImageFlipHorizontal(image) - local _o1 = ffi.new("Image[1]", image) - C.ImageFlipHorizontal(_o1) - return _o1[0] + C.ImageFlipHorizontal(ffi.cast("Image *", image)) + return image end ---Rotate image by input angle in degrees (-359 to 359) @@ -6090,27 +6654,24 @@ end ---@param degrees integer ---@return raylib.Image function M.ImageRotate(image, degrees) - local _o1 = ffi.new("Image[1]", image) - C.ImageRotate(_o1, degrees) - return _o1[0] + C.ImageRotate(ffi.cast("Image *", image), degrees) + return image end ---Rotate image clockwise 90deg ---@param image raylib.Image ---@return raylib.Image function M.ImageRotateCW(image) - local _o1 = ffi.new("Image[1]", image) - C.ImageRotateCW(_o1) - return _o1[0] + C.ImageRotateCW(ffi.cast("Image *", image)) + return image end ---Rotate image counter-clockwise 90deg ---@param image raylib.Image ---@return raylib.Image function M.ImageRotateCCW(image) - local _o1 = ffi.new("Image[1]", image) - C.ImageRotateCCW(_o1) - return _o1[0] + C.ImageRotateCCW(ffi.cast("Image *", image)) + return image end ---Modify image color: tint @@ -6118,27 +6679,24 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageColorTint(image, color) - local _o1 = ffi.new("Image[1]", image) - C.ImageColorTint(_o1, color) - return _o1[0] + C.ImageColorTint(ffi.cast("Image *", image), color) + return image end ---Modify image color: invert ---@param image raylib.Image ---@return raylib.Image function M.ImageColorInvert(image) - local _o1 = ffi.new("Image[1]", image) - C.ImageColorInvert(_o1) - return _o1[0] + C.ImageColorInvert(ffi.cast("Image *", image)) + return image end ---Modify image color: grayscale ---@param image raylib.Image ---@return raylib.Image function M.ImageColorGrayscale(image) - local _o1 = ffi.new("Image[1]", image) - C.ImageColorGrayscale(_o1) - return _o1[0] + C.ImageColorGrayscale(ffi.cast("Image *", image)) + return image end ---Modify image color: contrast (-100 to 100) @@ -6146,9 +6704,8 @@ end ---@param contrast integer ---@return raylib.Image function M.ImageColorContrast(image, contrast) - local _o1 = ffi.new("Image[1]", image) - C.ImageColorContrast(_o1, contrast) - return _o1[0] + C.ImageColorContrast(ffi.cast("Image *", image), contrast) + return image end ---Modify image color: brightness (-255 to 255) @@ -6156,9 +6713,8 @@ end ---@param brightness integer ---@return raylib.Image function M.ImageColorBrightness(image, brightness) - local _o1 = ffi.new("Image[1]", image) - C.ImageColorBrightness(_o1, brightness) - return _o1[0] + C.ImageColorBrightness(ffi.cast("Image *", image), brightness) + return image end ---Modify image color: replace color @@ -6167,39 +6723,52 @@ end ---@param replace raylib.Color ---@return raylib.Image function M.ImageColorReplace(image, color, replace) - local _o1 = ffi.new("Image[1]", image) - C.ImageColorReplace(_o1, color, replace) - return _o1[0] + C.ImageColorReplace(ffi.cast("Image *", image), color, replace) + return image end ---Load color data from image as a Color array (RGBA - 32bit) ---@param image raylib.Image ---@return ffi.cdata* function M.LoadImageColors(image) - return C.LoadImageColors(image) + return _own_ptr_LoadImageColors(C.LoadImageColors(image)) end ---Load colors palette from image as a Color array (RGBA - 32bit) ---@param image raylib.Image ---@param maxPaletteSize integer ----@param colorCount ffi.cdata* ----@return ffi.cdata* +---@param colorCount? ffi.cdata* +---@return ffi.cdata*, integer function M.LoadImagePalette(image, maxPaletteSize, colorCount) - return C.LoadImagePalette(image, maxPaletteSize, colorCount) + local _n3 = ffi.new("int[1]") + local _p = C.LoadImagePalette(image, maxPaletteSize, _n3) + local _c = _n3[0] + if colorCount ~= nil then colorCount[0] = _c end + return _own_ptr_LoadImagePalette(_p, _c), _c end ---Unload color data loaded with LoadImageColors() ---@param colors ffi.cdata* ---@return nil function M.UnloadImageColors(colors) - C.UnloadImageColors(colors) + if colors == nil then return end + ffi.gc(colors, nil) + if not _dead[colors] then + _release_LoadImageColors(colors) + _st.released = _st.released + 1 + end end ---Unload colors palette loaded with LoadImagePalette() ---@param colors ffi.cdata* ---@return nil function M.UnloadImagePalette(colors) - C.UnloadImagePalette(colors) + if colors == nil then return end + ffi.gc(colors, nil) + if not _dead[colors] then + _release_LoadImagePalette(colors) + _st.released = _st.released + 1 + end end ---Get image alpha border rectangle @@ -6224,9 +6793,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageClearBackground(dst, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageClearBackground(_o1, color) - return _o1[0] + C.ImageClearBackground(ffi.cast("Image *", dst), color) + return dst end ---Draw pixel within an image @@ -6236,9 +6804,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawPixel(dst, posX, posY, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawPixel(_o1, posX, posY, color) - return _o1[0] + C.ImageDrawPixel(ffi.cast("Image *", dst), posX, posY, color) + return dst end ---Draw pixel within an image (Vector version) @@ -6247,9 +6814,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawPixelV(dst, position, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawPixelV(_o1, position, color) - return _o1[0] + C.ImageDrawPixelV(ffi.cast("Image *", dst), position, color) + return dst end ---Draw line within an image @@ -6261,9 +6827,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawLine(dst, startPosX, startPosY, endPosX, endPosY, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawLine(_o1, startPosX, startPosY, endPosX, endPosY, color) - return _o1[0] + C.ImageDrawLine(ffi.cast("Image *", dst), startPosX, startPosY, endPosX, endPosY, color) + return dst end ---Draw line within an image (Vector version) @@ -6273,9 +6838,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawLineV(dst, start, end_, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawLineV(_o1, start, end_, color) - return _o1[0] + C.ImageDrawLineV(ffi.cast("Image *", dst), start, end_, color) + return dst end ---Draw a line defining thickness within an image @@ -6286,9 +6850,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawLineEx(dst, start, end_, thick, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawLineEx(_o1, start, end_, thick, color) - return _o1[0] + C.ImageDrawLineEx(ffi.cast("Image *", dst), start, end_, thick, color) + return dst end ---Draw a lines sequence within an image @@ -6298,12 +6861,11 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawLineStrip(dst, points, pointCount, color) - local _o1 = ffi.new("Image[1]", dst) local _a2 if type(points) == "table" then _a2 = to_array("Vector2", points) else _a2 = points end - C.ImageDrawLineStrip(_o1, _a2, pointCount, color) - return _o1[0] + C.ImageDrawLineStrip(ffi.cast("Image *", dst), _a2, pointCount, color) + return dst end ---Draw triangle within an image @@ -6314,9 +6876,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawTriangle(dst, v1, v2, v3, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawTriangle(_o1, v1, v2, v3, color) - return _o1[0] + C.ImageDrawTriangle(ffi.cast("Image *", dst), v1, v2, v3, color) + return dst end ---Draw triangle with interpolated colors within an image @@ -6329,9 +6890,8 @@ end ---@param c3 raylib.Color ---@return raylib.Image function M.ImageDrawTriangleGradient(dst, v1, v2, v3, c1, c2, c3) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawTriangleGradient(_o1, v1, v2, v3, c1, c2, c3) - return _o1[0] + C.ImageDrawTriangleGradient(ffi.cast("Image *", dst), v1, v2, v3, c1, c2, c3) + return dst end ---Draw triangle outline within an image @@ -6342,9 +6902,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawTriangleLines(dst, v1, v2, v3, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawTriangleLines(_o1, v1, v2, v3, color) - return _o1[0] + C.ImageDrawTriangleLines(ffi.cast("Image *", dst), v1, v2, v3, color) + return dst end ---Draw a triangle fan defined by points within an image (first vertex is the center) @@ -6354,12 +6913,11 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawTriangleFan(dst, points, pointCount, color) - local _o1 = ffi.new("Image[1]", dst) local _a2 if type(points) == "table" then _a2 = to_array("Vector2", points) else _a2 = points end - C.ImageDrawTriangleFan(_o1, _a2, pointCount, color) - return _o1[0] + C.ImageDrawTriangleFan(ffi.cast("Image *", dst), _a2, pointCount, color) + return dst end ---Draw a triangle strip defined by points within an image @@ -6369,12 +6927,11 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawTriangleStrip(dst, points, pointCount, color) - local _o1 = ffi.new("Image[1]", dst) local _a2 if type(points) == "table" then _a2 = to_array("Vector2", points) else _a2 = points end - C.ImageDrawTriangleStrip(_o1, _a2, pointCount, color) - return _o1[0] + C.ImageDrawTriangleStrip(ffi.cast("Image *", dst), _a2, pointCount, color) + return dst end ---Draw rectangle within an image @@ -6386,9 +6943,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawRectangle(dst, posX, posY, width, height, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawRectangle(_o1, posX, posY, width, height, color) - return _o1[0] + C.ImageDrawRectangle(ffi.cast("Image *", dst), posX, posY, width, height, color) + return dst end ---Draw rectangle within an image (Vector version) @@ -6398,9 +6954,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawRectangleV(dst, position, size, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawRectangleV(_o1, position, size, color) - return _o1[0] + C.ImageDrawRectangleV(ffi.cast("Image *", dst), position, size, color) + return dst end ---Draw rectangle within an image @@ -6409,9 +6964,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawRectangleRec(dst, rec, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawRectangleRec(_o1, rec, color) - return _o1[0] + C.ImageDrawRectangleRec(ffi.cast("Image *", dst), rec, color) + return dst end ---Draw a color-filled rectangle with pro parameters within and image @@ -6422,9 +6976,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawRectanglePro(dst, rec, origin, rotation, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawRectanglePro(_o1, rec, origin, rotation, color) - return _o1[0] + C.ImageDrawRectanglePro(ffi.cast("Image *", dst), rec, origin, rotation, color) + return dst end ---Draw rectangle lines within an image @@ -6436,9 +6989,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawRectangleLines(dst, posX, posY, width, height, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawRectangleLines(_o1, posX, posY, width, height, color) - return _o1[0] + C.ImageDrawRectangleLines(ffi.cast("Image *", dst), posX, posY, width, height, color) + return dst end ---Draw rectangle lines within an image with line thickness @@ -6448,9 +7000,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawRectangleLinesEx(dst, rec, thick, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawRectangleLinesEx(_o1, rec, thick, color) - return _o1[0] + C.ImageDrawRectangleLinesEx(ffi.cast("Image *", dst), rec, thick, color) + return dst end ---Draw rectangle with gradient colors within an image, counter-clockwise color order @@ -6462,9 +7013,8 @@ end ---@param col4 raylib.Color ---@return raylib.Image function M.ImageDrawRectangleGradientEx(dst, rec, col1, col2, col3, col4) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawRectangleGradientEx(_o1, rec, col1, col2, col3, col4) - return _o1[0] + C.ImageDrawRectangleGradientEx(ffi.cast("Image *", dst), rec, col1, col2, col3, col4) + return dst end ---Draw a filled circle within an image @@ -6475,9 +7025,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawCircle(dst, centerX, centerY, radius, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawCircle(_o1, centerX, centerY, radius, color) - return _o1[0] + C.ImageDrawCircle(ffi.cast("Image *", dst), centerX, centerY, radius, color) + return dst end ---Draw a filled circle within an image (Vector version) @@ -6487,9 +7036,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawCircleV(dst, center, radius, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawCircleV(_o1, center, radius, color) - return _o1[0] + C.ImageDrawCircleV(ffi.cast("Image *", dst), center, radius, color) + return dst end ---Draw circle outline within an image @@ -6500,9 +7048,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawCircleLines(dst, centerX, centerY, radius, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawCircleLines(_o1, centerX, centerY, radius, color) - return _o1[0] + C.ImageDrawCircleLines(ffi.cast("Image *", dst), centerX, centerY, radius, color) + return dst end ---Draw circle outline within an image (Vector version) @@ -6512,9 +7059,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawCircleLinesV(dst, center, radius, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawCircleLinesV(_o1, center, radius, color) - return _o1[0] + C.ImageDrawCircleLinesV(ffi.cast("Image *", dst), center, radius, color) + return dst end ---Draw a gradient-filled circle within an image @@ -6525,9 +7071,8 @@ end ---@param outer raylib.Color ---@return raylib.Image function M.ImageDrawCircleGradient(dst, center, radius, inner, outer) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawCircleGradient(_o1, center, radius, inner, outer) - return _o1[0] + C.ImageDrawCircleGradient(ffi.cast("Image *", dst), center, radius, inner, outer) + return dst end ---Draw an image within an image @@ -6538,9 +7083,8 @@ end ---@param tint raylib.Color ---@return raylib.Image function M.ImageDrawImage(dst, src, posX, posY, tint) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawImage(_o1, src, posX, posY, tint) - return _o1[0] + C.ImageDrawImage(ffi.cast("Image *", dst), src, posX, posY, tint) + return dst end ---Draw an image with scaling and rotation within an image @@ -6552,9 +7096,8 @@ end ---@param tint raylib.Color ---@return raylib.Image function M.ImageDrawImageEx(dst, src, position, rotation, scale, tint) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawImageEx(_o1, src, position, rotation, scale, tint) - return _o1[0] + C.ImageDrawImageEx(ffi.cast("Image *", dst), src, position, rotation, scale, tint) + return dst end ---Draw a part of an image defined by a rectangle within an image @@ -6565,9 +7108,8 @@ end ---@param tint raylib.Color ---@return raylib.Image function M.ImageDrawImageRec(dst, src, srcRec, position, tint) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawImageRec(_o1, src, srcRec, position, tint) - return _o1[0] + C.ImageDrawImageRec(ffi.cast("Image *", dst), src, srcRec, position, tint) + return dst end ---Draw a part of an image defined by a rectangle into destination rectangle, with scaling and rotation, within an image @@ -6580,9 +7122,8 @@ end ---@param tint raylib.Color ---@return raylib.Image function M.ImageDrawImagePro(dst, src, srcRec, dstRec, origin, rotation, tint) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawImagePro(_o1, src, srcRec, dstRec, origin, rotation, tint) - return _o1[0] + C.ImageDrawImagePro(ffi.cast("Image *", dst), src, srcRec, dstRec, origin, rotation, tint) + return dst end ---Draw text (using default font) within an image (destination) @@ -6594,9 +7135,8 @@ end ---@param color raylib.Color ---@return raylib.Image function M.ImageDrawText(dst, text, posX, posY, fontSize, color) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawText(_o1, text, posX, posY, fontSize, color) - return _o1[0] + C.ImageDrawText(ffi.cast("Image *", dst), text, posX, posY, fontSize, color) + return dst end ---Draw text (custom sprite font) within an image (destination) @@ -6609,9 +7149,8 @@ end ---@param tint raylib.Color ---@return raylib.Image function M.ImageDrawTextEx(dst, font, text, position, fontSize, spacing, tint) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawTextEx(_o1, font, text, position, fontSize, spacing, tint) - return _o1[0] + C.ImageDrawTextEx(ffi.cast("Image *", dst), font, text, position, fontSize, spacing, tint) + return dst end ---Draw text using Font and pro parameters (rotation) @@ -6626,23 +7165,22 @@ end ---@param tint raylib.Color ---@return raylib.Image function M.ImageDrawTextPro(dst, font, text, position, origin, rotation, fontSize, spacing, tint) - local _o1 = ffi.new("Image[1]", dst) - C.ImageDrawTextPro(_o1, font, text, position, origin, rotation, fontSize, spacing, tint) - return _o1[0] + C.ImageDrawTextPro(ffi.cast("Image *", dst), font, text, position, origin, rotation, fontSize, spacing, tint) + return dst end ---Load texture from file into GPU memory (VRAM) ---@param fileName string ---@return raylib.Texture2D function M.LoadTexture(fileName) - return C.LoadTexture(fileName) + return _own_Texture(C.LoadTexture(fileName)) end ---Load texture from image data ---@param image raylib.Image ---@return raylib.Texture2D function M.LoadTextureFromImage(image) - return C.LoadTextureFromImage(image) + return _own_Texture(C.LoadTextureFromImage(image)) end ---Load cubemap from image, multiple image cubemap layouts supported @@ -6650,7 +7188,7 @@ end ---@param layout integer ---@return raylib.TextureCubemap function M.LoadTextureCubemap(image, layout) - return C.LoadTextureCubemap(image, layout) + return _own_Texture(C.LoadTextureCubemap(image, layout)) end ---Load texture for rendering (framebuffer) @@ -6658,7 +7196,7 @@ end ---@param height integer ---@return raylib.RenderTexture2D function M.LoadRenderTexture(width, height) - return C.LoadRenderTexture(width, height) + return _own_RenderTexture(C.LoadRenderTexture(width, height)) end ---Load texture for rendering (framebuffer), with specific format @@ -6667,7 +7205,7 @@ end ---@param format integer ---@return raylib.RenderTexture2D function M.LoadRenderTextureEx(width, height, format) - return C.LoadRenderTextureEx(width, height, format) + return _own_RenderTexture(C.LoadRenderTextureEx(width, height, format)) end ---Check if texture is valid (loaded in GPU) @@ -6681,7 +7219,17 @@ end ---@param texture raylib.Texture2D ---@return nil function M.UnloadTexture(texture) - C.UnloadTexture(texture) + if texture == nil then return end + ffi.gc(texture, nil) + if not _can_unload("gpu") then + _dead[texture] = true + ffi.fill(texture, ffi.sizeof(texture)) + return + end + if not _dead[texture] then + _release_Texture(texture) + _st.released = _st.released + 1 + end end ---Check if render texture is valid (loaded in GPU) @@ -6695,7 +7243,17 @@ end ---@param target raylib.RenderTexture2D ---@return nil function M.UnloadRenderTexture(target) - C.UnloadRenderTexture(target) + if target == nil then return end + ffi.gc(target, nil) + if not _can_unload("gpu") then + _dead[target] = true + ffi.fill(target, ffi.sizeof(target)) + return + end + if not _dead[target] then + _release_RenderTexture(target) + _st.released = _st.released + 1 + end end ---Update GPU texture with new data (pixels should be able to fill texture) @@ -6725,9 +7283,8 @@ end ---@param texture raylib.Texture2D ---@return raylib.Texture2D function M.GenTextureMipmaps(texture) - local _o1 = ffi.new("Texture2D[1]", texture) - C.GenTextureMipmaps(_o1) - return _o1[0] + C.GenTextureMipmaps(ffi.cast("Texture2D *", texture)) + return texture end ---Set texture scaling filter mode @@ -6953,6 +7510,7 @@ function M.GetPixelDataSize(width, height, format) end ---Get the default Font +---NOTE: this is a view; raylib owns the default font. ---@return raylib.Font function M.GetFontDefault() return C.GetFontDefault() @@ -6962,7 +7520,7 @@ end ---@param fileName string ---@return raylib.Font function M.LoadFont(fileName) - return C.LoadFont(fileName) + return _own_Font(C.LoadFont(fileName)) end ---Load font from file with defined codepoints and generation size, use NULL for codepoints and 0 for codepointCount to load the default character set, font size is provided in pixels height @@ -6975,7 +7533,7 @@ function M.LoadFontEx(fileName, fontSize, codepoints, codepointCount) local _a3 if type(codepoints) == "table" then _a3 = to_array("int", codepoints) else _a3 = codepoints end - return C.LoadFontEx(fileName, fontSize, _a3, codepointCount) + return _own_Font(C.LoadFontEx(fileName, fontSize, _a3, codepointCount)) end ---Load font from Image (XNA style) @@ -6984,7 +7542,7 @@ end ---@param firstChar integer ---@return raylib.Font function M.LoadFontFromImage(image, key, firstChar) - return C.LoadFontFromImage(image, key, firstChar) + return _own_Font(C.LoadFontFromImage(image, key, firstChar)) end ---Load font from memory buffer, fileType refers to extension: i.e. '.ttf' @@ -7003,7 +7561,7 @@ function M.LoadFontFromMemory(fileType, fileData, dataSize, fontSize, codepoints local _a5 if type(codepoints) == "table" then _a5 = to_array("int", codepoints) else _a5 = codepoints end - return C.LoadFontFromMemory(fileType, _a2, dataSize, fontSize, _a5, codepointCount) + return _own_Font(C.LoadFontFromMemory(fileType, _a2, dataSize, fontSize, _a5, codepointCount)) end ---Check if font is valid (font data loaded, WARNING: GPU texture not checked) @@ -7020,8 +7578,8 @@ end ---@param codepoints integer[] ---@param codepointCount integer ---@param type integer ----@param glyphCount ffi.cdata* ----@return ffi.cdata* +---@param glyphCount? ffi.cdata* +---@return ffi.cdata*, integer function M.LoadFontData(fileData, dataSize, fontSize, codepoints, codepointCount, type, glyphCount) local _a1 if type(fileData) == "string" then _a1 = ffi.cast("const unsigned char *", fileData) @@ -7030,22 +7588,31 @@ function M.LoadFontData(fileData, dataSize, fontSize, codepoints, codepointCount local _a4 if type(codepoints) == "table" then _a4 = to_array("int", codepoints) else _a4 = codepoints end - return C.LoadFontData(_a1, dataSize, fontSize, _a4, codepointCount, type, glyphCount) + local _n7 = ffi.new("int[1]") + local _p = C.LoadFontData(_a1, dataSize, fontSize, _a4, codepointCount, type, _n7) + local _c = _n7[0] + if glyphCount ~= nil then glyphCount[0] = _c end + return _own_ptr_LoadFontData(_p, _c), _c end ---Generate image font atlas using chars info ----@param glyphs raylib.GlyphInfo[] ----@param glyphRecs ffi.cdata* +---@param glyphs raylib.GlyphInfo[]|ffi.cdata* ---@param glyphCount integer ---@param fontSize integer ---@param padding integer ---@param packMethod integer ----@return raylib.Image -function M.GenImageFontAtlas(glyphs, glyphRecs, glyphCount, fontSize, padding, packMethod) +---@return raylib.Image, ffi.cdata* +-- NOTE: the Rectangle* out-param belongs to the returned Image and is +-- released with it; the second result is a borrowed view. +function M.GenImageFontAtlas(glyphs, glyphCount, fontSize, padding, packMethod) local _a1 - if type(glyphs) == "table" then _a1 = to_array("GlyphInfo", glyphs) - else _a1 = glyphs end - return C.GenImageFontAtlas(_a1, glyphRecs, glyphCount, fontSize, padding, packMethod) + if type(glyphs) == "table" then _a1 = to_array("GlyphInfo", glyphs) else _a1 = glyphs end + local _recs = ffi.new("Rectangle *[1]") + local _img = C.GenImageFontAtlas(_a1, _recs, glyphCount, fontSize, padding, packMethod) + if _recs[0] == nil then + return _own_Image(_img), nil + end + return _own_Image_extra(_img, { ffi.cast("void *", _recs[0]) }), _recs[0] end ---Unload font chars info data (RAM) @@ -7053,14 +7620,29 @@ end ---@param glyphCount integer ---@return nil function M.UnloadFontData(glyphs, glyphCount) - C.UnloadFontData(glyphs, glyphCount) + if glyphs == nil then return end + ffi.gc(glyphs, nil) + if not _dead[glyphs] then + _release_LoadFontData(glyphs, glyphCount) + _st.released = _st.released + 1 + end end ---Unload font from GPU memory (VRAM) ---@param font raylib.Font ---@return nil function M.UnloadFont(font) - C.UnloadFont(font) + if font == nil then return end + ffi.gc(font, nil) + if not _can_unload("gpu") then + _dead[font] = true + ffi.fill(font, ffi.sizeof(font)) + return + end + if not _dead[font] then + _release_Font(font) + _st.released = _st.released + 1 + end end ---Export font as code file, returns true on success @@ -7191,6 +7773,7 @@ function M.GetGlyphIndex(font, codepoint) end ---Get glyph font info data for a codepoint (unicode character), fallback to '?' if not found +---NOTE: the returned GlyphInfo.image.data aliases the font's glyph array; keep the font alive while using it. ---@param font raylib.Font ---@param codepoint integer ---@return raylib.GlyphInfo @@ -7232,17 +7815,26 @@ end ---Load all codepoints from a UTF-8 text string, codepoints count returned by parameter ---@param text string ----@param count ffi.cdata* ----@return ffi.cdata* +---@param count? ffi.cdata* +---@return ffi.cdata*, integer function M.LoadCodepoints(text, count) - return C.LoadCodepoints(text, count) + local _n2 = ffi.new("int[1]") + local _p = C.LoadCodepoints(text, _n2) + local _c = _n2[0] + if count ~= nil then count[0] = _c end + return _own_ptr_LoadCodepoints(_p, _c), _c end ---Unload codepoints data from memory ---@param codepoints ffi.cdata* ---@return nil function M.UnloadCodepoints(codepoints) - C.UnloadCodepoints(codepoints) + if codepoints == nil then return end + ffi.gc(codepoints, nil) + if not _dead[codepoints] then + _release_LoadCodepoints(codepoints) + _st.released = _st.released + 1 + end end ---Get total number of codepoints in a UTF-8 encoded string @@ -7288,10 +7880,14 @@ end ---Load text as separate lines ('\n') ---@param text string ----@param count ffi.cdata* ----@return ffi.cdata* +---@param count? ffi.cdata* +---@return ffi.cdata*, integer function M.LoadTextLines(text, count) - return C.LoadTextLines(text, count) + local _n2 = ffi.new("int[1]") + local _p = C.LoadTextLines(text, _n2) + local _c = _n2[0] + if count ~= nil then count[0] = _c end + return _own_ptr_LoadTextLines(_p, _c), _c end ---Unload text lines @@ -7299,10 +7895,12 @@ end ---@param lineCount integer ---@return nil function M.UnloadTextLines(text, lineCount) - local _a1 - if type(text) == "table" then _a1 = ffi.cast("char **", to_array("const char *", text)) - else _a1 = text end - C.UnloadTextLines(_a1, lineCount) + if text == nil then return end + ffi.gc(text, nil) + if not _dead[text] then + _release_LoadTextLines(text, lineCount) + _st.released = _st.released + 1 + end end ---Copy one string to another, returns bytes copied @@ -7807,14 +8405,19 @@ end ---@param fileName string ---@return raylib.Model function M.LoadModel(fileName) - return C.LoadModel(fileName) + return _own_Model(C.LoadModel(fileName)) end ---Load model from generated mesh (default material) ---@param mesh raylib.Mesh ---@return raylib.Model +-- NOTE: the mesh's data becomes part of the model; the mesh is consumed +-- (disarmed and zeroed), so a later UnloadMesh(mesh) is a no-op. function M.LoadModelFromMesh(mesh) - return C.LoadModelFromMesh(mesh) + local _r = C.LoadModelFromMesh(mesh) + local _o = _own_Model(_r) + if _r.meshCount > 0 then _consume(mesh) end + return _o end ---Check if model is valid (loaded in GPU, VAO/VBOs) @@ -7828,7 +8431,17 @@ end ---@param model raylib.Model ---@return nil function M.UnloadModel(model) - C.UnloadModel(model) + if model == nil then return end + ffi.gc(model, nil) + if not _can_unload("gpu") then + _dead[model] = true + ffi.fill(model, ffi.sizeof(model)) + return + end + if not _dead[model] then + _release_Model(model) + _st.released = _st.released + 1 + end end ---Compute model bounding box limits (considers all meshes) @@ -7933,9 +8546,8 @@ end ---@param dynamic boolean ---@return raylib.Mesh function M.UploadMesh(mesh, dynamic) - local _o1 = ffi.new("Mesh[1]", mesh) - C.UploadMesh(_o1, dynamic) - return _o1[0] + C.UploadMesh(ffi.cast("Mesh *", mesh), dynamic) + return mesh end ---Update mesh vertex data in GPU for a specific buffer index @@ -7956,7 +8568,17 @@ end ---@param mesh raylib.Mesh ---@return nil function M.UnloadMesh(mesh) - C.UnloadMesh(mesh) + if mesh == nil then return end + ffi.gc(mesh, nil) + if not _can_unload("gpu") then + _dead[mesh] = true + ffi.fill(mesh, ffi.sizeof(mesh)) + return + end + if not _dead[mesh] then + _release_Mesh(mesh) + _st.released = _st.released + 1 + end end ---Draw a 3d mesh with material and transform @@ -7992,9 +8614,8 @@ end ---@param mesh raylib.Mesh ---@return raylib.Mesh function M.GenMeshTangents(mesh) - local _o1 = ffi.new("Mesh[1]", mesh) - C.GenMeshTangents(_o1) - return _o1[0] + C.GenMeshTangents(ffi.cast("Mesh *", mesh)) + return mesh end ---Export mesh data to file, returns true on success @@ -8018,7 +8639,7 @@ end ---@param radius number ---@return raylib.Mesh function M.GenMeshPoly(sides, radius) - return C.GenMeshPoly(sides, radius) + return _own_Mesh(C.GenMeshPoly(sides, radius)) end ---Generate plane mesh (with subdivisions) @@ -8028,7 +8649,7 @@ end ---@param resZ integer ---@return raylib.Mesh function M.GenMeshPlane(width, length, resX, resZ) - return C.GenMeshPlane(width, length, resX, resZ) + return _own_Mesh(C.GenMeshPlane(width, length, resX, resZ)) end ---Generate cuboid mesh @@ -8037,7 +8658,7 @@ end ---@param length number ---@return raylib.Mesh function M.GenMeshCube(width, height, length) - return C.GenMeshCube(width, height, length) + return _own_Mesh(C.GenMeshCube(width, height, length)) end ---Generate sphere mesh (standard sphere) @@ -8046,7 +8667,7 @@ end ---@param slices integer ---@return raylib.Mesh function M.GenMeshSphere(radius, rings, slices) - return C.GenMeshSphere(radius, rings, slices) + return _own_Mesh(C.GenMeshSphere(radius, rings, slices)) end ---Generate half-sphere mesh (no bottom cap) @@ -8055,7 +8676,7 @@ end ---@param slices integer ---@return raylib.Mesh function M.GenMeshHemiSphere(radius, rings, slices) - return C.GenMeshHemiSphere(radius, rings, slices) + return _own_Mesh(C.GenMeshHemiSphere(radius, rings, slices)) end ---Generate cylinder mesh @@ -8064,7 +8685,7 @@ end ---@param slices integer ---@return raylib.Mesh function M.GenMeshCylinder(radius, height, slices) - return C.GenMeshCylinder(radius, height, slices) + return _own_Mesh(C.GenMeshCylinder(radius, height, slices)) end ---Generate cone/pyramid mesh @@ -8073,7 +8694,7 @@ end ---@param slices integer ---@return raylib.Mesh function M.GenMeshCone(radius, height, slices) - return C.GenMeshCone(radius, height, slices) + return _own_Mesh(C.GenMeshCone(radius, height, slices)) end ---Generate torus mesh @@ -8083,7 +8704,7 @@ end ---@param sides integer ---@return raylib.Mesh function M.GenMeshTorus(radius, size, radSeg, sides) - return C.GenMeshTorus(radius, size, radSeg, sides) + return _own_Mesh(C.GenMeshTorus(radius, size, radSeg, sides)) end ---Generate trefoil knot mesh @@ -8093,7 +8714,7 @@ end ---@param sides integer ---@return raylib.Mesh function M.GenMeshKnot(radius, size, radSeg, sides) - return C.GenMeshKnot(radius, size, radSeg, sides) + return _own_Mesh(C.GenMeshKnot(radius, size, radSeg, sides)) end ---Generate heightmap mesh from image data @@ -8101,7 +8722,7 @@ end ---@param size raylib.Vector3 ---@return raylib.Mesh function M.GenMeshHeightmap(heightmap, size) - return C.GenMeshHeightmap(heightmap, size) + return _own_Mesh(C.GenMeshHeightmap(heightmap, size)) end ---Generate cubes-based map mesh from image data @@ -8109,21 +8730,25 @@ end ---@param cubeSize raylib.Vector3 ---@return raylib.Mesh function M.GenMeshCubicmap(cubicmap, cubeSize) - return C.GenMeshCubicmap(cubicmap, cubeSize) + return _own_Mesh(C.GenMeshCubicmap(cubicmap, cubeSize)) end ---Load materials from model file ---@param fileName string ----@param materialCount ffi.cdata* ----@return ffi.cdata* +---@param materialCount? ffi.cdata* +---@return ffi.cdata*, integer function M.LoadMaterials(fileName, materialCount) - return C.LoadMaterials(fileName, materialCount) + local _n2 = ffi.new("int[1]") + local _p = C.LoadMaterials(fileName, _n2) + local _c = _n2[0] + if materialCount ~= nil then materialCount[0] = _c end + return _own_ptr_LoadMaterials(_p, _c), _c end ---Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) ---@return raylib.Material function M.LoadMaterialDefault() - return C.LoadMaterialDefault() + return _own_Material(C.LoadMaterialDefault()) end ---Check if material is valid (shader assigned, map textures loaded in GPU) @@ -8137,18 +8762,26 @@ end ---@param material raylib.Material ---@return nil function M.UnloadMaterial(material) - C.UnloadMaterial(material) + if material == nil then return end + ffi.gc(material, nil) + if not _dead[material] then + _release_Material(material) + _st.released = _st.released + 1 + end end ---Set texture for a material map type (MATERIAL_MAP_DIFFUSE, MATERIAL_MAP_SPECULAR...) ---@param material raylib.Material ---@param mapType integer ---@param texture raylib.Texture2D ----@return raylib.Material +---@return nil +-- NOTE: the texture is pinned by the material's maps address (the material +-- may be a reference cdata such as model.materials[i]). function M.SetMaterialTexture(material, mapType, texture) - local _o1 = ffi.new("Material[1]", material) - C.SetMaterialTexture(_o1, mapType, texture) - return _o1[0] + if material.maps ~= nil then + _pins.material[tostring(ffi.cast("void *", material.maps))] = texture + end + C.SetMaterialTexture(ffi.cast("Material *", material), mapType, texture) end ---Set material for a mesh @@ -8157,17 +8790,21 @@ end ---@param materialId integer ---@return raylib.Model function M.SetModelMeshMaterial(model, meshId, materialId) - local _o1 = ffi.new("Model[1]", model) - C.SetModelMeshMaterial(_o1, meshId, materialId) - return _o1[0] + C.SetModelMeshMaterial(ffi.cast("Model *", model), meshId, materialId) + return model end ---Load model animations from file ---@param fileName string ----@param animCount ffi.cdata* ----@return ffi.cdata* +---@param animCount? ffi.cdata* +---@return ffi.cdata*, integer function M.LoadModelAnimations(fileName, animCount) - return C.LoadModelAnimations(fileName, animCount) + local _n2 = ffi.new("int[1]") + _n2[0] = 0 + local _p = C.LoadModelAnimations(fileName, _n2) + local _c = _n2[0] + if animCount ~= nil then animCount[0] = _c end + return _own_ptr_LoadModelAnimations(_p, _c), _c end ---Update model animation pose (vertex buffers and bone matrices) @@ -8196,7 +8833,12 @@ end ---@param animCount integer ---@return nil function M.UnloadModelAnimations(animations, animCount) - C.UnloadModelAnimations(animations, animCount) + if animations == nil then return end + ffi.gc(animations, nil) + if not _dead[animations] then + _release_LoadModelAnimations(animations, animCount) + _st.released = _st.released + 1 + end end ---Check model animation skeleton match @@ -8316,7 +8958,7 @@ end ---@param fileName string ---@return raylib.Wave function M.LoadWave(fileName) - return C.LoadWave(fileName) + return _own_Wave(C.LoadWave(fileName)) end ---Load wave from memory buffer, fileType refers to extension: i.e. '.wav' @@ -8329,7 +8971,7 @@ function M.LoadWaveFromMemory(fileType, fileData, dataSize) if type(fileData) == "string" then _a2 = ffi.cast("const unsigned char *", fileData) elseif type(fileData) == "table" then _a2 = to_array("unsigned char", fileData) else _a2 = fileData end - return C.LoadWaveFromMemory(fileType, _a2, dataSize) + return _own_Wave(C.LoadWaveFromMemory(fileType, _a2, dataSize)) end ---Check if wave data is valid (data loaded and parameters) @@ -8343,21 +8985,24 @@ end ---@param fileName string ---@return raylib.Sound function M.LoadSound(fileName) - return C.LoadSound(fileName) + return _own_Sound(C.LoadSound(fileName)) end ---Load sound from wave data ---@param wave raylib.Wave ---@return raylib.Sound function M.LoadSoundFromWave(wave) - return C.LoadSoundFromWave(wave) + return _own_Sound(C.LoadSoundFromWave(wave)) end ---Load sound alias, new sound that shares the same sample data as the source sound, does not own the sound data ---@param source raylib.Sound ---@return raylib.Sound +-- NOTE: the alias shares the source's sample data; the source is kept +-- alive until the alias is released, and the alias is released with +-- UnloadSoundAlias (not UnloadSound). function M.LoadSoundAlias(source) - return C.LoadSoundAlias(source) + return _own_SoundAlias_keep(C.LoadSoundAlias(source), source) end ---Check if sound is valid (data loaded and buffers initialized) @@ -8383,21 +9028,46 @@ end ---@param wave raylib.Wave ---@return nil function M.UnloadWave(wave) - C.UnloadWave(wave) + if wave == nil then return end + ffi.gc(wave, nil) + if not _dead[wave] then + _release_Wave(wave) + _st.released = _st.released + 1 + end end ---Unload sound ---@param sound raylib.Sound ---@return nil function M.UnloadSound(sound) - C.UnloadSound(sound) + if sound == nil then return end + ffi.gc(sound, nil) + if not _can_unload("audio") then + _dead[sound] = true + ffi.fill(sound, ffi.sizeof(sound)) + return + end + if not _dead[sound] then + _release_Sound(sound) + _st.released = _st.released + 1 + end end ---Unload sound alias (does not deallocate sample data) ---@param alias raylib.Sound ---@return nil function M.UnloadSoundAlias(alias) - C.UnloadSoundAlias(alias) + if alias == nil then return end + ffi.gc(alias, nil) + if not _can_unload("audio") then + _dead[alias] = true + ffi.fill(alias, ffi.sizeof(alias)) + return + end + if not _dead[alias] then + _release_SoundAlias(alias) + _st.released = _st.released + 1 + end end ---Export wave data to file, returns true on success @@ -8479,7 +9149,7 @@ end ---@param wave raylib.Wave ---@return raylib.Wave function M.WaveCopy(wave) - return C.WaveCopy(wave) + return _own_Wave(C.WaveCopy(wave)) end ---Crop a wave to defined frames range @@ -8488,9 +9158,8 @@ end ---@param finalFrame integer ---@return raylib.Wave function M.WaveCrop(wave, initFrame, finalFrame) - local _o1 = ffi.new("Wave[1]", wave) - C.WaveCrop(_o1, initFrame, finalFrame) - return _o1[0] + C.WaveCrop(ffi.cast("Wave *", wave), initFrame, finalFrame) + return wave end ---Convert wave data to desired format @@ -8500,43 +9169,49 @@ end ---@param channels integer ---@return raylib.Wave function M.WaveFormat(wave, sampleRate, sampleSize, channels) - local _o1 = ffi.new("Wave[1]", wave) - C.WaveFormat(_o1, sampleRate, sampleSize, channels) - return _o1[0] + C.WaveFormat(ffi.cast("Wave *", wave), sampleRate, sampleSize, channels) + return wave end ---Load samples data from wave as a 32bit float data array ---@param wave raylib.Wave ---@return ffi.cdata* function M.LoadWaveSamples(wave) - return C.LoadWaveSamples(wave) + return _own_ptr_LoadWaveSamples(C.LoadWaveSamples(wave)) end ---Unload samples data loaded with LoadWaveSamples() ---@param samples ffi.cdata* ---@return nil function M.UnloadWaveSamples(samples) - C.UnloadWaveSamples(samples) + if samples == nil then return end + ffi.gc(samples, nil) + if not _dead[samples] then + _release_LoadWaveSamples(samples) + _st.released = _st.released + 1 + end end ---Load music stream from file ---@param fileName string ---@return raylib.Music function M.LoadMusicStream(fileName) - return C.LoadMusicStream(fileName) + return _own_Music(C.LoadMusicStream(fileName)) end ---Load music stream from data ---@param fileType string ----@param data string|integer[] +---@param data string|integer[]|ffi.cdata* ---@param dataSize integer ---@return raylib.Music +-- NOTE: raylib retains the buffer; it is kept alive until the Music is +-- released (a finalizer upvalue, not a weak map). function M.LoadMusicStreamFromMemory(fileType, data, dataSize) local _a2 if type(data) == "string" then _a2 = ffi.cast("const unsigned char *", data) elseif type(data) == "table" then _a2 = to_array("unsigned char", data) else _a2 = data end - return C.LoadMusicStreamFromMemory(fileType, _a2, dataSize) + return _own_Music_keep(C.LoadMusicStreamFromMemory(fileType, _a2, dataSize), _a2) end ---Check if music stream is valid (context and buffers initialized) @@ -8550,7 +9225,17 @@ end ---@param music raylib.Music ---@return nil function M.UnloadMusicStream(music) - C.UnloadMusicStream(music) + if music == nil then return end + ffi.gc(music, nil) + if not _can_unload("audio") then + _dead[music] = true + ffi.fill(music, ffi.sizeof(music)) + return + end + if not _dead[music] then + _release_Music(music) + _st.released = _st.released + 1 + end end ---Start music playing @@ -8647,7 +9332,7 @@ end ---@param channels integer ---@return raylib.AudioStream function M.LoadAudioStream(sampleRate, sampleSize, channels) - return C.LoadAudioStream(sampleRate, sampleSize, channels) + return _own_AudioStream(C.LoadAudioStream(sampleRate, sampleSize, channels)) end ---Check if an audio stream is valid (buffers initialized) @@ -8661,7 +9346,17 @@ end ---@param stream raylib.AudioStream ---@return nil function M.UnloadAudioStream(stream) - C.UnloadAudioStream(stream) + if stream == nil then return end + ffi.gc(stream, nil) + if not _can_unload("audio") then + _dead[stream] = true + ffi.fill(stream, ffi.sizeof(stream)) + return + end + if not _dead[stream] then + _release_AudioStream(stream) + _st.released = _st.released + 1 + end end ---Update audio stream buffers with data @@ -9478,14 +10173,19 @@ end ---@param bufferElements integer ---@return raylib.rlRenderBatch function M.rlLoadRenderBatch(numBuffers, bufferElements) - return C.rlLoadRenderBatch(numBuffers, bufferElements) + return _own_ptr_rlLoadRenderBatch(C.rlLoadRenderBatch(numBuffers, bufferElements)) end ---Unload render batch system ---@param batch raylib.rlRenderBatch ---@return nil function M.rlUnloadRenderBatch(batch) - C.rlUnloadRenderBatch(batch) + if batch == nil then return end + ffi.gc(batch, nil) + if not _dead[batch] then + _release_rlLoadRenderBatch(batch) + _st.released = _st.released + 1 + end end ---Draw render batch data (Update->Draw->Reset) @@ -9766,7 +10466,7 @@ end ---@param format integer ---@return ffi.cdata* function M.rlReadTexturePixels(id, width, height, format) - return C.rlReadTexturePixels(id, width, height, format) + return _own_ptr_rlReadTexturePixels(C.rlReadTexturePixels(id, width, height, format)) end ---Read screen pixel data (color buffer) @@ -9774,7 +10474,7 @@ end ---@param height integer ---@return ffi.cdata* function M.rlReadScreenPixels(width, height) - return C.rlReadScreenPixels(width, height) + return _own_ptr_rlReadScreenPixels(C.rlReadScreenPixels(width, height)) end ---Load an empty framebuffer diff --git a/tests/cases/01_many_textures.lua b/tests/cases/01_many_textures.lua new file mode 100644 index 0000000..e839b39 --- /dev/null +++ b/tests/cases/01_many_textures.lua @@ -0,0 +1,46 @@ +-- 01: 10k textures all reach the GC and are released; RSS plateaus. +local M = dofile("tests/helpers.lua") +local R = M.load() + +if not M.window(64, 64) then + M.skip("01_many_textures", "no window") + return +end + +M.reset() +local N = 10000 +local img = R.GenImageColor(2, 2, R.RED) +M.ok(img.data ~= nil, "source image valid") + +local b0 = M.snapshot() +do + local tex = {} + for i = 1, N do tex[i] = R.LoadTextureFromImage(img) end +end + +M.eq(M.delta(b0, "armed"), N, "armed delta after batch 1") +M.gc(3) +M.eq(M.delta(b0, "released"), N, "released delta after batch 1") +M.eq(M.delta(b0, "errors"), 0, "errors after batch 1") + +-- Second batch: compared against the RSS after the first batch has been +-- collected, so allocator warm-up does not count as growth. +local rss1 = M.rss_kb() +local b1 = M.snapshot() +do + local tex = {} + for i = 1, N do tex[i] = R.LoadTextureFromImage(img) end +end +M.gc(3) +M.eq(M.delta(b1, "released"), N, "released delta after batch 2") +M.eq(M.delta(b1, "errors"), 0, "errors after batch 2") + +local rss2 = M.rss_kb() +if rss1 > 0 then + local growth = (rss2 - rss1) / rss1 + M.ok(growth < 0.05, string.format( + "rss did not plateau: %d kB -> %d kB (%.1f%%)", rss1, rss2, growth * 100)) +end + +R.UnloadImage(img) +print("ok 01_many_textures") diff --git a/tests/cases/02_explicit.lua b/tests/cases/02_explicit.lua new file mode 100644 index 0000000..52b96f7 --- /dev/null +++ b/tests/cases/02_explicit.lua @@ -0,0 +1,35 @@ +-- 02: explicit UnloadImage is immediate, idempotent, and does not double-free +-- when the object is later collected. +local M = dofile("tests/helpers.lua") +local R = M.load() + +M.reset() +local b = M.snapshot() + +local img = R.GenImageColor(4, 4, R.RED) +M.ok(img.data ~= nil, "image data allocated") +M.eq(M.delta(b, "armed"), 1, "image armed") + +R.UnloadImage(img) +M.eq(M.delta(b, "released"), 1, "explicit unload released exactly once") +M.eq(img.data, nil, "img.data nil after unload") +M.eq(img.width, 0, "img.width zero after unload") +M.eq(img.height, 0, "img.height zero after unload") + +-- Calling it again is a no-op. +R.UnloadImage(img) +M.eq(M.delta(b, "released"), 1, "second explicit unload is a no-op") + +-- Dropping the disarmed object must not release it a second time. +img = nil +M.gc(3) +M.eq(M.delta(b, "released"), 1, "GC after explicit unload is a no-op") + +-- A plain GC-collected image releases exactly once. +local img2 = R.GenImageColor(4, 4, R.RED) +img2 = nil +M.gc(3) +M.eq(M.delta(b, "released"), 2, "GC released the second image exactly once") +M.eq(M.delta(b, "errors"), 0, "no finalizer errors") + +print("ok 02_explicit") diff --git a/tests/cases/03_borrowed.lua b/tests/cases/03_borrowed.lua new file mode 100644 index 0000000..c5f9f45 --- /dev/null +++ b/tests/cases/03_borrowed.lua @@ -0,0 +1,32 @@ +-- 03: GetShapesTexture / GetFontDefault return borrowed views: they must not +-- be armed and must stay stable across a GC cycle. +local M = dofile("tests/helpers.lua") +local R = M.load() + +if not M.window(64, 64) then + M.skip("03_borrowed", "no window") + return +end + +M.reset() +local b = M.snapshot() + +local a = R.GetShapesTexture() +local f = R.GetFontDefault() +local ida, idb = a.id, f.texture.id +M.ok(ida ~= 0, "default shapes texture has an id") +M.eq(M.delta(b, "armed"), 0, "borrowed shapes texture was not armed") + +-- Drop the views (and anything derived from them) and force a full GC. If +-- these were armed, the finalizers would unload raylib's static resources. +a, f = nil, nil +M.gc(3) + +local a2 = R.GetShapesTexture() +local f2 = R.GetFontDefault() +M.eq(a2.id, ida, "shapes texture id survived GC") +M.eq(f2.texture.id, idb, "default font texture id survived GC") +M.eq(M.delta(b, "armed"), 0, "no borrowed resource was armed") +M.eq(M.delta(b, "errors"), 0, "no finalizer errors") + +print("ok 03_borrowed") diff --git a/tests/cases/04_model_from_mesh.lua b/tests/cases/04_model_from_mesh.lua new file mode 100644 index 0000000..86f7a97 --- /dev/null +++ b/tests/cases/04_model_from_mesh.lua @@ -0,0 +1,45 @@ +-- 04: LoadModelFromMesh consumes the mesh; unloading the model releases it +-- once, and a saved (zeroed) mesh copy is a harmless no-op. +local M = dofile("tests/helpers.lua") +local ffi = require("ffi") +local R = M.load() + +if not M.window(64, 64) then + M.skip("04_model_from_mesh", "no window") + return +end + +M.reset() +local b = M.snapshot() + +local mesh = R.GenMeshCube(1, 1, 1) +M.ok(mesh.vertexCount > 0, "cube mesh built") + +local model = R.LoadModelFromMesh(mesh) +M.eq(model.meshCount, 1, "model has one mesh") +M.ok(model.meshes[0].vertexCount > 0, "model mesh is valid") +if R.IsModelReady ~= nil then + M.ok(R.IsModelReady(model), "model is ready") +end + +-- Ownership moved to the model: the mesh was disarmed and zeroed. +M.ok(mesh.vertices == nil, + "mesh was consumed (vertices cleared) by LoadModelFromMesh") +local mesh_copy = ffi.new("Mesh[1]", mesh) + +mesh = nil +M.gc(3) +M.eq(M.delta(b, "released"), 0, "consumed mesh was not released separately") +M.eq(M.delta(b, "errors"), 0, "no finalizer errors before unload") + +R.UnloadModel(model) +M.eq(M.delta(b, "released"), 1, "UnloadModel released exactly once") + +-- A saved copy of the (zeroed) mesh must be a no-op, not a crash/double free. +R.UnloadMesh(mesh_copy[0]) +M.eq(M.delta(b, "errors"), 0, "saved mesh copy raised no errors") +M.ok(M.delta(b, "released") <= 2, + "saved mesh copy did not free the model's mesh again") +M.eq(M.delta(b, "errors"), 0, "no finalizer errors") + +print("ok 04_model_from_mesh") diff --git a/tests/cases/05_sound_alias.lua b/tests/cases/05_sound_alias.lua new file mode 100644 index 0000000..e62dbc0 --- /dev/null +++ b/tests/cases/05_sound_alias.lua @@ -0,0 +1,54 @@ +-- 05: LoadSoundAlias keeps the source alive, and dropping the alias does not +-- invalidate the source. +local M = dofile("tests/helpers.lua") +local R = M.load() + +if not M.audio() then + M.skip("05_sound_alias", "no audio device") + return +end + +M.reset() + +local data, size = M.wav_bytes(4410) -- 0.1 s, 44100 Hz mono s16 +local wave = R.LoadWaveFromMemory(".wav", data, size) +M.ok(wave.data ~= nil, "WAV decoded") +M.eq(wave.channels, 1, "wave is mono") +M.ok(wave.frameCount > 0, "wave has samples") + +local src = R.LoadSoundFromWave(wave) +M.ok(src.stream.buffer ~= nil, "sound created") +R.UnloadWave(wave) + +-- Test A: alias outlives the Lua reference to its source. +local alias = R.LoadSoundAlias(src) +M.ok(alias.stream.buffer ~= nil, "alias created") + +src = nil +M.gc(3) +M.ok(alias.stream.buffer ~= nil, "alias buffer valid after source GC") +M.ok(M.ow().errors == 0, "no finalizer errors with a live alias") + +R.UnloadSoundAlias(alias) +alias = nil +M.gc(3) + +-- Test B: dropping the alias first leaves the source usable. +local wave2 = R.LoadWaveFromMemory(".wav", data, size) +local src2 = R.LoadSoundFromWave(wave2) +R.UnloadWave(wave2) +M.ok(src2.stream.buffer ~= nil, "second sound created") + +local alias2 = R.LoadSoundAlias(src2) +M.ok(alias2.stream.buffer ~= nil, "second alias created") + +alias2 = nil +M.gc(3) +M.ok(src2.stream.buffer ~= nil, "source survives alias GC") +R.PlaySound(src2) -- must not crash / must not use a freed buffer + +R.UnloadSound(src2) +src2 = nil +M.gc(3) + +print("ok 05_sound_alias") diff --git a/tests/cases/06_teardown.lua b/tests/cases/06_teardown.lua new file mode 100644 index 0000000..619bd05 --- /dev/null +++ b/tests/cases/06_teardown.lua @@ -0,0 +1,52 @@ +-- 06: closing the window makes GPU finalizers skip instead of calling into a +-- dead GL context. The process must survive and report no errors. +local M = dofile("tests/helpers.lua") +local R = M.load() + +if not M.window(64, 64) then + M.skip("06_teardown", "no window") + return +end + +M.reset() +local img = R.GenImageColor(4, 4, R.RED) +local b = M.snapshot() + +-- Hold every resource until after CloseWindow so nothing can be collected +-- while the GPU context is still alive. +local pool = {} +for i = 1, 5 do + pool[i] = R.LoadTextureFromImage(img) + M.ok(pool[i].id ~= 0, "texture " .. i .. " created") +end +pool[6] = R.GenImageColor(4, 4, R.WHITE) +pool[7] = R.GenImageColor(4, 4, R.BLUE) +-- Kept out of the pool so it can be explicitly unloaded after the window dies. +local late = R.LoadTextureFromImage(img) +M.eq(M.delta(b, "armed"), 8, "six textures and two images armed") + +R.CloseWindow() + +-- Explicit unload after CloseWindow must also be a safe no-op: no GL call, the +-- handle is zeroed, and the counters stay clean. +local rel = M.snapshot() +R.UnloadTexture(late) +M.eq(M.delta(rel, "errors"), 0, "explicit unload after CloseWindow is safe") +M.eq(M.delta(rel, "released"), 0, "explicit unload after CloseWindow is skipped") +M.eq(late.id, 0, "explicit unload after CloseWindow zeroes the handle") +late = nil + +-- After CloseWindow the five texture finalizers must refuse to touch the dead +-- GPU context. The two RAM images may still be released. +pool = nil +M.gc(3) +M.ok(M.delta(b, "skipped") >= 5, + string.format("expected >=5 skipped finalizers, got %d", + M.delta(b, "skipped"))) +M.eq(M.delta(b, "errors"), 0, "no finalizer errors after CloseWindow") +M.eq(M.delta(b, "released"), 2, "RAM images still released after CloseWindow") + +img = nil +M.gc(2) + +print("ok 06_teardown") diff --git a/tests/cases/07_inout.lua b/tests/cases/07_inout.lua new file mode 100644 index 0000000..796a68f --- /dev/null +++ b/tests/cases/07_inout.lua @@ -0,0 +1,37 @@ +-- 07: inout Image parameters mutate the caller's cdata in place, and the +-- wrapper returns that same object so the GC sees exactly one owner. +local M = dofile("tests/helpers.lua") +local R = M.load() + +M.reset() +local b = M.snapshot() + +local rgba = R.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 +local gray = R.PIXELFORMAT_UNCOMPRESSED_GRAYSCALE + +local img = R.GenImageColor(4, 4, R.RED) +M.eq(img.format, rgba, "GenImageColor produced RGBA") + +local out = R.ImageFormat(img, gray) +M.ok(rawequal(out, img), "ImageFormat returned the caller's cdata") +M.eq(img.format, gray, "ImageFormat mutated the cdata") + +img = nil +out = nil +M.gc(3) +M.eq(M.delta(b, "released"), 1, "ImageFormat did not create a second owner") +M.eq(M.delta(b, "errors"), 0, "no finalizer errors") + +local img2 = R.GenImageColor(4, 4, R.RED) +local resized = R.ImageResize(img2, 2, 2) +M.ok(rawequal(resized, img2), "ImageResize returned the caller's cdata") +M.eq(img2.width, 2, "ImageResize width") +M.eq(img2.height, 2, "ImageResize height") + +img2 = nil +resized = nil +M.gc(3) +M.eq(M.delta(b, "released"), 2, "ImageResize did not create a second owner") +M.eq(M.delta(b, "errors"), 0, "no finalizer errors after resize") + +print("ok 07_inout") diff --git a/tests/cases/08_pins.lua b/tests/cases/08_pins.lua new file mode 100644 index 0000000..2b47287 --- /dev/null +++ b/tests/cases/08_pins.lua @@ -0,0 +1,62 @@ +-- 08: pinned textures (shapes texture, material maps) stay alive while pinned, +-- and the pins are dropped when the owning object is released. +local M = dofile("tests/helpers.lua") +local ffi = require("ffi") +local R = M.load() + +if not M.window(64, 64) then + M.skip("08_pins", "no window") + return +end + +M.reset() +local b = M.snapshot() + +local img = R.GenImageColor(2, 2, R.WHITE) + +-- (a) shapes texture pin +local tex = R.LoadTextureFromImage(img) +local tex_id = tex.id +M.ok(tex_id ~= 0, "shapes texture created") +local tex_copy = ffi.new("Texture2D[1]", tex) +M.eq(tex_copy[0].id, tex_id, "saved raw texture copy") + +R.SetShapesTexture(tex, ffi.new("Rectangle", 0, 0, 1, 1)) + +tex = nil +M.gc(3) +M.eq(M.delta(b, "released"), 0, "pinned shapes texture was not collected") +local shape = R.GetShapesTexture() +M.ok(shape.id ~= 0, "shapes texture is installed") +M.eq(shape.id, tex_id, "installed shapes texture is the pinned one") + +-- Explicit unload of the saved copy must restore the previous shapes texture +-- and not crash. (The original cdata is the one held by the pin.) +R.UnloadTexture(tex_copy[0]) +M.ok(R.GetShapesTexture().id ~= tex_id, "previous shapes texture restored") + +-- (b) material map pin +local mat = R.LoadMaterialDefault() +M.ok(mat.maps ~= nil, "default material has maps") +local tex2 = R.LoadTextureFromImage(img) +local tex2_id = tex2.id +R.SetMaterialTexture(mat, R.MATERIAL_MAP_DIFFUSE, tex2) +M.eq(mat.maps[R.MATERIAL_MAP_DIFFUSE].texture.id, tex2_id, + "material map references the texture") + +tex2 = nil +M.gc(3) +M.ok(mat.maps[R.MATERIAL_MAP_DIFFUSE].texture.id ~= 0, + "material pin kept the map texture alive") +M.eq(mat.maps[R.MATERIAL_MAP_DIFFUSE].texture.id, tex2_id, + "material map still points at the pinned texture") + +R.UnloadMaterial(mat) +mat = nil +-- Pins are dropped with the material; the texture can now go away. +M.gc(3) + +R.UnloadImage(img) +M.eq(M.delta(b, "errors"), 0, "no finalizer errors") + +print("ok 08_pins") diff --git a/tests/cases/08b_views.lua b/tests/cases/08b_views.lua new file mode 100644 index 0000000..56d8e35 --- /dev/null +++ b/tests/cases/08b_views.lua @@ -0,0 +1,36 @@ +-- 08b: model sub-objects (meshes[i], materials[i], shader views) are views: +-- reading them must not arm anything, and the model owns the release. +local M = dofile("tests/helpers.lua") +local R = M.load() + +if not M.window(64, 64) then + M.skip("08b_views", "no window") + return +end + +M.reset() + +local mesh = R.GenMeshCube(1, 1, 1) +local model = R.LoadModelFromMesh(mesh) +mesh = nil +M.eq(model.meshCount, 1, "model has one mesh") +M.eq(model.materialCount, 1, "model has one material") + +local b = M.snapshot() + +local m1 = model.meshes[0] +local mat1 = model.materials[0] +local probe = m1.vertexCount + mat1.shader.id +M.ok(m1.vertexCount > 0, "mesh view is readable (probe=" .. probe .. ")") + +m1, mat1 = nil, nil +M.gc(3) +M.eq(M.delta(b, "armed"), 0, "views never arm") + +R.UnloadModel(model) +M.ok(M.delta(b, "released") >= 1, "model released") +M.eq(M.delta(b, "errors"), 0, "no finalizer errors") +model = nil +M.gc(2) + +print("ok 08b_views") diff --git a/tests/cases/08c_font_atlas.lua b/tests/cases/08c_font_atlas.lua new file mode 100644 index 0000000..66ee284 --- /dev/null +++ b/tests/cases/08c_font_atlas.lua @@ -0,0 +1,36 @@ +-- 08c: GenImageFontAtlas attaches the Rectangle* output to the returned Image; +-- both must be freed exactly once (run under valgrind for the real proof). +local M = dofile("tests/helpers.lua") +local ffi = require("ffi") +local R = M.load() + +M.reset() +local b = M.snapshot() + +local keep = {} +local glyphs = ffi.new("GlyphInfo[2]") +for i = 0, 1 do + local im = R.GenImageColor(4, 4, R.WHITE) + keep[#keep + 1] = im + glyphs[i].value = 65 + i + glyphs[i].offsetX = 0 + glyphs[i].offsetY = 0 + glyphs[i].advanceX = 4 + glyphs[i].image = im +end + +local atlas, recs = R.GenImageFontAtlas(glyphs, 2, 8, 1, 0) +M.ok(atlas ~= nil, "font atlas returned") +M.ok(atlas.data ~= nil, "font atlas has pixel data") +M.ok(recs ~= nil, "glyph rectangles returned") + +atlas, recs = nil, nil +keep = nil +glyphs = nil +M.gc(3) + +M.ok(M.delta(b, "released") >= 1, + "atlas Image and attached Rectangle* were released") +M.eq(M.delta(b, "errors"), 0, "no finalizer errors") + +print("ok 08c_font_atlas") diff --git a/tests/cases/09_pointers.lua b/tests/cases/09_pointers.lua new file mode 100644 index 0000000..391e571 --- /dev/null +++ b/tests/cases/09_pointers.lua @@ -0,0 +1,50 @@ +-- 09: every owned-pointer return releases exactly one allocation at GC time. +local M = dofile("tests/helpers.lua") +local ffi = require("ffi") +local R = M.load() + +M.reset() + +local img = R.GenImageColor(2, 2, R.RED) +M.ok(img.data ~= nil, "source image valid") + +-- Baseline after the image exists: the image is armed too, and it is released +-- explicitly at the end of the case. +local b = M.snapshot() + +local count = M.out_int() +local comp_size = M.out_int() + +-- Keep every result alive until the batch is complete, then drop them all at +-- once so a single GC verifies the whole set. +local keep = {} +keep[#keep + 1] = R.LoadImageColors(img) +keep[#keep + 1] = R.LoadImagePalette(img, 8, count) +keep[#keep + 1] = R.LoadRandomSequence(4, 1, 5) +keep[#keep + 1] = R.LoadCodepoints("abc", count) +keep[#keep + 1] = R.LoadTextLines("a\nb\n", count) +keep[#keep + 1] = R.CompressData("abcd", 4, comp_size) +keep[#keep + 1] = R.DecodeDataBase64( + R.EncodeDataBase64("abcd", 4, count), count) +keep[#keep + 1] = R.TextReplaceAlloc("a", "a", "b") +local n = #keep +M.ok(n >= 8, "created at least 8 owned pointers, got " .. n) +for i = 1, n do + M.ok(keep[i] ~= nil, "pointer " .. i .. " is non-nil") +end + +keep = nil +M.gc(3) + +-- 7 of the 8 results are owned pointers; EncodeDataBase64/TextReplaceAlloc +-- return owned strings that the wrapper copies and frees immediately (valgrind +-- proves those). Every owned pointer must be armed and released exactly once. +M.ok(M.delta(b, "armed") >= 7, + string.format("expected >=7 armed pointers, got %d", M.delta(b, "armed"))) +M.ok(M.delta(b, "released") >= 7, + string.format("expected >=7 released pointers, got %d", + M.delta(b, "released"))) +M.eq(M.delta(b, "errors"), 0, "no finalizer errors") + +R.UnloadImage(img) +print("ok 09_pointers") diff --git a/tests/cases/10_ram.lua b/tests/cases/10_ram.lua new file mode 100644 index 0000000..ff66481 --- /dev/null +++ b/tests/cases/10_ram.lua @@ -0,0 +1,57 @@ +-- 10: RAM-only owned structs (Image, AutomationEventList, FilePathList, Wave) +-- release at GC time and Image churn does not grow RSS. +local M = dofile("tests/helpers.lua") +local R = M.load() + +M.reset() +local b = M.snapshot() + +do + local img = R.GenImageColor(4, 4, R.RED) + M.ok(img.data ~= nil, "image allocated") +end +M.gc(2) + +do + local list = R.LoadAutomationEventList(nil) + M.ok(list.events ~= nil, "empty automation event list allocated") +end +M.gc(2) + +do + local files = R.LoadDirectoryFiles(".") + M.ok(files.paths ~= nil, "directory file list allocated") + M.ok(files.count > 0, "directory file list is non-empty") +end +M.gc(2) + +do + local data, size = M.wav_bytes(441) + local wave = R.LoadWaveFromMemory(".wav", data, size) + M.ok(wave.data ~= nil, "wave allocated") +end +M.gc(2) + +M.ok(M.delta(b, "released") >= 4, + string.format("expected >=4 released RAM resources, got %d", + M.delta(b, "released"))) +M.eq(M.delta(b, "errors"), 0, "no finalizer errors") + +-- 200 batches of 128x128 images: a leaked 64 kB image per batch would add +-- ~12.8 MB. Allow generous allocator noise, but not a real leak. +local rss0 = M.rss_kb() +for i = 1, 200 do + local im = R.GenImageColor(128, 128, R.RED) + M.ok(im.data ~= nil, "batch image " .. i .. " allocated") + M.gc(1) +end +M.gc(3) +local rss1 = M.rss_kb() +if rss0 > 0 and not M.under_valgrind() then + local growth_kb = rss1 - rss0 + M.ok(growth_kb < 8 * 1024, string.format( + "rss grew %d kB across 200 image batches (%d -> %d kB)", + growth_kb, rss0, rss1)) +end + +print("ok 10_ram") diff --git a/tests/cases/11_strings.lua b/tests/cases/11_strings.lua new file mode 100644 index 0000000..f592928 --- /dev/null +++ b/tests/cases/11_strings.lua @@ -0,0 +1,47 @@ +-- 11: string-returning wrappers copy and free inside the wrapper. This is a +-- regression test for TextInsertAlloc / TextReplaceAlloc / TextReplaceBetweenAlloc +-- and friends: no reference is kept, so RSS must not grow. Valgrind is the +-- authoritative leak check. +local M = dofile("tests/helpers.lua") +local ffi = require("ffi") +local R = M.load() + +M.reset() +local b = M.snapshot() + +local path = M.tmpfile("hate-no-d string regression\n") +local cps = ffi.new("int[3]", 97, 98, 99) +local out_size = M.out_int() +local failures = {} + +local function check(label, v) + if v == nil then failures[#failures + 1] = label end +end + +M.gc(2) +local rss0 = M.rss_kb() + +for _ = 1, 2000 do + check("LoadFileText", R.LoadFileText(path)) + check("LoadUTF8", R.LoadUTF8(cps, 3)) + check("EncodeDataBase64", R.EncodeDataBase64("hello", 5, out_size)) + check("TextInsertAlloc", R.TextInsertAlloc("abcd", "X", 2)) + check("TextReplaceAlloc", R.TextReplaceAlloc("aaaa", "a", "b")) + check("TextReplaceBetweenAlloc", + R.TextReplaceBetweenAlloc("abcdef", "b", "e", "X")) +end + +M.gc(3) +local rss1 = M.rss_kb() +os.remove(path) + +M.eq(#failures, 0, "wrappers returned nil: " .. table.concat(failures, ", ")) +M.eq(M.delta(b, "errors"), 0, "no finalizer errors") +if rss0 > 0 and not M.under_valgrind() then + local growth_kb = rss1 - rss0 + M.ok(growth_kb < 20 * 1024, string.format( + "rss grew %d kB across 2000 string iterations (%d -> %d kB)", + growth_kb, rss0, rss1)) +end + +print("ok 11_strings") diff --git a/tests/helpers.lua b/tests/helpers.lua new file mode 100644 index 0000000..705778e --- /dev/null +++ b/tests/helpers.lua @@ -0,0 +1,189 @@ +-- tests/helpers.lua -- shared support for the hate-no-d test cases. +-- +-- Cases are plain Lua runs under ./hate-no-d (the embedded raylib + LuaJIT +-- runtime). The module is cached here so a case can call helpers repeatedly +-- without re-executing hate-no-d.lua. + +local ffi = require("ffi") + +local M = {} + +local ROOT = os.getenv("HATE_NO_D_ROOT") or "." +local CACHE = {} + +--- Load (and cache) the generated binding. +function M.load() + if CACHE.M == nil then + CACHE.M = dofile(ROOT .. "/hate-no-d.lua") + -- Tests exercise thousands of loads; raylib's INFO logging would drown the + -- assertions (and valgrind output). + if CACHE.M.SetTraceLogLevel and CACHE.M.LOG_WARNING then + CACHE.M.SetTraceLogLevel(CACHE.M.LOG_WARNING) + end + end + return CACHE.M +end + +--- The generated raylib module table (alias used by the spec's examples). +function M.R() + return M.load() +end + +--- Run the Lua GC n times. +function M.gc(n) + for _ = 1, (n or 2) do collectgarbage("collect") end +end + +--- M._ownership, with a clear error when the generator has not landed yet. +function M.ow() + local mod = M.load() + local o = mod._ownership + if type(o) ~= "table" then + error("hate-no-d.lua has no M._ownership (regenerate the binding)", 2) + end + return o +end + +function M.reset() + M.ow().reset() +end + +function M.snapshot() + local o = M.ow() + return { + armed = o.armed, + released = o.released, + skipped = o.skipped, + errors = o.errors, + } +end + +function M.delta(before, field) + return M.ow()[field] - before[field] +end + +function M.eq(a, b, msg) + if a ~= b then + error(string.format("%s: expected %s, got %s", + msg or "assert", tostring(b), tostring(a)), 2) + end +end + +function M.ok(v, msg) + if not v then error(msg or "assertion failed", 2) end +end + +--- RSS in kB from /proc/self/status, or 0 when unavailable. +function M.rss_kb() + local f = io.open("/proc/self/status", "r") + if f == nil then return 0 end + local rss = 0 + for line in f:lines() do + local kb = line:match("^VmRSS:%s*(%d+)%s*kB") + if kb then rss = tonumber(kb); break end + end + f:close() + return rss +end + +--- True when the runner told us there is no display. +function M.headless() + return os.getenv("HATE_NO_D_HEADLESS") == "1" +end + +--- True when running under valgrind (RSS measurements are meaningless then). +function M.under_valgrind() + return os.getenv("HATE_NO_D_VALGRIND") == "1" +end + +--- Ensure a window exists. Returns false (rather than failing) when the +--- environment cannot provide one, so callers can print "skip ". +function M.window(w, h) + if M.headless() then return false end + local R = M.load() + if not R.C.IsWindowReady() then + R.InitWindow(w or 64, h or 64, "hate-no-d test") + end + return R.C.IsWindowReady() and true or false +end + +--- Ensure an audio device exists (same skip-friendly contract as window()). +function M.audio() + local R = M.load() + if not R.IsAudioDeviceReady() then + pcall(R.InitAudioDevice) + end + return R.IsAudioDeviceReady() and true or false +end + +function M.skip(name, reason) + if reason then + print(string.format("skip %s (%s)", name, reason)) + else + print("skip " .. name) + end +end + +--- Accept either a Lua string (owned-string wrappers) or a cdata char* and +--- return a Lua string. Used where lane A may still hand back a pointer. +function M.tostr(x) + if type(x) == "string" then return x end + if x == nil then return nil end + return ffi.string(x) +end + +function M.out_int(v) + local p = ffi.new("int[1]") + if v ~= nil then p[0] = v end + return p +end + +function M.tmpfile(contents) + local path = os.tmpname() + local f = assert(io.open(path, "wb")) + f:write(contents) + f:close() + return path +end + +--- Build a PCM WAV in memory: mono, 44100 Hz, signed 16-bit, `samples` +--- samples of silence. Returns (cdata uint8_t[44 + samples*2], size). +function M.wav_bytes(samples) + local data_size = samples * 2 + local total = 44 + data_size + local b = ffi.new("uint8_t[?]", total) + + local function put8(off, v) b[off] = v end + local function put16(off, v) + b[off] = v % 256 + b[off + 1] = math.floor(v / 256) % 256 + end + local function put32(off, v) + b[off] = v % 256 + b[off + 1] = math.floor(v / 256) % 256 + b[off + 2] = math.floor(v / 65536) % 256 + b[off + 3] = math.floor(v / 16777216) % 256 + end + local function puts(off, s) + for i = 1, #s do b[off + i - 1] = s:byte(i) end + end + + puts(0, "RIFF") + put32(4, 36 + data_size) + puts(8, "WAVE") + puts(12, "fmt ") + put32(16, 16) -- fmt chunk size + put16(20, 1) -- PCM + put16(22, 1) -- mono + put32(24, 44100) -- sample rate + put32(28, 44100 * 2) -- byte rate + put16(32, 2) -- block align + put16(34, 16) -- bits per sample + puts(36, "data") + put32(40, data_size) + -- samples stay zero (silence) + + return b, total +end + +return M diff --git a/tests/run-valgrind.sh b/tests/run-valgrind.sh new file mode 100755 index 0000000..a93498a --- /dev/null +++ b/tests/run-valgrind.sh @@ -0,0 +1,51 @@ +#!/bin/sh +# RAM-only cases under valgrind. Definite leaks are fatal (exit code 42). +# +# GPU finalizers are deliberately excluded: a headless/valgrind process has no +# GL context, so those cases would only exercise the "skip" gate. +set -u + +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" || exit 1 +export HATE_NO_D_ROOT="$ROOT" + +if ! command -v valgrind >/dev/null 2>&1; then + echo "skip valgrind (not installed)" + exit 0 +fi + +if [ ! -x ./hate-no-d ]; then + echo "run-valgrind.sh: ./hate-no-d not built (run make)" >&2 + exit 1 +fi + +CASES="02_explicit 07_inout 08c_font_atlas 09_pointers 10_ram 11_strings" +fail=0 +HATE_NO_D_VALGRIND=1 +export HATE_NO_D_VALGRIND + +for name in $CASES; do + case="tests/cases/$name.lua" + if [ ! -f "$case" ]; then + echo "FAIL $name (missing $case)" >&2 + fail=1 + continue + fi + echo "valgrind $name" + if valgrind --quiet --error-exitcode=42 \ + --leak-check=full --show-leak-kinds=definite \ + --errors-for-leak-kinds=definite \ + --suppressions=tests/valgrind.supp \ + ./hate-no-d "$case"; then + : + else + status=$? + echo "FAIL $name (valgrind exit $status)" >&2 + fail=1 + fi +done + +if [ "$fail" -eq 0 ]; then + echo "check-valgrind: ok" +fi +exit "$fail" diff --git a/tests/run.sh b/tests/run.sh new file mode 100755 index 0000000..6cb3fcb --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,62 @@ +#!/bin/sh +# Functional test matrix for hate-no-d. +# +# Every case is a self-contained process: it prints "ok " or +# "skip (...)", or raises with a specific message. Cases must run under +# ./hate-no-d -- the system luajit has no raylib symbols. +set -u + +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" || exit 1 +export HATE_NO_D_ROOT="$ROOT" + +if [ ! -x ./hate-no-d ]; then + echo "run.sh: ./hate-no-d not built (run make)" >&2 + exit 1 +fi + +# If there is no display, retry the whole matrix under a virtual X server when +# one is available. Otherwise mark the run headless and let window cases skip. +if [ -z "${DISPLAY:-}" ] && [ "${HATE_NO_D_XVFB:-0}" != "1" ]; then + if command -v xvfb-run >/dev/null 2>&1; then + HATE_NO_D_XVFB=1 + export HATE_NO_D_XVFB + exec xvfb-run -a "$0" "$@" + fi + echo "run.sh: no DISPLAY and no xvfb-run; window cases will be skipped" >&2 + HATE_NO_D_HEADLESS=1 + export HATE_NO_D_HEADLESS +fi + +# Cases that need a window. The cases themselves also gate on IsWindowReady; +# this list just avoids starting them at all when the runner knows it is +# headless. +WINDOW_CASES="01_many_textures 03_borrowed 04_model_from_mesh 06_teardown 08_pins 08b_views" + +is_window_case() { + for w in $WINDOW_CASES; do + [ "$w" = "$1" ] && return 0 + done + return 1 +} + +fail=0 +for case in tests/cases/*.lua; do + name=$(basename "$case" .lua) + if [ "${HATE_NO_D_HEADLESS:-0}" = "1" ] && is_window_case "$name"; then + echo "skip $name (no display)" + continue + fi + if out=$(./hate-no-d "$case" 2>&1); then + echo "$out" + else + echo "FAIL $name" >&2 + echo "$out" >&2 + fail=1 + fi +done + +if [ "$fail" -eq 0 ]; then + echo "test: ok" +fi +exit "$fail" diff --git a/tests/valgrind.supp b/tests/valgrind.supp new file mode 100644 index 0000000..0ada004 --- /dev/null +++ b/tests/valgrind.supp @@ -0,0 +1,15 @@ +# Valgrind suppressions for the hate-no-d test suite. +# +# Start empty. Only suppress reports that originate inside LuaJIT, the JIT +# tracer, or glibc internals -- never frames from _release_* / Unload* / +# MemFree, because those are exactly what the RAM cases exist to check. +# +# Each entry needs a comment naming the rule, for example: +# +# # LuaJIT allocator arena still reachable at exit (not a definite leak). +# { +# luajit-alloc-arena +# Memcheck:Leak +# match-leak-kinds: reachable +# ... +# }