From b4458195b93024c67d9e8ec34b9acd49f75c954b Mon Sep 17 00:00:00 2001 From: 4DBug Date: Fri, 16 Oct 2026 22:33:29 -0500 Subject: [PATCH] 0.4.0 --- .github/README.md | 55 +- .github/workflows/release.yml | 14 +- README.md | 55 +- backends/imgui_impl_roblox.lua | 1649 ------ backends/{ => love}/imgui_impl_love.lua | 0 backends/roblox/imgui_impl_roblox.lua | 484 ++ backends/roblox/layers.lua | 335 ++ backends/roblox/overlays.lua | 79 + backends/roblox/parallel.lua | 398 ++ backends/roblox/raster.lua | 474 ++ backends/roblox/render.lua | 843 +++ backends/roblox/textures.lua | 169 + backends/roblox/worker.luau | 20 + build/ImGui.linemap.json | 2 +- build/ImGui.luau | 4741 ++++++++++------- build/ImGuiTyped.luau | 30 + build/ImGuiWorker.client.luau | 497 ++ build/imgui_love.linemap.json | 2 +- build/imgui_love.lua | 859 ++- default.project.json | 8 +- docs/PORTING.md | 9 +- examples/example_roblox/main.client.luau | 1 + .../example_roblox_parallel/main.client.luau | 234 + imgui.lua | 260 +- imgui_demo.lua | 109 +- imgui_draw.lua | 149 +- imgui_h.lua | 52 +- imgui_internal.lua | 78 +- imgui_tables.lua | 40 +- imgui_widgets.lua | 102 +- imstb_rectpack.lua | 8 +- imstb_textedit.lua | 12 +- imstb_truetype.lua | 22 +- imstd_minstdio.lua | 27 +- tools/bundle.py | 73 +- tools/gen_types.py | 21 +- tools/test/check_all.sh | 7 + tools/test/prof.py | 2 +- tools/test/roblox_mock.luau | 13 +- tools/test/run.py | 11 +- tools/test/scripts/t_assets_scroll.luau | 108 + tools/test/scripts/t_parallel.luau | 171 + tools/test/scripts/t_pool_ctx.luau | 32 + tools/test/scripts/t_tile_bound.luau | 49 + tools/test/undefined.py | 5 +- wally.toml | 2 +- 46 files changed, 7897 insertions(+), 4414 deletions(-) delete mode 100644 backends/imgui_impl_roblox.lua rename backends/{ => love}/imgui_impl_love.lua (100%) create mode 100644 backends/roblox/imgui_impl_roblox.lua create mode 100644 backends/roblox/layers.lua create mode 100644 backends/roblox/overlays.lua create mode 100644 backends/roblox/parallel.lua create mode 100644 backends/roblox/raster.lua create mode 100644 backends/roblox/render.lua create mode 100644 backends/roblox/textures.lua create mode 100644 backends/roblox/worker.luau create mode 100644 build/ImGuiWorker.client.luau create mode 100644 examples/example_roblox_parallel/main.client.luau create mode 100644 tools/test/scripts/t_assets_scroll.luau create mode 100644 tools/test/scripts/t_parallel.luau create mode 100644 tools/test/scripts/t_pool_ctx.luau create mode 100644 tools/test/scripts/t_tile_bound.luau diff --git a/.github/README.md b/.github/README.md index 7a2eb6b..ada5af1 100644 --- a/.github/README.md +++ b/.github/README.md @@ -25,7 +25,7 @@ This port brings that to Roblox (and LÖVE): debug overlays, admin panels, in-ga ### Usage -**The core of Dear ImGui is a set of files with no dependencies**, plus one platform backend from [backends/](/backends/). `tools/bundle.py` combines them into a single file: `build/ImGui.luau` (ModuleScript, Roblox backend) or, with `--target love`, `build/imgui_love.lua` (LÖVE backend). Your UI code is the same for both. +**The core of Dear ImGui is a set of files with no dependencies**, plus one platform backend from [backends/](/backends/) (`backends/roblox/`, `backends/love/`). `tools/bundle.py` combines them into a single file: `build/ImGui.luau` (ModuleScript, Roblox backend) or, with `--target love`, `build/imgui_love.lua` (LÖVE backend). Your UI code is the same for both. Dear ImGui is **immediate mode**: you call widget functions every frame, and their return values tell you what the user did. There is no widget object to keep in sync with your state. @@ -116,7 +116,7 @@ The Style Editor (`ImGui.ShowStyleEditor()`) and the Metrics/Debugger (`ImGui.Sh ### Getting Started & Integration (Roblox) -With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/imgui-luau@0.3.0"` under `[dependencies]` in your `wally.toml`, run `wally install`, then `require(ReplicatedStorage.Packages.ImGui)`. Or from source: +With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/imgui-luau@0.4.0"` under `[dependencies]` in your `wally.toml`, run `wally install`, then `require(ReplicatedStorage.Packages.ImGui)`. Or from source: 1. Build the module: `python3 tools/bundle.py` writes `build/ImGui.luau` (`--no-demo` leaves the demo out) and `build/ImGuiTyped.luau`, a small typed entry module (Luau types for the public `ImGui.*` API, `ImVec2`/`ImVec4` and the flag enums) that requires `build/ImGui.luau` as its child `Impl`. The Wally package and the Rojo projects use that layout, so you get autocomplete and type errors in `--!strict` scripts. The single-file `ImGui.luau` also works on its own, just untyped. 2. Sync with [Rojo](https://rojo.space): [`default.project.json`](/default.project.json) puts the module in `ReplicatedStorage.ImGui` and the example LocalScript in `StarterPlayerScripts`. @@ -155,6 +155,8 @@ Backend options: | `ImGui_ImplRoblox.SetRedrawBudget(ms)` | Max milliseconds per frame spent redrawing changed tiles (opt-in; default `0` = no limit, every change is drawn the same frame). With a budget, tiles over it keep their old pixels for a few frames, so big changes are spread over frames instead of one long frame (parts of the UI may update a frame or two apart). | | `ImGui_ImplRoblox.SetBusyRenderRate(hz)` | Optional lower redraw rate while scrolling, resizing or moving windows (default off). | | `ImGui_ImplRoblox.SetProfiling(true)` | MicroProfiler (Ctrl+F6) labels for every backend stage. | +| `ImGui_ImplRoblox.GetStats()` | Live resource counts: `Tiles`, `EditableImages`, `EditableImageBytes`, `EditableImageCap` (all EditableImages share a 64 MB budget; scrolled-away tiles are freed/recycled), `Instances`. | +| `ImGui_ImplRoblox.SetStageTiming(on)` | Opt-in per-stage timing of the last rendered frame in `GetStats().Frame`: seconds for `Compare`, `Collect`, `Hash`, `Raster`, `Upload`, `Other`, `Total`, plus `TilesRasterized`, `PixelsRasterized` (dirty-rect area), `Uploads`, `TilesCreated`, `TilesFreed`. Off by default (one boolean check per stage). | | `ImGui_ImplRoblox.AddFile(path, bytes)` | Register a file (e.g. a `.ttf`) so `io.Fonts:AddFontFromFileTTF(path, size)` can load it. | Fonts: ProggyClean (default), ProggyTiny, ProggyForever, Cousine, DroidSans, Karla and Roboto are embedded from [fonts/](/fonts/): @@ -164,9 +166,46 @@ io.Fonts:AddFontDefault() io.Fonts:AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0) ``` +### Parallel rendering (opt-in, Roblox) + +Changed tiles can be rasterized on Actors (parallel Luau) instead of the main thread, still uploaded **in the same frame**. It is part of the backend but off until you call `ImGui_ImplRoblox.EnableParallel` (when off, the backend only checks one field per redrawn tile). + +- The rasterizer is [backends/roblox/raster.lua](/backends/roblox/raster.lua): pure buffer code used by both the backend and the worker, so the pixels are identical (tested by `tools/test/scripts/t_parallel.luau`). +- `build/ImGuiWorker.client.luau` (LocalScript): the Actor script, with the rasterizer pasted in by `bundle.py` (self-contained, no `require`). It must be the child `Worker` of the `ImGui` module (or pass `{ Worker = ... }`). Scripts can't be created at runtime, so the backend clones it into each Actor it creates (under `PlayerScripts`). The template does nothing where it sits. + +Rojo layout (as in [`default.project.json`](/default.project.json)): + +```json +"ImGui": { + "$path": "build/ImGuiTyped.luau", + "Impl": { "$path": "build/ImGui.luau" }, + "Worker": { "$path": "build/ImGuiWorker.client.luau" } +} +``` + +```lua +ImGui_ImplRoblox.EnableParallel({ Actors = 4 }) -- also: MinTiles = 4, MinPixels = 16384, MaxBytesPerPixel = 3, Worker + +RunService.PreSimulation:Connect(function() -- NOT RenderStepped (see below) + ImGui_ImplRoblox.NewFrame() + ImGui.NewFrame() + -- ... your windows ... + ImGui.Render() + ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData()) -- collects, hashes, packs and dispatches the dirty tiles +end) +-- PostSimulation (connected by EnableParallel): FinishParallel() uploads every result, and rasterizes on the main +-- thread whatever didn't come back. ImGui_ImplRoblox.DisableParallel() goes back to inline rasterization. +``` + +**Frame ordering.** A Roblox frame runs `PreRender` (`RenderStepped`), `PreAnimation`, `PreSimulation` (`Stepped`), `PostSimulation` (`Heartbeat`). What the scripts changed up to the end of `PostSimulation` of frame N is drawn by the render that follows the next `PreRender` (N+1), together with whatever `PreRender` N+1 changes. So `RenderDrawData` in `PreSimulation` (layer `Position`/`ZIndex`/`Visible` changes) plus `Finish` in `PostSimulation` (the pixels) land in the same render: no frame shows moved layers with old pixels. Actor work requested in `PreSimulation` runs in that frame's parallel phases, and the results are back before `PostSimulation`. +- The executor only dispatches between `PreAnimation` and its `Finish`. A `RenderDrawData` anywhere else (`RenderStepped`/`PreRender`, after `Finish`, with too little work: fewer than `MinTiles` tiles or `MinPixels` dirty pixels, or with dense primitives: more than `MaxBytesPerPixel` packed payload bytes per dirty pixel, e.g. text-heavy frames, where packing costs more than rasterizing; `0` = no limit) is rasterized and uploaded on the main thread right away, like without the executor. That is always correct, just not parallel. +- Minimal example: [examples/example_roblox_parallel/main.client.luau](/examples/example_roblox_parallel/main.client.luau) (the demo window, 2 Actors; map it instead of `examples/example_roblox` in `default.project.json`). +- If your frame ends elsewhere, call `ImGui_ImplRoblox.FinishParallel()` yourself. It must run before the next render, and after the parallel phase if you want the workers' results. +- `ImGui_ImplRoblox.GetParallelStats()`: `ParallelFlushes`, `SerialFlushes`, `Tiles`, `Fallbacks` (worker results missing at `Finish`), `Late`, `Pack`/`Flush`/`Finish` (main-thread seconds, cumulative). `ImGui_ImplRoblox.GetParallelConfig()` returns the live config table (thresholds can be changed at any time; a new `Actors` count needs another `EnableParallel()`). + ### How it works (Roblox backend) -Dear ImGui itself never draws anything: every frame it produces `ImDrawData`, a list of textured, coloured triangles plus clip rectangles, and expects the backend to put them on screen. On desktop that is a few GPU draw calls. Roblox has no API to draw arbitrary triangles in 2D, so the Roblox backend ([backends/imgui_impl_roblox.lua](/backends/imgui_impl_roblox.lua)) does what a GPU would do, in Luau, and pushes the result into **EditableImages**. +Dear ImGui itself never draws anything: every frame it produces `ImDrawData`, a list of textured, coloured triangles plus clip rectangles, and expects the backend to put them on screen. On desktop that is a few GPU draw calls. Roblox has no API to draw arbitrary triangles in 2D, so the Roblox backend ([backends/roblox/](/backends/roblox): `imgui_impl_roblox.lua` + its modules `textures`, `layers`, `render`, `parallel`, `overlays`, `raster`) does what a GPU would do, in Luau, and pushes the result into **EditableImages**. **Why software rasterization?** The alternatives don't fit Dear ImGui: - *One GUI Instance per widget/shape* (what most Roblox UI libraries do) means re-creating, re-parenting or diffing thousands of Instances every frame, can't express anti-aliased curves, per-vertex gradients or font-atlas glyphs, and would no longer be Dear ImGui's renderer output. @@ -189,21 +228,21 @@ The cost is CPU time in Luau, so the backend is built around **not drawing**: | Backend | File | Build | Renderer | Example | | --- | --- | --- | --- | --- | -| Roblox (primary) | [backends/imgui_impl_roblox.lua](/backends/imgui_impl_roblox.lua) | `python3 tools/bundle.py` | Luau software rasterizer into EditableImage tiles | [examples/example_roblox](/examples/example_roblox) | -| LÖVE 11.x | [backends/imgui_impl_love.lua](/backends/imgui_impl_love.lua) | `python3 tools/bundle.py --target love` | GPU, one `Mesh` per draw list | [examples/example_love](/examples/example_love) | +| Roblox (primary) | [backends/roblox/imgui_impl_roblox.lua](/backends/roblox/imgui_impl_roblox.lua) | `python3 tools/bundle.py` | Luau software rasterizer into EditableImage tiles | [examples/example_roblox](/examples/example_roblox) | +| LÖVE 11.x | [backends/love/imgui_impl_love.lua](/backends/love/imgui_impl_love.lua) | `python3 tools/bundle.py --target love` | GPU, one `Mesh` per draw list | [examples/example_love](/examples/example_love) | -A backend implements the usual Dear ImGui contract (`Init`, `NewFrame`, `RenderDrawData`, input → `io:Add*Event`, texture updates via `ImTextureData`). Adding another Lua host means a new `backends/imgui_impl_.lua` plus a `--target` in `tools/bundle.py`. +A backend implements the usual Dear ImGui contract (`Init`, `NewFrame`, `RenderDrawData`, input → `io:Add*Event`, texture updates via `ImTextureData`). Adding another Lua host means a new `backends//imgui_impl_.lua` plus a `--target` in `tools/bundle.py`. #### LÖVE -The same sources also build for [LÖVE](https://love2d.org) (LuaJIT), with a GPU renderer in [backends/imgui_impl_love.lua](/backends/imgui_impl_love.lua): +The same sources also build for [LÖVE](https://love2d.org) (LuaJIT), with a GPU renderer in [backends/love/imgui_impl_love.lua](/backends/love/imgui_impl_love.lua): ``` python3 tools/bundle.py --target love # -> build/imgui_love.lua (LÖVE backend + shims from the LÖVE backend) love examples/example_love ``` -Roblox stays the primary target: the Roblox build is untouched by this (no shims, `@native` kept); the LÖVE build strips `@native` and adds small `bit32`/`buffer`/`utf8`/`table` shims (the COMPAT section of [backends/imgui_impl_love.lua](/backends/imgui_impl_love.lua)). `tools/test/love/run.sh` checks that LuaJIT produces exactly the same draw data as Luau. +Roblox stays the primary target: the Roblox build is untouched by this (no shims, `@native` kept); the LÖVE build strips `@native` and adds small `bit32`/`buffer`/`utf8`/`table` shims (the COMPAT section of [backends/love/imgui_impl_love.lua](/backends/love/imgui_impl_love.lua)). `tools/test/love/run.sh` checks that LuaJIT produces exactly the same draw data as Luau. #### Prebuilt releases diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6ecb23c..4dd6c0b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -34,7 +34,7 @@ jobs: IMGUI_BUNDLE_STRICT: "1" # fail if enum folding (needs the luau CLI above) can't run run: | mkdir -p dist - python3 tools/bundle.py dist/roblox # ImGui.luau (library + demo) + python3 tools/bundle.py dist/roblox # ImGui.luau (library + demo), ImGuiTyped.luau, ImGuiWorker.client.luau python3 tools/bundle.py --target love dist/love # imgui_love.lua (library + demo) # minified variants (comments/whitespace stripped, same code): tools/minify.py python3 tools/minify.py dist/roblox/ImGui.luau dist/ImGui.min.luau @@ -44,6 +44,8 @@ jobs: run: | python3 tools/sync_github_readme.py --check luau-compile --null dist/roblox/ImGui.luau + luau-compile --null dist/roblox/ImGuiWorker.client.luau + ! grep -n "require" dist/roblox/ImGuiWorker.client.luau # parallel worker: self-contained (worker.luau + raster.lua inlined) sed 's|require(script:WaitForChild("Impl"))|nil|' dist/roblox/ImGuiTyped.luau > /tmp/ImGuiTyped.luau && luau-analyze /tmp/ImGuiTyped.luau luajit -bl dist/love/imgui_love.lua > /dev/null python3 tools/minify.py --test @@ -71,9 +73,10 @@ jobs: cd dist cp roblox/ImGui.luau ImGui.luau cp love/imgui_love.lua imgui_love.lua + cp roblox/ImGuiWorker.client.luau ImGuiWorker.client.luau # Roblox: module + example LocalScript + Rojo project - mkdir -p pkg-roblox/build && cp ImGui.luau roblox/ImGuiTyped.luau pkg-roblox/build/ && cp ../default.project.json pkg-roblox/ - mkdir -p pkg-roblox/examples && cp -r ../examples/example_roblox pkg-roblox/examples/ + mkdir -p pkg-roblox/build && cp ImGui.luau roblox/ImGuiTyped.luau ImGuiWorker.client.luau pkg-roblox/build/ && cp ../default.project.json pkg-roblox/ + mkdir -p pkg-roblox/examples && cp -r ../examples/example_roblox ../examples/example_roblox_parallel pkg-roblox/examples/ (cd pkg-roblox && zip -qr ../imgui-luau-roblox-$V.zip .) # LÖVE: bundle + fonts + examples (run: love examples/example_love) mkdir -p pkg-love/build && cp imgui_love.lua pkg-love/build/ && cp -r ../fonts pkg-love/ && rm -f pkg-love/fonts/*.lua @@ -87,6 +90,7 @@ jobs: with: files: | dist/ImGui.luau + dist/ImGuiWorker.client.luau dist/imgui_love.lua dist/*.min.luau dist/*.min.lua @@ -102,7 +106,7 @@ jobs: grep -q "^version = \"${GITHUB_REF_NAME#v}\"" wally.toml || { echo "wally.toml version != tag"; exit 1; } curl -fsSL -o wally.zip https://github.com/UpliftGames/wally/releases/download/v0.3.2/wally-v0.3.2-linux.zip unzip -q wally.zip -d wallybin && chmod +x wallybin/wally - mkdir -p dist/wally/src && cp wally.toml dist/wally/ && cp dist/roblox/ImGuiTyped.luau dist/wally/src/init.luau && cp dist/roblox/ImGui.luau dist/wally/src/Impl.luau + mkdir -p dist/wally/src && cp wally.toml dist/wally/ && cp dist/roblox/ImGuiTyped.luau dist/wally/src/init.luau && cp dist/roblox/ImGui.luau dist/wally/src/Impl.luau && cp dist/roblox/ImGuiWorker.client.luau dist/wally/src/Worker.client.luau echo '{"name":"imgui-luau","tree":{"$path":"src"}}' > dist/wally/default.project.json wallybin/wally login --token "$WALLY_TOKEN" wallybin/wally publish --project-path dist/wally @@ -115,4 +119,4 @@ jobs: gh release delete latest --yes --cleanup-tag || true gh release create latest --latest --title "Latest build (${GITHUB_SHA::7})" \ --notes "Automatic build of ${GITHUB_SHA} on ${GITHUB_REF_NAME}. Tag a commit v* for a versioned release." \ - dist/ImGui.luau dist/imgui_love.lua dist/*.min.luau dist/*.min.lua dist/*.zip + dist/ImGui.luau dist/ImGuiWorker.client.luau dist/imgui_love.lua dist/*.min.luau dist/*.min.lua dist/*.zip diff --git a/README.md b/README.md index 0ddb454..2bc20ea 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ This port brings that to Roblox (and LÖVE): debug overlays, admin panels, in-ga ### Usage -**The core of Dear ImGui is a set of files with no dependencies**, plus one platform backend from [backends/](backends/). `tools/bundle.py` combines them into a single file: `build/ImGui.luau` (ModuleScript, Roblox backend) or, with `--target love`, `build/imgui_love.lua` (LÖVE backend). Your UI code is the same for both. +**The core of Dear ImGui is a set of files with no dependencies**, plus one platform backend from [backends/](backends/) (`backends/roblox/`, `backends/love/`). `tools/bundle.py` combines them into a single file: `build/ImGui.luau` (ModuleScript, Roblox backend) or, with `--target love`, `build/imgui_love.lua` (LÖVE backend). Your UI code is the same for both. Dear ImGui is **immediate mode**: you call widget functions every frame, and their return values tell you what the user did. There is no widget object to keep in sync with your state. @@ -113,7 +113,7 @@ The Style Editor (`ImGui.ShowStyleEditor()`) and the Metrics/Debugger (`ImGui.Sh ### Getting Started & Integration (Roblox) -With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/imgui-luau@0.3.0"` under `[dependencies]` in your `wally.toml`, run `wally install`, then `require(ReplicatedStorage.Packages.ImGui)`. Or from source: +With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/imgui-luau@0.4.0"` under `[dependencies]` in your `wally.toml`, run `wally install`, then `require(ReplicatedStorage.Packages.ImGui)`. Or from source: 1. Build the module: `python3 tools/bundle.py` writes `build/ImGui.luau` (`--no-demo` leaves the demo out) and `build/ImGuiTyped.luau`, a small typed entry module (Luau types for the public `ImGui.*` API, `ImVec2`/`ImVec4` and the flag enums) that requires `build/ImGui.luau` as its child `Impl`. The Wally package and the Rojo projects use that layout, so you get autocomplete and type errors in `--!strict` scripts. The single-file `ImGui.luau` also works on its own, just untyped. 2. Sync with [Rojo](https://rojo.space): [`default.project.json`](default.project.json) puts the module in `ReplicatedStorage.ImGui` and the example LocalScript in `StarterPlayerScripts`. @@ -152,6 +152,8 @@ Backend options: | `ImGui_ImplRoblox.SetRedrawBudget(ms)` | Max milliseconds per frame spent redrawing changed tiles (opt-in; default `0` = no limit, every change is drawn the same frame). With a budget, tiles over it keep their old pixels for a few frames, so big changes are spread over frames instead of one long frame (parts of the UI may update a frame or two apart). | | `ImGui_ImplRoblox.SetBusyRenderRate(hz)` | Optional lower redraw rate while scrolling, resizing or moving windows (default off). | | `ImGui_ImplRoblox.SetProfiling(true)` | MicroProfiler (Ctrl+F6) labels for every backend stage. | +| `ImGui_ImplRoblox.GetStats()` | Live resource counts: `Tiles`, `EditableImages`, `EditableImageBytes`, `EditableImageCap` (all EditableImages share a 64 MB budget; scrolled-away tiles are freed/recycled), `Instances`. | +| `ImGui_ImplRoblox.SetStageTiming(on)` | Opt-in per-stage timing of the last rendered frame in `GetStats().Frame`: seconds for `Compare`, `Collect`, `Hash`, `Raster`, `Upload`, `Other`, `Total`, plus `TilesRasterized`, `PixelsRasterized` (dirty-rect area), `Uploads`, `TilesCreated`, `TilesFreed`. Off by default (one boolean check per stage). | | `ImGui_ImplRoblox.AddFile(path, bytes)` | Register a file (e.g. a `.ttf`) so `io.Fonts:AddFontFromFileTTF(path, size)` can load it. | Fonts: ProggyClean (default), ProggyTiny, ProggyForever, Cousine, DroidSans, Karla and Roboto are embedded from [fonts/](fonts/): @@ -161,9 +163,46 @@ io.Fonts:AddFontDefault() io.Fonts:AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0) ``` +### Parallel rendering (opt-in, Roblox) + +Changed tiles can be rasterized on Actors (parallel Luau) instead of the main thread, still uploaded **in the same frame**. It is part of the backend but off until you call `ImGui_ImplRoblox.EnableParallel` (when off, the backend only checks one field per redrawn tile). + +- The rasterizer is [backends/roblox/raster.lua](backends/roblox/raster.lua): pure buffer code used by both the backend and the worker, so the pixels are identical (tested by `tools/test/scripts/t_parallel.luau`). +- `build/ImGuiWorker.client.luau` (LocalScript): the Actor script, with the rasterizer pasted in by `bundle.py` (self-contained, no `require`). It must be the child `Worker` of the `ImGui` module (or pass `{ Worker = ... }`). Scripts can't be created at runtime, so the backend clones it into each Actor it creates (under `PlayerScripts`). The template does nothing where it sits. + +Rojo layout (as in [`default.project.json`](default.project.json)): + +```json +"ImGui": { + "$path": "build/ImGuiTyped.luau", + "Impl": { "$path": "build/ImGui.luau" }, + "Worker": { "$path": "build/ImGuiWorker.client.luau" } +} +``` + +```lua +ImGui_ImplRoblox.EnableParallel({ Actors = 4 }) -- also: MinTiles = 4, MinPixels = 16384, MaxBytesPerPixel = 3, Worker + +RunService.PreSimulation:Connect(function() -- NOT RenderStepped (see below) + ImGui_ImplRoblox.NewFrame() + ImGui.NewFrame() + -- ... your windows ... + ImGui.Render() + ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData()) -- collects, hashes, packs and dispatches the dirty tiles +end) +-- PostSimulation (connected by EnableParallel): FinishParallel() uploads every result, and rasterizes on the main +-- thread whatever didn't come back. ImGui_ImplRoblox.DisableParallel() goes back to inline rasterization. +``` + +**Frame ordering.** A Roblox frame runs `PreRender` (`RenderStepped`), `PreAnimation`, `PreSimulation` (`Stepped`), `PostSimulation` (`Heartbeat`). What the scripts changed up to the end of `PostSimulation` of frame N is drawn by the render that follows the next `PreRender` (N+1), together with whatever `PreRender` N+1 changes. So `RenderDrawData` in `PreSimulation` (layer `Position`/`ZIndex`/`Visible` changes) plus `Finish` in `PostSimulation` (the pixels) land in the same render: no frame shows moved layers with old pixels. Actor work requested in `PreSimulation` runs in that frame's parallel phases, and the results are back before `PostSimulation`. +- The executor only dispatches between `PreAnimation` and its `Finish`. A `RenderDrawData` anywhere else (`RenderStepped`/`PreRender`, after `Finish`, with too little work: fewer than `MinTiles` tiles or `MinPixels` dirty pixels, or with dense primitives: more than `MaxBytesPerPixel` packed payload bytes per dirty pixel, e.g. text-heavy frames, where packing costs more than rasterizing; `0` = no limit) is rasterized and uploaded on the main thread right away, like without the executor. That is always correct, just not parallel. +- Minimal example: [examples/example_roblox_parallel/main.client.luau](examples/example_roblox_parallel/main.client.luau) (the demo window, 2 Actors; map it instead of `examples/example_roblox` in `default.project.json`). +- If your frame ends elsewhere, call `ImGui_ImplRoblox.FinishParallel()` yourself. It must run before the next render, and after the parallel phase if you want the workers' results. +- `ImGui_ImplRoblox.GetParallelStats()`: `ParallelFlushes`, `SerialFlushes`, `Tiles`, `Fallbacks` (worker results missing at `Finish`), `Late`, `Pack`/`Flush`/`Finish` (main-thread seconds, cumulative). `ImGui_ImplRoblox.GetParallelConfig()` returns the live config table (thresholds can be changed at any time; a new `Actors` count needs another `EnableParallel()`). + ### How it works (Roblox backend) -Dear ImGui itself never draws anything: every frame it produces `ImDrawData`, a list of textured, coloured triangles plus clip rectangles, and expects the backend to put them on screen. On desktop that is a few GPU draw calls. Roblox has no API to draw arbitrary triangles in 2D, so the Roblox backend ([backends/imgui_impl_roblox.lua](backends/imgui_impl_roblox.lua)) does what a GPU would do, in Luau, and pushes the result into **EditableImages**. +Dear ImGui itself never draws anything: every frame it produces `ImDrawData`, a list of textured, coloured triangles plus clip rectangles, and expects the backend to put them on screen. On desktop that is a few GPU draw calls. Roblox has no API to draw arbitrary triangles in 2D, so the Roblox backend ([backends/roblox/](backends/roblox): `imgui_impl_roblox.lua` + its modules `textures`, `layers`, `render`, `parallel`, `overlays`, `raster`) does what a GPU would do, in Luau, and pushes the result into **EditableImages**. **Why software rasterization?** The alternatives don't fit Dear ImGui: - *One GUI Instance per widget/shape* (what most Roblox UI libraries do) means re-creating, re-parenting or diffing thousands of Instances every frame, can't express anti-aliased curves, per-vertex gradients or font-atlas glyphs, and would no longer be Dear ImGui's renderer output. @@ -186,21 +225,21 @@ The cost is CPU time in Luau, so the backend is built around **not drawing**: | Backend | File | Build | Renderer | Example | | --- | --- | --- | --- | --- | -| Roblox (primary) | [backends/imgui_impl_roblox.lua](backends/imgui_impl_roblox.lua) | `python3 tools/bundle.py` | Luau software rasterizer into EditableImage tiles | [examples/example_roblox](examples/example_roblox) | -| LÖVE 11.x | [backends/imgui_impl_love.lua](backends/imgui_impl_love.lua) | `python3 tools/bundle.py --target love` | GPU, one `Mesh` per draw list | [examples/example_love](examples/example_love) | +| Roblox (primary) | [backends/roblox/imgui_impl_roblox.lua](backends/roblox/imgui_impl_roblox.lua) | `python3 tools/bundle.py` | Luau software rasterizer into EditableImage tiles | [examples/example_roblox](examples/example_roblox) | +| LÖVE 11.x | [backends/love/imgui_impl_love.lua](backends/love/imgui_impl_love.lua) | `python3 tools/bundle.py --target love` | GPU, one `Mesh` per draw list | [examples/example_love](examples/example_love) | -A backend implements the usual Dear ImGui contract (`Init`, `NewFrame`, `RenderDrawData`, input → `io:Add*Event`, texture updates via `ImTextureData`). Adding another Lua host means a new `backends/imgui_impl_.lua` plus a `--target` in `tools/bundle.py`. +A backend implements the usual Dear ImGui contract (`Init`, `NewFrame`, `RenderDrawData`, input → `io:Add*Event`, texture updates via `ImTextureData`). Adding another Lua host means a new `backends//imgui_impl_.lua` plus a `--target` in `tools/bundle.py`. #### LÖVE -The same sources also build for [LÖVE](https://love2d.org) (LuaJIT), with a GPU renderer in [backends/imgui_impl_love.lua](backends/imgui_impl_love.lua): +The same sources also build for [LÖVE](https://love2d.org) (LuaJIT), with a GPU renderer in [backends/love/imgui_impl_love.lua](backends/love/imgui_impl_love.lua): ``` python3 tools/bundle.py --target love # -> build/imgui_love.lua (LÖVE backend + shims from the LÖVE backend) love examples/example_love ``` -Roblox stays the primary target: the Roblox build is untouched by this (no shims, `@native` kept); the LÖVE build strips `@native` and adds small `bit32`/`buffer`/`utf8`/`table` shims (the COMPAT section of [backends/imgui_impl_love.lua](backends/imgui_impl_love.lua)). `tools/test/love/run.sh` checks that LuaJIT produces exactly the same draw data as Luau. +Roblox stays the primary target: the Roblox build is untouched by this (no shims, `@native` kept); the LÖVE build strips `@native` and adds small `bit32`/`buffer`/`utf8`/`table` shims (the COMPAT section of [backends/love/imgui_impl_love.lua](backends/love/imgui_impl_love.lua)). `tools/test/love/run.sh` checks that LuaJIT produces exactly the same draw data as Luau. #### Prebuilt releases diff --git a/backends/imgui_impl_roblox.lua b/backends/imgui_impl_roblox.lua deleted file mode 100644 index 4f24440..0000000 --- a/backends/imgui_impl_roblox.lua +++ /dev/null @@ -1,1649 +0,0 @@ ---- ImGui Backend for Roblox ---- - Renderer: exact software rasterizer (1:1 with imgui's triangles) into 256x256 EditableImage tiles at native ---- screen resolution; only tiles whose content changed are redrawn/uploaded (see RenderDrawData). ---- - Platform: UserInputService ---- - Files: an in-memory file system (VFS), pre-filled with the fonts from imgui_impl_roblox_fonts.lua ---- Requires "Allow Mesh / Image APIs" (EditableImage) in game settings. - -local UserInputService = game:GetService("UserInputService") -local Players = game:GetService("Players") -local AssetService = game:GetService("AssetService") - -local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max -local readu8, readu32, writeu32, readstring = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.readstring -local readf64 = buffer.readf64 -local band, rshift = bit32.band, bit32.rshift - -local ImGui_ImplRoblox_GetBackendData -local ImGui_ImplRoblox_UpdateTexture -local ImGui_ImplRoblox_RenderDrawData -local ImGui_ImplRoblox_Shutdown - -local KEY_MAP = {} -- Enum.KeyCode -> ImGuiKey -do - local names = { - Return = "Enter", Escape = "Escape", Backspace = "Backspace", Tab = "Tab", Space = "Space", KeypadEnter = "KeypadEnter", - Up = "UpArrow", Down = "DownArrow", Left = "LeftArrow", Right = "RightArrow", - Home = "Home", End = "End", PageUp = "PageUp", PageDown = "PageDown", Insert = "Insert", Delete = "Delete", - LeftControl = "LeftCtrl", RightControl = "RightCtrl", LeftShift = "LeftShift", RightShift = "RightShift", - LeftAlt = "LeftAlt", RightAlt = "RightAlt", LeftSuper = "LeftSuper", RightSuper = "RightSuper", - Quote = "Apostrophe", Comma = "Comma", Minus = "Minus", Period = "Period", Slash = "Slash", Semicolon = "Semicolon", - Equals = "Equal", LeftBracket = "LeftBracket", BackSlash = "Backslash", RightBracket = "RightBracket", Backquote = "GraveAccent", - CapsLock = "CapsLock", - KeypadPeriod = "KeypadDecimal", KeypadDivide = "KeypadDivide", KeypadMultiply = "KeypadMultiply", - KeypadMinus = "KeypadSubtract", KeypadPlus = "KeypadAdd", KeypadEquals = "KeypadEqual", - } - local digits = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" } - for i = 0, 9 do - names[digits[i + 1]] = "K" .. i - names["Keypad" .. digits[i + 1]] = "Keypad" .. i - end - for i = 1, 12 do names["F" .. i] = "F" .. i end - for c in ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"):gmatch(".") do names[c] = c end - - for rbx_name, imgui_name in pairs(names) do - KEY_MAP[Enum.KeyCode[rbx_name]] = ImGuiKey[imgui_name] - end -end - --- Roblox has no "text input" event, so characters come from KeyCode.Value (ASCII for printable keys) + a US layout shift table. -local SHIFTED = { - ["1"] = "!", ["2"] = "@", ["3"] = "#", ["4"] = "$", ["5"] = "%", ["6"] = "^", ["7"] = "&", ["8"] = "*", ["9"] = "(", ["0"] = ")", - ["-"] = "_", ["="] = "+", ["["] = "{", ["]"] = "}", ["\\"] = "|", [";"] = ":", ["'"] = "\"", [","] = "<", ["."] = ">", ["/"] = "?", ["`"] = "~", -} - -local MOUSE_BUTTONS = { - [Enum.UserInputType.MouseButton1] = 0, -- ImGuiMouseButton.Left - [Enum.UserInputType.MouseButton2] = 1, -- ImGuiMouseButton.Right - [Enum.UserInputType.MouseButton3] = 2, -- ImGuiMouseButton.Middle -} - ---- @return boolean ctrl, boolean shift, boolean alt -local function ImGui_ImplRoblox_UpdateKeyModifiers() - local io = ImGui.GetIO() - local K = Enum.KeyCode - local ctrl = UserInputService:IsKeyDown(K.LeftControl) or UserInputService:IsKeyDown(K.RightControl) - local shift = UserInputService:IsKeyDown(K.LeftShift) or UserInputService:IsKeyDown(K.RightShift) - local alt = UserInputService:IsKeyDown(K.LeftAlt) or UserInputService:IsKeyDown(K.RightAlt) - io:AddKeyEvent(ImGuiMod_Ctrl, ctrl) - io:AddKeyEvent(ImGuiMod_Shift, shift) - io:AddKeyEvent(ImGuiMod_Alt, alt) - io:AddKeyEvent(ImGuiMod_Super, UserInputService:IsKeyDown(K.LeftSuper) or UserInputService:IsKeyDown(K.RightSuper)) - return ctrl, shift, alt -end - ---- @return table? -function ImGui_ImplRoblox_GetBackendData() - return ImGui.GetCurrentContext() and ImGui.GetIO().BackendPlatformUserData or nil -end - -local function ImGui_ImplRoblox_UpdateMonitors(w, h) - local platform_io = ImGui.GetPlatformIO() - platform_io.Monitors:resize(0) - - local imgui_monitor = ImGuiPlatformMonitor() - ImVec2_Copy(imgui_monitor.MainSize, ImVec2(w, h)) - ImVec2_Copy(imgui_monitor.WorkSize, ImVec2(w, h)) - - platform_io.Monitors:push_back(imgui_monitor) -end - ---------------------------------------------------------- --- PLATFORM DATA & CALLBACKS ---------------------------------------------------------- - --- Games can't touch the OS clipboard, so copy/paste only works inside ImGui -local clipboard = "" -local function ImGui_ImplRoblox_PlatformSetClipboardText(ctx, text) clipboard = text end -local proxy_focused = false -local function ImGui_ImplRoblox_PlatformGetClipboardText(ctx) if proxy_focused then return "" end return clipboard end - ---------------------------------------------------------- --- FILE SYSTEM (in-memory, Roblox has no file access) ---------------------------------------------------------- - -local VFS = {} -- path -> string of raw bytes - ---- Registers a file so ImGui can load it, e.g. ImGui_ImplRoblox.AddFile("fonts/MyFont.ttf", bytes) ---- then io.Fonts:AddFontFromFileTTF("fonts/MyFont.ttf", 16) -local function ImGui_ImplRoblox_AddFile(path, bytes) VFS[path] = bytes end - -for path, hex in pairs(IM_INCLUDE("imgui_impl_roblox_fonts.lua")) do - VFS[path] = hex:gsub("%s", ""):gsub("%x%x", function(h) return string.char(tonumber(h, 16)) end) -end - -function ImStd.ImFileOpen(filename, mode) - local data = VFS[filename] - return data and { Data = data, Pos = 0 } or nil -end - -function ImStd.ImFileClose(f) end - -function ImStd.ImFileGetSize(f) return #f.Data end - -function ImStd.ImFileRead(f, data, count) - local s, pos = f.Data, f.Pos - count = min(count, #s - pos) - for i = 1, count do data[i] = string.byte(s, pos + i) end - f.Pos = pos + count - return count -end - -function ImStd.ImFileLoadToMemory(filename, mode) - local f = ImStd.ImFileOpen(filename, mode) - if not f or #f.Data == 0 then return end - local file_data = {} - local size = ImStd.ImFileRead(f, file_data, #f.Data) - return file_data, size -end - ---------------------------------------------------------- --- TEXTURE MANAGEMENT ---------------------------------------------------------- - --- Copies a region of ImTextureData pixels (1-based byte table) into our RGBA8 buffer -@native -local function CopyTexturePixels(tex, dst, x, y, w, h) - local bpp, tex_w = tex.BytesPerPixel, tex.Width - for row = 0, h - 1 do - local src, src_base = tex:GetPixelsAt(x, y + row) - local dst_off = ((y + row) * tex_w + x) * 4 - if bpp == 4 then - for i = 0, w - 1 do - local s = src_base + i * 4 - writeu32(dst, dst_off + i * 4, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216) - end - else -- Alpha8: white with alpha - for i = 0, w - 1 do - writeu32(dst, dst_off + i * 4, 16777215 + src[src_base + i] * 16777216) - end - end - end -end - -function ImGui_ImplRoblox_UpdateTexture(tex) - local bd = ImGui_ImplRoblox_GetBackendData() - if tex.Status == ImTextureStatus.WantCreate then - local t = { Buffer = buffer.create(tex.Width * tex.Height * 4), Width = tex.Width, Height = tex.Height } - CopyTexturePixels(tex, t.Buffer, 0, 0, tex.Width, tex.Height) - - bd.TextureCount = bd.TextureCount + 1 - bd.Textures[bd.TextureCount] = t - tex.BackendUserData = bd.TextureCount - tex:SetTexID(bd.TextureCount) - tex:SetStatus(ImTextureStatus.OK) - elseif tex.Status == ImTextureStatus.WantUpdates then - local t = bd.Textures[tex.BackendUserData] - IM_ASSERT(t ~= nil) - for _, r in tex.Updates:iter() do - CopyTexturePixels(tex, t.Buffer, r.x, r.y, r.w, r.h) - end - tex:SetStatus(ImTextureStatus.OK) - elseif tex.Status == ImTextureStatus.WantDestroy then - if tex.BackendUserData then - bd.Textures[tex.BackendUserData] = nil - tex.BackendUserData = nil - end - tex:SetTexID(ImTextureID_Invalid) - tex:SetStatus(ImTextureStatus.Destroyed) - end -end - ---- User texture from RGBA8 pixels (e.g. EditableImage:ReadPixelsBuffer()). Returns an ImTextureRef for ---- ImGui.Image / draw_list:AddImage. Ids are never reused, so cached tiles can't show a stale image. -function ImGui_ImplRoblox_CreateTexture(pixels, w, h) - local bd = ImGui_ImplRoblox_GetBackendData() - bd.TextureCount = bd.TextureCount + 1 - bd.Textures[bd.TextureCount] = { Buffer = pixels, Width = w, Height = h } - return ImTextureRef(bd.TextureCount) -end - -function ImGui_ImplRoblox_DestroyTexture(tex_ref) - ImGui_ImplRoblox_GetBackendData().Textures[tex_ref._TexID] = nil -end - ---------------------------------------------------------- --- RENDERING (software rasterizer into tile buffers) ---------------------------------------------------------- --- Buffer layout: 4 bytes per pixel, R G B A, row-major, 0-based offsets. ImU32 colours are already R | G<<8 | B<<16 | A<<24. --- Blending is non-premultiplied "over" with a transparent (alpha 0) background, so the game stays visible behind ImGui. - -local buf, buf_w -- buffer/width of the tile being drawn -local rect_cols = table.create(256, 0) -- scratch: texel column offsets for DrawRect -local sub_bufs, n_sub_bufs = {}, 0 -- scratch: partial tile upload buffers by size -local TILE_SIZE -- Vector2, set below - --- Blends one pixel (r, g, b, a are 0..255). One u32 read/write, one division in the general case. --- FillSpan below inlines the same math with per-span constants - keep the two in sync. -@native -local function BlendPixel(o, r, g, b, a) - if a >= 255 then - writeu32(buf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080) - return - end - if a <= 0 then return end - local d = readu32(buf, o) - local da = rshift(d, 24) - if da == 0 then - writeu32(buf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216) - return - end - local sa = a / 255 - local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) - if da == 255 then - local ns = 1 - sa - writeu32(buf, o, floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256 + floor(b * sa + db * ns + 0.5) * 65536 + 4278190080) - else - local k = da * ((1 - sa) / 255) - local oa = sa + k - local inv = 1 / oa - writeu32(buf, o, floor((r * sa + dr * k) * inv + 0.5) + floor((g * sa + dg * k) * inv + 0.5) * 256 - + floor((b * sa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) - end -end - --- Fills pixels [x0, x1) of row y with one colour -@native -local function FillSpan(y, x0, x1, r, g, b, a) - if a <= 0 then return end - local o0 = (y * buf_w + x0) * 4 - local o1 = o0 + (x1 - x0 - 1) * 4 - if a >= 255 then - local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080 - for o = o0, o1, 4 do writeu32(buf, o, packed) end - return - end - local packed0 = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216 - local sa = a / 255 - local ns = 1 - sa - local c1 = ns / 255 - local rs, gs, bs = r * sa, g * sa, b * sa - local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination - for o = o0, o1, 4 do - local d = readu32(buf, o) - local da = rshift(d, 24) - if d == last_d then - writeu32(buf, o, last_v) - elseif da == 0 then - writeu32(buf, o, packed0) - else - last_d = d - local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) - if da == 255 then - last_v = floor(rs + dr * ns + 0.5) + floor(gs + dg * ns + 0.5) * 256 + floor(bs + db * ns + 0.5) * 65536 + 4278190080 - else - local k = da * c1 - local oa = sa + k - local inv = 1 / oa - last_v = floor((rs + dr * k) * inv + 0.5) + floor((gs + dg * k) * inv + 0.5) * 256 - + floor((bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 - end - writeu32(buf, o, last_v) - end - end -end - -@native -local function UnpackColor(col) - return col % 256, floor(col / 256) % 256, floor(col / 65536) % 256, floor(col / 16777216) % 256 -end - --- Nearest texel at (u, v) as r, g, b, a (0..255) -@native -local function SampleTexture(t, u, v) - local tw, th = t.Width, t.Height - local tx, ty = floor(u * tw), floor(v * th) - if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end - if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end - local o = (ty * tw + tx) * 4 - local tb = t.Buffer - return readu8(tb, o), readu8(tb, o + 1), readu8(tb, o + 2), readu8(tb, o + 3) -end - --- Axis aligned, single colour quad (rects, glyphs, images). Pixel centers inside [x0, x1) x [y0, y1) are drawn. -@native -local function DrawRect(x0, y0, x1, y1, u0, v0, u1, v1, col, t, cx0, cy0, cx1, cy1) - local r, g, b, a = UnpackColor(col) - if a == 0 then return end - local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0) - local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1) - if px0 >= px1 or py0 >= py1 then return end - - if not t or (u0 == u1 and v0 == v1) then - if t then - local tr, tg, tb, ta = SampleTexture(t, u0, v0) - r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255 - end - if a <= 0 then return end - -- Rows of a flat rect usually blend over identical rows: when this row's destination equals the previous - -- row's (exact string compare), the result is identical too, so memcpy the previous row's result. - local len = (px1 - px0) * 4 - local prev_dst, prev_o = nil, 0 - for y = py0, py1 - 1 do - local o = (y * buf_w + px0) * 4 - if a >= 255 then - if prev_dst then buffer.copy(buf, o, buf, prev_o, len) else FillSpan(y, px0, px1, r, g, b, a); prev_dst = true end - else - local dst = readstring(buf, o, len) - if dst == prev_dst then - buffer.copy(buf, o, buf, prev_o, len) - else - FillSpan(y, px0, px1, r, g, b, a) - prev_dst = dst - end - end - prev_o = o - end - return - end - - local du, dv = (u1 - u0) / (x1 - x0), (v1 - v0) / (y1 - y0) - local tw, th, tbuf = t.Width, t.Height, t.Buffer - local r255, g255, b255, a255 = r / 255, g / 255, b / 255, a / 255 - -- The texel column only depends on x: compute it once per column instead of once per pixel - local ncol = px1 - px0 - local cols = rect_cols - for c = 1, ncol do - local tx = floor((u0 + (px0 + c - 1 + 0.5 - x0) * du) * tw) - if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end - cols[c] = tx * 4 - end - for y = py0, py1 - 1 do - local ty = floor((v0 + (y + 0.5 - y0) * dv) * th) - if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end - local trow4 = ty * tw * 4 - local o = (y * buf_w + px0) * 4 - for c = 1, ncol do - local to = trow4 + cols[c] - local ta = readu8(tbuf, to + 3) - if ta > 0 then - local sa = ta * a255 - local sr, sg, sb = readu8(tbuf, to) * r255, readu8(tbuf, to + 1) * g255, readu8(tbuf, to + 2) * b255 - if sa >= 255 then -- (BlendPixel's opaque case, inlined: most glyph texels) - writeu32(buf, o, floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + 4278190080) - else - BlendPixel(o, sr, sg, sb, sa) - end - end - o = o + 4 - end - end -end - --- Generic triangle: per-vertex colour + uv, top-left fill rule, clipped to [cx0, cx1) x [cy0, cy1) -@native -local function DrawTriangle(vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, ox, oy) - local x0, y0 = readf64(vbuf, va) - ox, readf64(vbuf, va + 8) - oy - local x1, y1 = readf64(vbuf, vb) - ox, readf64(vbuf, vb + 8) - oy - local x2, y2 = readf64(vbuf, vc) - ox, readf64(vbuf, vc + 8) - oy - local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0) - if area == 0 then return end - if area < 0 then -- make the winding consistent so "inside" means all edge functions >= 0 - vb, vc = vc, vb - x1, y1, x2, y2 = x2, y2, x1, y1 - area = -area - end - - local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1) - local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1) - if minx > maxx or miny > maxy then return end - - -- Edge functions E(p) = A*px + B*py + C, w0 is opposite va, w1 opposite vb, w2 opposite vc - local A0, B0 = y1 - y2, x2 - x1; local C0 = -(A0 * x1 + B0 * y1) - local A1, B1 = y2 - y0, x0 - x2; local C1 = -(A1 * x2 + B1 * y2) - local A2, B2 = y0 - y1, x1 - x0; local C2 = -(A2 * x0 + B2 * y0) - local tl0 = A0 > 0 or (A0 == 0 and B0 > 0) - local tl1 = A1 > 0 or (A1 == 0 and B1 > 0) - local tl2 = A2 > 0 or (A2 == 0 and B2 > 0) - - local inv = 1 / area - local ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32)) - local rb, gb, bb, ab = UnpackColor(readu32(vbuf, vb + 32)) - local rc, gc, bc, ac = UnpackColor(readu32(vbuf, vc + 32)) - local ua, vva, ub, vvb, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vb + 16), readf64(vbuf, vb + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) - - local textured = t and not (ua == ub and ua == uc and vva == vvb and vva == vvc) - if t and not textured then -- constant uv (e.g. the atlas white pixel): fold the texel into the vertex colours - local tr, tg, tb, ta = SampleTexture(t, ua, vva) - ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255 - rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255 - rc, gc, bc, ac = rc * tr / 255, gc * tg / 255, bc * tb / 255, ac * ta / 255 - end - local flat = not textured and ra == rb and ra == rc and ga == gb and ga == gc and ba == bb and ba == bc and aa == ab and aa == ac - if flat and aa <= 0 then return end - - for y = miny, maxy do - local py = y + 0.5 - -- Narrow the x range of this row using the edges (expanded by one pixel, exact test below) - local xl, xr = minx, maxx - local e0, e1, e2 = B0 * py + C0, B1 * py + C1, B2 * py + C2 - if A0 ~= 0 then local xe = -e0 / A0 - 0.5; if A0 > 0 then xl = max(xl, floor(xe)) else xr = min(xr, ceil(xe)) end end - if A1 ~= 0 then local xe = -e1 / A1 - 0.5; if A1 > 0 then xl = max(xl, floor(xe)) else xr = min(xr, ceil(xe)) end end - if A2 ~= 0 then local xe = -e2 / A2 - 0.5; if A2 > 0 then xl = max(xl, floor(xe)) else xr = min(xr, ceil(xe)) end end - - local row = y * buf_w - for x = xl, xr do - local px = x + 0.5 - local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2 - if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then - local o = (row + x) * 4 - if flat then - BlendPixel(o, ra, ga, ba, aa) - else - w0, w1, w2 = w0 * inv, w1 * inv, w2 * inv - local r = w0 * ra + w1 * rb + w2 * rc - local g = w0 * ga + w1 * gb + w2 * gc - local b = w0 * ba + w1 * bb + w2 * bc - local a = w0 * aa + w1 * ab + w2 * ac - if textured then - local tr, tg, tb, ta = SampleTexture(t, w0 * ua + w1 * ub + w2 * uc, w0 * vva + w1 * vvb + w2 * vvc) - r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255 - end - BlendPixel(o, r, g, b, a) - end - end - end - end -end - --- Layers: every ImDrawList (one per top level window, popup, tooltip, plus the viewport bg/fg lists) gets its own --- Frame, stacked by draw order. A layer is covered by TILE x TILE EditableImages (one ImageLabel each) placed --- relative to the layer's origin (top-left of its content). Primitives are hashed into tiles in layer-relative --- coordinates, so moving a window only moves its Frame: no tile changes, nothing re-rasterized or uploaded. --- Only tiles whose hash changed are redrawn; the hash covers everything that affects a tile's pixels. -local TILE = 128 -TILE_SIZE = Vector2.new(TILE, TILE) -local P1, P2 = 2147483647, 2147483629 -- two independent 31 bit hashes per tile (collision odds ~2^-62) -local KEY_W = 64 -- tile key = ty * KEY_W + tx (layers up to 16384 px wide) -local CLIP_PAD = 2048 -- content up to this far off screen is kept, so dragging a window past the edge doesn't redraw it -local LAYER_KEEP_FRAMES = 120 -- unused layers are destroyed after this many rendered frames -local MAX_DEFER_FRAMES = 8 -- a tile is redrawn at the latest this many frames after it changed, even over the redraw budget - --- Primitive arrays (reused between frames, no per-frame allocation) -local pr_a, pr_b, pr_c, pr_d, pr_t, pr_g = {}, {}, {}, {}, {}, {} -- vertices (pr_d == false -> triangle), texture, gradient kind -local pr_cx0, pr_cy0, pr_cx1, pr_cy1 = {}, {}, {}, {} -- clip (screen pixels) -local pr_bx0, pr_by0, pr_bx1, pr_by1 = {}, {}, {}, {} -- clipped bounds (screen pixels) -local pr_tex = {} -- texture id -local pr_vb = {} -- vertex buffer (draw list VtxBuffer.Buf) -local pr_k = {} -- layer kind (1..3) -local plist1, plist2, plist3 = {}, {}, {} -- primitive indices per layer kind -local cm_free, cm_kind, cm_x0, cm_y0, cm_x1, cm_y1 = {}, {}, {}, {}, {}, {} -- per draw command (collect -> Snapshot) - -@native -local function HashVertex(h1, h2, vbuf, v, ox, oy) - local x, y = readf64(vbuf, v) - ox, readf64(vbuf, v + 8) - oy - local uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24) - local c = readu32(vbuf, v + 32) - h1 = (h1 * 48271 + x * 4096 + y) % P1 - h1 = (h1 * 48271 + uv * 4096) % P1 - h1 = (h1 * 48271 + c) % P1 - h2 = (h2 * 16807 + y * 4093 + x) % P2 - h2 = (h2 * 16807 + uv * 65521) % P2 - h2 = (h2 * 16807 + c) % P2 - return h1, h2 -end - --- Axis aligned quad with a linear colour gradient and constant uv (ColorPicker hue/SV/alpha bars, AddRectFilledMultiColor). --- kind 1: colour varies along y (ca top, cb bottom), kind 2: along x (ca left, cb right). Same pixels as the two triangles. -@native -local function DrawRectGradient(x0, y0, x1, y1, ca, cb, kind, t, u, v, cx0, cy0, cx1, cy1) - local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0) - local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1) - if px0 >= px1 or py0 >= py1 then return end - local ra, ga, ba, aa = UnpackColor(ca) - local rb, gb, bb, ab = UnpackColor(cb) - if t then - local tr, tg, tb, ta = SampleTexture(t, u, v) - ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255 - rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255 - end - if kind == 1 then - local inv = 1 / (y1 - y0) - for y = py0, py1 - 1 do - local f = (y + 0.5 - y0) * inv - local nf = 1 - f - FillSpan(y, px0, px1, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f) - end - else - -- Every row gets the same colours: when a row's destination equals the previous row's, copy its result - local inv = 1 / (x1 - x0) - local len = (px1 - px0) * 4 - local opaque = aa >= 255 and ab >= 255 - local prev_dst, prev_o = nil, 0 - for y = py0, py1 - 1 do - local o = (y * buf_w + px0) * 4 - local dst = (not opaque) and readstring(buf, o, len) or true - if prev_dst ~= nil and dst == prev_dst then - buffer.copy(buf, o, buf, prev_o, len) - else - local oo = o - for x = px0, px1 - 1 do - local f = (x + 0.5 - x0) * inv - local nf = 1 - f - BlendPixel(oo, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f) - oo = oo + 4 - end - prev_dst = dst - end - prev_o = o - end - end -end - --- Layer kinds per draw list: 1 = drawn before the window content (background, title bar, borders, scrollbar), --- 2 = window content (positioned at the scroll origin inside a ClipsDescendants frame, so scrolling just moves it), --- 3 = anything not clipped to the content drawn after content started (menu bar, overlays). Stacked 1 < 2 < 3. -local function NewFrame(parent, clips) - local frame = Instance.new("Frame") - frame.Name = "Layer" - frame.BackgroundTransparency = 1 - frame.BorderSizePixel = 0 - frame.Size = UDim2.fromOffset(0, 0) - frame.ClipsDescendants = clips - frame.Visible = false - frame.Parent = parent - return frame -end - -local function GetLayer(bd, draw_list, kind) - local set = bd.Layers[draw_list] - if not set then set = { LastUsed = 0 }; bd.Layers[draw_list] = set end - local layer = set[kind] - if layer then return layer end - local root, frame - if kind == 2 then - root = NewFrame(bd.Gui, true) - frame = NewFrame(root, false); frame.Visible = true - else - frame = NewFrame(bd.Gui, false); root = frame - end - layer = { Root = root, Frame = frame, Tiles = {}, TH1 = {}, TH2 = {}, TN = {}, TL = {}, TL1 = {}, TL2 = {}, TLF = {}, TX = {}, TY = {}, Touched = {}, NTouched = 0, - Visible = false, X = false, Y = false, Z = -1, CX0 = false, CY0 = false, CX1 = false, CY1 = false } - set[kind] = layer - return layer -end - -local function HideLayer(layer) - if layer.Visible then layer.Visible = false; layer.Root.Visible = false end -end - -local function GetTile(bd, layer, key, tx, ty) - local tile = layer.Tiles[key] - if tile then return tile end - local img = AssetService:CreateEditableImage({ Size = Vector2.new(TILE, TILE) }) - assert(img, "imgui_impl_roblox: EditableImage memory budget exceeded") - local label = Instance.new("ImageLabel") - label.Name = "Tile" .. key - label.BackgroundTransparency = 1 - label.BorderSizePixel = 0 - local scale = bd.Scale - label.Size = UDim2.fromOffset(TILE / scale, TILE / scale) - label.Position = UDim2.fromOffset(tx * TILE / scale, ty * TILE / scale) - label.ResampleMode = Enum.ResamplerMode.Pixelated - label.ImageContent = Content.fromObject(img) - label.Visible = false - label.Active = bd.TilesActive - label.Parent = layer.Frame - tile = { Image = img, Label = label, Buffer = buffer.create(TILE * TILE * 4), H1 = -1, H2 = -1, Visible = false, BX0 = TILE, BY0 = TILE, BX1 = 0, BY1 = 0, - ON = -1, OH1 = {}, OH2 = {}, OF = {}, OB0 = {}, OB1 = {}, OB2 = {}, OB3 = {} } -- last drawn primitive list (hashes, bounds in tile) - layer.Tiles[key] = tile - return tile -end - -local function DestroyLayerSet(set) - for kind = 1, 3 do - local layer = set[kind] - if layer then - for _, tile in pairs(layer.Tiles) do tile.Image:Destroy() end - layer.Root:Destroy() - end - end -end - -local function DestroyTiles(bd) - for _, set in pairs(bd.Layers) do DestroyLayerSet(set) end - bd.Layers = {} -end - --- Snapshot of everything in a draw list that affects its layers, compared exactly with the next frame's list: --- 1 = identical (only restack), 2 = everything moved by the same whole pixels (dx, dy) (only move the layers: a window --- being dragged), 0 = changed (full path). Compared in place (no strings built): early exit at the first difference. -local writef64 = buffer.writef64 -local CMD_STRIDE = 70 -- clip (4 f64), ElemCount, IdxOffset, VtxOffset (u32), tex id (f64), kind (u8), free (u8), bounds of its primitives (4 x i32) - -@native -local function Snapshot(set, draw_list, ox, oy, sw, sh) - local nv = draw_list.VtxBuffer.Size * VTX_STRIDE - local idx, ni = draw_list.IdxBuffer.Data, draw_list.IdxBuffer.Size - local ncmd = draw_list.CmdBuffer.Size - local sv, si, sc = set.SV, set.SI, set.SC - if not sv or buffer.len(sv) < nv then sv = buffer.create(max(nv, 64) * 2); set.SV = sv end - if not si or buffer.len(si) < ni * 4 then si = buffer.create(max(ni, 16) * 8); set.SI = si end - if not sc or buffer.len(sc) < ncmd * CMD_STRIDE then sc = buffer.create(max(ncmd, 4) * CMD_STRIDE * 2); set.SC = sc end - buffer.copy(sv, 0, draw_list.VtxBuffer.Buf, 0, nv) - for i = 1, ni do writeu32(si, (i - 1) * 4, idx[i]) end - local o, ci = 0, 0 - for _, pcmd in draw_list.CmdBuffer:iter() do - if pcmd.UserCallback ~= nil then set.SnapOK = false; return end - local c = pcmd.ClipRect - writef64(sc, o, c.x); writef64(sc, o + 8, c.y); writef64(sc, o + 16, c.z); writef64(sc, o + 24, c.w) - writeu32(sc, o + 32, pcmd.ElemCount); writeu32(sc, o + 36, pcmd.IdxOffset); writeu32(sc, o + 40, pcmd.VtxOffset) - writef64(sc, o + 44, pcmd:GetTexID()) - ci += 1 - buffer.writeu8(sc, o + 52, cm_kind[ci] or 0); buffer.writeu8(sc, o + 53, cm_free[ci] and 1 or 0) - if cm_free[ci] then - buffer.writei32(sc, o + 54, cm_x0[ci]); buffer.writei32(sc, o + 58, cm_y0[ci]); buffer.writei32(sc, o + 62, cm_x1[ci]); buffer.writei32(sc, o + 66, cm_y1[ci]) - end - o += CMD_STRIDE - end - set.SVN, set.SIN, set.SCN = nv, ni, ncmd - set.SOX, set.SOY, set.SSW, set.SSH = ox, oy, sw, sh - set.SCC = draw_list._ContentClipX0 ~= nil - set.SCX0, set.SCY0, set.SCX1, set.SCY1 = draw_list._ContentClipX0 or 0, draw_list._ContentClipY0 or 0, draw_list._ContentClipX1 or 0, draw_list._ContentClipY1 or 0 - set.SSX, set.SSY = draw_list._ScrollOriginX or 0, draw_list._ScrollOriginY or 0 - set.SnapOK = true -end - --- a + d == b exactly, with no rounding in a + d (so every later "x - origin" gives the same result as before the move) -@native -local function ShiftedExact(a, d, b) - local s = a + d - if s ~= b then return false end - local bb = s - a - return (a - (s - bb)) + (d - bb) == 0 -end - -@native -local function CompareDrawList(set, draw_list, ox, oy, sw, sh) - if not set or not set.SnapOK then return 0 end - local nv = draw_list.VtxBuffer.Size * VTX_STRIDE - local ni, ncmd = draw_list.IdxBuffer.Size, draw_list.CmdBuffer.Size - if nv ~= set.SVN or ni ~= set.SIN or ncmd ~= set.SCN or ox ~= set.SOX or oy ~= set.SOY or sw ~= set.SSW or sh ~= set.SSH then return 0 end - if (draw_list._ContentClipX0 ~= nil) ~= set.SCC then return 0 end - local vb, sv = draw_list.VtxBuffer.Buf, set.SV - if nv == 0 then return 1 end - -- translation from the first vertex: whole pixels only, and only with DisplayPos at 0 (so it stays exact) - local dx, dy = readf64(vb, 0) - readf64(sv, 0), readf64(vb, 8) - readf64(sv, 8) - if dx ~= dx or dy ~= dy then return 0 end - if dx ~= 0 or dy ~= 0 then - if dx ~= floor(dx) or dy ~= floor(dy) or ox ~= 0 or oy ~= 0 or not set.SLimFree then return 0 end - -- everything must stay as far from the clip limits as before (nothing newly clamped) - if set.SEX0 + dx < -CLIP_PAD or set.SEY0 + dy < -CLIP_PAD or set.SEX1 + dx > sw + CLIP_PAD or set.SEY1 + dy > sh + CLIP_PAD then return 0 end - end - local idx, si = draw_list.IdxBuffer.Data, set.SI - for i = 1, ni do if idx[i] ~= readu32(si, (i - 1) * 4) then return 0 end end - local sc, o = set.SC, 0 - local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1, draw_list._ContentClipY1 - local seen_content = false - for _, pcmd in draw_list.CmdBuffer:iter() do - if pcmd.UserCallback ~= nil then return 0 end - if pcmd.ElemCount ~= readu32(sc, o + 32) or pcmd.IdxOffset ~= readu32(sc, o + 36) or pcmd.VtxOffset ~= readu32(sc, o + 40) or pcmd:GetTexID() ~= readf64(sc, o + 44) then return 0 end - local c = pcmd.ClipRect - if dx == 0 and dy == 0 then - if c.x ~= readf64(sc, o) or c.y ~= readf64(sc, o + 8) or c.z ~= readf64(sc, o + 16) or c.w ~= readf64(sc, o + 24) then return 0 end - elseif not (ShiftedExact(readf64(sc, o), dx, c.x) and ShiftedExact(readf64(sc, o + 8), dy, c.y) - and ShiftedExact(readf64(sc, o + 16), dx, c.z) and ShiftedExact(readf64(sc, o + 24), dy, c.w)) then - -- An unchanged clip rect (e.g. the viewport) is fine if it clipped none of this command's primitives before - -- the move and still clips none after it - if c.x ~= readf64(sc, o) or c.y ~= readf64(sc, o + 8) or c.z ~= readf64(sc, o + 16) or c.w ~= readf64(sc, o + 24) - or buffer.readu8(sc, o + 53) == 0 then return 0 end - if buffer.readi32(sc, o + 54) + dx < floor(c.x) or buffer.readi32(sc, o + 58) + dy < floor(c.y) - or buffer.readi32(sc, o + 62) + dx > floor(c.z) or buffer.readi32(sc, o + 66) + dy > floor(c.w) then return 0 end - end - -- same layer kind as before (same rule as the collect pass) - if pcmd.ElemCount > 0 then - local kind = 1 - if ccx0 and c.x >= ccx0 and c.y >= ccy0 and c.z <= ccx1 and c.w <= ccy1 then kind = 2; seen_content = true - elseif seen_content then kind = 3 end - if kind ~= buffer.readu8(sc, o + 52) then return 0 end - end - o += CMD_STRIDE - end - if dx == 0 and dy == 0 then - if set.SCC and (draw_list._ContentClipX0 ~= set.SCX0 or draw_list._ContentClipY0 ~= set.SCY0 or draw_list._ContentClipX1 ~= set.SCX1 - or draw_list._ContentClipY1 ~= set.SCY1 or draw_list._ScrollOriginX ~= set.SSX or draw_list._ScrollOriginY ~= set.SSY) then return 0 end - for v = 0, nv - VTX_STRIDE, VTX_STRIDE do - if readf64(vb, v) ~= readf64(sv, v) or readf64(vb, v + 8) ~= readf64(sv, v + 8) or readf64(vb, v + 16) ~= readf64(sv, v + 16) - or readf64(vb, v + 24) ~= readf64(sv, v + 24) or readu32(vb, v + 32) ~= readu32(sv, v + 32) then return 0 end - end - return 1 - end - if set.SCC and not (ShiftedExact(set.SCX0, dx, draw_list._ContentClipX0) and ShiftedExact(set.SCY0, dy, draw_list._ContentClipY0) - and ShiftedExact(set.SCX1, dx, draw_list._ContentClipX1) and ShiftedExact(set.SCY1, dy, draw_list._ContentClipY1) - and ShiftedExact(set.SSX, dx, draw_list._ScrollOriginX) and ShiftedExact(set.SSY, dy, draw_list._ScrollOriginY)) then return 0 end - for v = 0, nv - VTX_STRIDE, VTX_STRIDE do - if not ShiftedExact(readf64(sv, v), dx, readf64(vb, v)) or not ShiftedExact(readf64(sv, v + 8), dy, readf64(vb, v + 8)) - or readf64(vb, v + 16) ~= readf64(sv, v + 16) or readf64(vb, v + 24) ~= readf64(sv, v + 24) or readu32(vb, v + 32) ~= readu32(sv, v + 32) then return 0 end - end - return 2, dx, dy -end - --- A window moved by whole pixels: its tiles are unchanged, only the layer frames move -local function ShiftLayer(layer, dx, dy, scale) - layer.X += dx; layer.Y += dy - local root = layer.Root - if root ~= layer.Frame then - layer.CX0 += dx; layer.CY0 += dy; layer.CX1 += dx; layer.CY1 += dy - root.Position = UDim2.fromOffset(layer.CX0 / scale, layer.CY0 / scale) - else - root.Position = UDim2.fromOffset(layer.X / scale, layer.Y / scale) - end -end - --- Overlays: user Instances (e.g. a Frame holding a ViewportFrame) placed inside a window, registered every frame with --- ImGui_ImplRoblox.SetOverlay() while that window is current. They stack right above the window's layers, move with --- it, and (clip = true) are clipped to the window's content area like its widgets. -local function OverlayHolder(bd, draw_list, clip) - local hs = bd.OverlayHolders[draw_list] - if not hs then hs = {}; bd.OverlayHolders[draw_list] = hs end - local h = hs[clip] - if not h then - h = Instance.new("Frame") - h.Name = clip and "OverlayClip" or "Overlay" - h.BackgroundTransparency = 1 - h.BorderSizePixel = 0 - h.ClipsDescendants = clip - h.Size = UDim2.fromOffset(0, 0) - h.Parent = bd.Gui - hs[clip] = h - end - return h -end - -local function PlaceOverlays(bd, draw_list, z, ox, oy) - local list = bd.Overlays[draw_list] - local hs = bd.OverlayHolders[draw_list] - if not list then - if hs then for _, h in pairs(hs) do h.Visible = false end end - return z - end - local scale, frame_no = bd.Scale, bd.FrameNo - z += 1 - local used = {} - for _, o in ipairs(list) do - local clip = o.Clip and draw_list._ContentClipX0 ~= nil - local h = OverlayHolder(bd, draw_list, clip) - local hx, hy = 0, 0 - if clip then - hx, hy = draw_list._ContentClipX0 - ox, draw_list._ContentClipY0 - oy - if not used[h] then - h.Position = UDim2.fromOffset(hx / scale, hy / scale) - h.Size = UDim2.fromOffset((draw_list._ContentClipX1 - draw_list._ContentClipX0) / scale, (draw_list._ContentClipY1 - draw_list._ContentClipY0) / scale) - end - elseif not used[h] then - h.Position = UDim2.fromOffset(0, 0) - end - used[h] = true - h.ZIndex = z - h.Visible = true - local f = o.Frame - if f.Parent ~= h then f.Parent = h end - f.Position = UDim2.fromOffset((o.X - ox - hx) / scale, (o.Y - oy - hy) / scale) - f.Size = UDim2.fromOffset(o.W / scale, o.H / scale) - f.Visible = true - bd.OverlayShown[f] = frame_no - end - if hs then for _, h in pairs(hs) do if not used[h] then h.Visible = false end end end - return z -end - ---- Show `frame` this frame at (x, y, w, h) (imgui coordinates) inside the current window. Call every frame it should ---- be visible; frames not submitted are hidden. clip: clip to the window's content area (scrolls with it). -function ImGui_ImplRoblox_SetOverlay(frame, x, y, w, h, clip) - local bd = ImGui_ImplRoblox_GetBackendData() - local dl = ImGui.GetWindowDrawList() - local list = bd.Overlays[dl] - if not list then list = {}; bd.Overlays[dl] = list end - list[#list + 1] = { Frame = frame, X = x, Y = y, W = w, H = h, Clip = clip ~= false } -end - --- MicroProfiler labels, enabled with ImGui_ImplRoblox.SetProfiling(true) -local profilebegin, profileend = debug.profilebegin, debug.profileend -local profiling = false -local function PB(name) if profiling then profilebegin(name) end end -local function PE() if profiling then profileend() end end - -@native -local function DrawLayer(bd, layer, plist, np, lx0, ly0, ox, oy, force, z, clip_x0, clip_y0, clip_x1, clip_y1) - local scale = bd.Scale - local deferred = false - -- Pass 2: hash primitives into layer-relative tiles - PB("ImGui tile hash") - local th1, th2, tn, tl, touched = layer.TH1, layer.TH2, layer.TN, layer.TL, layer.Touched - local tl1, tl2, tlf = layer.TL1, layer.TL2, layer.TLF -- per-tile list of the primitives' hashes (for partial redraws) - for k = 1, layer.NTouched do tn[touched[k]] = 0 end - local nt = 0 - for pi = 1, np do - local p = plist[pi] - local tex_id = pr_tex[p] - -- The clip rect only affects pixels inside the primitive's bounds, so hash the clipped bounds (relative) - -- instead of the clip itself: a window clipped by the (fixed) viewport rect stays hash-stable when moved. - local cx0, cy0, cx1, cy1 = pr_bx0[p] - lx0, pr_by0[p] - ly0, pr_bx1[p] - lx0, pr_by1[p] - ly0 - local vbuf = pr_vb[p] - local va, vd = pr_a[p], pr_d[p] - -- Flat rect (single colour, no gradient, constant uv): its pixels in a tile are exactly its clipped pixel rect - -- inside that tile filled with one colour, so hash that per tile instead of the vertices. Resizing a window - -- then only changes the tiles its edges cross, not every tile its background covers. - local flat_rect, rcol, ruv = false, 0, 0 - if vd and not pr_g[p] then - local u0, v0 = readf64(vbuf, va + 16), readf64(vbuf, va + 24) - local vc = pr_c[p] - if not pr_t[p] or (u0 == readf64(vbuf, vc + 16) and v0 == readf64(vbuf, vc + 24)) then - flat_rect, rcol, ruv = true, readu32(vbuf, va + 32), u0 * 8192 + v0 - end - end - local h1, h2 = 0, 0 - local fsig = -1 -- flat rect: colour/uv/texture without the geometry (-1: not a flat rect) - if flat_rect then fsig = ((rcol * 8191 + ruv * 4096) % P1 * 64 + tex_id) % P1 end - if not flat_rect then - h1 = ((cx0 * 8191 + cy0) * 8191 + cx1) % P1 - h2 = ((cy1 * 8191 + cx1) * 8191 + cy0 + tex_id) % P2 - local vax, vay = lx0 + ox, ly0 + oy - if vd then - -- Axis aligned quad: the collect pass checked that TR/BL (positions, uvs, colours) follow from TL/BR - -- (and the gradient kind), so TL + BR + kind determine its pixels - h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay) - h1, h2 = HashVertex(h1, h2, vbuf, pr_c[p], vax, vay) - local gk = pr_g[p] - if gk then h1 = (h1 * 48271 + gk) % P1; h2 = (h2 * 16807 + gk * 3) % P2 end - else - h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay) - h1, h2 = HashVertex(h1, h2, vbuf, pr_b[p], vax, vay) - h1, h2 = HashVertex(h1, h2, vbuf, pr_c[p], vax, vay) - end - end - for ty = floor((pr_by0[p] - ly0) / TILE), floor((pr_by1[p] - 1 - ly0) / TILE) do - for tx = floor((pr_bx0[p] - lx0) / TILE), floor((pr_bx1[p] - 1 - lx0) / TILE) do - if flat_rect then - local tx0, ty0 = tx * TILE, ty * TILE - local ix0, iy0 = max(cx0 - tx0, 0), max(cy0 - ty0, 0) - local ix1, iy1 = min(cx1 - tx0, TILE), min(cy1 - ty0, TILE) - local r = ((ix0 * 131 + iy0) * 131 + ix1) * 131 + iy1 - h1 = ((r * 48271 + rcol) % P1 * 48271 + ruv * 4096 + 7) % P1 - h2 = ((r * 16807 + rcol + tex_id) % P2 * 16807 + ruv * 65521 + 11) % P2 - end - local key = ty * KEY_W + tx - local k = tn[key] - if not k or k == 0 then - k = 0 - th1[key], th2[key] = 0, 0 - if not tl[key] then tl[key] = {}; tl1[key] = {}; tl2[key] = {}; tlf[key] = {} end - nt = nt + 1 - touched[nt] = key - layer.TX[key], layer.TY[key] = tx, ty - end - k = k + 1 - tn[key] = k - tl[key][k] = p - tl1[key][k], tl2[key][k], tlf[key][k] = h1, h2, fsig - th1[key] = (th1[key] * 48271 + h1) % P1 - th2[key] = (th2[key] * 16807 + h2 + k) % P2 - end - end - end - layer.NTouched = nt - PE() - - -- Place the layer (this is all a window move costs) - local root = layer.Root - if root ~= layer.Frame then - -- content: clip frame at the content clip rect, tiles frame at the scroll origin relative to it - if layer.CX0 ~= clip_x0 or layer.CY0 ~= clip_y0 or layer.CX1 ~= clip_x1 or layer.CY1 ~= clip_y1 then - layer.CX0, layer.CY0, layer.CX1, layer.CY1 = clip_x0, clip_y0, clip_x1, clip_y1 - root.Position = UDim2.fromOffset(clip_x0 / scale, clip_y0 / scale) - root.Size = UDim2.fromOffset((clip_x1 - clip_x0) / scale, (clip_y1 - clip_y0) / scale) - layer.X = false - end - if layer.X ~= lx0 or layer.Y ~= ly0 then - layer.X, layer.Y = lx0, ly0 - layer.Frame.Position = UDim2.fromOffset((lx0 - clip_x0) / scale, (ly0 - clip_y0) / scale) - end - elseif layer.X ~= lx0 or layer.Y ~= ly0 then - layer.X, layer.Y = lx0, ly0 - root.Position = UDim2.fromOffset(lx0 / scale, ly0 / scale) - end - if layer.Z ~= z then layer.Z = z; root.ZIndex = z end - if not layer.Visible then layer.Visible = true; root.Visible = true end - - -- Pass 3: redraw + upload changed tiles, hide unused ones - PB("ImGui raster+upload") - for key, tile in pairs(layer.Tiles) do - if not tn[key] or tn[key] == 0 then - if tile.Visible then tile.Visible = false; tile.Label.Visible = false; tile.H1 = -1; tile.ON = -1 end - end - end - for kk = 1, nt do - local key = touched[kk] - local count = tn[key] - local tx, ty = layer.TX[key], layer.TY[key] - local tile = GetTile(bd, layer, key, tx, ty) - local dirty = force or tile.H1 ~= th1[key] or tile.H2 ~= th2[key] - if dirty and bd.RedrawStarted and (tile.Deferred or 0) < MAX_DEFER_FRAMES - and ((bd.RedrawBudget > 0 and os.clock() - bd.FrameT0 >= bd.RedrawBudget) or (bd.TileLimit and bd.FrameTiles >= bd.TileLimit)) then -- (TileLimit: test hook, tools/test/scripts/t_pixels.luau) - -- Over this frame's redraw budget: keep showing the old pixels, redraw on a following frame. The tile's - -- stored hashes/list still describe what it shows, so the next comparison is against the real content. - tile.Deferred = (tile.Deferred or 0) + 1 - if force then tile.H1 = -1; tile.ON = -1 end -- full redraw later (force doesn't persist) - deferred = true - dirty = false - end - if dirty then - bd.RedrawStarted = true - bd.FrameTiles += 1 - tile.Deferred = 0 - tile.H1, tile.H2 = th1[key], th2[key] - local x0, y0 = lx0 + tx * TILE, ly0 + ty * TILE - local x1, y1 = x0 + TILE, y0 + TILE - buf, buf_w = tile.Buffer, TILE - local list, lh1, lh2 = tl[key], tl1[key], tl2[key] - local oh1, oh2, ob0, ob1, ob2, ob3, on = tile.OH1, tile.OH2, tile.OB0, tile.OB1, tile.OB2, tile.OB3, tile.ON - -- New content bounds (union of the primitives' bounds in this tile) - local nx0, ny0, nx1, ny1 = TILE, TILE, 0, 0 - for k = 1, count do - local p = list[k] - local a, b = pr_bx0[p] - x0, pr_by0[p] - y0 - local c, d = pr_bx1[p] - x0, pr_by1[p] - y0 - if a < nx0 then nx0 = a end - if b < ny0 then ny0 = b end - if c > nx1 then nx1 = c end - if d > ny1 then ny1 = d end - end - nx0, ny0, nx1, ny1 = max(nx0, 0), max(ny0, 0), min(nx1, TILE), min(ny1, TILE) - local rx0, ry0, rx1, ry1 - if force or on < 0 then - -- Dirty region = old content bounds + new content bounds. Outside it the tile is already - -- transparent, so only this region is cleared and uploaded (edge tiles are often mostly empty). - rx0, ry0, rx1, ry1 = min(nx0, tile.BX0), min(ny0, tile.BY0), max(nx1, tile.BX1), max(ny1, tile.BY1) - else - -- Partial redraw: the primitives before the first and after the last changed one are the same as last - -- time. A pixel that no changed primitive (old or new) touches is covered by the same primitives in the - -- same order, so it is already correct: only the bounds of the changed ones are cleared and redrawn. - local i, lim = 1, min(on, count) - while i <= lim and oh1[i] == lh1[i] and oh2[i] == lh2[i] do i += 1 end - local j = 0 - while j <= lim - i and oh1[on - j] == lh1[count - j] and oh2[on - j] == lh2[count - j] do j += 1 end - rx0, ry0, rx1, ry1 = TILE, TILE, 0, 0 - local of, lf = tile.OF, tlf[key] - local paired = on - j - i == count - j - i - for k = i, count - j do - local p = list[k] - local a, b, c, d = max(pr_bx0[p] - x0, 0), max(pr_by0[p] - y0, 0), min(pr_bx1[p] - x0, TILE), min(pr_by1[p] - y0, TILE) - local oa, ob, oc, od = ob0[k], ob1[k], ob2[k], ob3[k] - if paired and lf[k] >= 0 and lf[k] == of[k] then - -- Same flat rect (colour/uv/texture) with new bounds: pixels inside both are unchanged, only the - -- strips between the old and new edges can differ (e.g. a window background growing on resize) - local uy0, uy1 = min(b, ob), max(d, od) - local ux0, ux1 = min(a, oa), max(c, oc) - if a ~= oa then ux0 = min(a, oa); local e = max(a, oa); rx0 = min(rx0, ux0); rx1 = max(rx1, e); ry0 = min(ry0, uy0); ry1 = max(ry1, uy1) end - if c ~= oc then local e = min(c, oc); rx0 = min(rx0, e); rx1 = max(rx1, max(c, oc)); ry0 = min(ry0, uy0); ry1 = max(ry1, uy1) end - if b ~= ob then ry0 = min(ry0, min(b, ob)); ry1 = max(ry1, max(b, ob)); rx0 = min(rx0, ux0); rx1 = max(rx1, ux1) end - if d ~= od then ry0 = min(ry0, min(d, od)); ry1 = max(ry1, max(d, od)); rx0 = min(rx0, ux0); rx1 = max(rx1, ux1) end - else - if a < rx0 then rx0 = a end - if b < ry0 then ry0 = b end - if c > rx1 then rx1 = c end - if d > ry1 then ry1 = d end - if k <= on - j then - if oa < rx0 then rx0 = oa end - if ob < ry0 then ry0 = ob end - if oc > rx1 then rx1 = oc end - if od > ry1 then ry1 = od end - end - end - end - for k = count - j + 1, on - j do -- old middle longer than the new one - if ob0[k] < rx0 then rx0 = ob0[k] end - if ob1[k] < ry0 then ry0 = ob1[k] end - if ob2[k] > rx1 then rx1 = ob2[k] end - if ob3[k] > ry1 then ry1 = ob3[k] end - end - end - tile.BX0, tile.BY0, tile.BX1, tile.BY1 = nx0, ny0, nx1, ny1 - -- Remember this list for the next partial redraw - for k = 1, count do - local p = list[k] - oh1[k], oh2[k], tile.OF[k] = lh1[k], lh2[k], tlf[key][k] - ob0[k], ob1[k], ob2[k], ob3[k] = max(pr_bx0[p] - x0, 0), max(pr_by0[p] - y0, 0), min(pr_bx1[p] - x0, TILE), min(pr_by1[p] - y0, TILE) - end - tile.ON = count - local rw = rx1 - rx0 - if rw == TILE then - buffer.fill(buf, ry0 * TILE * 4, 0, (ry1 - ry0) * TILE * 4) - else - for y = ry0, ry1 - 1 do buffer.fill(buf, (y * TILE + rx0) * 4, 0, rw * 4) end - end - local tox, toy = ox + x0, oy + y0 - for k = 1, count do - local p = list[k] - -- clip to the dirty region (only those pixels are redrawn) - local cx0, cy0 = max(pr_cx0[p] - x0, rx0), max(pr_cy0[p] - y0, ry0) - local cx1, cy1 = min(pr_cx1[p] - x0, rx1), min(pr_cy1[p] - y0, ry1) - if cx0 >= cx1 or cy0 >= cy1 or pr_bx0[p] - x0 >= rx1 or pr_by0[p] - y0 >= ry1 or pr_bx1[p] - x0 <= rx0 or pr_by1[p] - y0 <= ry0 then continue end - local va, vc, vd, vbuf = pr_a[p], pr_c[p], pr_d[p], pr_vb[p] - if vd then - local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox, readf64(vbuf, vc + 8) - toy - local gk = pr_g[p] - if gk then - DrawRectGradient(ax, ay, cx, cy, readu32(vbuf, va + 32), readu32(vbuf, vc + 32), gk, pr_t[p], readf64(vbuf, va + 16), readf64(vbuf, va + 24), cx0, cy0, cx1, cy1) - else - DrawRect(ax, ay, cx, cy, readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24), readu32(vbuf, va + 32), pr_t[p], cx0, cy0, cx1, cy1) - end - else - DrawTriangle(vbuf, va, pr_b[p], vc, pr_t[p], cx0, cy0, cx1, cy1, tox, toy) - end - end - PB("ImGui upload") - if rw == TILE and ry0 == 0 and ry1 == TILE then - tile.Image:WritePixelsBuffer(Vector2.zero, TILE_SIZE, buf) - elseif rw > 0 and ry1 > ry0 then - local rh = ry1 - ry0 - local sk = rw * 1024 + rh -- partial upload buffers are reused (WritePixelsBuffer needs the exact size) - local sub = sub_bufs[sk] - if not sub then - if n_sub_bufs >= 256 then table.clear(sub_bufs); n_sub_bufs = 0 end - sub = buffer.create(rw * rh * 4); sub_bufs[sk] = sub; n_sub_bufs += 1 - end - for y = 0, rh - 1 do buffer.copy(sub, y * rw * 4, buf, ((ry0 + y) * TILE + rx0) * 4, rw * 4) end - tile.Image:WritePixelsBuffer(Vector2.new(rx0, ry0), Vector2.new(rw, rh), sub) - end - PE() - end - if not tile.Visible and (tile.Deferred or 0) == 0 then -- (a deferred tile that was hidden holds old pixels: stays hidden until drawn) - tile.Visible = true - tile.Label.Visible = true - end - end - PE() - return deferred -end - -@native -function ImGui_ImplRoblox_RenderDrawData(draw_data) - local bd = ImGui_ImplRoblox_GetBackendData() - PB("ImGui RenderDrawData") - bd.FrameT0 = os.clock() - bd.FrameTiles = 0 - bd.RedrawStarted = false -- the first dirty tile of a frame is always redrawn (progress), the rest within the budget - bd.Stale = nil - - PB("ImGui textures") - if draw_data.Textures ~= nil then - for _, tex in draw_data.Textures:iter() do - if tex.Status ~= ImTextureStatus.OK then - -- No redraw needed for WantUpdates: it only writes texture portions which have never been used before - -- (new glyphs/rects), so no existing tile samples them. Created textures get a new (never reused) id. - ImGui_ImplRoblox_UpdateTexture(tex) - end - end - end - PE() - - -- Render rate cap: textures are always updated (imgui expects it), tiles only at bd.RenderRate Hz - -- Optional lower cap while scrolling / resizing / moving a window (SetBusyRenderRate, off by default) - local rate = bd.RenderRate - if bd.BusyRenderRate > 0 then - local g = ImGui.GetCurrentContext() - local busy = g.WheelingWindow ~= nil or g.MovingWindow ~= nil -- (io.MouseWheel is already cleared by EndFrame) - if not busy and g.ActiveId ~= 0 then - local w = g.ActiveIdWindow - local cur = g.MouseCursor -- ResizeAll..ResizeNWSE while a resize grip/border is held - busy = (cur >= ImGuiMouseCursor.ResizeAll and cur <= ImGuiMouseCursor.ResizeNWSE) - or (w ~= nil and (g.ActiveId == ImGui.GetWindowScrollbarID(w, ImGuiAxis.X) or g.ActiveId == ImGui.GetWindowScrollbarID(w, ImGuiAxis.Y))) - end - if busy and (rate <= 0 or bd.BusyRenderRate < rate) then rate = bd.BusyRenderRate end - end - if rate > 0 then - local now = os.clock() - -- Skipped: kept pending, so if no new frame comes (the app stopped rendering) Heartbeat still draws it - if now + 0.002 < bd.NextRender then bd.Pending = draw_data; PE(); return end - bd.NextRender = math.max(bd.NextRender + 1 / rate, now) - end - - local sw, sh = floor(draw_data.DisplaySize.x), floor(draw_data.DisplaySize.y) - if sw <= 0 or sh <= 0 then PE(); return end - local ox, oy = draw_data.DisplayPos.x, draw_data.DisplayPos.y - local lim_x0, lim_y0, lim_x1, lim_y1 = -CLIP_PAD, -CLIP_PAD, sw + CLIP_PAD, sh + CLIP_PAD - bd.FrameNo += 1 - local frame_no = bd.FrameNo - local force = bd.ForceRedraw - bd.ForceRedraw = false - - local n = 0 - local z = 0 - local any_deferred = false - for _, draw_list in draw_data.CmdLists:iter() do - -- Unchanged draw list (same vertices, indices, commands, origin and scroll): its layers are already correct, - -- only restack them. Moved by whole pixels (a dragged window): only move its layers. Either way no collect + hash. - PB("ImGui unchanged check") - local set = bd.Layers[draw_list] - local same, sdx, sdy = 0, 0, 0 - if not force then same, sdx, sdy = CompareDrawList(set, draw_list, ox, oy, sw, sh) end - if same ~= 0 then - for kind = 1, 3 do - local layer = set[kind] - if layer and layer.Visible then - if same == 2 then ShiftLayer(layer, sdx, sdy, bd.Scale) end - z += 1 - if layer.Z ~= z then layer.Z = z; layer.Root.ZIndex = z end - end - end - if same == 2 then - Snapshot(set, draw_list, ox, oy, sw, sh) - set.SEX0 += sdx; set.SEY0 += sdy; set.SEX1 += sdx; set.SEY1 += sdy - end - set.LastUsed = frame_no - z = PlaceOverlays(bd, draw_list, z, ox, oy) - PE() - continue - end - PE() - -- Pass 1: collect this list's primitives and their bounds - PB("ImGui collect") - local first = n + 1 - local vbuf, idx = draw_list.VtxBuffer.Buf, draw_list.IdxBuffer.Data - local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1, draw_list._ContentClipY1 - local content_x0, content_y0, content_x1, content_y1 - if ccx0 then - content_x0, content_y0 = max(floor(ccx0 - ox), lim_x0), max(floor(ccy0 - oy), lim_y0) - content_x1, content_y1 = min(floor(ccx1 - ox), lim_x1), min(floor(ccy1 - oy), lim_y1) - end - local seen_content = false - -- extents of everything clamped by the clip limits below (lim_free: nothing was), for the move fast path - local ex0, ey0, ex1, ey1 = math.huge, math.huge, -math.huge, -math.huge - local lim_free = true - if ccx0 then - local a, b, c, d = floor(ccx0 - ox), floor(ccy0 - oy), floor(ccx1 - ox), floor(ccy1 - oy) - if a < lim_x0 or b < lim_y0 or c > lim_x1 or d > lim_y1 then lim_free = false end - ex0, ey0, ex1, ey1 = min(ex0, a), min(ey0, b), max(ex1, c), max(ey1, d) - end - local ci = 0 - for _, pcmd in draw_list.CmdBuffer:iter() do - ci += 1 - cm_free[ci], cm_kind[ci] = false, 0 - if pcmd.UserCallback ~= nil then - pcmd.UserCallback(draw_list, pcmd) - elseif pcmd.ElemCount > 0 then - local clip = pcmd.ClipRect - local rcx0, rcy0, rcx1, rcy1 = floor(clip.x - ox), floor(clip.y - oy), floor(clip.z - ox), floor(clip.w - oy) - if rcx0 < lim_x0 or rcy0 < lim_y0 or rcx1 > lim_x1 or rcy1 > lim_y1 then lim_free = false end - if rcx0 < ex0 then ex0 = rcx0 end - if rcy0 < ey0 then ey0 = rcy0 end - if rcx1 > ex1 then ex1 = rcx1 end - if rcy1 > ey1 then ey1 = rcy1 end - local cx0, cy0 = max(rcx0, lim_x0), max(rcy0, lim_y0) - local cx1, cy1 = min(rcx1, lim_x1), min(rcy1, lim_y1) - local kind = 1 - if ccx0 and clip.x >= ccx0 and clip.y >= ccy0 and clip.z <= ccx1 and clip.w <= ccy1 then - kind = 2; seen_content = true - if clip.x == ccx0 and clip.y == ccy0 and clip.z == ccx1 and clip.w == ccy1 then - -- clipped by the layer's clip frame instead: partly visible rows stay hash-stable while scrolling - cx0, cy0, cx1, cy1 = lim_x0, lim_y0, lim_x1, lim_y1 - end - elseif seen_content then - kind = 3 - end - cm_kind[ci] = kind - local cfree, cex0, cey0, cex1, cey1 = cx1 > cx0 and cy1 > cy0, math.huge, math.huge, -math.huge, -math.huge - if cx1 > cx0 and cy1 > cy0 then - local tex_id = pcmd:GetTexID() - local t = bd.Textures[tex_id] - local vo = pcmd.VtxOffset - local i, last = pcmd.IdxOffset + 1, pcmd.IdxOffset + pcmd.ElemCount - while i <= last do - local ia, ic = idx[i], idx[i + 2] - -- byte offsets of the vertices (index is 1-based) - local va, vb, vc = (vo + ia - 1) * VTX_STRIDE, (vo + idx[i + 1] - 1) * VTX_STRIDE, (vo + ic - 1) * VTX_STRIDE - local vd = false - local gk = false - local pax, pay = readf64(vbuf, va), readf64(vbuf, va + 8) - local pbx, pby = readf64(vbuf, vb), readf64(vbuf, vb + 8) - local pcx, pcy = readf64(vbuf, vc), readf64(vbuf, vc + 8) - local bx0, by0, bx1, by1 - if i + 5 <= last and idx[i + 3] == ia and idx[i + 4] == ic then - local d = (vo + idx[i + 5] - 1) * VTX_STRIDE - local pdx, pdy = readf64(vbuf, d), readf64(vbuf, d + 8) - -- axis aligned quad (TL, TR, BR, BL) - if pay == pby and pbx == pcx and pcy == pdy and pdx == pax and pax < pbx and pay < pdy then - local col, colb, colc, cold = readu32(vbuf, va + 32), readu32(vbuf, vb + 32), readu32(vbuf, vc + 32), readu32(vbuf, d + 32) - local tax, tay = readf64(vbuf, va + 16), readf64(vbuf, va + 24) - local tbx, tby = readf64(vbuf, vb + 16), readf64(vbuf, vb + 24) - local tcx, tcy = readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) - local tdx, tdy = readf64(vbuf, d + 16), readf64(vbuf, d + 24) - if colb == col and colc == col and cold == col then - if tbx == tcx and tby == tay and tdx == tax and tdy == tcy then vd = d end - elseif tax == tbx and tax == tcx and tax == tdx and tay == tby and tay == tcy and tay == tdy then - -- constant uv, linear gradient: vertical (top/bottom pairs equal) or horizontal (left/right pairs equal) - if colb == col and cold == colc then vd = d; gk = 1 - elseif cold == col and colb == colc then vd = d; gk = 2 end - end - if vd then - bx0, by0 = ceil(pax - ox - 0.5), ceil(pay - oy - 0.5) - bx1, by1 = ceil(pcx - ox - 0.5), ceil(pcy - oy - 0.5) - end - end - end - if vd then - i = i + 6 - else - bx0, by0 = floor(min(pax, pbx, pcx) - ox), floor(min(pay, pby, pcy) - oy) - bx1, by1 = ceil(max(pax, pbx, pcx) - ox) + 1, ceil(max(pay, pby, pcy) - oy) + 1 - i = i + 3 - end - if bx0 < cx0 or by0 < cy0 or bx1 > cx1 or by1 > cy1 then cfree = false end - if bx0 < cex0 then cex0 = bx0 end - if by0 < cey0 then cey0 = by0 end - if bx1 > cex1 then cex1 = bx1 end - if by1 > cey1 then cey1 = by1 end - if bx0 < ex0 then ex0 = bx0 end - if by0 < ey0 then ey0 = by0 end - if bx1 > ex1 then ex1 = bx1 end - if by1 > ey1 then ey1 = by1 end - if bx0 < lim_x0 or by0 < lim_y0 or bx1 > lim_x1 or by1 > lim_y1 then lim_free = false end - if bx0 < cx0 then bx0 = cx0 end - if by0 < cy0 then by0 = cy0 end - if bx1 > cx1 then bx1 = cx1 end - if by1 > cy1 then by1 = cy1 end - if bx0 < bx1 and by0 < by1 then - n = n + 1 - pr_a[n], pr_b[n], pr_c[n], pr_d[n], pr_t[n], pr_g[n], pr_tex[n], pr_vb[n] = va, vb, vc, vd, t, gk, tex_id, vbuf - pr_cx0[n], pr_cy0[n], pr_cx1[n], pr_cy1[n] = cx0, cy0, cx1, cy1 - pr_bx0[n], pr_by0[n], pr_bx1[n], pr_by1[n] = bx0, by0, bx1, by1 - pr_k[n] = kind - end - end - end - if cex0 > cex1 then cex0, cey0, cex1, cey1 = 0, 0, 0, 0 end -- (no primitives) - cm_free[ci] = cfree - cm_x0[ci], cm_y0[ci], cm_x1[ci], cm_y1[ci] = cex0, cey0, cex1, cey1 - end - end - PE() - - -- Split into layer kinds and place each one - set = bd.Layers[draw_list] - local list_deferred = false - local nk1, nk2, nk3 = 0, 0, 0 - local o1x, o1y, o3x, o3y = math.huge, math.huge, math.huge, math.huge - for p = first, n do - local k = pr_k[p] - if k == 1 then - nk1 += 1; plist1[nk1] = p - if pr_bx0[p] < o1x then o1x = pr_bx0[p] end - if pr_by0[p] < o1y then o1y = pr_by0[p] end - elseif k == 2 then - nk2 += 1; plist2[nk2] = p - else - nk3 += 1; plist3[nk3] = p - if pr_bx0[p] < o3x then o3x = pr_bx0[p] end - if pr_by0[p] < o3y then o3y = pr_by0[p] end - end - end - if nk1 > 0 then - z += 1 - if DrawLayer(bd, GetLayer(bd, draw_list, 1), plist1, nk1, o1x, o1y, ox, oy, force, z) then list_deferred = true end - elseif set and set[1] then HideLayer(set[1]) end - if nk2 > 0 then - z += 1 - if DrawLayer(bd, GetLayer(bd, draw_list, 2), plist2, nk2, floor(draw_list._ScrollOriginX - ox), floor(draw_list._ScrollOriginY - oy), ox, oy, force, z, - content_x0, content_y0, content_x1, content_y1) then list_deferred = true end - elseif set and set[2] then HideLayer(set[2]) end - if nk3 > 0 then - z += 1 - if DrawLayer(bd, GetLayer(bd, draw_list, 3), plist3, nk3, o3x, o3y, ox, oy, force, z) then list_deferred = true end - elseif set and set[3] then HideLayer(set[3]) end - set = bd.Layers[draw_list] - -- (deferred tiles: not "unchanged" next frame even if the draw list is, so they get redrawn) - if set then - set.LastUsed = frame_no - if list_deferred then set.SnapOK = false else - Snapshot(set, draw_list, ox, oy, sw, sh) - set.SLimFree = lim_free - set.SEX0, set.SEY0, set.SEX1, set.SEY1 = ex0, ey0, ex1, ey1 - end - end - if list_deferred then any_deferred = true end - z = PlaceOverlays(bd, draw_list, z, ox, oy) - end - - -- Overlay frames not submitted this frame are hidden (never destroyed: the user owns them) - for frame, shown in pairs(bd.OverlayShown) do - if shown ~= frame_no then frame.Visible = false; bd.OverlayShown[frame] = nil end - end - table.clear(bd.Overlays) - - -- Hide layers not drawn this frame; free long unused ones (closed windows, old tooltips) - for draw_list, set in pairs(bd.Layers) do - if set.LastUsed ~= frame_no then - set.SnapOK = false -- hidden now: must go through the full path when shown again - for kind = 1, 3 do if set[kind] then HideLayer(set[kind]) end end - if frame_no - set.LastUsed > LAYER_KEEP_FRAMES then - DestroyLayerSet(set) - bd.Layers[draw_list] = nil - end - end - end - - -- drop references so old vertex tables can be collected - for k = n + 1, bd.LastPrimCount do pr_t[k], pr_vb[k] = nil, nil end - bd.LastPrimCount = n - -- Tiles left for later: if the app doesn't submit a new frame, Heartbeat finishes them from this draw data - if any_deferred then bd.Stale = draw_data; bd.StaleHB = bd.HB end - PE() -end - ---------------------------------------------------------- --- CORE LIFECYCLE ---------------------------------------------------------- - ---- @param parent Instance? # where the ScreenGui goes, defaults to the local player's PlayerGui ---- @param render_scale number? # imgui pixels per Roblox UI point (defaults to 1). Roblox UI points are scaled by the ---- # OS display scale, so on a 150% display pass 1.5 to render at physical resolution ---- # (imgui then looks the same size as a desktop imgui app). Change later with SetRenderScale(). -function ImGui_ImplRoblox_Init(parent, render_scale) - local io = ImGui.GetIO() - - local gui = Instance.new("ScreenGui") - gui.Name = "ImGui" - gui.IgnoreGuiInset = true -- so GetMouseLocation() and the tiles share the same origin - gui.ResetOnSpawn = false - gui.DisplayOrder = 1000 - gui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling -- layers (one Frame per draw list) stack by ZIndex - gui.Parent = parent or Players.LocalPlayer:WaitForChild("PlayerGui") - - local bd = { - Time = os.clock(), Gui = gui, Connections = {}, - Textures = {}, TextureCount = 0, MouseX = -1, MouseY = -1, - Layers = {}, Overlays = {}, OverlayHolders = {}, OverlayShown = {}, FrameNo = 0, Scale = render_scale or 1, TilesActive = false, RenderRate = 60, BusyRenderRate = 0, RedrawBudget = 0, HB = 0, NextRender = 0, LastPrimCount = 0, ForceRedraw = true, - } - io.BackendPlatformUserData = bd - io.BackendPlatformName = "imgui_impl_roblox" - io.BackendRendererName = "imgui_impl_roblox" - - io.BackendFlags = bit32.bor(io.BackendFlags, ImGuiBackendFlags.RendererHasTextures, ImGuiBackendFlags.RendererHasVtxOffset) - - local platform_io = ImGui.GetPlatformIO() - platform_io.Platform_SetClipboardTextFn = ImGui_ImplRoblox_PlatformSetClipboardText - platform_io.Platform_GetClipboardTextFn = ImGui_ImplRoblox_PlatformGetClipboardText - - local screen = gui.AbsoluteSize - ImGui_ImplRoblox_UpdateMonitors(screen.X, screen.Y) - - local function connect(signal, fn) table.insert(bd.Connections, signal:Connect(fn)) end - - connect(UserInputService.InputBegan, function(input, game_processed) - local io = ImGui.GetIO() - local button = MOUSE_BUTTONS[input.UserInputType] - if button then - io:AddMouseSourceEvent(ImGuiMouseSource.Mouse) - io:AddMouseButtonEvent(button, true) - elseif input.UserInputType == Enum.UserInputType.Keyboard and (not game_processed or proxy_focused) then - local ctrl, shift, alt = ImGui_ImplRoblox_UpdateKeyModifiers() - local key = KEY_MAP[input.KeyCode] - if key then io:AddKeyEvent(key, true) end - if proxy_focused and (key == ImGuiKey.Backspace or key == ImGuiKey.Delete) then ImGui_ImplRoblox_GetBackendData().DeleteKeySeen = true end - - -- Text: printable ASCII keys, skipped while Ctrl/Alt are held (shortcuts) - local v = input.KeyCode.Value - if v >= 32 and v < 127 and not (ctrl or alt) then - local c = string.char(v) - if shift then c = SHIFTED[c] or c:upper() end - -- While the proxy may own text input, hold the char: NewFrame uses the proxy's text if it changed - -- (correct layout/unicode), otherwise these. So typing works even if the proxy silently lost focus. - if proxy_focused then table.insert(ImGui_ImplRoblox_GetBackendData().PendingChars, string.byte(c)) - else io:AddInputCharacter(string.byte(c)) end - end - end - end) - - connect(UserInputService.InputEnded, function(input, game_processed) - local io = ImGui.GetIO() - local button = MOUSE_BUTTONS[input.UserInputType] - if button then - io:AddMouseButtonEvent(button, false) - elseif input.UserInputType == Enum.UserInputType.Keyboard then - ImGui_ImplRoblox_UpdateKeyModifiers() - local key = KEY_MAP[input.KeyCode] - if key then io:AddKeyEvent(key, false) end - end - end) - - connect(UserInputService.InputChanged, function(input, game_processed) - if input.UserInputType == Enum.UserInputType.MouseWheel then - ImGui.GetIO():AddMouseWheelEvent(0, input.Position.Z) - end - end) - - bd.PendingChars = {} - - -- Render rate cap trailing edge: the last frame submitted is always drawn, even if it was skipped and the app - -- then stopped calling NewFrame (e.g. it rendered one empty frame to hide its windows) - connect(game:GetService("RunService").Heartbeat, function() - local d = bd.Pending - if d and os.clock() + 0.002 >= bd.NextRender then - bd.Pending = nil - ImGui_ImplRoblox_RenderDrawData(d) - elseif bd.Stale and bd.HB > bd.StaleHB then -- deferred tiles of a frame not followed by a new one - ImGui_ImplRoblox_RenderDrawData(bd.Stale) - end - bd.HB += 1 - end) - - connect(UserInputService.WindowFocused, function() ImGui.GetIO():AddFocusEvent(true) end) - connect(UserInputService.WindowFocusReleased, function() ImGui.GetIO():AddFocusEvent(false) end) -end - --- Text proxy (opt-in, ImGui_ImplRoblox.SetTextProxy(true)): a hidden TextBox holds focus while an imgui text field is --- active, so the OS gives us typing (any layout/unicode), paste (Ctrl+V) and copy/cut (Ctrl+C/X of imgui's selection). --- Off: typing comes from KeyCodes (printable ASCII), no OS clipboard. -function ImGui_ImplRoblox_SetTextProxy(enabled) - local bd = ImGui_ImplRoblox_GetBackendData() - if not enabled then - if bd.Proxy then bd.Proxy:Destroy(); bd.Proxy = nil end - proxy_focused = false - return - end - if bd.Proxy then return end - local proxy = Instance.new("TextBox") - proxy.Name = "TextProxy" - proxy.BackgroundTransparency = 1 - proxy.TextTransparency = 0 -- kept opaque but parked off screen: a transparent TextBox may not get native paste - proxy.BorderSizePixel = 0 - proxy.Size = UDim2.fromOffset(200, 20) - proxy.Position = UDim2.fromOffset(-10000, -10000) - proxy.MultiLine = true - proxy.ClearTextOnFocus = false - proxy.TextEditable = true - proxy.Text = "" - proxy.Parent = bd.Gui - bd.Proxy, bd.ProxyText = proxy, "" - -- Clicking elsewhere (or Roblox taking focus) ends the edit, like clicking outside the field in imgui. - -- (Text is polled in NewFrame instead of using Text changed signals: those are deferred in Roblox.) - proxy.FocusLost:Connect(function() - if bd.ProxyReleasing then return end - -- Roblox drops TextBox focus on any click, including clicks inside imgui (e.g. moving the cursor within the - -- same field). Those must not end the edit: just recapture next frame. Only a click outside imgui ends it. - if ImGui.GetIO().WantCaptureMouse then bd.ProxyLostId = nil; return end - bd.ProxyLostId = bd.ProxyActiveId -- don't recapture for the same field - local g = ImGui.GetCurrentContext() - if g and g.ActiveId ~= 0 and g.ActiveId == bd.ProxyActiveId then ImGui.ClearActiveID() end - end) -end - -function ImGui_ImplRoblox_Shutdown() - local io = ImGui.GetIO() - local bd = ImGui_ImplRoblox_GetBackendData() - for _, c in ipairs(bd.Connections) do c:Disconnect() end - DestroyTiles(bd) - bd.Gui:Destroy() - - io.BackendPlatformUserData = nil - io.BackendPlatformName = nil - io.BackendRendererName = nil - io.BackendFlags = bit32.band(io.BackendFlags, bit32.bnot(bit32.bor( - ImGuiBackendFlags.RendererHasTextures, - ImGuiBackendFlags.RendererHasVtxOffset - ))) -end - -function ImGui_ImplRoblox_NewFrame() - PB("ImGui NewFrame (backend)") - local io = ImGui.GetIO() - local bd = ImGui_ImplRoblox_GetBackendData() - if bd.Pending then bd.Pending = nil; table.clear(bd.Overlays) end -- skipped frame superseded (its draw lists get reset) - bd.Stale = nil - - local screen = bd.Gui.AbsoluteSize - local w, h = floor(screen.X * bd.Scale), floor(screen.Y * bd.Scale) - if w ~= bd.ScreenW or h ~= bd.ScreenH then - bd.ScreenW, bd.ScreenH = w, h - ImGui_ImplRoblox_UpdateMonitors(w, h) - end - ImVec2_CopyV(io.DisplaySize, w, h) - - local current_time = os.clock() - io.DeltaTime = (current_time > bd.Time) and (current_time - bd.Time) or (1.0 / 60.0) - bd.Time = current_time - - local m = UserInputService:GetMouseLocation() - if m.X ~= bd.MouseX or m.Y ~= bd.MouseY then - bd.MouseX, bd.MouseY = m.X, m.Y - io:AddMouseSourceEvent(ImGuiMouseSource.Mouse) - io:AddMousePosEvent(m.X * bd.Scale, m.Y * bd.Scale) - end - - -- Text proxy: focused while an imgui text field is active. proxy_focused only when Roblox really gave it focus, - -- otherwise the KeyCode fallback keeps typing working. - local proxy = bd.Proxy - local g = ImGui.GetCurrentContext() - local focused_box = proxy and UserInputService:GetFocusedTextBox() - if not proxy then - -- text proxy disabled: KeyCode typing only - elseif io.WantTextInput and g.ActiveId ~= 0 then - if g.ActiveId ~= bd.ProxyActiveId or g.ActiveIdIsJustActivated or g.IO.MouseClicked[0] then bd.ProxyActiveId = g.ActiveId; bd.ProxyLostId = nil end -- (re)clicking a field recaptures - local mouse_up = not (io.MouseDown[0] or io.MouseDown[1] or io.MouseDown[2]) - if focused_box ~= proxy and mouse_up and bd.ProxyLostId ~= g.ActiveId and (focused_box == nil or not focused_box:IsDescendantOf(game)) then - bd.ProxyText = proxy.Text -- what it already holds is not new input (else re-typing it would collapse imgui's selection) - proxy:CaptureFocus() - focused_box = UserInputService:GetFocusedTextBox() - end - elseif focused_box == proxy then - bd.ProxyReleasing = true - proxy:ReleaseFocus() - bd.ProxyReleasing = false - focused_box = nil - end - proxy_focused = proxy ~= nil and focused_box == proxy - local used_proxy_text = false - if proxy_focused then - -- 1) whatever the OS put in the proxy since last frame (typing, paste, cut) replaces imgui's selection - local text = proxy.Text - if text ~= bd.ProxyText and text ~= bd.ProxyLastRaw then -- (LastRaw: don't re-send if our reset hasn't applied yet) - bd.ProxyLastRaw = text - -- InputText ignores characters while Ctrl is held (upstream, so shortcuts don't type); a paste arrives with - -- Ctrl still down, so release Ctrl around the characters in the event queue. - local ctrl = io.KeyCtrl or UserInputService:IsKeyDown(Enum.KeyCode.LeftControl) or UserInputService:IsKeyDown(Enum.KeyCode.RightControl) - if ctrl then io:AddKeyEvent(ImGuiMod_Ctrl, false) end - local prev = bd.ProxyText or "" - if #text < #prev and prev:sub(1, #text) == text and text:sub(-1) ~= "\n" then - -- The TextBox deleted from its own text (Backspace/Delete; Roblox can't hold a real selection in it, so it - -- may remove just 1 char). Apply the deletion with imgui's own selection instead: one Backspace deletes - -- the whole imgui selection, or one char if none. Skipped if imgui already got the key event. - if not bd.DeleteKeySeen then io:AddKeyEvent(ImGuiKey.Backspace, true); io:AddKeyEvent(ImGuiKey.Backspace, false) end - elseif text ~= "\n" and text ~= "\r" and text ~= "\t" then -- Enter/Tab arrive as key events - local prev = bd.ProxyText or "" - if #text > 0 and (prev == "" or text:sub(1, #prev) ~= prev or #text <= #prev) then - for _, cp in utf8.codes(text) do io:AddInputCharacter(cp) end - elseif #text > #prev then - for _, cp in utf8.codes(text:sub(#prev + 1)) do io:AddInputCharacter(cp) end - end - end - if ctrl then io:AddKeyEvent(ImGuiMod_Ctrl, true) end - used_proxy_text = true - bd.ProxyText = nil - end - -- 2) mirror imgui's selection, fully selected, so the native Ctrl+C / Ctrl+X copy exactly that - local st = g.InputTextState - local sel = "" - if st and st.ID ~= 0 and st.ID == g.ActiveId and st.Stb and st:HasSelection() then - local a, b = math.min(st.Stb.select_start, st.Stb.select_end), math.max(st.Stb.select_start, st.Stb.select_end) - sel = ImGui._ByteArrayToString(st.TextA.Data, a, b) -- stb positions are 1-based in this port - end - if sel ~= bd.ProxyText then - proxy.Text = sel - bd.ProxyLastRaw = nil - bd.ProxyText = sel - end - -- keep imgui's selection fully selected in the proxy, so Ctrl+C copies it and typing/Ctrl+V replaces it - local want_sel, want_cur = (#sel > 0) and 1 or -1, #sel + 1 - if proxy.SelectionStart ~= want_sel then proxy.SelectionStart = want_sel end - if proxy.CursorPosition ~= want_cur then proxy.CursorPosition = want_cur end - end - - bd.DeleteKeySeen = false - - -- Held KeyCode chars: dropped if the proxy delivered the text, otherwise typed (proxy didn't really get the keys) - local pending = bd.PendingChars - if #pending > 0 then - if not used_proxy_text then for _, c in ipairs(pending) do io:AddInputCharacter(c) end end - table.clear(pending) - end - - -- While the mouse is over imgui, make the tiles Active so Roblox stops passing clicks/wheel to the game (camera zoom etc.) - local want = io.WantCaptureMouse - if want ~= bd.TilesActive then - bd.TilesActive = want - for _, set in pairs(bd.Layers) do for kind = 1, 3 do local layer = set[kind]; if layer then for _, tile in pairs(layer.Tiles) do tile.Label.Active = want end end end end - end - PE() -end - ---- Opt-in: max milliseconds per frame spent redrawing changed tiles (default 0 = no limit, every change is drawn the ---- same frame). With a budget (e.g. 1.5), tiles over it keep ---- their previous pixels and are redrawn on the following frames (each one at most a few frames late), so a big change ---- (resizing a large window, opening one, scrolling a long list) is spread over frames instead of one long frame. -function ImGui_ImplRoblox_SetRedrawBudget(ms) - ImGui_ImplRoblox_GetBackendData().RedrawBudget = (ms or 0) / 1000 -end - ---- Max tile redraws per second (default 60; 0 = every frame, limited by the redraw budget instead). imgui logic still runs every frame. -function ImGui_ImplRoblox_SetRenderRate(hz) - ImGui_ImplRoblox_GetBackendData().RenderRate = hz or 0 -end - ---- Optional: max tile redraws per second while scrolling, resizing or moving a window (0 = off, the default) -function ImGui_ImplRoblox_SetBusyRenderRate(hz) - ImGui_ImplRoblox_GetBackendData().BusyRenderRate = hz or 0 -end - ---- Toggle MicroProfiler labels (debug.profilebegin) for the backend -function ImGui_ImplRoblox_SetProfiling(enabled) profiling = enabled and true or false end -local function ImGui_ImplRoblox_IsProfiling() return profiling end - -function ImGui_ImplRoblox_SetRenderScale(scale) - local bd = ImGui_ImplRoblox_GetBackendData() - if scale == bd.Scale then return end - bd.Scale = scale - DestroyTiles(bd) - bd.ForceRedraw = true -end - -ImGui_ImplRoblox = { - Init = ImGui_ImplRoblox_Init, - Shutdown = ImGui_ImplRoblox_Shutdown, - NewFrame = ImGui_ImplRoblox_NewFrame, - RenderDrawData = ImGui_ImplRoblox_RenderDrawData, - AddFile = ImGui_ImplRoblox_AddFile, - SetRenderScale = ImGui_ImplRoblox_SetRenderScale, - SetRenderRate = ImGui_ImplRoblox_SetRenderRate, - SetRedrawBudget = ImGui_ImplRoblox_SetRedrawBudget, - SetOverlay = ImGui_ImplRoblox_SetOverlay, - SetTextProxy = ImGui_ImplRoblox_SetTextProxy, - CreateTexture = ImGui_ImplRoblox_CreateTexture, - DestroyTexture = ImGui_ImplRoblox_DestroyTexture, - GetRenderScale = function() return ImGui_ImplRoblox_GetBackendData().Scale end, - SetBusyRenderRate = ImGui_ImplRoblox_SetBusyRenderRate, - SetProfiling = ImGui_ImplRoblox_SetProfiling, - IsProfiling = ImGui_ImplRoblox_IsProfiling, -} - -return true -- [Roblox] ModuleScripts must return exactly one value diff --git a/backends/imgui_impl_love.lua b/backends/love/imgui_impl_love.lua similarity index 100% rename from backends/imgui_impl_love.lua rename to backends/love/imgui_impl_love.lua diff --git a/backends/roblox/imgui_impl_roblox.lua b/backends/roblox/imgui_impl_roblox.lua new file mode 100644 index 0000000..c856461 --- /dev/null +++ b/backends/roblox/imgui_impl_roblox.lua @@ -0,0 +1,484 @@ +-- ImGui backend for Roblox: platform, input, files, Init/Shutdown and the public API; rendering in render.lua. +-- Requires "Allow Mesh / Image APIs" (EditableImage) in game settings. +local Textures = IM_INCLUDE("roblox/textures.lua") +local Layers = IM_INCLUDE("roblox/layers.lua") +local Render = IM_INCLUDE("roblox/render.lua") +local Parallel = IM_INCLUDE("roblox/parallel.lua") + +local UserInputService = game:GetService("UserInputService") +local Players = game:GetService("Players") + +local floor, min = math.floor, math.min +local EditableImages, PB, PE = Textures.EditableImages, Textures.PB, Textures.PE +local ImGui_ImplRoblox_GetBackendData = Textures.GetBackendData +local ImGui_ImplRoblox_RenderDrawData = Render.RenderDrawData +local DestroyTiles = Layers.DestroyTiles + +local KEY_MAP = {} +do + local names = { + Return = "Enter", Escape = "Escape", Backspace = "Backspace", Tab = "Tab", Space = "Space", + KeypadEnter = "KeypadEnter", + Up = "UpArrow", Down = "DownArrow", Left = "LeftArrow", Right = "RightArrow", + Home = "Home", End = "End", PageUp = "PageUp", PageDown = "PageDown", Insert = "Insert", Delete = "Delete", + LeftControl = "LeftCtrl", RightControl = "RightCtrl", LeftShift = "LeftShift", RightShift = "RightShift", + LeftAlt = "LeftAlt", RightAlt = "RightAlt", LeftSuper = "LeftSuper", RightSuper = "RightSuper", + Quote = "Apostrophe", Comma = "Comma", Minus = "Minus", Period = "Period", Slash = "Slash", + Semicolon = "Semicolon", + Equals = "Equal", LeftBracket = "LeftBracket", BackSlash = "Backslash", RightBracket = "RightBracket", + Backquote = "GraveAccent", + CapsLock = "CapsLock", + KeypadPeriod = "KeypadDecimal", KeypadDivide = "KeypadDivide", KeypadMultiply = "KeypadMultiply", + KeypadMinus = "KeypadSubtract", KeypadPlus = "KeypadAdd", KeypadEquals = "KeypadEqual", + } + local digits = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" } + for i = 0, 9 do + names[digits[i + 1]] = "K" .. i + names["Keypad" .. digits[i + 1]] = "Keypad" .. i + end + for i = 1, 12 do names["F" .. i] = "F" .. i end + for c in ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"):gmatch(".") do names[c] = c end + + for rbx_name, imgui_name in pairs(names) do + KEY_MAP[Enum.KeyCode[rbx_name]] = ImGuiKey[imgui_name] + end +end + +-- No text input event: characters come from KeyCode.Value (printable ASCII) + a US layout shift table +local SHIFTED = { + ["1"] = "!", ["2"] = "@", ["3"] = "#", ["4"] = "$", ["5"] = "%", ["6"] = "^", ["7"] = "&", ["8"] = "*", ["9"] = "(", + ["0"] = ")", + ["-"] = "_", ["="] = "+", ["["] = "{", ["]"] = "}", ["\\"] = "|", [";"] = ":", ["'"] = "\"", [","] = "<", + ["."] = ">", ["/"] = "?", ["`"] = "~", +} + +local MOUSE_BUTTONS = { + [Enum.UserInputType.MouseButton1] = 0, + [Enum.UserInputType.MouseButton2] = 1, + [Enum.UserInputType.MouseButton3] = 2, +} + +local function ImGui_ImplRoblox_UpdateKeyModifiers() + local io = ImGui.GetIO() + local K = Enum.KeyCode + local ctrl = UserInputService:IsKeyDown(K.LeftControl) or UserInputService:IsKeyDown(K.RightControl) + local shift = UserInputService:IsKeyDown(K.LeftShift) or UserInputService:IsKeyDown(K.RightShift) + local alt = UserInputService:IsKeyDown(K.LeftAlt) or UserInputService:IsKeyDown(K.RightAlt) + io:AddKeyEvent(ImGuiMod_Ctrl, ctrl) + io:AddKeyEvent(ImGuiMod_Shift, shift) + io:AddKeyEvent(ImGuiMod_Alt, alt) + io:AddKeyEvent(ImGuiMod_Super, UserInputService:IsKeyDown(K.LeftSuper) or UserInputService:IsKeyDown(K.RightSuper)) + return ctrl, shift, alt +end + +local function ImGui_ImplRoblox_UpdateMonitors(w, h) + local platform_io = ImGui.GetPlatformIO() + platform_io.Monitors:resize(0) + + local imgui_monitor = ImGuiPlatformMonitor() + ImVec2_Copy(imgui_monitor.MainSize, ImVec2(w, h)) + ImVec2_Copy(imgui_monitor.WorkSize, ImVec2(w, h)) + + platform_io.Monitors:push_back(imgui_monitor) +end + +-- Games can't touch the OS clipboard, so copy/paste only works inside ImGui +local Clipboard = "" +local function ImGui_ImplRoblox_PlatformSetClipboardText(ctx, text) Clipboard = text end +local ProxyFocused = false +local function ImGui_ImplRoblox_PlatformGetClipboardText(ctx) if ProxyFocused then return "" end return Clipboard end + +local VFS = {} + +local function ImGui_ImplRoblox_AddFile(path, bytes) VFS[path] = bytes end + +for path, hex in pairs(IM_INCLUDE("imgui_impl_roblox_fonts.lua")) do + VFS[path] = hex:gsub("%s", ""):gsub("%x%x", function(h) return string.char(tonumber(h, 16)) end) +end + +function ImStd.ImFileOpen(filename, mode) + local data = VFS[filename] + return data and { Data = data, Pos = 0 } or nil +end + +function ImStd.ImFileClose(f) end + +function ImStd.ImFileGetSize(f) return #f.Data end + +function ImStd.ImFileRead(f, data, count) + local s, pos = f.Data, f.Pos + count = min(count, #s - pos) + for i = 1, count do data[i] = string.byte(s, pos + i) end + f.Pos = pos + count + return count +end + +function ImStd.ImFileLoadToMemory(filename, mode) + local f = ImStd.ImFileOpen(filename, mode) + if not f or #f.Data == 0 then return end + local file_data = {} + local size = ImStd.ImFileRead(f, file_data, #f.Data) + return file_data, size +end + +-- render_scale: imgui pixels per Roblox UI point (default 1; 1.5 on a 150% display = physical resolution) +function ImGui_ImplRoblox_Init(parent, render_scale) + local io = ImGui.GetIO() + + local gui = Instance.new("ScreenGui") + gui.Name = "ImGui" + gui.IgnoreGuiInset = true -- so GetMouseLocation() and the tiles share the same origin + gui.ResetOnSpawn = false + gui.DisplayOrder = 1000 + gui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling -- layers (one Frame per draw list) stack by ZIndex + gui.Parent = parent or Players.LocalPlayer:WaitForChild("PlayerGui") + + local BackendData = { + Time = os.clock(), Gui = gui, Connections = {}, + Textures = Textures.Records, MouseX = -1, MouseY = -1, + Layers = {}, Overlays = {}, OverlayHolders = {}, OverlayShown = {}, FrameNo = 0, Scale = render_scale or 1, + TilesActive = false, RenderRate = 60, BusyRenderRate = 0, RedrawBudget = 0, HeartbeatCount = 0, + NextRender = 0, LastPrimCount = 0, ForceRedraw = true, + } + io.BackendPlatformUserData = BackendData + EditableImages.Backends[BackendData] = true + io.BackendPlatformName = "imgui_impl_roblox" + io.BackendRendererName = "imgui_impl_roblox" + + io.BackendFlags = bit32.bor(io.BackendFlags, ImGuiBackendFlags.RendererHasTextures, + ImGuiBackendFlags.RendererHasVtxOffset) + + local platform_io = ImGui.GetPlatformIO() + platform_io.Platform_SetClipboardTextFn = ImGui_ImplRoblox_PlatformSetClipboardText + platform_io.Platform_GetClipboardTextFn = ImGui_ImplRoblox_PlatformGetClipboardText + + local screen = gui.AbsoluteSize + ImGui_ImplRoblox_UpdateMonitors(screen.X, screen.Y) + + local function connect(signal, fn) table.insert(BackendData.Connections, signal:Connect(fn)) end + + connect(UserInputService.InputBegan, function(input, game_processed) + local io = ImGui.GetIO() + local button = MOUSE_BUTTONS[input.UserInputType] + if button then + io:AddMouseSourceEvent(ImGuiMouseSource.Mouse) + io:AddMouseButtonEvent(button, true) + elseif input.UserInputType == Enum.UserInputType.Keyboard and (not game_processed or ProxyFocused) then + local ctrl, shift, alt = ImGui_ImplRoblox_UpdateKeyModifiers() + local key = KEY_MAP[input.KeyCode] + if key then io:AddKeyEvent(key, true) end + if ProxyFocused and (key == ImGuiKey.Backspace or key == ImGuiKey.Delete) then + ImGui_ImplRoblox_GetBackendData().DeleteKeySeen = true + end + + local v = input.KeyCode.Value + if v >= 32 and v < 127 and not (ctrl or alt) then + local c = string.char(v) + if shift then c = SHIFTED[c] or c:upper() end + -- while the proxy may own input, hold the char: NewFrame types it only if the proxy didn't deliver text + if ProxyFocused then table.insert(ImGui_ImplRoblox_GetBackendData().PendingChars, string.byte(c)) + else io:AddInputCharacter(string.byte(c)) end + end + end + end) + + connect(UserInputService.InputEnded, function(input, game_processed) + local io = ImGui.GetIO() + local button = MOUSE_BUTTONS[input.UserInputType] + if button then + io:AddMouseButtonEvent(button, false) + elseif input.UserInputType == Enum.UserInputType.Keyboard then + ImGui_ImplRoblox_UpdateKeyModifiers() + local key = KEY_MAP[input.KeyCode] + if key then io:AddKeyEvent(key, false) end + end + end) + + connect(UserInputService.InputChanged, function(input, game_processed) + if input.UserInputType == Enum.UserInputType.MouseWheel then + ImGui.GetIO():AddMouseWheelEvent(0, input.Position.Z) + end + end) + + BackendData.PendingChars = {} + + -- Render rate cap trailing edge: the last frame submitted is always drawn, even if the app then stopped rendering + connect(game:GetService("RunService").Heartbeat, function() + local d = BackendData.Pending + if d and os.clock() + 0.002 >= BackendData.NextRender then + BackendData.Pending = nil + ImGui_ImplRoblox_RenderDrawData(d) + elseif BackendData.Stale and BackendData.HeartbeatCount > BackendData.StaleHeartbeat then + ImGui_ImplRoblox_RenderDrawData(BackendData.Stale) + end + BackendData.HeartbeatCount += 1 + end) + + connect(UserInputService.WindowFocused, function() ImGui.GetIO():AddFocusEvent(true) end) + connect(UserInputService.WindowFocusReleased, function() ImGui.GetIO():AddFocusEvent(false) end) +end + +-- Text proxy (opt-in): a hidden TextBox holds focus while a text field is active (OS typing, paste, copy/cut) +function ImGui_ImplRoblox_SetTextProxy(enabled) + local BackendData = ImGui_ImplRoblox_GetBackendData() + if not enabled then + if BackendData.Proxy then + BackendData.Proxy:Destroy() + BackendData.Proxy = nil + end + ProxyFocused = false + return + end + if BackendData.Proxy then return end + local proxy = Instance.new("TextBox") + proxy.Name = "TextProxy" + proxy.BackgroundTransparency = 1 + proxy.TextTransparency = 0 -- kept opaque but parked off screen: a transparent TextBox may not get native paste + proxy.BorderSizePixel = 0 + proxy.Size = UDim2.fromOffset(200, 20) + proxy.Position = UDim2.fromOffset(-10000, -10000) + proxy.MultiLine = true + proxy.ClearTextOnFocus = false + proxy.TextEditable = true + proxy.Text = "" + proxy.Parent = BackendData.Gui + BackendData.Proxy, BackendData.ProxyText = proxy, "" + -- Text is polled in NewFrame: TextBox change signals are deferred in Roblox + proxy.FocusLost:Connect(function() + if BackendData.ProxyReleasing then return end + -- Roblox drops TextBox focus on any click, also inside imgui: only a click outside imgui ends the edit + if ImGui.GetIO().WantCaptureMouse then + BackendData.ProxyLostId = nil + return + end + BackendData.ProxyLostId = BackendData.ProxyActiveId + local g = ImGui.GetCurrentContext() + if g and g.ActiveId ~= 0 and g.ActiveId == BackendData.ProxyActiveId then ImGui.ClearActiveID() end + end) +end + +local function ImGui_ImplRoblox_Shutdown() + local io = ImGui.GetIO() + local BackendData = ImGui_ImplRoblox_GetBackendData() + for _, c in ipairs(BackendData.Connections) do c:Disconnect() end + DestroyTiles(BackendData) + EditableImages.Backends[BackendData] = nil + BackendData.Gui:Destroy() + + io.BackendPlatformUserData = nil + io.BackendPlatformName = nil + io.BackendRendererName = nil + io.BackendFlags = bit32.band(io.BackendFlags, bit32.bnot(bit32.bor( + ImGuiBackendFlags.RendererHasTextures, + ImGuiBackendFlags.RendererHasVtxOffset + ))) +end + + +function ImGui_ImplRoblox_NewFrame() + PB("ImGui NewFrame (backend)") + local io = ImGui.GetIO() + local BackendData = ImGui_ImplRoblox_GetBackendData() + if BackendData.Pending then -- skipped frame superseded (its draw lists get reset) + BackendData.Pending = nil + table.clear(BackendData.Overlays) + end + BackendData.Stale = nil + + local screen = BackendData.Gui.AbsoluteSize + local w, h = floor(screen.X * BackendData.Scale), floor(screen.Y * BackendData.Scale) + if w ~= BackendData.ScreenW or h ~= BackendData.ScreenH then + BackendData.ScreenW, BackendData.ScreenH = w, h + ImGui_ImplRoblox_UpdateMonitors(w, h) + end + ImVec2_CopyV(io.DisplaySize, w, h) + + local current_time = os.clock() + io.DeltaTime = (current_time > BackendData.Time) and (current_time - BackendData.Time) or (1.0 / 60.0) + BackendData.Time = current_time + + local m = UserInputService:GetMouseLocation() + if m.X ~= BackendData.MouseX or m.Y ~= BackendData.MouseY then + BackendData.MouseX, BackendData.MouseY = m.X, m.Y + io:AddMouseSourceEvent(ImGuiMouseSource.Mouse) + io:AddMousePosEvent(m.X * BackendData.Scale, m.Y * BackendData.Scale) + end + + local proxy = BackendData.Proxy + local g = ImGui.GetCurrentContext() + local focused_box = proxy and UserInputService:GetFocusedTextBox() + if not proxy then + elseif io.WantTextInput and g.ActiveId ~= 0 then + if g.ActiveId ~= BackendData.ProxyActiveId or g.ActiveIdIsJustActivated or g.IO.MouseClicked[0] then + BackendData.ProxyActiveId = g.ActiveId + BackendData.ProxyLostId = nil + end + local mouse_up = not (io.MouseDown[0] or io.MouseDown[1] or io.MouseDown[2]) + if focused_box ~= proxy and mouse_up and BackendData.ProxyLostId ~= g.ActiveId + and (focused_box == nil or not focused_box:IsDescendantOf(game)) then + -- what it already holds is not new input (else re-typing it would collapse imgui's selection) + BackendData.ProxyText = proxy.Text + proxy:CaptureFocus() + focused_box = UserInputService:GetFocusedTextBox() + end + elseif focused_box == proxy then + BackendData.ProxyReleasing = true + proxy:ReleaseFocus() + BackendData.ProxyReleasing = false + focused_box = nil + end + ProxyFocused = proxy ~= nil and focused_box == proxy + local used_proxy_text = false + if ProxyFocused then + local text = proxy.Text + if text ~= BackendData.ProxyText and text ~= BackendData.ProxyLastRaw then + BackendData.ProxyLastRaw = text + -- InputText ignores chars while Ctrl is held; a paste arrives with Ctrl down, so release it around them + local ctrl = io.KeyCtrl or UserInputService:IsKeyDown(Enum.KeyCode.LeftControl) + or UserInputService:IsKeyDown(Enum.KeyCode.RightControl) + if ctrl then io:AddKeyEvent(ImGuiMod_Ctrl, false) end + local prev = BackendData.ProxyText or "" + if #text < #prev and prev:sub(1, #text) == text and text:sub(-1) ~= "\n" then + -- the TextBox deleted from its own text (no real selection): one Backspace on imgui's selection + if not BackendData.DeleteKeySeen then + io:AddKeyEvent(ImGuiKey.Backspace, true) + io:AddKeyEvent(ImGuiKey.Backspace, false) + end + elseif text ~= "\n" and text ~= "\r" and text ~= "\t" then -- Enter/Tab arrive as key events + local prev = BackendData.ProxyText or "" + if #text > 0 and (prev == "" or text:sub(1, #prev) ~= prev or #text <= #prev) then + for _, cp in utf8.codes(text) do io:AddInputCharacter(cp) end + elseif #text > #prev then + for _, cp in utf8.codes(text:sub(#prev + 1)) do io:AddInputCharacter(cp) end + end + end + if ctrl then io:AddKeyEvent(ImGuiMod_Ctrl, true) end + used_proxy_text = true + BackendData.ProxyText = nil + end + local st = g.InputTextState + local sel = "" + if st and st.ID ~= 0 and st.ID == g.ActiveId and st.Stb and st:HasSelection() then + local a, b = math.min(st.Stb.select_start, st.Stb.select_end), + math.max(st.Stb.select_start, st.Stb.select_end) + sel = ImGui._ByteArrayToString(st.TextA.Data, a, b) -- stb positions are 1-based in this port + end + if sel ~= BackendData.ProxyText then + proxy.Text = sel + BackendData.ProxyLastRaw = nil + BackendData.ProxyText = sel + end + -- mirror imgui's selection, fully selected, so native Ctrl+C copies it and typing/Ctrl+V replaces it + local want_sel, want_cur = (#sel > 0) and 1 or -1, #sel + 1 + if proxy.SelectionStart ~= want_sel then proxy.SelectionStart = want_sel end + if proxy.CursorPosition ~= want_cur then proxy.CursorPosition = want_cur end + end + + BackendData.DeleteKeySeen = false + + local pending = BackendData.PendingChars + if #pending > 0 then + if not used_proxy_text then for _, c in ipairs(pending) do io:AddInputCharacter(c) end end + table.clear(pending) + end + + -- Tiles Active while over imgui, so Roblox stops passing clicks/wheel to the game (camera zoom etc.) + local want = io.WantCaptureMouse + if want ~= BackendData.TilesActive then + BackendData.TilesActive = want + for _, set in pairs(BackendData.Layers) do + for kind = 1, 3 do + local layer = set[kind] + if layer then for _, tile in pairs(layer.Tiles) do tile.Label.Active = want end end + end + end + end + PE() +end + +-- Public API (documented in README.md) +function ImGui_ImplRoblox_SetRedrawBudget(ms) + ImGui_ImplRoblox_GetBackendData().RedrawBudget = (ms or 0) / 1000 +end + +function ImGui_ImplRoblox_SetRenderRate(hz) + ImGui_ImplRoblox_GetBackendData().RenderRate = hz or 0 +end + +function ImGui_ImplRoblox_SetBusyRenderRate(hz) + ImGui_ImplRoblox_GetBackendData().BusyRenderRate = hz or 0 +end + +function ImGui_ImplRoblox_SetProfiling(enabled) Textures.SetProfiling(enabled) end +local ImGui_ImplRoblox_IsProfiling = Textures.IsProfiling + +function ImGui_ImplRoblox_SetStageTiming(enabled) + EditableImages.StageTiming = enabled and true or false + if not EditableImages.StageTiming then EditableImages.StageFrame = nil end +end + +function ImGui_ImplRoblox_SetRenderScale(scale) + local BackendData = ImGui_ImplRoblox_GetBackendData() + if scale == BackendData.Scale then return end + BackendData.Scale = scale + DestroyTiles(BackendData) + BackendData.ForceRedraw = true +end + +function ImGui_ImplRoblox_GetStats() + local BackendData = ImGui_ImplRoblox_GetBackendData() + local tiles = 0 + for _, set in pairs(BackendData.Layers) do + for kind = 1, 3 do if set[kind] then for _ in pairs(set[kind].Tiles) do tiles += 1 end end end + end + return { Tiles = tiles, EditableImages = EditableImages.Count, EditableImageBytes = EditableImages.Bytes, + EditableImageCap = EditableImages.Cap, Instances = #BackendData.Gui:GetDescendants(), + Frame = BackendData.FrameStats, Renders = BackendData.FrameNo } +end + +function ImGui_ImplRoblox_SetEditableImageCap(bytes) + EditableImages.Cap = bytes or 64 * 1024 * 1024 + EditableImages.Evict(EditableImages.Bytes - EditableImages.Cap) +end + +function ImGui_ImplRoblox_EnableParallel(opts) Parallel.Enable(opts) end + +function ImGui_ImplRoblox_DisableParallel() Parallel.Disable() end + +function ImGui_ImplRoblox_FinishParallel() Parallel.Finish() end + +function ImGui_ImplRoblox_BeginParallelFrame() Parallel.BeginFrame() end + +function ImGui_ImplRoblox_GetParallelStats() return Parallel.Stats end + +function ImGui_ImplRoblox_GetParallelConfig() return Parallel.Config end + +ImGui_ImplRoblox = { + Init = ImGui_ImplRoblox_Init, + Shutdown = ImGui_ImplRoblox_Shutdown, + NewFrame = ImGui_ImplRoblox_NewFrame, + RenderDrawData = ImGui_ImplRoblox_RenderDrawData, + AddFile = ImGui_ImplRoblox_AddFile, + CreateTexture = ImGui_ImplRoblox_CreateTexture, + DestroyTexture = ImGui_ImplRoblox_DestroyTexture, + SetOverlay = ImGui_ImplRoblox_SetOverlay, + SetTextProxy = ImGui_ImplRoblox_SetTextProxy, + SetRenderScale = ImGui_ImplRoblox_SetRenderScale, + GetRenderScale = function() return ImGui_ImplRoblox_GetBackendData().Scale end, + SetRenderRate = ImGui_ImplRoblox_SetRenderRate, + SetBusyRenderRate = ImGui_ImplRoblox_SetBusyRenderRate, + SetRedrawBudget = ImGui_ImplRoblox_SetRedrawBudget, + SetProfiling = ImGui_ImplRoblox_SetProfiling, + IsProfiling = ImGui_ImplRoblox_IsProfiling, + SetStageTiming = ImGui_ImplRoblox_SetStageTiming, + GetStats = ImGui_ImplRoblox_GetStats, + SetEditableImageCap = ImGui_ImplRoblox_SetEditableImageCap, + EnableParallel = ImGui_ImplRoblox_EnableParallel, + DisableParallel = ImGui_ImplRoblox_DisableParallel, + FinishParallel = ImGui_ImplRoblox_FinishParallel, + BeginParallelFrame = ImGui_ImplRoblox_BeginParallelFrame, + GetParallelStats = ImGui_ImplRoblox_GetParallelStats, + GetParallelConfig = ImGui_ImplRoblox_GetParallelConfig, +} + +return true -- [Roblox] ModuleScripts must return exactly one value \ No newline at end of file diff --git a/backends/roblox/layers.lua b/backends/roblox/layers.lua new file mode 100644 index 0000000..a650fc3 --- /dev/null +++ b/backends/roblox/layers.lua @@ -0,0 +1,335 @@ +-- Layers and tiles (one Frame per draw list and kind, TILE x TILE EditableImages); draw list snapshot/compare +local Raster = IM_INCLUDE("roblox/raster.lua") +local Textures = IM_INCLUDE("roblox/textures.lua") + +local floor, max = math.floor, math.max +local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64 +local TILE = Raster.TILE +local EditableImages = Textures.EditableImages + +local M = {} +-- content up to this far off screen is kept, so dragging a window past the edge doesn't redraw it +local CLIP_PAD = 2048 +M.CLIP_PAD = CLIP_PAD +-- per draw command, filled by CollectPrims for Snapshot: no primitive clipped, layer kind, bounds of its primitives +local CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1 = {}, {}, {}, {}, {}, {} +M.CmdUnclipped, M.CmdKind, M.CmdBoundsX0, M.CmdBoundsY0, M.CmdBoundsX1, M.CmdBoundsY1 = + CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1 +-- free per-tile primitive lists, 4 at a time +EditableImages.ListPool = {} + +-- Kinds: 1 = before the window content (background, title bar, scrollbar), 2 = content (at the scroll origin in a +-- ClipsDescendants frame, so scrolling just moves it), 3 = drawn after content, not clipped to it (menu bar). +local function NewFrame(parent, clips) + local frame = Instance.new("Frame") + frame.Name = "Layer" + frame.BackgroundTransparency = 1 + frame.BorderSizePixel = 0 + frame.Size = UDim2.fromOffset(0, 0) + frame.ClipsDescendants = clips + frame.Visible = false + frame.Parent = parent + return frame +end + +function M.GetLayer(BackendData, draw_list, kind) + local set = BackendData.Layers[draw_list] + if not set then + set = { LastUsed = 0 } + BackendData.Layers[draw_list] = set + end + local layer = set[kind] + if layer then return layer end + local root, frame + if kind == 2 then + root = NewFrame(BackendData.Gui, true) + frame = NewFrame(root, false) + frame.Visible = true + else + frame = NewFrame(BackendData.Gui, false) + root = frame + end + layer = { + Root = root, Frame = frame, Tiles = {}, + TileHash1 = {}, TileHash2 = {}, TileCounts = {}, TileLists = {}, + TileListHash1 = {}, TileListHash2 = {}, TileListFlat = {}, TileX = {}, TileY = {}, + Touched = {}, TouchedCount = 0, + Visible = false, X = false, Y = false, Z = -1, + ClipX0 = false, ClipY0 = false, ClipX1 = false, ClipY1 = false, + } + set[kind] = layer + return layer +end + +function M.HideLayer(layer) + if layer.Visible then + layer.Visible = false + layer.Root.Visible = false + end +end + +-- recycle: to EditableImages.Pool. Its label stays parented (hidden): Studio reparenting costs far more than a +-- property set, and a scrolling layer's next tile usually goes back into the same frame +function EditableImages.FreeTile(layer, key, recycle) + local tile = layer.Tiles[key] + if recycle and #EditableImages.Pool < EditableImages.PoolMax then + table.insert(EditableImages.Pool, tile) + else + EditableImages.Destroy(tile.Image) + tile.Label:Destroy() + end + layer.Tiles[key] = nil + if EditableImages.StageTiming then EditableImages.AddStat("TilesFreed", 1) end + if (layer.TileCounts[key] or 0) > 0 then return end -- touched this frame: its primitive list is still needed + local lp = EditableImages.ListPool + if layer.TileLists[key] and #lp < 256 then + lp[#lp + 1] = layer.TileLists[key] + lp[#lp + 1] = layer.TileListHash1[key] + lp[#lp + 1] = layer.TileListHash2[key] + lp[#lp + 1] = layer.TileListFlat[key] + end + layer.TileLists[key], layer.TileListHash1[key], layer.TileListHash2[key], layer.TileListFlat[key] = + nil, nil, nil, nil + layer.TileHash1[key], layer.TileHash2[key], layer.TileCounts[key], layer.TileX[key], layer.TileY[key] = + nil, nil, nil, nil, nil +end + +function M.GetTile(BackendData, layer, key, tx, ty) + local tile = layer.Tiles[key] + if tile then return tile end + local scale = BackendData.Scale + local old = table.remove(EditableImages.Pool) + local label, img + if old then + label, img = old.Label, old.Image + else + img = EditableImages.Create(TILE, TILE) + if not img then return nil end -- over the budget even after eviction: the caller skips this tile this frame + label = Instance.new("ImageLabel") + label.Name = "Tile" + label.BackgroundTransparency = 1 + label.BorderSizePixel = 0 + label.ResampleMode = Enum.ResamplerMode.Pixelated + label.ImageContent = Content.fromObject(img) + label.Visible = false + end + if not old or old.Scale ~= scale then label.Size = UDim2.fromOffset(TILE / scale, TILE / scale) end + label.Position = UDim2.fromOffset(tx * TILE / scale, ty * TILE / scale) + if not old or old.Active ~= BackendData.TilesActive then label.Active = BackendData.TilesActive end + if not old or old.Parent ~= layer.Frame then label.Parent = layer.Frame end + -- Content*: content bounds; Valid*: where Buffer == image pixels. A recycled tile keeps both (they still describe + -- its image): its first draw is a full one (DrawnCount -1) that only clears old + new content bounds. + if old then + tile = old + tile.Hash1, tile.Hash2, tile.Visible, tile.Used, tile.Deferred, tile.DrawnCount = + -1, -1, false, BackendData.FrameNo, nil, -1 + tile.Scale, tile.Active, tile.Parent = scale, BackendData.TilesActive, layer.Frame + else + tile = { + Image = img, Label = label, Buffer = buffer.create(TILE * TILE * 4), + Hash1 = -1, Hash2 = -1, Visible = false, Used = BackendData.FrameNo, + ContentX0 = TILE, ContentY0 = TILE, ContentX1 = 0, ContentY1 = 0, + ValidX0 = 0, ValidY0 = 0, ValidX1 = TILE, ValidY1 = TILE, + Scale = scale, Active = BackendData.TilesActive, Parent = layer.Frame, + DrawnCount = -1, DrawnHash1 = {}, DrawnHash2 = {}, DrawnFlat = {}, + DrawnX0 = {}, DrawnY0 = {}, DrawnX1 = {}, DrawnY1 = {}, + } + end + layer.Tiles[key] = tile + if EditableImages.StageTiming then EditableImages.AddStat("TilesCreated", 1) end + return tile +end + +function M.DestroyLayerSet(set) + for kind = 1, 3 do + local layer = set[kind] + if layer then + for _, tile in pairs(layer.Tiles) do EditableImages.Destroy(tile.Image) end + for _, t in EditableImages.Pool do + if t.Parent == layer.Frame then + t.Label.Parent = nil + t.Parent = nil + end + end + layer.Root:Destroy() + end + end +end + +function M.DestroyTiles(BackendData) + for _, set in pairs(BackendData.Layers) do M.DestroyLayerSet(set) end + BackendData.Layers = {} +end + +-- Snapshot compared exactly with the next frame's list: 1 = identical (only restack), 2 = moved by whole pixels +-- (only move the layers), 0 = changed. Per command: clip (4 f64), ElemCount, IdxOffset, VtxOffset (u32), tex id +-- (f64), kind (u8), unclipped (u8), bounds of its primitives (4 x i32). +local CMD_STRIDE = 70 + +@native +function M.Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) + local nv = draw_list.VtxBuffer.Size * VTX_STRIDE + local idx, ni = draw_list.IdxBuffer.Data, draw_list.IdxBuffer.Size + local ncmd = draw_list.CmdBuffer.Size + local sv, si, sc = set.SnapVtx, set.SnapIdx, set.SnapCmds + if not sv or buffer.len(sv) < nv then + sv = buffer.create(max(nv, 64) * 2) + set.SnapVtx = sv + end + if not si then + si = {} + set.SnapIdx = si + end + if not sc or buffer.len(sc) < ncmd * CMD_STRIDE then + sc = buffer.create(max(ncmd, 4) * CMD_STRIDE * 2) + set.SnapCmds = sc + end + buffer.copy(sv, 0, draw_list.VtxBuffer.Buf, 0, nv) + table.move(idx, 1, ni, 1, si) + local o, ci = 0, 0 + for _, pcmd in draw_list.CmdBuffer:iter() do + if pcmd.UserCallback ~= nil then + set.SnapOK = false + return + end + local c = pcmd.ClipRect + writef64(sc, o, c.x) + writef64(sc, o + 8, c.y) + writef64(sc, o + 16, c.z) + writef64(sc, o + 24, c.w) + writeu32(sc, o + 32, pcmd.ElemCount) + writeu32(sc, o + 36, pcmd.IdxOffset) + writeu32(sc, o + 40, pcmd.VtxOffset) + writef64(sc, o + 44, pcmd:GetTexID()) + ci += 1 + buffer.writeu8(sc, o + 52, CmdKind[ci] or 0) + buffer.writeu8(sc, o + 53, CmdUnclipped[ci] and 1 or 0) + if CmdUnclipped[ci] then + buffer.writei32(sc, o + 54, CmdBoundsX0[ci]) + buffer.writei32(sc, o + 58, CmdBoundsY0[ci]) + buffer.writei32(sc, o + 62, CmdBoundsX1[ci]) + buffer.writei32(sc, o + 66, CmdBoundsY1[ci]) + end + o += CMD_STRIDE + end + set.SnapVtxBytes, set.SnapIdxCount, set.SnapCmdCount = nv, ni, ncmd + set.SnapOriginX, set.SnapOriginY, set.SnapScreenW, set.SnapScreenH = ox, oy, ScreenWidth, ScreenHeight + set.SnapHasContent = draw_list._ContentClipX0 ~= nil + set.SnapContentX0, set.SnapContentY0, set.SnapContentX1, set.SnapContentY1 = + draw_list._ContentClipX0 or 0, draw_list._ContentClipY0 or 0, draw_list._ContentClipX1 or 0, + draw_list._ContentClipY1 or 0 + set.SnapScrollX, set.SnapScrollY = draw_list._ScrollOriginX or 0, draw_list._ScrollOriginY or 0 + set.SnapOK = true +end + +-- a + d == b exactly, with no rounding in a + d (so every later "x - origin" gives the same result as before the move) +@native +local function ShiftedExact(a, d, b) + local s = a + d + if s ~= b then return false end + local bb = s - a + return (a - (s - bb)) + (d - bb) == 0 +end + +@native +function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) + if not set or not set.SnapOK then return 0 end + local nv = draw_list.VtxBuffer.Size * VTX_STRIDE + local ni, ncmd = draw_list.IdxBuffer.Size, draw_list.CmdBuffer.Size + if nv ~= set.SnapVtxBytes or ni ~= set.SnapIdxCount or ncmd ~= set.SnapCmdCount or ox ~= set.SnapOriginX + or oy ~= set.SnapOriginY or ScreenWidth ~= set.SnapScreenW or ScreenHeight ~= set.SnapScreenH then + return 0 + end + if (draw_list._ContentClipX0 ~= nil) ~= set.SnapHasContent then return 0 end + local vb, sv = draw_list.VtxBuffer.Buf, set.SnapVtx + if nv == 0 then return 1 end + -- translation from the first vertex: whole pixels only, and only with DisplayPos at 0 (so it stays exact) + local dx, dy = readf64(vb, 0) - readf64(sv, 0), readf64(vb, 8) - readf64(sv, 8) + if dx ~= dx or dy ~= dy then return 0 end + if dx == 0 and dy == 0 then + -- u32 loop, not readstring ==: that allocated 2 vertex-buffer strings per list per frame (GC spikes) + for o = 0, nv - 4, 4 do if readu32(vb, o) ~= readu32(sv, o) then return 0 end end + else + if dx ~= floor(dx) or dy ~= floor(dy) or ox ~= 0 or oy ~= 0 or not set.SnapLimitFree then return 0 end + -- everything must stay as far from the clip limits as before (nothing newly clamped) + if set.SnapExtentX0 + dx < -CLIP_PAD or set.SnapExtentY0 + dy < -CLIP_PAD + or set.SnapExtentX1 + dx > ScreenWidth + CLIP_PAD or set.SnapExtentY1 + dy > ScreenHeight + CLIP_PAD then + return 0 + end + end + local idx, si = draw_list.IdxBuffer.Data, set.SnapIdx + for i = 1, ni do if idx[i] ~= si[i] then return 0 end end + local sc, o = set.SnapCmds, 0 + local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1, + draw_list._ContentClipY1 + local seen_content = false + for _, pcmd in draw_list.CmdBuffer:iter() do + if pcmd.UserCallback ~= nil then return 0 end + if pcmd.ElemCount ~= readu32(sc, o + 32) or pcmd.IdxOffset ~= readu32(sc, o + 36) + or pcmd.VtxOffset ~= readu32(sc, o + 40) or pcmd:GetTexID() ~= readf64(sc, o + 44) then + return 0 + end + local c = pcmd.ClipRect + if dx == 0 and dy == 0 then + if c.x ~= readf64(sc, o) or c.y ~= readf64(sc, o + 8) or c.z ~= readf64(sc, o + 16) + or c.w ~= readf64(sc, o + 24) then + return 0 + end + elseif not (ShiftedExact(readf64(sc, o), dx, c.x) and ShiftedExact(readf64(sc, o + 8), dy, c.y) + and ShiftedExact(readf64(sc, o + 16), dx, c.z) and ShiftedExact(readf64(sc, o + 24), dy, c.w)) then + -- an unchanged clip rect (e.g. the viewport) is fine if it clips none of this command's primitives + if c.x ~= readf64(sc, o) or c.y ~= readf64(sc, o + 8) or c.z ~= readf64(sc, o + 16) + or c.w ~= readf64(sc, o + 24) + or buffer.readu8(sc, o + 53) == 0 then return 0 end + if buffer.readi32(sc, o + 54) + dx < floor(c.x) or buffer.readi32(sc, o + 58) + dy < floor(c.y) + or buffer.readi32(sc, o + 62) + dx > floor(c.z) + or buffer.readi32(sc, o + 66) + dy > floor(c.w) then return 0 end + end + if pcmd.ElemCount > 0 then + local kind = 1 + if ccx0 and c.x >= ccx0 and c.y >= ccy0 and c.z <= ccx1 and c.w <= ccy1 then + kind = 2 + seen_content = true + elseif seen_content then kind = 3 end + if kind ~= buffer.readu8(sc, o + 52) then return 0 end + end + o += CMD_STRIDE + end + if dx == 0 and dy == 0 then + if set.SnapHasContent and (draw_list._ContentClipX0 ~= set.SnapContentX0 + or draw_list._ContentClipY0 ~= set.SnapContentY0 or draw_list._ContentClipX1 ~= set.SnapContentX1 + or draw_list._ContentClipY1 ~= set.SnapContentY1 or draw_list._ScrollOriginX ~= set.SnapScrollX + or draw_list._ScrollOriginY ~= set.SnapScrollY) then return 0 end + return 1 + end + if set.SnapHasContent and not (ShiftedExact(set.SnapContentX0, dx, draw_list._ContentClipX0) + and ShiftedExact(set.SnapContentY0, dy, draw_list._ContentClipY0) + and ShiftedExact(set.SnapContentX1, dx, draw_list._ContentClipX1) + and ShiftedExact(set.SnapContentY1, dy, draw_list._ContentClipY1) + and ShiftedExact(set.SnapScrollX, dx, draw_list._ScrollOriginX) + and ShiftedExact(set.SnapScrollY, dy, draw_list._ScrollOriginY)) then return 0 end + for v = 0, nv - VTX_STRIDE, VTX_STRIDE do + if not ShiftedExact(readf64(sv, v), dx, readf64(vb, v)) + or not ShiftedExact(readf64(sv, v + 8), dy, readf64(vb, v + 8)) + or readf64(vb, v + 16) ~= readf64(sv, v + 16) or readf64(vb, v + 24) ~= readf64(sv, v + 24) + or readu32(vb, v + 32) ~= readu32(sv, v + 32) then return 0 end + end + return 2, dx, dy +end + +function M.ShiftLayer(layer, dx, dy, scale) + layer.X += dx + layer.Y += dy + local root = layer.Root + if root ~= layer.Frame then + layer.ClipX0 += dx + layer.ClipY0 += dy + layer.ClipX1 += dx + layer.ClipY1 += dy + root.Position = UDim2.fromOffset(layer.ClipX0 / scale, layer.ClipY0 / scale) + else + root.Position = UDim2.fromOffset(layer.X / scale, layer.Y / scale) + end +end + +return M diff --git a/backends/roblox/overlays.lua b/backends/roblox/overlays.lua new file mode 100644 index 0000000..bdc4b6c --- /dev/null +++ b/backends/roblox/overlays.lua @@ -0,0 +1,79 @@ +-- Overlays: user Instances placed inside a window (SetOverlay), stacked right above its layers and moving with it. +local Textures = IM_INCLUDE("roblox/textures.lua") + +local M = {} + +local function OverlayHolder(BackendData, draw_list, clip) + local hs = BackendData.OverlayHolders[draw_list] + if not hs then + hs = {} + BackendData.OverlayHolders[draw_list] = hs + end + local h = hs[clip] + if not h then + h = Instance.new("Frame") + h.Name = clip and "OverlayClip" or "Overlay" + h.BackgroundTransparency = 1 + h.BorderSizePixel = 0 + h.ClipsDescendants = clip + h.Size = UDim2.fromOffset(0, 0) + h.Parent = BackendData.Gui + hs[clip] = h + end + return h +end + +local OverlayUsed = {} +function M.PlaceOverlays(BackendData, draw_list, z, ox, oy) + local list = BackendData.Overlays[draw_list] + local hs = BackendData.OverlayHolders[draw_list] + if not list then + if hs then for _, h in pairs(hs) do h.Visible = false end end + return z + end + local scale, frame_no = BackendData.Scale, BackendData.FrameNo + z += 1 + local used = OverlayUsed + table.clear(used) + for _, o in ipairs(list) do + local clip = o.Clip and draw_list._ContentClipX0 ~= nil + local h = OverlayHolder(BackendData, draw_list, clip) + local hx, hy = 0, 0 + if clip then + hx, hy = draw_list._ContentClipX0 - ox, draw_list._ContentClipY0 - oy + if not used[h] then + h.Position = UDim2.fromOffset(hx / scale, hy / scale) + h.Size = UDim2.fromOffset((draw_list._ContentClipX1 - draw_list._ContentClipX0) / scale, + (draw_list._ContentClipY1 - draw_list._ContentClipY0) / scale) + end + elseif not used[h] then + h.Position = UDim2.fromOffset(0, 0) + end + used[h] = true + h.ZIndex = z + h.Visible = true + local f = o.Frame + if f.Parent ~= h then f.Parent = h end + f.Position = UDim2.fromOffset((o.X - ox - hx) / scale, (o.Y - oy - hy) / scale) + f.Size = UDim2.fromOffset(o.W / scale, o.H / scale) + f.Visible = true + BackendData.OverlayShown[f] = frame_no + end + if hs then for _, h in pairs(hs) do if not used[h] then h.Visible = false end end end + return z +end + +--- Show `frame` this frame at (x, y, w, h) (imgui coordinates) inside the current window. Call every frame it should +--- be visible; frames not submitted are hidden. clip: clip to the window's content area (scrolls with it). +function ImGui_ImplRoblox_SetOverlay(frame, x, y, w, h, clip) + local BackendData = Textures.GetBackendData() + local dl = ImGui.GetWindowDrawList() + local list = BackendData.Overlays[dl] + if not list then + list = {} + BackendData.Overlays[dl] = list + end + list[#list + 1] = { Frame = frame, X = x, Y = y, W = w, H = h, Clip = clip ~= false } +end + +return M diff --git a/backends/roblox/parallel.lua b/backends/roblox/parallel.lua new file mode 100644 index 0000000..e28a349 --- /dev/null +++ b/backends/roblox/parallel.lua @@ -0,0 +1,398 @@ +-- Parallel executor (opt-in, EnableParallel): Tile packs each dirty tile per Actor, Flush sends the batch while the +-- dispatch window (PreAnimation .. Finish) is open, else rasterizes it at once; Finish uploads every result. +local Raster = IM_INCLUDE("roblox/raster.lua") +local Textures = IM_INCLUDE("roblox/textures.lua") +local Render = IM_INCLUDE("roblox/render.lua") + +local Players = game:GetService("Players") +local EditableImages, Records = Textures.EditableImages, Textures.Records +local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient = Render.PrimA, Render.PrimB, Render.PrimC, Render.PrimD, + Render.PrimTexture, Render.PrimGradient +local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = Render.PrimClipX0, Render.PrimClipY0, Render.PrimClipX1, + Render.PrimClipY1 +local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = Render.PrimBoundsX0, Render.PrimBoundsY0, + Render.PrimBoundsX1, Render.PrimBoundsY1 +local PrimTexId, PrimVtxBuffer = Render.PrimTexId, Render.PrimVtxBuffer + +local M = Render.Parallel +local writei32, writef64, copy = buffer.writei32, buffer.writef64, buffer.copy +local RasterJobs = Raster.RasterJobs +local VTX, REC, REC_A, REC_B, REC_C, JOB = Raster.VTX, Raster.REC, Raster.REC_A, Raster.REC_B, Raster.REC_C, Raster.JOB +assert(VTX == VTX_STRIDE, "raster.lua: vertex layout differs from ImDrawVert") + +-- Sync / SyncDrop / Inline: test hooks (inline "workers"; drop half their results; bypass the executor) +M.Config = { Actors = 4, MinTiles = 4, MinPixels = 16384, MaxBytesPerPixel = 3, Sync = false, SyncDrop = false, + Inline = false, Worker = nil } +M.Stats = { + ParallelFlushes = 0, SerialFlushes = 0, Tiles = 0, Fallbacks = 0, Late = 0, Pack = 0, Flush = 0, Finish = 0, + SendBytes = 0, TexSends = 0, TexBytes = 0, Rects = 0, Recv = 0, RecvBytes = 0, +} +local Stats = M.Stats + +local NA = 1 +local Pb, Pn, Tb, Tn, load, used = {}, {}, {}, {}, {}, {} +local stamp, poff, stamp_base = {}, {}, 0 +local free_batches, free_bufs, free_bytes = {}, {}, 0 +local function newBatch() + return table.remove(free_batches) + or { N = 0, Px = 0, Img = {}, Actor = {}, NR = {}, Rect = {}, P = {}, T = {}, TL = {}, Res = {} } +end +local function takeBuf(len: number): buffer + local l = free_bufs[len] + local b = l and table.remove(l) + if b then + free_bytes -= len + return b + end + return buffer.create(len) +end +local function giveBuf(b: buffer) + local len = buffer.len(b) + local l = free_bufs[len] + if not l then + l = {} + free_bufs[len] = l + end + if #l < 8 and free_bytes + len <= 4194304 then + l[#l + 1] = b + free_bytes += len + end +end +local jobs = newBatch() +local NO_TEX = {} +local cur = {} +local pending, by_id, batch_no = {}, {}, 0 +local open = false +local actors, ready, conns, folder = {}, false, {}, nil +local sent = {} + +local function grow(b: buffer, need: number): buffer + local n = buffer.len(b) + if need <= n then + return b + end + while n < need do + n *= 2 + end + local nb = buffer.create(n) + copy(nb, 0, b) + return nb +end + +local function reset() + for a = 1, NA do + Pn[a], Tn[a], load[a] = 0, 0, 0 + if used[a] then + table.clear(used[a]) + end + end + stamp_base += 64 + jobs = newBatch() +end + +-- One dirty tile (rects in EditableImages.DX0..DY1[1..nr], primitives list[1..count]) -> the least loaded Actor +@native +function M.Tile(img, list, count: number, x0: number, y0: number, tox: number, toy: number, nr: number) + local t0 = os.clock() + local DX0, DY0, DX1, DY1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1 + local area = 0 + for r = 1, nr do + area += (DX1[r] - DX0[r]) * (DY1[r] - DY0[r]) + end + local a = 1 + for i = 2, NA do + if load[i] < load[a] then + a = i + end + end + load[a] += area + 200 + jobs.Px += area + local j = jobs.N + 1 + jobs.N = j + jobs.Img[j], jobs.Actor[j], jobs.NR[j] = img, a, nr + Stats.Rects += nr + local R = jobs.Rect + local ri = #R + for r = 1, nr do + R[ri + 1], R[ri + 2], R[ri + 3], R[ri + 4] = DX0[r], DY0[r], DX1[r], DY1[r] + ri += 4 + end + + local T, to = grow(Tb[a], Tn[a] + JOB + nr * 16 + count * 4), Tn[a] + Tb[a] = T + writef64(T, to, tox) + writef64(T, to + 8, toy) + writei32(T, to + 16, x0) + writei32(T, to + 20, y0) + writei32(T, to + 24, nr) + writei32(T, to + 28, count) + to += JOB + for r = 1, nr do + writei32(T, to, DX0[r]) + writei32(T, to + 4, DY0[r]) + writei32(T, to + 8, DX1[r]) + writei32(T, to + 12, DY1[r]) + to += 16 + end + local P, pn = grow(Pb[a], Pn[a] + count * REC), Pn[a] + Pb[a] = P + local st = stamp_base + a + local u = used[a] + for k = 1, count do + local p = list[k] + if stamp[p] ~= st then + stamp[p], poff[p] = st, pn + local d, t = PrimD[p], PrimTexture[p] + local gk = PrimGradient[p] + writei32(P, pn, d and (gk and gk + 1 or 1) or 0) + writei32(P, pn + 4, t and PrimTexId[p] or -1) + if t then + u[t] = PrimTexId[p] + end + writei32(P, pn + 8, PrimClipX0[p]) + writei32(P, pn + 12, PrimClipY0[p]) + writei32(P, pn + 16, PrimClipX1[p]) + writei32(P, pn + 20, PrimClipY1[p]) + writei32(P, pn + 24, PrimBoundsX0[p]) + writei32(P, pn + 28, PrimBoundsY0[p]) + writei32(P, pn + 32, PrimBoundsX1[p]) + writei32(P, pn + 36, PrimBoundsY1[p]) + local vb = PrimVtxBuffer[p] + copy(P, pn + REC_A, vb, PrimA[p], VTX) + copy(P, pn + REC_C, vb, PrimC[p], VTX) + if not d then + copy(P, pn + REC_B, vb, PrimB[p], VTX) + end + pn += REC + end + writei32(T, to, poff[p]) + to += 4 + end + Pn[a], Tn[a] = pn, to + Stats.Pack += os.clock() - t0 +end + +local function upload(b) + local alive, R, ri = EditableImages.ImageBytes, b.Rect, 0 + table.clear(cur) + for j = 1, b.N do + local a = b.Actor[j] + local outs, c = b.Res[a], cur[a] or 0 + local img = b.Img[j] + for _ = 1, b.NR[j] do + c += 1 + if alive[img] then + local x0, y0 = R[ri + 1], R[ri + 2] + img:WritePixelsBuffer(Vector2.new(x0, y0), Vector2.new(R[ri + 3] - x0, R[ri + 4] - y0), outs[c]) + end + ri += 4 + end + cur[a] = c + end +end + +-- Uploads every pending batch (late worker results rasterized here) and closes the dispatch window +function M.Finish() + open = false + if #pending == 0 then + return + end + local t0 = os.clock() + for _, b in pending do + for a = 1, NA do + if b.TL[a] > 0 and not b.Res[a] then + b.Res[a] = RasterJobs(b.P[a], b.T[a], b.TL[a], Records) + if b.Sent then + Stats.Fallbacks += 1 + end + end + end + upload(b) + by_id[b.Id] = nil + for a = 1, NA do + if b.P[a] then + giveBuf(b.P[a]) + giveBuf(b.T[a]) + end + end + b.N, b.Px, b.Sent = 0, 0, false + table.clear(b.Img) + table.clear(b.Actor) + table.clear(b.NR) + table.clear(b.Rect) + table.clear(b.P) + table.clear(b.T) + table.clear(b.TL) + table.clear(b.Res) + if #free_batches < 8 then + free_batches[#free_batches + 1] = b + end + end + table.clear(pending) + Stats.Finish += os.clock() - t0 +end + +function M.Flush() + local n = jobs.N + if n == 0 then + if not open then + M.Finish() + end + return + end + local t0 = os.clock() + local cfg = M.Config + local par = open and (cfg.Sync or ready) and n >= cfg.MinTiles and jobs.Px >= cfg.MinPixels + if par and cfg.MaxBytesPerPixel > 0 then + local bytes = 0 + for a = 1, NA do + bytes += Pn[a] + Tn[a] + end + par = bytes <= cfg.MaxBytesPerPixel * jobs.Px + end + batch_no += 1 + local b = jobs + b.Id, b.Sent = batch_no, par + for a = 1, NA do + local tl = Tn[a] + b.TL[a] = tl + if tl == 0 then + continue + end + if not par then + b.Res[a] = RasterJobs(Pb[a], Tb[a], tl, Records) + continue + end + -- recycled copies rounded up to 4 KB (SendMessage copies the whole buffer) + local P, T = takeBuf(Pn[a] + 4095 - (Pn[a] + 4095) % 4096), takeBuf(tl + 4095 - (tl + 4095) % 4096) + copy(P, 0, Pb[a], 0, Pn[a]) + copy(T, 0, Tb[a], 0, tl) + b.P[a], b.T[a] = P, T + + local tex, s = NO_TEX, sent[a] + for rec, id in used[a] do + local v = rec.V or 0 + if s[rec] ~= v then + if tex == NO_TEX then + tex = {} + end + s[rec] = v + tex[#tex + 1] = { id, rec.Buffer, rec.Width, rec.Height } + Stats.TexSends += 1 + Stats.TexBytes += buffer.len(rec.Buffer) + end + end + Stats.SendBytes += Pn[a] + tl + if cfg.Sync then + if not (cfg.SyncDrop and a % 2 == 0) then + b.Res[a] = RasterJobs(P, T, tl, Records) + end + else + actors[a]:SendMessage("job", batch_no, P, T, tex, tl) + end + end + if par then + Stats.ParallelFlushes += 1 + else + Stats.SerialFlushes += 1 + end + Stats.Tiles += n + by_id[batch_no] = b + pending[#pending + 1] = b + reset() + Stats.Flush += os.clock() - t0 + if not open then + M.Finish() + end +end + +function M.BeginFrame() + open = true +end + +local function setActors(n) + NA = n + for a = 1, n do + Pb[a] = Pb[a] or buffer.create(4096) + Tb[a] = Tb[a] or buffer.create(1024) + used[a] = used[a] or {} + sent[a] = setmetatable({}, { __mode = "k" }) + end + reset() +end +setActors(1) + +function M.Disable() + M.Finish() + for _, c in conns do + c:Disconnect() + end + table.clear(conns) + if folder then + folder:Destroy() + folder = nil + end + table.clear(actors) + ready, open = false, false + M.On, M.Active = false, false +end + +function M.Enable(opts) + M.Disable() + for k, v in opts or {} do + M.Config[k] = v + end + local cfg = M.Config + setActors(math.max(1, cfg.Actors)) + M.On = true + if cfg.Sync then + return + end + local RunService = game:GetService("RunService") + -- bundle: script is the library ModuleScript (e.g. ImGui.Impl under the typed module) + local template = cfg.Worker or script:FindFirstChild("Worker") + or (script.Parent and script.Parent:FindFirstChild("Worker")) + assert(template, "ImGui_ImplRoblox.EnableParallel: no Worker LocalScript (build/ImGuiWorker.client.luau) as a" + .. " child of the ImGui module; or pass { Worker = ... }") + folder = Instance.new("Folder") + folder.Name = "ImGuiRasterActors" + for a = 1, NA do + local actor = Instance.new("Actor") + actor.Name = "Raster" .. a + local done = Instance.new("BindableEvent") + done.Name = "Done" + done.Parent = actor + table.insert(conns, done.Event:Connect(function(id, outs) + local t0, b = os.clock(), by_id[id] + if b then + b.Res[a] = outs + else + Stats.Late += 1 + end + for _, o in outs do + Stats.RecvBytes += buffer.len(o) + end + Stats.Recv += os.clock() - t0 + end)) + local w = template:Clone() + w.Parent = actor + actor.Parent = folder + actors[a] = actor + end + folder.Parent = Players.LocalPlayer:WaitForChild("PlayerScripts") + ready = false + table.insert(conns, RunService.PreAnimation:Connect(function() + if not ready then + ready = true + for _, act in actors do + if not act:GetAttribute("Ready") then + ready = false + end + end + end + open = true + end)) + table.insert(conns, RunService.PostSimulation:Connect(M.Finish)) +end + +return M diff --git a/backends/roblox/raster.lua b/backends/roblox/raster.lua new file mode 100644 index 0000000..7e36707 --- /dev/null +++ b/backends/roblox/raster.lua @@ -0,0 +1,474 @@ +-- Software rasterizer: pure buffer code shared by the backend and the parallel worker (inlined into ImGuiWorker). +-- Target: RGBA8 row-major (ImU32 is already R | G<<8 | B<<16 | A<<24), non-premultiplied "over" onto transparent. +local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 +local readf64 = buffer.readf64 +local band, rshift = bit32.band, bit32.rshift +local readi32 = buffer.readi32 + +local M = { + TILE = 128, + -- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs. + -- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2), tex id (-1: none), clip x0 y0 x1 y1, + -- bounds x0 y0 x1 y1 (screen pixels, i32), then raw vertices (VTX bytes: x y u v f64, col u32): a at REC_A, + -- c at REC_C, b at REC_B. + -- T job: tox toy (f64), x0 y0 nr count (i32), nr x rect x0 y0 x1 y1 (i32, tile pixels), count x P offset (i32). + VTX = 36, REC = 148, REC_A = 40, REC_C = 76, REC_B = 112, JOB = 32, +} +local TILE = M.TILE + +local TargetBuffer: buffer, TargetWidth = buffer.create(0), 0 +local PrevRow = buffer.create(1024) + +-- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else +-- remembers this row. u32 loop, not readstring ==: that allocated a string per row. +@native +local function RowRepeats(o: number, len: number, has_prev: boolean): boolean + if has_prev then + local same = true + for k = 0, len - 4, 4 do + if readu32(TargetBuffer, o + k) ~= readu32(PrevRow, k) then + same = false + break + end + end + if same then return true end + end + if buffer.len(PrevRow) < len then PrevRow = buffer.create(len) end + buffer.copy(PrevRow, 0, TargetBuffer, o, len) + return false +end +local RectColumns = table.create(256, 0) + +-- FillSpan and DrawTriangle's flat path inline this math with per-span constants: keep them in sync. +@native +local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number, b: number, a: number) + if a >= 255 then + writeu32(TargetBuffer, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080) + return + end + if a <= 0 then return end + local d = readu32(TargetBuffer, o) + if d < 16777216 then + writeu32(TargetBuffer, o, + floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216) + return + end + local sa = a / 255 + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + local ns = 1 - sa + writeu32(TargetBuffer, o, + floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256 + floor(b * sa + db * ns + 0.5) * 65536 + + 4278190080) + else + local k = rshift(d, 24) * ((1 - sa) / 255) + local oa = sa + k + local inv = 1 / oa + writeu32(TargetBuffer, o, floor((r * sa + dr * k) * inv + 0.5) + floor((g * sa + dg * k) * inv + 0.5) * 256 + + floor((b * sa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + end +end + +@native +local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number, + b: number, a: number) + if a <= 0 then return end + local w4 = (x1 - x0 - 1) * 4 + if a >= 255 then + local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080 + local first = (y0 * TargetWidth + x0) * 4 + for o = first, first + w4, 4 do writeu32(TargetBuffer, o, packed) end + for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end + return + end + local packed0 = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216 + local sa = a / 255 + local ns = 1 - sa + local c1 = ns / 255 + local rs, gs, bs = r * sa, g * sa, b * sa + local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination + for y = y0, y1 - 1 do + local o0 = (y * TargetWidth + x0) * 4 + for o = o0, o0 + w4, 4 do + local d = readu32(TargetBuffer, o) + if d == last_d then + writeu32(TargetBuffer, o, last_v) + elseif d < 16777216 then + writeu32(TargetBuffer, o, packed0) + else + last_d = d + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + last_v = floor(rs + dr * ns + 0.5) + floor(gs + dg * ns + 0.5) * 256 + + floor(bs + db * ns + 0.5) * 65536 + 4278190080 + else + local k = rshift(d, 24) * c1 + local oa = sa + k + local inv = 1 / oa + last_v = floor((rs + dr * k) * inv + 0.5) + floor((gs + dg * k) * inv + 0.5) * 256 + + floor((bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 + end + writeu32(TargetBuffer, o, last_v) + end + end + end +end + +@native +local function UnpackColor(col: number) + return col % 256, floor(col / 256) % 256, floor(col / 65536) % 256, floor(col / 16777216) % 256 +end + +@native +local function SampleTexture(t, u: number, v: number) + local tw, th = t.Width, t.Height + local tx, ty = floor(u * tw), floor(v * th) + if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end + if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end + local o = (ty * tw + tx) * 4 + local tb = t.Buffer + return readu8(tb, o), readu8(tb, o + 1), readu8(tb, o + 2), readu8(tb, o + 3) +end + +@native +local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, u0: number, v0: number, + u1: number, v1: number, col: number, t, cx0: number, cy0: number, cx1: number, cy1: number) + local r, g, b, a = UnpackColor(col) + if a == 0 then return end + local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0) + local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1) + if px0 >= px1 or py0 >= py1 then return end + + if not t or (u0 == u1 and v0 == v1) then + if t then + local tr, tg, tb, ta = SampleTexture(t, u0, v0) + r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255 + end + if a <= 0 then return end + if a >= 255 or px1 - px0 < 32 then + FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a) + return + end + -- Wide translucent rect: rows usually blend over identical rows, so copy the previous row's result + local len = (px1 - px0) * 4 + local prev_o = 0 + for y = py0, py1 - 1 do + local o = (y * TargetWidth + px0) * 4 + if RowRepeats(o, len, y > py0) then + buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len) + else + FillSpan(TargetBuffer, y, y + 1, px0, px1, r, g, b, a) + end + prev_o = o + end + return + end + + local du, dv = (u1 - u0) / (x1 - x0), (v1 - v0) / (y1 - y0) + local tw: number, th: number, tbuf: buffer, dbuf: buffer = t.Width, t.Height, t.Buffer, TargetBuffer + local r255, g255, b255, a255 = r / 255, g / 255, b / 255, a / 255 + local ncol = px1 - px0 + local cols = RectColumns + for c = 1, ncol do + local tx = floor((u0 + (px0 + c - 1 + 0.5 - x0) * du) * tw) + if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end + cols[c] = tx * 4 + end + for y = py0, py1 - 1 do + local ty = floor((v0 + (y + 0.5 - y0) * dv) * th) + if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end + local trow4 = ty * tw * 4 + local o = (y * TargetWidth + px0) * 4 + for c = 1, ncol do + local tv = readu32(tbuf, trow4 + cols[c]) + if tv >= 16777216 then + local sa = rshift(tv, 24) * a255 + local sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, + band(rshift(tv, 16), 255) * b255 + if sa >= 255 then + writeu32(dbuf, o, floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + 4278190080) + else + BlendPixel(dbuf, o, sr, sg, sb, sa) + end + end + o = o + 4 + end + end +end + +@native +local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, vc: number, t, cx0: number, cy0: number, + cx1: number, cy1: number, ox: number, oy: number) + local x0, y0 = readf64(vbuf, va) - ox, readf64(vbuf, va + 8) - oy + local x1, y1 = readf64(vbuf, vb) - ox, readf64(vbuf, vb + 8) - oy + local x2, y2 = readf64(vbuf, vc) - ox, readf64(vbuf, vc + 8) - oy + local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0) + if area == 0 then return end + if area < 0 then + vb, vc = vc, vb + x1, y1, x2, y2 = x2, y2, x1, y1 + area = -area + end + + local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1) + local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1) + if minx > maxx or miny > maxy then return end + + local A0, B0 = y1 - y2, x2 - x1 + local C0 = -(A0 * x1 + B0 * y1) + local A1, B1 = y2 - y0, x0 - x2 + local C1 = -(A1 * x2 + B1 * y2) + local A2, B2 = y0 - y1, x1 - x0 + local C2 = -(A2 * x0 + B2 * y0) + local tl0 = A0 > 0 or (A0 == 0 and B0 > 0) + local tl1 = A1 > 0 or (A1 == 0 and B1 > 0) + local tl2 = A2 > 0 or (A2 == 0 and B2 > 0) + + local inv = 1 / area + local n0, n1, n2 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0 + local ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32)) + local rb, gb, bb, ab = UnpackColor(readu32(vbuf, vb + 32)) + local rc, gc, bc, ac = UnpackColor(readu32(vbuf, vc + 32)) + local ua, vva, ub, vvb, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vb + 16), + readf64(vbuf, vb + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) + + local textured = t and not (ua == ub and ua == uc and vva == vvb and vva == vvc) + if t and not textured then -- constant uv (atlas white pixel): fold the texel into the vertex colours + local tr, tg, tb, ta = SampleTexture(t, ua, vva) + ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255 + rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255 + rc, gc, bc, ac = rc * tr / 255, gc * tg / 255, bc * tb / 255, ac * ta / 255 + end + local flat = not textured and ra == rb and ra == rc and ga == gb and ga == gc and ba == bb and ba == bc and aa == ab + and aa == ac + if flat and aa <= 0 then return end + local f_opaque, f_packed, f_sa, f_ns, f_c1, f_rs, f_gs, f_bs = false, 0, 0, 0, 0, 0, 0, 0 + if flat then + f_opaque = aa >= 255 + f_packed = floor(ra + 0.5) + floor(ga + 0.5) * 256 + floor(ba + 0.5) * 65536 + + (f_opaque and 4278190080 or floor(aa + 0.5) * 16777216) + f_sa = aa / 255 + f_ns = 1 - f_sa + f_c1 = f_ns / 255 + f_rs, f_gs, f_bs = ra * f_sa, ga * f_sa, ba * f_sa + end + + for y = miny, maxy do + local py = y + 0.5 + local xl, xr = minx, maxx + local e0, e1, e2 = B0 * py + C0, B1 * py + C1, B2 * py + C2 + -- (e * n is -e / A within an ulp; the 1e-6 margin covers that, and the exact tests below decide) + if A0 > 0 then + xl = max(xl, floor(e0 * n0 - 0.500001)) + elseif A0 < 0 then + xr = min(xr, ceil(e0 * n0 - 0.499999)) + end + if A1 > 0 then + xl = max(xl, floor(e1 * n1 - 0.500001)) + elseif A1 < 0 then + xr = min(xr, ceil(e1 * n1 - 0.499999)) + end + if A2 > 0 then + xl = max(xl, floor(e2 * n2 - 0.500001)) + elseif A2 < 0 then + xr = min(xr, ceil(e2 * n2 - 0.499999)) + end + + while xl <= xr do + local px = xl + 0.5 + local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2 + if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then + break + end + xl += 1 + end + while xr > xl do + local px = xr + 0.5 + local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2 + if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then + break + end + xr -= 1 + end + if xl > xr then continue end + local o = (y * TargetWidth + xl) * 4 + if flat then + local o1 = o + (xr - xl) * 4 + if f_opaque then + for oo = o, o1, 4 do writeu32(dbuf, oo, f_packed) end + continue + end + local last_d, last_v = -1, 0 + for oo = o, o1, 4 do + local d = readu32(dbuf, oo) + if d == last_d then + writeu32(dbuf, oo, last_v) + elseif d < 16777216 then + writeu32(dbuf, oo, f_packed) + else + last_d = d + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + last_v = floor(f_rs + dr * f_ns + 0.5) + floor(f_gs + dg * f_ns + 0.5) * 256 + + floor(f_bs + db * f_ns + 0.5) * 65536 + 4278190080 + else + local k = rshift(d, 24) * f_c1 + local oa = f_sa + k + local inv = 1 / oa + last_v = floor((f_rs + dr * k) * inv + 0.5) + floor((f_gs + dg * k) * inv + 0.5) * 256 + + floor((f_bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 + end + writeu32(dbuf, oo, last_v) + end + end + continue + end + for x = xl, xr do + local px = x + 0.5 + local w0, w1, w2 = (A0 * px + e0) * inv, (A1 * px + e1) * inv, (A2 * px + e2) * inv + local a = w0 * aa + w1 * ab + w2 * ac + if textured then + local r = w0 * ra + w1 * rb + w2 * rc + local g = w0 * ga + w1 * gb + w2 * gc + local b = w0 * ba + w1 * bb + w2 * bc + local tr, tg, tb, ta = SampleTexture(t, w0 * ua + w1 * ub + w2 * uc, w0 * vva + w1 * vvb + w2 * vvc) + BlendPixel(dbuf, o, r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255) + elseif a > 0 then + BlendPixel(dbuf, o, w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc, + w0 * ba + w1 * bb + w2 * bc, a) + end + o += 4 + end + end +end + +-- Linear gradient quad, constant uv. kind 1: along y (ca top, cb bottom), 2: along x. Same pixels as the triangles. +@native +local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, ca: number, + cb: number, kind: number, t, u: number, v: number, cx0: number, cy0: number, cx1: number, cy1: number) + local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0) + local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1) + if px0 >= px1 or py0 >= py1 then return end + local ra, ga, ba, aa = UnpackColor(ca) + local rb, gb, bb, ab = UnpackColor(cb) + if t then + local tr, tg, tb, ta = SampleTexture(t, u, v) + ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255 + rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255 + end + if kind == 1 then + local inv = 1 / (y1 - y0) + for y = py0, py1 - 1 do + local f = (y + 0.5 - y0) * inv + local nf = 1 - f + FillSpan(TargetBuffer, y, y + 1, px0, px1, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, + aa * nf + ab * f) + end + else + local inv = 1 / (x1 - x0) + local len = (px1 - px0) * 4 + local opaque = aa >= 255 and ab >= 255 + local prev_o = 0 + for y = py0, py1 - 1 do + local o = (y * TargetWidth + px0) * 4 + if y > py0 and (opaque or RowRepeats(o, len, true)) + or (y == py0 and not opaque and RowRepeats(o, len, false)) then + buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len) + else + local oo = o + for x = px0, px1 - 1 do + local f = (x + 0.5 - x0) * inv + local nf = 1 - f + BlendPixel(TargetBuffer, oo, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f) + oo = oo + 4 + end + end + prev_o = o + end + end +end + +function M.SetTarget(buf: buffer, width: number) + TargetBuffer, TargetWidth = buf, width +end + +@native +function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number) + local rw = rx1 - rx0 + if rw == TargetWidth then + buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4) + else + for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4, 0, rw * 4) end + end +end + +@native +function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: number) + for y = 0, rh - 1 do + buffer.copy(dst, y * rw * 4, TargetBuffer, ((ry0 + y) * TargetWidth + rx0) * 4, rw * 4) + end +end + +-- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2 +@native +local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, tox: number, toy: number, + cx0: number, cy0: number, cx1: number, cy1: number) + if kind == 0 then + DrawTriangle(TargetBuffer, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, tox, toy) + return + end + local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox, + readf64(vbuf, vc + 8) - toy + if kind == 1 then + DrawRect(TargetBuffer, ax, ay, cx, cy, readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16), + readf64(vbuf, vc + 24), readu32(vbuf, va + 32), t, cx0, cy0, cx1, cy1) + else + DrawRectGradient(TargetBuffer, ax, ay, cx, cy, readu32(vbuf, va + 32), readu32(vbuf, vc + 32), kind - 1, t, + readf64(vbuf, va + 16), readf64(vbuf, va + 24), cx0, cy0, cx1, cy1) + end +end +M.DrawPrim = DrawPrim + +-- Packed tile jobs -> one exact-size buffer per rect, in job order (worker + main-thread fallback) +local Scratch = buffer.create(TILE * TILE * 4) +@native +function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } + local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect + local REC_A, REC_B, REC_C = M.REC_A, M.REC_B, M.REC_C + M.SetTarget(Scratch, TILE) + local out, no = {}, 0 + local o = 0 + while o < tlen do + local tox, toy = readf64(T, o), readf64(T, o + 8) + local x0, y0, nr, count = readi32(T, o + 16), readi32(T, o + 20), readi32(T, o + 24), readi32(T, o + 28) + local ro = o + 32 + local po = ro + nr * 16 + o = po + count * 4 + for r = 0, nr - 1 do + local rx0, ry0, rx1, ry1 = readi32(T, ro + r * 16), readi32(T, ro + r * 16 + 4), + readi32(T, ro + r * 16 + 8), readi32(T, ro + r * 16 + 12) + ClearRect(rx0, ry0, rx1, ry1) + for k = 0, count - 1 do + local q = readi32(T, po + k * 4) + local cx0, cy0 = max(readi32(P, q + 8) - x0, rx0), max(readi32(P, q + 12) - y0, ry0) + local cx1, cy1 = min(readi32(P, q + 16) - x0, rx1), min(readi32(P, q + 20) - y0, ry1) + if cx0 >= cx1 or cy0 >= cy1 or readi32(P, q + 24) - x0 >= rx1 or readi32(P, q + 28) - y0 >= ry1 + or readi32(P, q + 32) - x0 <= rx0 or readi32(P, q + 36) - y0 <= ry0 then + continue + end + local tid, t = readi32(P, q + 4), nil + if tid >= 0 then t = textures[tid] end + DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, tox, toy, cx0, cy0, cx1, cy1) + end + local rw, rh = rx1 - rx0, ry1 - ry0 + local sub = buffer.create(rw * rh * 4) + CopySubRect(sub, rx0, ry0, rw, rh) + no += 1 + out[no] = sub + end + end + return out +end + +return M diff --git a/backends/roblox/render.lua b/backends/roblox/render.lua new file mode 100644 index 0000000..b576a3f --- /dev/null +++ b/backends/roblox/render.lua @@ -0,0 +1,843 @@ +-- Rendering: collect primitives, hash them into tiles, redraw + upload changed tiles (RenderDrawData). +local Raster = IM_INCLUDE("roblox/raster.lua") +local Textures = IM_INCLUDE("roblox/textures.lua") +local Layers = IM_INCLUDE("roblox/layers.lua") +local Overlays = IM_INCLUDE("roblox/overlays.lua") + +local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max +local readu32, readf64 = buffer.readu32, buffer.readf64 +local SetTarget, ClearRect, DrawPrim, CopySubRect = Raster.SetTarget, Raster.ClearRect, Raster.DrawPrim, + Raster.CopySubRect +local TILE = Raster.TILE +local TILE_SIZE = Vector2.new(TILE, TILE) +local EditableImages, PB, PE, GetBackendData, UpdateTexture = Textures.EditableImages, Textures.PB, Textures.PE, + Textures.GetBackendData, Textures.UpdateTexture +local GetLayer, HideLayer, GetTile, DestroyLayerSet, Snapshot, CompareDrawList, ShiftLayer = Layers.GetLayer, + Layers.HideLayer, Layers.GetTile, Layers.DestroyLayerSet, Layers.Snapshot, Layers.CompareDrawList, Layers.ShiftLayer +local CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1 = Layers.CmdUnclipped, Layers.CmdKind, + Layers.CmdBoundsX0, Layers.CmdBoundsY0, Layers.CmdBoundsX1, Layers.CmdBoundsY1 +local CLIP_PAD = Layers.CLIP_PAD +local PlaceOverlays = Overlays.PlaceOverlays + +local M = {} +-- Parallel executor state; parallel.lua adds its functions. On: enabled; Active: used by the current RenderDrawData. +local Parallel = { On = false, Active = false } +M.Parallel = Parallel + +local P1, P2 = 2147483647, 2147483629 -- two independent 31 bit hashes per tile (collision odds ~2^-62) +local LAYER_KEEP_FRAMES = 120 +local MAX_DEFER_FRAMES = 8 -- a changed tile is redrawn at the latest this many frames later, even over the budget + +local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient = {}, {}, {}, {}, {}, {} +local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = {}, {}, {}, {} +local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = {}, {}, {}, {} +local PrimTexId, PrimVtxBuffer, PrimKind = {}, {}, {} +local LayerPrims1, LayerPrims2, LayerPrims3 = {}, {}, {} +M.PrimA, M.PrimB, M.PrimC, M.PrimD = PrimA, PrimB, PrimC, PrimD +M.PrimTexture, M.PrimGradient = PrimTexture, PrimGradient +M.PrimClipX0, M.PrimClipY0, M.PrimClipX1, M.PrimClipY1 = PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 +M.PrimBoundsX0, M.PrimBoundsY0, M.PrimBoundsX1, M.PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 +M.PrimTexId, M.PrimVtxBuffer = PrimTexId, PrimVtxBuffer + +-- Adds [a, c) x [b, d) to the n dirty rects DX0..DY1 (merged unless that wastes area), returns the count +EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1 = {}, {}, {}, {} +@native +function EditableImages.AddRect(n: number, a: number, b: number, c: number, d: number): number + if a >= c or b >= d then return n end + local X0, Y0, X1, Y1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1 + local best, best_grow = 1, math.huge + for i = 1, n do + local e, f, g, h = X0[i], Y0[i], X1[i], Y1[i] + local ux0, uy0, ux1, uy1 = min(a, e), min(b, f), max(c, g), max(d, h) + local box, own = (ux1 - ux0) * (uy1 - uy0), (g - e) * (h - f) + local ov = max(min(c, g) - max(a, e), 0) * max(min(d, h) - max(b, f), 0) + -- waste outside both rects vs. apart: the overlap twice + a primitive pass and an upload (~2048 px) + if box - ((c - a) * (d - b) + own - ov) <= ov + 2048 then + X0[i], Y0[i], X1[i], Y1[i] = ux0, uy0, ux1, uy1 + return n + end + if box - own < best_grow then best, best_grow = i, box - own end + end + if n < 4 then + n += 1 + X0[n], Y0[n], X1[n], Y1[n] = a, b, c, d + else + X0[best], Y0[best], X1[best], Y1[best] = min(a, X0[best]), min(b, Y0[best]), max(c, X1[best]), max(d, Y1[best]) + end + return n +end + +@native +local function HashVertex(h1: number, h2: number, vbuf: buffer, v: number, ox: number, oy: number) + local x, y = readf64(vbuf, v) - ox, readf64(vbuf, v + 8) - oy + local uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24) + local c = readu32(vbuf, v + 32) + h1 = (h1 * 48271 + x * 4096 + y) % P1 + h1 = (h1 * 48271 + uv * 4096 + c) % P1 + h2 = (h2 * 16807 + y * 4093 + x) % P2 + h2 = (h2 * 16807 + uv * 65521 + c * 3) % P2 + return h1, h2 +end + +@native +local function HashTiles(layer, plist, np, lx0, ly0, ox, oy) + local TileHash1, TileHash2, TileCounts, TileLists, Touched = + layer.TileHash1, layer.TileHash2, layer.TileCounts, layer.TileLists, layer.Touched + local TileListHash1, TileListHash2, TileListFlat = layer.TileListHash1, layer.TileListHash2, layer.TileListFlat + for k = 1, layer.TouchedCount do TileCounts[Touched[k]] = 0 end + local TouchedCount = 0 + local CurKey, CurCount, CurHash1, CurHash2, CurList, CurListHash1, CurListHash2, CurListFlat = + nil, 0, 0, 0, nil, nil, nil, nil + local TileXs, TileYs = layer.TileX, layer.TileY + for pi = 1, np do + local p = plist[pi] + local tex_id = PrimTexId[p] + -- hash the clipped bounds, not the clip: a window clipped by the fixed viewport stays hash-stable when moved + local cx0, cy0, cx1, cy1 = PrimBoundsX0[p] - lx0, PrimBoundsY0[p] - ly0, PrimBoundsX1[p] - lx0, + PrimBoundsY1[p] - ly0 + local vbuf = PrimVtxBuffer[p] + local va, vd = PrimA[p], PrimD[p] + -- flat rect: hash its clipped rect per tile, so resizing only changes the tiles its edges cross + local FlatRect, RectColor, RectUV = false, 0, 0 + if vd and not PrimGradient[p] then + local u0, v0 = readf64(vbuf, va + 16), readf64(vbuf, va + 24) + local vc = PrimC[p] + if not PrimTexture[p] or (u0 == readf64(vbuf, vc + 16) and v0 == readf64(vbuf, vc + 24)) then + FlatRect, RectColor, RectUV = true, readu32(vbuf, va + 32), u0 * 8192 + v0 + end + end + local h1, h2 = 0, 0 + local FlatSig = -1 + if FlatRect then FlatSig = ((RectColor * 8191 + RectUV * 4096) % P1 * 64 + tex_id) % P1 end + if not FlatRect then + h1 = ((cx0 * 8191 + cy0) * 8191 + cx1) % P1 + h2 = ((cy1 * 8191 + cx1) * 8191 + cy0 + tex_id) % P2 + local vax, vay = lx0 + ox, ly0 + oy + if vd then + -- axis aligned quad: CollectPrims checked that TR/BL follow from TL/BR (+ kind) + h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay) + h1, h2 = HashVertex(h1, h2, vbuf, PrimC[p], vax, vay) + local gk = PrimGradient[p] + if gk then + h1 = (h1 * 48271 + gk) % P1 + h2 = (h2 * 16807 + gk * 3) % P2 + end + else + h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay) + h1, h2 = HashVertex(h1, h2, vbuf, PrimB[p], vax, vay) + h1, h2 = HashVertex(h1, h2, vbuf, PrimC[p], vax, vay) + end + end + for ty = floor((PrimBoundsY0[p] - ly0) / TILE), floor((PrimBoundsY1[p] - 1 - ly0) / TILE) do + for tx = floor((PrimBoundsX0[p] - lx0) / TILE), floor((PrimBoundsX1[p] - 1 - lx0) / TILE) do + if FlatRect then + local tx0, ty0 = tx * TILE, ty * TILE + local ix0, iy0 = max(cx0 - tx0, 0), max(cy0 - ty0, 0) + local ix1, iy1 = min(cx1 - tx0, TILE), min(cy1 - ty0, TILE) + local r = ((ix0 * 131 + iy0) * 131 + ix1) * 131 + iy1 + h1 = ((r * 48271 + RectColor) % P1 * 48271 + RectUV * 4096 + 7) % P1 + h2 = ((r * 16807 + RectColor + tex_id) % P2 * 16807 + RectUV * 65521 + 11) % P2 + end + -- unique for |tx|, |ty| < 32768 (content tiles go negative) + local key = (ty + 32768) * 65536 + tx + 32768 + if key ~= CurKey then + if CurKey then + TileCounts[CurKey], TileHash1[CurKey], TileHash2[CurKey] = CurCount, CurHash1, CurHash2 + end + CurKey = key + CurCount = TileCounts[key] + if not CurCount or CurCount == 0 then + CurCount, CurHash1, CurHash2 = 0, 0, 0 + if not TileLists[key] then + local ListPool = EditableImages.ListPool + local m = #ListPool + if m >= 4 then + TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key] = + ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m] + ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m] = nil, nil, nil, nil + else + TileLists[key] = {} + TileListHash1[key] = {} + TileListHash2[key] = {} + TileListFlat[key] = {} + end + end + TouchedCount = TouchedCount + 1 + Touched[TouchedCount] = key + TileXs[key], TileYs[key] = tx, ty + else + CurHash1, CurHash2 = TileHash1[key], TileHash2[key] + end + CurList, CurListHash1, CurListHash2, CurListFlat = + TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key] + end + CurCount += 1 + CurList[CurCount], CurListHash1[CurCount], CurListHash2[CurCount], CurListFlat[CurCount] = + p, h1, h2, FlatSig + CurHash1 = (CurHash1 * 48271 + h1) % P1 + CurHash2 = (CurHash2 * 16807 + h2 + CurCount) % P2 + end + end + end + if CurKey then TileCounts[CurKey], TileHash1[CurKey], TileHash2[CurKey] = CurCount, CurHash1, CurHash2 end + layer.TouchedCount = TouchedCount + return TouchedCount +end + +local function PlaceLayer(layer, scale, lx0, ly0, z, clip_x0, clip_y0, clip_x1, clip_y1) + local root = layer.Root + if root ~= layer.Frame then + if layer.ClipX0 ~= clip_x0 or layer.ClipY0 ~= clip_y0 or layer.ClipX1 ~= clip_x1 or layer.ClipY1 ~= clip_y1 then + layer.ClipX0, layer.ClipY0, layer.ClipX1, layer.ClipY1 = clip_x0, clip_y0, clip_x1, clip_y1 + root.Position = UDim2.fromOffset(clip_x0 / scale, clip_y0 / scale) + root.Size = UDim2.fromOffset((clip_x1 - clip_x0) / scale, (clip_y1 - clip_y0) / scale) + layer.X = false + end + if layer.X ~= lx0 or layer.Y ~= ly0 then + layer.X, layer.Y = lx0, ly0 + layer.Frame.Position = UDim2.fromOffset((lx0 - clip_x0) / scale, (ly0 - clip_y0) / scale) + end + elseif layer.X ~= lx0 or layer.Y ~= ly0 then + layer.X, layer.Y = lx0, ly0 + root.Position = UDim2.fromOffset(lx0 / scale, ly0 / scale) + end + if layer.Z ~= z then + layer.Z = z + root.ZIndex = z + end + if not layer.Visible then + layer.Visible = true + root.Visible = true + end +end + +local function SweepTiles(BackendData, layer, TouchedCount, lx0, ly0, clip_x0, clip_y0, clip_x1, clip_y1) + local TileCounts, Touched = layer.TileCounts, layer.Touched + -- content layer: only tiles inside its clip frame are kept, so scrolling holds the visible tiles + a few spares + local FrameNo, VisibleCount, SpareCap = BackendData.FrameNo, TouchedCount, TouchedCount + if layer.Root ~= layer.Frame then + for kk = 1, TouchedCount do + local key = Touched[kk] + local x0, y0 = lx0 + layer.TileX[key] * TILE, ly0 + layer.TileY[key] * TILE + if x0 >= clip_x1 or y0 >= clip_y1 or x0 + TILE <= clip_x0 or y0 + TILE <= clip_y0 then + TileCounts[key] = 0 + VisibleCount -= 1 + end + end + SpareCap = min(VisibleCount, 4) + end + -- unused tiles stay for a quick scroll back: at most SpareCap of them, for at most KEEP_FRAMES + local spare = 0 + for key, tile in pairs(layer.Tiles) do + if not TileCounts[key] or TileCounts[key] == 0 then + if tile.Visible then + tile.Visible = false + tile.Label.Visible = false + tile.Hash1 = -1 + tile.DrawnCount = -1 + end + spare += 1 + if spare > SpareCap or FrameNo - tile.Used > EditableImages.KEEP_FRAMES then + EditableImages.FreeTile(layer, key, true) + end + end + end +end + +@native +local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, vy0, vx1, vy1) + local qx0, qy0, qx1, qy1 = tile.ValidX0, tile.ValidY0, tile.ValidX1, tile.ValidY1 + local list, ListHash1, ListHash2 = layer.TileLists[key], layer.TileListHash1[key], layer.TileListHash2[key] + local DrawnHash1, DrawnHash2, DrawnX0, DrawnY0, DrawnX1, DrawnY1, DrawnCount = + tile.DrawnHash1, tile.DrawnHash2, tile.DrawnX0, tile.DrawnY0, tile.DrawnX1, tile.DrawnY1, + tile.DrawnCount + local nx0, ny0, nx1, ny1 = TILE, TILE, 0, 0 + for k = 1, count do + local p = list[k] + local a, b = PrimBoundsX0[p] - x0, PrimBoundsY0[p] - y0 + local c, d = PrimBoundsX1[p] - x0, PrimBoundsY1[p] - y0 + if a < nx0 then nx0 = a end + if b < ny0 then ny0 = b end + if c > nx1 then nx1 = c end + if d > ny1 then ny1 = d end + end + nx0, ny0, nx1, ny1 = max(nx0, 0), max(ny0, 0), min(nx1, TILE), min(ny1, TILE) + local DX0, DY0, DX1, DY1, AddRect = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, + EditableImages.DY1, EditableImages.AddRect + local DirtyCount = 0 + if force or DrawnCount < 0 then + -- outside the old + new content bounds the valid part is already transparent + DirtyCount = AddRect(AddRect(0, tile.ContentX0, tile.ContentY0, tile.ContentX1, tile.ContentY1), nx0, + ny0, nx1, ny1) + else + -- partial redraw: a pixel no changed primitive (old or new) touches is covered by the same primitives in the + -- same order, so only the bounds of the changed ones are redrawn + local i, lim = 1, min(DrawnCount, count) + while i <= lim and DrawnHash1[i] == ListHash1[i] and DrawnHash2[i] == ListHash2[i] do i += 1 end + local j = 0 + while j <= lim - i and DrawnHash1[DrawnCount - j] == ListHash1[count - j] + and DrawnHash2[DrawnCount - j] == ListHash2[count - j] do + j += 1 + end + local of, lf = tile.DrawnFlat, layer.TileListFlat[key] + local paired = DrawnCount - j - i == count - j - i + for k = i, count - j do + local p = list[k] + local a, b, c, d = max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0), + min(PrimBoundsX1[p] - x0, TILE), min(PrimBoundsY1[p] - y0, TILE) + local oa, ob, oc, od = DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k] + if paired and lf[k] >= 0 and lf[k] == of[k] then + -- same flat rect, new bounds: only the strips between the old and new edges can differ + local uy0, uy1 = min(b, ob), max(d, od) + local ux0, ux1 = min(a, oa), max(c, oc) + if a ~= oa then DirtyCount = AddRect(DirtyCount, ux0, uy0, max(a, oa), uy1) end + if c ~= oc then DirtyCount = AddRect(DirtyCount, min(c, oc), uy0, ux1, uy1) end + if b ~= ob then DirtyCount = AddRect(DirtyCount, ux0, uy0, ux1, max(b, ob)) end + if d ~= od then DirtyCount = AddRect(DirtyCount, ux0, min(d, od), ux1, uy1) end + else + DirtyCount = AddRect(DirtyCount, a, b, c, d) + if k <= DrawnCount - j then DirtyCount = AddRect(DirtyCount, oa, ob, oc, od) end + end + end + for k = count - j + 1, DrawnCount - j do + DirtyCount = AddRect(DirtyCount, DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k]) + end + end + -- clip D to V, then add the exposed part that isn't valid. cut: part of D inside the valid rect was clipped away + local cut, RectCount = false, 0 + for r = 1, DirtyCount do + local a, b, c, d = DX0[r], DY0[r], DX1[r], DY1[r] + local ix0, iy0, ix1, iy1 = max(a, qx0), max(b, qy0), min(c, qx1), min(d, qy1) + if ix0 < ix1 and iy0 < iy1 and (ix0 < vx0 or iy0 < vy0 or ix1 > vx1 or iy1 > vy1) then cut = true end + a, b, c, d = max(a, vx0), max(b, vy0), min(c, vx1), min(d, vy1) + if a < c and b < d then + RectCount += 1 + DX0[RectCount], DY0[RectCount], DX1[RectCount], DY1[RectCount] = a, b, c, d + end + end + if exposed then + local ex0, ey0, ex1, ey1 = vx0, vy0, vx1, vy1 + if qx0 <= vx0 and qx1 >= vx1 then + if qy0 <= vy0 and qy1 > vy0 then ey0 = qy1 elseif qy1 >= vy1 and qy0 < vy1 then ey1 = qy0 end + elseif qy0 <= vy0 and qy1 >= vy1 then + if qx0 <= vx0 and qx1 > vx0 then ex0 = qx1 elseif qx1 >= vx1 and qx0 < vx1 then ex1 = qx0 end + end + RectCount = AddRect(RectCount, ex0, ey0, ex1, ey1) + end + if cut then + qx0, qy0, qx1, qy1 = vx0, vy0, vx1, vy1 + elseif exposed then + if (qx0 == vx0 and qx1 == vx1 and qy0 <= vy1 and vy0 <= qy1) + or (qy0 == vy0 and qy1 == vy1 and qx0 <= vx1 and vx0 <= qx1) + or (qx0 >= vx0 and qy0 >= vy0 and qx1 <= vx1 and qy1 <= vy1) then + qx0, qy0, qx1, qy1 = min(qx0, vx0), min(qy0, vy0), max(qx1, vx1), max(qy1, vy1) + else + qx0, qy0, qx1, qy1 = vx0, vy0, vx1, vy1 + end + end + tile.ValidX0, tile.ValidY0, tile.ValidX1, tile.ValidY1 = qx0, qy0, qx1, qy1 + tile.ContentX0, tile.ContentY0, tile.ContentX1, tile.ContentY1 = nx0, ny0, nx1, ny1 + local DrawnFlat, ListFlat = tile.DrawnFlat, layer.TileListFlat[key] + for k = 1, count do + local p = list[k] + DrawnHash1[k], DrawnHash2[k], DrawnFlat[k] = ListHash1[k], ListHash2[k], ListFlat[k] + DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k] = + max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0), min(PrimBoundsX1[p] - x0, TILE), + min(PrimBoundsY1[p] - y0, TILE) + end + tile.DrawnCount = count + return RectCount +end + +@native +local function RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1) + ClearRect(rx0, ry0, rx1, ry1) + for k = 1, count do + local p = list[k] + local cx0, cy0 = max(PrimClipX0[p] - x0, rx0), max(PrimClipY0[p] - y0, ry0) + local cx1, cy1 = min(PrimClipX1[p] - x0, rx1), min(PrimClipY1[p] - y0, ry1) + if cx0 >= cx1 or cy0 >= cy1 or PrimBoundsX0[p] - x0 >= rx1 or PrimBoundsY0[p] - y0 >= ry1 + or PrimBoundsX1[p] - x0 <= rx0 or PrimBoundsY1[p] - y0 <= ry0 then + continue + end + local kind, gk = 0, PrimGradient[p] + if PrimD[p] then kind = gk and gk + 1 or 1 end + DrawPrim(kind, PrimTexture[p], PrimVtxBuffer[p], PrimA[p], PrimB[p], PrimC[p], tox, toy, cx0, cy0, cx1, cy1) + end +end + +-- WritePixelsBuffer needs the exact size: partial upload buffers are reused by size +local SubBuffers, SubBufferCount = {}, 0 +local function UploadRect(img, buf, rx0, ry0, rx1, ry1) + local rw, rh = rx1 - rx0, ry1 - ry0 + if rw == TILE and rh == TILE then + img:WritePixelsBuffer(Vector2.zero, TILE_SIZE, buf) + return + end + local sk = rw * 1024 + rh + local sub = SubBuffers[sk] + if not sub then + if SubBufferCount >= 256 then + table.clear(SubBuffers) + SubBufferCount = 0 + end + sub = buffer.create(rw * rh * 4) + SubBuffers[sk] = sub + SubBufferCount += 1 + end + CopySubRect(sub, rx0, ry0, rw, rh) + img:WritePixelsBuffer(Vector2.new(rx0, ry0), Vector2.new(rw, rh), sub) +end + +local function RedrawTile(BackendData, layer, key, tile, count, x0, y0, ox, oy, force, exposed, vx0, vy0, vx1, vy1) + BackendData.RedrawStarted = true + BackendData.FrameTiles += 1 + tile.Deferred = 0 + tile.Hash1, tile.Hash2 = layer.TileHash1[key], layer.TileHash2[key] + local RectCount = DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, vy0, vx1, vy1) + local list = layer.TileLists[key] + local tox, toy = ox + x0, oy + y0 + local Timing = EditableImages.StageTiming and EditableImages.StageFrame + if Timing and RectCount > 0 then Timing.TilesRasterized += 1 end + -- parallel: rasterized + uploaded later in the frame (pixels outside the rects are never read) + if Parallel.Active and RectCount > 0 then + Parallel.Tile(tile.Image, list, count, x0, y0, tox, toy, RectCount) + return + end + SetTarget(tile.Buffer, TILE) + local DX0, DY0, DX1, DY1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1 + for r = 1, RectCount do + local rx0, ry0, rx1, ry1 = DX0[r], DY0[r], DX1[r], DY1[r] + RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1) + PB("ImGui upload") + local t_up = Timing and os.clock() + if Timing then + Timing.PixelsRasterized += (rx1 - rx0) * (ry1 - ry0) + Timing.Uploads += 1 + end + UploadRect(tile.Image, tile.Buffer, rx0, ry0, rx1, ry1) + if Timing then Timing.Upload += os.clock() - t_up end + PE() + end +end + +local function DrawLayer(BackendData, layer, plist, np, lx0, ly0, ox, oy, force, z, clip_x0, clip_y0, clip_x1, clip_y1) + PB("ImGui tile hash") + if EditableImages.StageTiming then EditableImages.BeginStage() end + local TouchedCount = HashTiles(layer, plist, np, lx0, ly0, ox, oy) + if EditableImages.StageTiming then EditableImages.EndStage("Hash") end + PE() + + PlaceLayer(layer, BackendData.Scale, lx0, ly0, z, clip_x0, clip_y0, clip_x1, clip_y1) + + PB("ImGui raster+upload") + if EditableImages.StageTiming then EditableImages.BeginStage() end + SweepTiles(BackendData, layer, TouchedCount, lx0, ly0, clip_x0, clip_y0, clip_x1, clip_y1) + local TileCounts, Touched, TileHash1, TileHash2 = layer.TileCounts, layer.Touched, layer.TileHash1, layer.TileHash2 + local content = layer.Root ~= layer.Frame + local FrameNo, deferred = BackendData.FrameNo, false + for kk = 1, TouchedCount do + local key = Touched[kk] + local count = TileCounts[key] + if not count or count == 0 then continue end -- outside the content clip, or list freed + local tx, ty = layer.TileX[key], layer.TileY[key] + local tile = GetTile(BackendData, layer, key, tx, ty) + if not tile then continue end + tile.Used = FrameNo + local x0, y0 = lx0 + tx * TILE, ly0 + ty * TILE + -- redraws are clipped to the visible part; a part scrolled into view that isn't valid is redrawn then + local vx0, vy0, vx1, vy1 = 0, 0, TILE, TILE + if content then + vx0, vy0, vx1, vy1 = max(clip_x0 - x0, 0), max(clip_y0 - y0, 0), min(clip_x1 - x0, TILE), min(clip_y1 - y0, + TILE) + end + local exposed = vx0 < tile.ValidX0 or vy0 < tile.ValidY0 or vx1 > tile.ValidX1 or vy1 > tile.ValidY1 + local dirty = force or exposed or tile.Hash1 ~= TileHash1[key] or tile.Hash2 ~= TileHash2[key] + if dirty and BackendData.RedrawStarted and (tile.Deferred or 0) < MAX_DEFER_FRAMES + and ((BackendData.RedrawBudget > 0 and os.clock() - BackendData.FrameStartTime >= BackendData.RedrawBudget) + or (BackendData.TileLimit and BackendData.FrameTiles >= BackendData.TileLimit)) then + -- over budget (TileLimit: t_pixels hook): keep the old pixels (the stored hashes describe them) + tile.Deferred = (tile.Deferred or 0) + 1 + if force then + tile.Hash1 = -1 + tile.DrawnCount = -1 + end + deferred = true + dirty = false + end + if dirty then RedrawTile(BackendData, layer, key, tile, count, x0, y0, ox, oy, force, exposed, vx0, vy0, vx1, vy1) end + -- a deferred tile that was hidden holds old pixels: stays hidden until drawn + if not tile.Visible and (tile.Deferred or 0) == 0 then + tile.Visible = true + tile.Label.Visible = true + end + end + if EditableImages.StageTiming then + EditableImages.EndStage("Raster") + end + PE() + return deferred +end + +local function UpdateTextures(draw_data) + PB("ImGui textures") + if draw_data.Textures ~= nil then + for _, tex in draw_data.Textures:iter() do + if tex.Status ~= ImTextureStatus.OK then + -- WantUpdates only writes regions no tile has sampled yet: no redraw needed + UpdateTexture(tex) + end + end + end + PE() +end + +local function RenderRateAllows(BackendData, draw_data) + local rate = BackendData.RenderRate + if BackendData.BusyRenderRate > 0 then + local g = ImGui.GetCurrentContext() + local busy = g.WheelingWindow ~= nil or g.MovingWindow ~= nil -- (io.MouseWheel is already cleared by EndFrame) + if not busy and g.ActiveId ~= 0 then + local w = g.ActiveIdWindow + local cur = g.MouseCursor + busy = (cur >= ImGuiMouseCursor.ResizeAll and cur <= ImGuiMouseCursor.ResizeNWSE) + or (w ~= nil and (g.ActiveId == ImGui.GetWindowScrollbarID(w, ImGuiAxis.X) + or g.ActiveId == ImGui.GetWindowScrollbarID(w, ImGuiAxis.Y))) + end + if busy and (rate <= 0 or BackendData.BusyRenderRate < rate) then rate = BackendData.BusyRenderRate end + end + if rate > 0 then + local now = os.clock() + -- skipped: kept pending, Heartbeat draws it if no new frame comes + if now + 0.002 < BackendData.NextRender then + BackendData.Pending = draw_data + return false + end + BackendData.NextRender = math.max(BackendData.NextRender + 1 / rate, now) + end + return true +end + +local function ReuseDrawList(BackendData, set, draw_list, same, sdx, sdy, z, ox, oy, ScreenWidth, ScreenHeight) + for kind = 1, 3 do + local layer = set[kind] + if layer and layer.Visible then + if same == 2 then ShiftLayer(layer, sdx, sdy, BackendData.Scale) end + z += 1 + if layer.Z ~= z then + layer.Z = z + layer.Root.ZIndex = z + end + end + end + if same == 2 then + Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) + set.SnapExtentX0 += sdx + set.SnapExtentY0 += sdy + set.SnapExtentX1 += sdx + set.SnapExtentY1 += sdy + end + set.LastUsed = BackendData.FrameNo + return PlaceOverlays(BackendData, draw_list, z, ox, oy) +end + +-- Collects primitives into Prim* (from n + 1) and commands into Cmd*; returns n, LimitFree and the extents +@native +local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, LimitX1, LimitY1) + local vbuf, idx = draw_list.VtxBuffer.Buf, draw_list.IdxBuffer.Data + local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1, + draw_list._ContentClipY1 + local SeenContent = false + local ex0, ey0, ex1, ey1 = math.huge, math.huge, -math.huge, -math.huge + local LimitFree = true + if ccx0 then + local a, b, c, d = floor(ccx0 - ox), floor(ccy0 - oy), floor(ccx1 - ox), floor(ccy1 - oy) + if a < LimitX0 or b < LimitY0 or c > LimitX1 or d > LimitY1 then LimitFree = false end + ex0, ey0, ex1, ey1 = min(ex0, a), min(ey0, b), max(ex1, c), max(ey1, d) + end + local ci = 0 + for _, pcmd in draw_list.CmdBuffer:iter() do + ci += 1 + CmdUnclipped[ci], CmdKind[ci] = false, 0 + if pcmd.UserCallback ~= nil then + pcmd.UserCallback(draw_list, pcmd) + elseif pcmd.ElemCount > 0 then + local clip = pcmd.ClipRect + local rcx0, rcy0, rcx1, rcy1 = floor(clip.x - ox), floor(clip.y - oy), floor(clip.z - ox), + floor(clip.w - oy) + if rcx0 < LimitX0 or rcy0 < LimitY0 or rcx1 > LimitX1 or rcy1 > LimitY1 then LimitFree = false end + if rcx0 < ex0 then ex0 = rcx0 end + if rcy0 < ey0 then ey0 = rcy0 end + if rcx1 > ex1 then ex1 = rcx1 end + if rcy1 > ey1 then ey1 = rcy1 end + local cx0, cy0 = max(rcx0, LimitX0), max(rcy0, LimitY0) + local cx1, cy1 = min(rcx1, LimitX1), min(rcy1, LimitY1) + local kind = 1 + if ccx0 and clip.x >= ccx0 and clip.y >= ccy0 and clip.z <= ccx1 and clip.w <= ccy1 then + kind = 2 + SeenContent = true + if clip.x == ccx0 and clip.y == ccy0 and clip.z == ccx1 and clip.w == ccy1 then + -- clipped by the layer's clip frame instead: partly visible rows stay hash-stable while scrolling + cx0, cy0, cx1, cy1 = LimitX0, LimitY0, LimitX1, LimitY1 + end + elseif SeenContent then + kind = 3 + end + CmdKind[ci] = kind + local CmdFree, cex0, cey0, cex1, cey1 = + cx1 > cx0 and cy1 > cy0, math.huge, math.huge, -math.huge, -math.huge + if cx1 > cx0 and cy1 > cy0 then + local tex_id = pcmd:GetTexID() + local t = BackendData.Textures[tex_id] + local vo = pcmd.VtxOffset + local i, last = pcmd.IdxOffset + 1, pcmd.IdxOffset + pcmd.ElemCount + while i <= last do + local ia, ic = idx[i], idx[i + 2] + local va, vb, vc = (vo + ia - 1) * VTX_STRIDE, (vo + idx[i + 1] - 1) * VTX_STRIDE, + (vo + ic - 1) * VTX_STRIDE + local vd = false + local gk = false + local pax, pay = readf64(vbuf, va), readf64(vbuf, va + 8) + local pbx, pby = readf64(vbuf, vb), readf64(vbuf, vb + 8) + local pcx, pcy = readf64(vbuf, vc), readf64(vbuf, vc + 8) + local bx0, by0, bx1, by1 + if i + 5 <= last and idx[i + 3] == ia and idx[i + 4] == ic then + local d = (vo + idx[i + 5] - 1) * VTX_STRIDE + local pdx, pdy = readf64(vbuf, d), readf64(vbuf, d + 8) + if pay == pby and pbx == pcx and pcy == pdy and pdx == pax and pax < pbx and pay < pdy then + local col, colb, colc, cold = readu32(vbuf, va + 32), readu32(vbuf, vb + 32), + readu32(vbuf, vc + 32), readu32(vbuf, d + 32) + local tax, tay = readf64(vbuf, va + 16), readf64(vbuf, va + 24) + local tbx, tby = readf64(vbuf, vb + 16), readf64(vbuf, vb + 24) + local tcx, tcy = readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) + local tdx, tdy = readf64(vbuf, d + 16), readf64(vbuf, d + 24) + if colb == col and colc == col and cold == col then + if tbx == tcx and tby == tay and tdx == tax and tdy == tcy then vd = d end + elseif tax == tbx and tax == tcx and tax == tdx and tay == tby and tay == tcy + and tay == tdy then + if colb == col and cold == colc then + vd = d + gk = 1 + elseif cold == col and colb == colc then + vd = d + gk = 2 + end + end + if vd then + bx0, by0 = ceil(pax - ox - 0.5), ceil(pay - oy - 0.5) + bx1, by1 = ceil(pcx - ox - 0.5), ceil(pcy - oy - 0.5) + end + end + end + if vd then + i = i + 6 + else + bx0, by0 = floor(min(pax, pbx, pcx) - ox), floor(min(pay, pby, pcy) - oy) + bx1, by1 = ceil(max(pax, pbx, pcx) - ox) + 1, ceil(max(pay, pby, pcy) - oy) + 1 + i = i + 3 + end + if bx0 < cx0 or by0 < cy0 or bx1 > cx1 or by1 > cy1 then CmdFree = false end + if bx0 < cex0 then cex0 = bx0 end + if by0 < cey0 then cey0 = by0 end + if bx1 > cex1 then cex1 = bx1 end + if by1 > cey1 then cey1 = by1 end + if bx0 < ex0 then ex0 = bx0 end + if by0 < ey0 then ey0 = by0 end + if bx1 > ex1 then ex1 = bx1 end + if by1 > ey1 then ey1 = by1 end + if bx0 < LimitX0 or by0 < LimitY0 or bx1 > LimitX1 or by1 > LimitY1 then LimitFree = false end + if bx0 < cx0 then bx0 = cx0 end + if by0 < cy0 then by0 = cy0 end + if bx1 > cx1 then bx1 = cx1 end + if by1 > cy1 then by1 = cy1 end + if bx0 < bx1 and by0 < by1 then + n = n + 1 + PrimA[n], PrimB[n], PrimC[n], PrimD[n], PrimTexture[n], PrimGradient[n], PrimTexId[n], + PrimVtxBuffer[n] = va, vb, vc, vd, t, gk, tex_id, vbuf + PrimClipX0[n], PrimClipY0[n], PrimClipX1[n], PrimClipY1[n] = cx0, cy0, cx1, cy1 + PrimBoundsX0[n], PrimBoundsY0[n], PrimBoundsX1[n], PrimBoundsY1[n] = bx0, by0, bx1, by1 + PrimKind[n] = kind + end + end + end + if cex0 > cex1 then cex0, cey0, cex1, cey1 = 0, 0, 0, 0 end + CmdUnclipped[ci] = CmdFree + CmdBoundsX0[ci], CmdBoundsY0[ci], CmdBoundsX1[ci], CmdBoundsY1[ci] = cex0, cey0, cex1, cey1 + end + end + return n, LimitFree, ex0, ey0, ex1, ey1 +end + +@native +local function DrawLists(BackendData, draw_list, first, n, z, ox, oy, force, LimitX0, LimitY0, LimitX1, LimitY1) + local set = BackendData.Layers[draw_list] + local ListDeferred = false + local Kind1Count, Kind2Count, Kind3Count = 0, 0, 0 + local Kind1X, Kind1Y, Kind3X, Kind3Y = math.huge, math.huge, math.huge, math.huge + for p = first, n do + local k = PrimKind[p] + if k == 1 then + Kind1Count += 1 + LayerPrims1[Kind1Count] = p + if PrimBoundsX0[p] < Kind1X then Kind1X = PrimBoundsX0[p] end + if PrimBoundsY0[p] < Kind1Y then Kind1Y = PrimBoundsY0[p] end + elseif k == 2 then + Kind2Count += 1 + LayerPrims2[Kind2Count] = p + else + Kind3Count += 1 + LayerPrims3[Kind3Count] = p + if PrimBoundsX0[p] < Kind3X then Kind3X = PrimBoundsX0[p] end + if PrimBoundsY0[p] < Kind3Y then Kind3Y = PrimBoundsY0[p] end + end + end + if Kind1Count > 0 then + z += 1 + if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 1), LayerPrims1, Kind1Count, Kind1X, Kind1Y, ox, + oy, force, z) then + ListDeferred = true + end + elseif set and set[1] then HideLayer(set[1]) end + if Kind2Count > 0 then + local ccx0 = draw_list._ContentClipX0 + local ContentX0, ContentY0, ContentX1, ContentY1 + if ccx0 then + ContentX0, ContentY0 = max(floor(ccx0 - ox), LimitX0), max(floor(draw_list._ContentClipY0 - oy), LimitY0) + ContentX1, ContentY1 = min(floor(draw_list._ContentClipX1 - ox), LimitX1), + min(floor(draw_list._ContentClipY1 - oy), LimitY1) + end + z += 1 + if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 2), LayerPrims2, Kind2Count, + floor(draw_list._ScrollOriginX - ox), floor(draw_list._ScrollOriginY - oy), ox, oy, force, z, + ContentX0, ContentY0, ContentX1, ContentY1) then ListDeferred = true end + elseif set and set[2] then HideLayer(set[2]) end + if Kind3Count > 0 then + z += 1 + if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 3), LayerPrims3, Kind3Count, Kind3X, Kind3Y, ox, + oy, force, z) then + ListDeferred = true + end + elseif set and set[3] then HideLayer(set[3]) end + return z, ListDeferred +end + +-- Overlay frames are only hidden (the user owns them); unused layers hidden, long unused ones freed +local function SweepLayers(BackendData, FrameNo) + for frame, shown in pairs(BackendData.OverlayShown) do + if shown ~= FrameNo then + frame.Visible = false + BackendData.OverlayShown[frame] = nil + end + end + table.clear(BackendData.Overlays) + + for draw_list, set in pairs(BackendData.Layers) do + if set.LastUsed ~= FrameNo then + set.SnapOK = false + for kind = 1, 3 do if set[kind] then HideLayer(set[kind]) end end + if FrameNo - set.LastUsed > LAYER_KEEP_FRAMES then + DestroyLayerSet(set) + BackendData.Layers[draw_list] = nil + end + end + end +end + +function M.RenderDrawData(draw_data) + local BackendData = GetBackendData() + PB("ImGui RenderDrawData") + BackendData.FrameStartTime = os.clock() + if EditableImages.StageTiming then + EditableImages.StageFrame = { Compare = 0, Collect = 0, Hash = 0, Raster = 0, Upload = 0, Other = 0, Total = 0, + TilesRasterized = 0, PixelsRasterized = 0, Uploads = 0, TilesCreated = 0, TilesFreed = 0 } end + BackendData.FrameTiles = 0 + -- the first dirty tile of a frame is always redrawn (progress), the rest within the budget + BackendData.RedrawStarted = false + BackendData.Stale = nil + + UpdateTextures(draw_data) + if not RenderRateAllows(BackendData, draw_data) then + PE() + return + end + + local ScreenWidth, ScreenHeight = floor(draw_data.DisplaySize.x), floor(draw_data.DisplaySize.y) + if ScreenWidth <= 0 or ScreenHeight <= 0 then + PE() + return + end + local ox, oy = draw_data.DisplayPos.x, draw_data.DisplayPos.y + local LimitX0, LimitY0, LimitX1, LimitY1 = -CLIP_PAD, -CLIP_PAD, ScreenWidth + CLIP_PAD, ScreenHeight + CLIP_PAD + BackendData.FrameNo += 1 + local FrameNo = BackendData.FrameNo + local force = BackendData.ForceRedraw + BackendData.ForceRedraw = false + Parallel.Active = Parallel.On and not Parallel.Config.Inline + + local n = 0 + local z = 0 + local AnyDeferred = false + for _, draw_list in draw_data.CmdLists:iter() do + PB("ImGui unchanged check") + if EditableImages.StageTiming then EditableImages.BeginStage() end + local set = BackendData.Layers[draw_list] + local same, sdx, sdy = 0, 0, 0 + if not force then same, sdx, sdy = CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) end + if same ~= 0 then + z = ReuseDrawList(BackendData, set, draw_list, same, sdx, sdy, z, ox, oy, ScreenWidth, ScreenHeight) + if EditableImages.StageTiming then EditableImages.EndStage("Compare") end + PE() + continue + end + if EditableImages.StageTiming then EditableImages.EndStage("Compare") end + PE() + + PB("ImGui collect") + if EditableImages.StageTiming then EditableImages.BeginStage() end + local first = n + 1 + local LimitFree, ex0, ey0, ex1, ey1 + n, LimitFree, ex0, ey0, ex1, ey1 = CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, LimitX1, + LimitY1) + if EditableImages.StageTiming then EditableImages.EndStage("Collect") end + PE() + + local ListDeferred + z, ListDeferred = DrawLists(BackendData, draw_list, first, n, z, ox, oy, force, LimitX0, LimitY0, LimitX1, + LimitY1) + set = BackendData.Layers[draw_list] + -- deferred tiles: not "unchanged" next frame, so they get redrawn + if set then + set.LastUsed = FrameNo + if ListDeferred then set.SnapOK = false else + Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) + set.SnapLimitFree = LimitFree + set.SnapExtentX0, set.SnapExtentY0, set.SnapExtentX1, set.SnapExtentY1 = ex0, ey0, ex1, ey1 + end + end + if ListDeferred then AnyDeferred = true end + z = PlaceOverlays(BackendData, draw_list, z, ox, oy) + end + + SweepLayers(BackendData, FrameNo) + -- drop references so old vertex tables can be collected + for k = n + 1, BackendData.LastPrimCount do PrimTexture[k], PrimVtxBuffer[k] = nil, nil end + BackendData.LastPrimCount = n + -- Tiles left for later: if the app doesn't submit a new frame, Heartbeat finishes them from this draw data + if AnyDeferred then + BackendData.Stale = draw_data + BackendData.StaleHeartbeat = BackendData.HeartbeatCount + end + if Parallel.Active then + Parallel.Flush() + end + if EditableImages.StageTiming and EditableImages.StageFrame then + local f = EditableImages.StageFrame + f.Raster -= f.Upload + f.Total = os.clock() - BackendData.FrameStartTime + f.Other = f.Total - f.Compare - f.Collect - f.Hash - f.Raster - f.Upload + BackendData.FrameStats = f + end + PE() +end + +return M diff --git a/backends/roblox/textures.lua b/backends/roblox/textures.lua new file mode 100644 index 0000000..8a5019b --- /dev/null +++ b/backends/roblox/textures.lua @@ -0,0 +1,169 @@ +-- Texture records, the module-wide EditableImage budget, profiling labels and stage timing stats. +local Raster = IM_INCLUDE("roblox/raster.lua") + +local AssetService = game:GetService("AssetService") +local writeu32 = buffer.writeu32 +local TILE = Raster.TILE + +local M = {} + +-- One table, not locals: shared by every context and module. FreeTile is set by layers.lua (Evict needs it). +local EditableImages = { + Cap = 64 * 1024 * 1024, Bytes = 0, Count = 0, ImageBytes = setmetatable({}, { __mode = "k" }), + Pool = {}, PoolMax = 16, + Backends = setmetatable({}, { __mode = "k" }), + LastTextureId = 0, KEEP_FRAMES = 30, + StageTiming = false, +} +M.EditableImages = EditableImages + +local ProfileBegin, ProfileEnd = debug.profilebegin, debug.profileend +local Profiling = false +function M.PB(name) if Profiling then ProfileBegin(name) end end +function M.PE() if Profiling then ProfileEnd() end end +function M.SetProfiling(enabled) Profiling = enabled and true or false end +function M.IsProfiling() return Profiling end + +-- StageTiming on: RenderDrawData accumulates os.clock per stage into StageFrame (GetStats().Frame) +function EditableImages.BeginStage() EditableImages.StageStart = os.clock() end +function EditableImages.EndStage(stage) + local f = EditableImages.StageFrame + if f then f[stage] += os.clock() - EditableImages.StageStart end +end +function EditableImages.AddStat(name, n) + local f = EditableImages.StageFrame + if f then f[name] += n end +end + +function M.GetBackendData() + return ImGui.GetCurrentContext() and ImGui.GetIO().BackendPlatformUserData or nil +end + +@native +local function CopyTexturePixels(tex, dst, x, y, w, h) + local bpp, tex_w = tex.BytesPerPixel, tex.Width + for row = 0, h - 1 do + local src, src_base = tex:GetPixelsAt(x, y + row) + local dst_off = ((y + row) * tex_w + x) * 4 + if bpp == 4 then + for i = 0, w - 1 do + local s = src_base + i * 4 + writeu32(dst, dst_off + i * 4, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216) + end + else -- Alpha8: white with alpha + for i = 0, w - 1 do + writeu32(dst, dst_off + i * 4, 16777215 + src[src_base + i] * 16777216) + end + end + end +end + +-- Shared by every context: a font atlas shared between contexts is created under one, drawn under the others +local Records = {} +M.Records = Records + +local function CreateTextureRecord(tex) + local t = { Buffer = buffer.create(tex.Width * tex.Height * 4), Width = tex.Width, Height = tex.Height } + CopyTexturePixels(tex, t.Buffer, 0, 0, tex.Width, tex.Height) + EditableImages.LastTextureId += 1 + Records[EditableImages.LastTextureId] = t + tex.BackendUserData = EditableImages.LastTextureId + tex:SetTexID(EditableImages.LastTextureId) + tex:SetStatus(ImTextureStatus.OK) +end + +function M.UpdateTexture(tex) + if tex.Status == ImTextureStatus.WantCreate then + CreateTextureRecord(tex) + elseif tex.Status == ImTextureStatus.WantUpdates then + local t = Records[tex.BackendUserData] + if t == nil or t.Width ~= tex.Width or t.Height ~= tex.Height then + CreateTextureRecord(tex) + return + end + for _, r in tex.Updates:iter() do + CopyTexturePixels(tex, t.Buffer, r.x, r.y, r.w, r.h) + end + t.V = (t.V or 0) + 1 -- parallel workers hold copies, resent when this changes + tex:SetStatus(ImTextureStatus.OK) + elseif tex.Status == ImTextureStatus.WantDestroy then + if tex.BackendUserData then + Records[tex.BackendUserData] = nil + tex.BackendUserData = nil + end + tex:SetTexID(ImTextureID_Invalid) + tex:SetStatus(ImTextureStatus.Destroyed) + end +end + +-- User texture from RGBA8 pixels. Ids are never reused, so cached tiles can't show a stale image. +function ImGui_ImplRoblox_CreateTexture(pixels, w, h) + EditableImages.LastTextureId += 1 + Records[EditableImages.LastTextureId] = { Buffer = pixels, Width = w, Height = h } + return ImTextureRef(EditableImages.LastTextureId) +end + +function ImGui_ImplRoblox_DestroyTexture(tex_ref) + Records[tex_ref._TexID] = nil +end + +-- Every EditableImage goes through Create/Destroy, counted against Cap. Over the cap (or CreateEditableImage failing): +-- evict idle tiles, retry once; still nothing -> nil, the caller skips the tile this frame. +function EditableImages.Create(w, h) + local need = w * h * 4 + if need > EditableImages.Cap then return nil end + for attempt = 1, 2 do + if EditableImages.Bytes + need <= EditableImages.Cap then + local ok, img = pcall(AssetService.CreateEditableImage, AssetService, { Size = Vector2.new(w, h) }) + if ok and img then + EditableImages.ImageBytes[img] = need + EditableImages.Bytes += need + EditableImages.Count += 1 + return img + end + if attempt == 1 then EditableImages.Evict(math.huge) end -- engine refused: free everything evictable + elseif attempt == 1 then + EditableImages.Evict(EditableImages.Bytes + need - EditableImages.Cap) + end + end + return nil +end + +function EditableImages.Destroy(img) + local s = EditableImages.ImageBytes[img] + if s then + EditableImages.ImageBytes[img] = nil + EditableImages.Bytes -= s + EditableImages.Count -= 1 + end + img:Destroy() +end + +-- The free list first, then idle tiles (not shown, not used this frame) of every context +function EditableImages.Evict(need) + local freed = 0 + while freed < need and #EditableImages.Pool > 0 do + local t = table.remove(EditableImages.Pool) + EditableImages.Destroy(t.Image) + t.Label:Destroy() + freed += TILE * TILE * 4 + end + if freed >= need then return end + for BackendData in EditableImages.Backends do + for _, set in pairs(BackendData.Layers) do + for kind = 1, 3 do + local l = set[kind] + if l then + for k, t in pairs(l.Tiles) do + if t.Used ~= BackendData.FrameNo and not (t.Visible and l.Visible) then + EditableImages.FreeTile(l, k) + freed += TILE * TILE * 4 + end + end + end + end + end + end +end + +return M diff --git a/backends/roblox/worker.luau b/backends/roblox/worker.luau new file mode 100644 index 0000000..cf4c992 --- /dev/null +++ b/backends/roblox/worker.luau @@ -0,0 +1,20 @@ +-- Parallel raster worker (Actor LocalScript). The build inlines raster.lua for the Raster line. +local Actor = script:GetActor() +if not Actor then + return +end + +local Raster = require(script.Parent:WaitForChild("Raster")) +local Done = Actor:WaitForChild("Done") +local Textures = {} + +Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength) + for _, Texture in TexUpdates do + Textures[Texture[1]] = { Buffer = Texture[2], Width = Texture[3], Height = Texture[4] } + end + local Results = Raster.RasterJobs(Prims, Tiles, TileLength, Textures) + task.synchronize() + Done:Fire(Id, Results) +end) + +Actor:SetAttribute("Ready", true) diff --git a/build/ImGui.linemap.json b/build/ImGui.linemap.json index 38bb745..35c6118 100644 --- a/build/ImGui.linemap.json +++ b/build/ImGui.linemap.json @@ -1 +1 @@ -[[46, "imgui.lua"], [22675, "imgui_demo.lua"], [34533, "imgui_draw.lua"], [42860, "imgui_h.lua"], [45857, "imgui_impl_roblox.lua"], [47509, "imgui_impl_roblox_fonts.lua"], [53912, "imgui_internal.lua"], [57884, "imgui_tables.lua"], [62976, "imgui_widgets.lua"], [75210, "imstb_rectpack.lua"], [75874, "imstb_textedit.lua"], [77416, "imstb_truetype.lua"], [80204, "imstd_minstdio.lua"]] \ No newline at end of file +[[46, "imgui.lua"], [22647, "imgui_demo.lua"], [34504, "imgui_draw.lua"], [42828, "imgui_h.lua"], [45827, "roblox/raster.lua"], [46303, "roblox/textures.lua"], [46474, "roblox/layers.lua"], [46811, "roblox/overlays.lua"], [46892, "roblox/render.lua"], [47737, "roblox/parallel.lua"], [48136, "imgui_impl_roblox.lua"], [48623, "imgui_impl_roblox_fonts.lua"], [55026, "imgui_internal.lua"], [58992, "imgui_tables.lua"], [64084, "imgui_widgets.lua"], [76318, "imstb_rectpack.lua"], [76982, "imstb_textedit.lua"], [78524, "imstb_truetype.lua"], [81312, "imstd_minstdio.lua"]] \ No newline at end of file diff --git a/build/ImGui.luau b/build/ImGui.luau index c3cbb71..3f9ae9e 100644 --- a/build/ImGui.luau +++ b/build/ImGui.luau @@ -1,7 +1,7 @@ --!optimize 2 -- GENERATED by tools/bundle.py from *.lua, backends/, fonts/ - do not edit -local ImGui, ImVec2, ImVec4, ImRect, ImVec2_Copy, HelpMarker, IMGUI_DEMO_MARKER, ImGuiTableFlags, ImStd, ImVector, ImDrawFlags, ImGuiInputFlags, ImRect_Copy, ImStb, ImGuiDataType, IM_TRUNC, ImGuiKey, ImGuiStyleVarInfo, ImVec2_CopyV, IM_ASSERT_USER_ERROR, ImGuiHoveredFlags, ImHashStr, IM_ASSERT_USER_ERROR_RET, ImIsPowerOfTwo, ImS32, ImGuiColorEditFlags, ImVec4_Copy, ImAbs, ExampleAppConsoleMT, IM_ROUND, ImFormatString, ImGuiTableColumnFlags, ImGuiTreeNodeFlags, PopStyleCompact, PushStyleCompact, IM_ASSERT_PARANOID, ImU16, ExampleNames, ImGuiWindowFlags, ImGuiItemFlags, ImGui_ImplRoblox_GetBackendData, stbte, ImColor, ImCos, ImGuiButtonFlags, ImGuiDebugLogFlags, ImGuiListClipper, ImGuiLocKey, ImU32, ExampleTreeFuncs, ImS16, _PathArcToFastExXY, ImGuiMultiSelectFlags, ImSin, ImGuiTabBarFlags, ImLengthSqr, ImUpperPowerOfTwo, IM_F32_TO_INT8_SAT, ImFontAtlasPackGetRect, ImS64, DockSettingsRenameNodeReferences, ExampleDualListBoxMT, IM_DRAWLIST_TEX_LINES_WIDTH_MAX, ImCeil, ImFabs, ImGuiCol, ImGuiSelectionBasicStorage, ImS8, ImU8, ExampleAppPropertyEditorMT, ImGuiChildFlags, ImGuiDockNodeFlags, ImGuiLastItemData_Copy, IMGUI_DEBUG_LOG_IO, ImAddClampOverflow, ImGuiScrollFlags, ImLog, ImMemchr, ImStrByte, ImSubClampOverflow, ExampleSelectionWithDeletionMT, IMGUI_DEBUG_LOG_VIEWPORT, ImFontCalcWordWrapPositionEx, ImGuiInputEvent, ImGuiPackedDate, ImGuiTextBuffer, ImHashData, ImPow, ImTrunc64, ImU64, CustomConstraints, ExampleAppLogMT, IMGUI_DEBUG_LOG_FONT, IMGUI_DEBUG_LOG_SELECTION, IMGUI_DISABLE_DEBUG_TOOLS, ImFontAtlasBuildInit, ImFontAtlasFontDestroyOutput, ImGuiComboFlags, ImGuiLastItemData, ImGuiPayload_IsDataType, ImGuiPopupFlags, ImGuiSliderFlags, ImGuiTextFilter, ImRotate, ImSqrt, ImTextClassifierSetCharClass, ImTextureRef, MyDocument, ShowExampleMenuFile, CalcCornerArcStepAndCount, CalcNextScrollFromScrollTargetAndClamp, DataTypeFormatStringCached, IMGUI_PAYLOAD_TYPE_WINDOW, IMGUI_VERSION, ImCharIsBlankW, ImCharIsSeparatorW, ImFmod, ImFontAtlasBakedAddFontGlyph, ImFontAtlasPackAddRect, ImFontBaked_BuildLoadGlyph, ImFontConfig, ImGuiInputTextFlags, ImGuiLogFlags, ImGuiNavMoveFlags, ImGuiStyle_Copy, ImVec1_Copy, ExampleAsset_s_current_sort_specs, ExampleMemberInfo, ExampleTree_CreateNode, IMGUI_PAYLOAD_TYPE_COLOR_4F, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC, IM_F32_TO_INT8_UNBOUND, IM_PI, ImCharIsBlankA, ImFontAtlasBuildNotifySetFont, ImFontAtlasBuildRenderBitmapFromString, ImFontAtlasFontDestroySourceData, ImFontAtlasFontDiscardBakes, ImFontAtlasFontSourceAddToFont, ImFontAtlasFontSourceInit, ImFontAtlasRectId_GetIndex, ImFontAtlasTextureAdd, ImFontAtlasTextureBlockQueueUpload, ImFontAtlasTextureGrow, ImFontBaked_BuildGrowIndex, ImFontGlyph, ImGuiTableColumn, ImGuiWindowClass, ImGui_ImplRoblox_RenderDrawData, ImParseFormatFindStart, ImRect_CopyFromV4, ImTextureRect, MyItem_s_current_sort_specs, stb_textedit_key, stbtt_GetGlyphBitmapBoxSubpixel, DockSettingsHandler_ClearAll, EditTableSizingFlags, ExampleSelectionWithDeletion, FormatCached, IMGUI_DEBUG_LOG_TABLE +local ImGui, ImVec2, ImVec4, ImRect, ImVec2_Copy, HelpMarker, IMGUI_DEMO_MARKER, ImGuiTableFlags, ImStd, ImVector, ImDrawFlags, ImGuiInputFlags, ImRect_Copy, ImStb, ImGuiDataType, IM_TRUNC, ImGuiKey, ImGuiStyleVarInfo, ImVec2_CopyV, IM_ASSERT_USER_ERROR, ImGuiHoveredFlags, ImHashStr, IM_ASSERT_USER_ERROR_RET, ImIsPowerOfTwo, ImS32, ImGuiColorEditFlags, ImVec4_Copy, ImAbs, ExampleAppConsoleMT, IM_ROUND, ImFormatString, ImGuiTableColumnFlags, ImGuiTreeNodeFlags, PopStyleCompact, PushStyleCompact, IM_ASSERT_PARANOID, ImU16, ExampleNames, ImGuiWindowFlags, ImGuiItemFlags, stbte, ImColor, ImCos, ImGuiButtonFlags, ImGuiDebugLogFlags, ImGuiListClipper, ImGuiLocKey, ImU32, ExampleTreeFuncs, ImS16, _PathArcToFastExXY, ImGuiMultiSelectFlags, ImSin, ImGuiTabBarFlags, ImLengthSqr, ImUpperPowerOfTwo, IM_F32_TO_INT8_SAT, ImFontAtlasPackGetRect, ImS64, DockSettingsRenameNodeReferences, ExampleDualListBoxMT, IM_DRAWLIST_TEX_LINES_WIDTH_MAX, ImCeil, ImFabs, ImGuiCol, ImGuiSelectionBasicStorage, ImS8, ImU8, ExampleAppPropertyEditorMT, ImGuiChildFlags, ImGuiDockNodeFlags, ImGuiLastItemData_Copy, IMGUI_DEBUG_LOG_IO, ImAddClampOverflow, ImGuiScrollFlags, ImLog, ImMemchr, ImStrByte, ImSubClampOverflow, ExampleSelectionWithDeletionMT, IMGUI_DEBUG_LOG_VIEWPORT, ImFontCalcWordWrapPositionEx, ImGuiInputEvent, ImGuiPackedDate, ImGuiTextBuffer, ImHashData, ImPow, ImTrunc64, ImU64, CustomConstraints, ExampleAppLogMT, IMGUI_DEBUG_LOG_FONT, IMGUI_DEBUG_LOG_SELECTION, IMGUI_DISABLE_DEBUG_TOOLS, ImFontAtlasBuildInit, ImFontAtlasFontDestroyOutput, ImGuiComboFlags, ImGuiLastItemData, ImGuiPayload_IsDataType, ImGuiPopupFlags, ImGuiSliderFlags, ImGuiTextFilter, ImRotate, ImSqrt, ImTextClassifierSetCharClass, ImTextureRef, MyDocument, ShowExampleMenuFile, CalcCornerArcStepAndCount, CalcNextScrollFromScrollTargetAndClamp, DataTypeFormatStringCached, IMGUI_PAYLOAD_TYPE_WINDOW, IMGUI_VERSION, ImCharIsBlankW, ImCharIsSeparatorW, ImFmod, ImFontAtlasBakedAddFontGlyph, ImFontAtlasPackAddRect, ImFontBaked_BuildLoadGlyph, ImFontConfig, ImGuiInputTextFlags, ImGuiLogFlags, ImGuiNavMoveFlags, ImGuiStyle_Copy, ImVec1_Copy, ExampleAsset_s_current_sort_specs, ExampleMemberInfo, ExampleTree_CreateNode, IMGUI_PAYLOAD_TYPE_COLOR_4F, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC, IM_F32_TO_INT8_UNBOUND, IM_PI, ImCharIsBlankA, ImFontAtlasBuildNotifySetFont, ImFontAtlasBuildRenderBitmapFromString, ImFontAtlasFontDestroySourceData, ImFontAtlasFontDiscardBakes, ImFontAtlasFontSourceAddToFont, ImFontAtlasFontSourceInit, ImFontAtlasRectId_GetIndex, ImFontAtlasTextureAdd, ImFontAtlasTextureBlockQueueUpload, ImFontAtlasTextureGrow, ImFontBaked_BuildGrowIndex, ImFontGlyph, ImGuiTableColumn, ImGuiWindowClass, ImParseFormatFindStart, ImRect_CopyFromV4, ImTextureRect, MyItem_s_current_sort_specs, stb_textedit_key, stbtt_GetGlyphBitmapBoxSubpixel, DockSettingsHandler_ClearAll, EditTableSizingFlags, ExampleSelectionWithDeletion, FormatCached, IMGUI_DEBUG_LOG_TABLE, IMGUI_PAYLOAD_TYPE_COLOR_3F, IM_FREE local type, mathMin, mathMax, mathFloor, mathCeil, bitOr, bitLShift = type, math.min, math.max, math.floor, math.ceil, bit32.bor, bit32.lshift local function IM_COL32(R, G, B, A) return (bitOr(bitLShift(A, 24 --[[IM_COL32_A_SHIFT]]), bitLShift(B, 16 --[[IM_COL32_B_SHIFT]]), bitLShift(G, 8 --[[IM_COL32_G_SHIFT]]), bitLShift(R, 0 --[[IM_COL32_R_SHIFT]]))) end @native @@ -284,7 +284,7 @@ __FILES['imgui.lua'] = function() -- - See https://github.com/ocornut/imgui/wiki/Getting-Started, and README.md of this repository. -- - Run and study the examples and demo in imgui_demo.lua to get acquainted with the library. -- - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder --- (backends/imgui_impl_roblox.lua for Roblox, backends/imgui_impl_love.lua for LÖVE). +-- (backends/roblox/imgui_impl_roblox.lua for Roblox, backends/love/imgui_impl_love.lua for LÖVE). -- - Build a single file with tools/bundle.py: build/ImGui.luau (Roblox ModuleScript) or build/imgui_love.lua (LÖVE), -- then require() / load it. All exported names (ImGui, ImVec2, ImVec4, IM_COL32, every ImGui*Flags enum...) are fields of the returned table. -- - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. @@ -387,9 +387,9 @@ __FILES['imgui.lua'] = function() -- ------------------------------------ -- -- A backend implements the usual Dear ImGui contract: Init, NewFrame, RenderDrawData, inputs -> io:AddXXXEvent(), --- texture updates via ImTextureData. Adding another Lua host means a new backends/imgui_impl_.lua. +-- texture updates via ImTextureData. Adding another Lua host means a new backends//imgui_impl_.lua. -- -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for basic instructions. --- -> the backends in backends/imgui_impl_roblox.lua and backends/imgui_impl_love.lua are complete implementations. +-- -> the backends in backends/roblox/imgui_impl_roblox.lua and backends/love/imgui_impl_love.lua are complete implementations. -- -- Basic application/backend skeleton: -- @@ -463,13 +463,12 @@ __FILES['imgui.lua'] = function() -- (Core Code) --- Flags: --- IMGUI_DISABLE_OBSOLETE_FUNCTIONS = true -- This flag is not implemented +-- [Port] IMGUI_DISABLE_OBSOLETE_FUNCTIONS = true -- This flag is not implemented --- NOTE: you must implement ImStd.ImFileOpen if you are not in GMod IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS = true -- Don't implement ImStd.ImFileOpen/ImStd.ImFileClose/ImStd.ImFileRead/ImFileWrite so you can implement them yourself IMGUI_DISABLE_DEBUG_TOOLS = false -- Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty -IMGUI_DISABLE_TIME_FUNCTIONS = false -- Disable setting platform_io.Platform_SessionDate from os.date() in Initialize() +IMGUI_DISABLE_TIME_FUNCTIONS = false -- [Port] Disable setting platform_io.Platform_SessionDate from os.date() in Initialize() -- Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be ~= nil. -- - ImGui.CreateContext() will automatically set this pointer if it is nil. @@ -488,9 +487,9 @@ end ImGui = {} -ImStd = {} -- Contains functions that originally don't belong to cpp namespaces +ImStd = {} -- [Port] Contains functions that originally don't belong to cpp namespaces --- IM_INCLUDE(name) is provided by the bundle (see tools/bundle.py): runs the bundled file once, returns its result. +-- [Port] IM_INCLUDE(name) is provided by the bundle (see tools/bundle.py): runs the bundled file once, returns its result. function ImGui._GetTypeFunc() return type end @@ -519,7 +518,7 @@ function ImGui.MemAlloc(constructor, size) end -- IM_FREE() == ImGui.MemFree() --- This does not set `owner[field]` to nil! +-- [Port] This does not set `owner[field]` to nil! --- @param owner table --- @param field string|int function ImGui.MemFree(owner, field) @@ -581,8 +580,8 @@ IM_INCLUDE"imgui_tables.lua" do --[[ [SECTION] imgui_dragdrop (was imgui_dragdrop.lua) ]] --- Dear ImGui --- Drag and drop: 1:1 port of imgui.cpp [SECTION] DRAG AND DROP (docking branch) --- Payload `Data` is any Lua value (no copy is made). `data_size` is optional and only kept for API parity. +-- [Port] Drag and drop: 1:1 port of imgui.cpp [SECTION] DRAG AND DROP (docking branch) +-- [Port] Payload `Data` is any Lua value (no copy is made). `data_size` is optional and only kept for API parity. ------------------------------------------------------------------------------- -- [SECTION] DRAG AND DROP @@ -913,15 +912,15 @@ function ImGui.EndDragDropTarget() if g.DragDropPayload.Delivery then ImGui.ClearDragDrop() end end --- Payload methods (C++ ImGuiPayload members): payload:IsDataType(t) etc. also work through these globals +-- [Port] Payload methods (C++ ImGuiPayload members): payload:IsDataType(t) etc. also work through these globals function ImGui.PayloadIsDataType(payload, t) return ImGuiPayload_IsDataType(payload, t) end end --[[ [SECTION] imgui_dragdrop (was imgui_dragdrop.lua) ]] do --[[ [SECTION] imgui_docking (was imgui_docking.lua) ]] --- Dear ImGui --- Docking: 1:1 port of imgui.cpp [SECTION] DOCKING (docking branch, 1.93 WIP) +-- [Port] Docking: 1:1 port of imgui.cpp [SECTION] DOCKING (docking branch, 1.93 WIP) -- --- Port notes: +-- [Port] Port notes: -- - Main viewport only (no multi-viewports on Roblox): viewport creation/merging code paths are kept where cheap, but -- windows always live in the main viewport. -- - ImGuiDockContext.Nodes (ImGuiStorage in C++) is a Lua table ID -> node. Iterations that upstream does over the @@ -1190,7 +1189,7 @@ end local function IsRectInverted(r) return r.Min.x > r.Max.x or r.Min.y > r.Max.y end ---- Sorted snapshot of node IDs (upstream iterates ImGuiStorage which is sorted by key) +--- [Port] Sorted snapshot of node IDs (upstream iterates ImGuiStorage which is sorted by key) local function DockContextNodesSorted(ctx) local ids = {} for id in pairs(ctx.DockContext.Nodes) do ids[#ids + 1] = id end @@ -1725,7 +1724,7 @@ local function FixLargeWindowsWhenUndocking(size, ref_viewport) end function ImGui.DockContextProcessUndockWindow(ctx, window, clear_persistent_docking_ref) - if clear_persistent_docking_ref == nil then clear_persistent_docking_ref = true end -- C++ default argument + if clear_persistent_docking_ref == nil then clear_persistent_docking_ref = true end -- [Port] C++ default argument if window.DockNode then ImGui.DockNodeRemoveWindow(window.DockNode, window, clear_persistent_docking_ref and 0 or window.DockId) else @@ -1971,7 +1970,7 @@ function ImGui.DockNodeMoveWindows(dst_node, src_node) end -- Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar(). - -- Snapshot: DockNodeAddWindow() won't touch src_node.Windows since window.DockNode is cleared first + -- [Port] Snapshot: DockNodeAddWindow() won't touch src_node.Windows since window.DockNode is cleared first local windows = {} for i = 1, src_node.Windows.Size do windows[i] = src_node.Windows.Data[i] end for _, window in ipairs(windows) do @@ -2670,7 +2669,7 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) end -- If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value - local tabs_unsorted_start = tab_bar.Tabs.Size -- 0-based + local tabs_unsorted_start = tab_bar.Tabs.Size -- [Port] 0-based local tab_n = tab_bar.Tabs.Size - 1 while tab_n >= 0 and bit32.band(tab_bar.Tabs.Data[tab_n + 1].Flags, 8388608 --[[ImGuiTabItemFlags.Unsorted]]) ~= 0 do -- FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting? @@ -2917,12 +2916,12 @@ function ImGui.DockNodeCalcTabBarLayout(node) return out_title_rect, r, window_menu_button_pos, out_close_button_pos end ---- Modifies pos_old/size_old/pos_new/size_new in place (ImVec2 tables) +--- [Port] Modifies pos_old/size_old/pos_new/size_new in place (ImVec2 tables) function ImGui.DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, dir, size_new_desired) local g = ImGui.GetCurrentContext() local dock_spacing = g.Style.ItemInnerSpacing.x local axis = (dir == 0 --[[ImGuiDir.Left]] or dir == 1 --[[ImGuiDir.Right]]) and 1 --[[ImGuiAxis.X]] or 2 --[[ImGuiAxis.Y]] - local a, o = axis, 3 - axis -- the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index + local a, o = axis, 3 - axis -- [Port] the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index pos_new[o] = pos_old[o] size_new[o] = size_old[o] @@ -3407,7 +3406,7 @@ function ImGui.DockNodeTreeUpdateSplitter(node) -- Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally) local axis = node.SplitAxis assert(axis ~= 0 --[[ImGuiAxis.None]]) - local a, o = axis, 3 - axis -- the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index + local a, o = axis, 3 - axis -- [Port] the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index local bb = ImRect(ImVec2(child_0.Pos.x, child_0.Pos.y), ImVec2(child_1.Pos.x, child_1.Pos.y)) bb.Min[a] = bb.Min[a] + child_0.Size[a] bb.Max[o] = bb.Max[o] + child_1.Size[o] @@ -4561,7 +4560,7 @@ DockSettingsHandler_WriteAll = function(ctx, handler, buf) end ------------------------------------------------------------------------------- --- Docking: helpers (imgui_internal.h inlines) + widgets used by docking +-- [Port] Docking: helpers (imgui_internal.h inlines) + widgets used by docking ------------------------------------------------------------------------------- function ImGui.DockNodeGetRootNode(node) @@ -4632,7 +4631,7 @@ function ImGui.RenderArrowDockMenu(draw_list, p_min, sz, col) ImGui.RenderArrowPointingAt(draw_list, p_min + ImVec2(sz * 0.50, sz * 0.85), ImVec2(sz * 0.30, sz * 0.40), 3 --[[ImGuiDir.Down]], col) end --- Upstream CollapseButton (docking branch): replaces the port's simpler version +-- [Port] Upstream CollapseButton (docking branch): replaces the port's simpler version -- The Collapse button also functions as a Dock Menu button. function ImGui.CollapseButton(id, pos, dock_node) local g = ImGui.GetCurrentContext() @@ -4644,7 +4643,6 @@ function ImGui.CollapseButton(id, pos, dock_node) if is_clipped then return pressed end -- Render - --local is_dock_menu = (window.DockNodeAsHost and not window.Collapsed) local bg_col = ImGui.GetColorU32((held and hovered) and 24 --[[ImGuiCol.ButtonActive]] or (hovered and 23 --[[ImGuiCol.ButtonHovered]] or 22 --[[ImGuiCol.Button]])) local text_col = ImGui.GetColorU32(0 --[[ImGuiCol.Text]]) if hovered or held then @@ -4742,7 +4740,7 @@ local TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5, 1.0) -- Multiplied by g.Style.M local IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111 -- Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter. local string = string -ImFormatString = string.format -- TODO: an simplified version that operates on byte tables directly? +ImFormatString = string.format --- @module "imstd_minstdio" ImStd.sscanf = IM_INCLUDE"imstd_minstdio.lua" @@ -4754,47 +4752,34 @@ local bit32 = bit32 -- [SECTION] MISC HELPERS/UTILITIES (File functions) ------------------------------------------------------------------------------- ---- This closes the _file. +--- [Port] This closes the _file. --- @param _file any # File object function IM_FILE_CLOSE(_file) end ---- This returns the size of _file in bytes. +--- [Port] This returns the size of _file in bytes. --- @param _file any # File object --- @return int function IM_FILE_SIZE(_file) return -1 end ---- This writes _str into _file. +--- [Port] This writes _str into _file. --- @param _file any # File object --- @param _str string function IM_FILE_WRITE(_file, _str) end ---- This reads the specified _count of chars and returns them as a binary string. +--- [Port] This reads the specified _count of chars and returns them as a binary string. --- @param _file any # File object --- @param _count int --- @return string function IM_FILE_READ(_file, _count) return "" end ---- This opens the file at _filename in _mode and returns the File object. +--- [Port] This opens the file at _filename in _mode and returns the File object. --- @param _filename string --- @param _mode string # e.g. "rb" --- @return any function ImStd.ImFileOpen(_filename, _mode) end ---- [GMod] Platform specific -if gmod then - IM_FILE_CLOSE = FindMetaTable("File").Close --- @type function - IM_FILE_SIZE = FindMetaTable("File").Size --- @type function - IM_FILE_WRITE = FindMetaTable("File").Write --- @type function - IM_FILE_READ = FindMetaTable("File").Read --- @type function -end - -- Default file functions if not IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS then - --- [GMod] Another Platform specific - if gmod then - function ImStd.ImFileOpen(filename, mode) return file.Open(filename, mode, "GAME") end - end - function ImStd.ImFileClose(f) IM_FILE_CLOSE(f) end function ImStd.ImFileGetSize(f) return IM_FILE_SIZE(f) end @@ -4802,7 +4787,7 @@ if not IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS then --- @param data table # 1-based table to store result data --- @param count int # Amount of bytes to read from `f` function ImStd.ImFileRead(f, data, count) - local CHUNK_SIZE = 8000 -- We don't read byte by byte + local CHUNK_SIZE = 8000 -- [Port] We don't read byte by byte local offset = 0 while offset < count do @@ -4918,7 +4903,7 @@ local ImGuiResizeGripDef = { -- Data for resizing from borders -- InnerDir: Normal toward inside, SegmentN1/SegmentN2: End positions, normalized (0,0: upper left), OuterAngle: Angle toward outside ---- [1] Left, [2] Right, [3] Up, [4] Down +--- [Port] [1] Left, [2] Right, [3] Up, [4] Down local ImGuiResizeBorderDef = { {InnerDir = ImVec2( 1, 0), SegmentN1 = ImVec2( 0, 1), SegmentN2 = ImVec2( 0, 0), OuterAngle = IM_PI * 1.00}, -- Left {InnerDir = ImVec2(-1, 0), SegmentN1 = ImVec2( 1, 0), SegmentN2 = ImVec2( 1, 1), OuterAngle = IM_PI * 0.00}, -- Right @@ -4983,13 +4968,12 @@ end -- Zero-terminated string hash, with support for ### to reset back to seed value. -- e.g. "label###id" outputs the same hash as "id" (and "label" is generally displayed by the UI functions) --- Use FNV1a, as one ImGui FIXME suggested +-- [Port] Use FNV1a, as one ImGui FIXME suggested --- @param str string --- @param size int? --- @param seed int? --- @return int -- [Luau] memo for whole-string hashes: labels are re-hashed with the same seed every frame. --- ponytail: whole-memo reset at HASH_MEMO_MAX entries, LRU if ID churn makes it thrash local hash_memo, hash_memo_n, HASH_MEMO_MAX = {}, 0, 16384 local ImHashStrRaw @@ -5014,7 +4998,7 @@ end function ImHashStrRaw(str, size, seed) if str == "" or size == 0 then - return seed -- need to match cpp code edge case behavior while using FNV ourselves + return seed -- [Port] need to match cpp code edge case behavior while using FNV ourselves end local FNV_OFFSET_BASIS = 0x811C9DC5 @@ -5194,7 +5178,6 @@ function ImStd.ImTextFindValidUtf8CodepointEnd(text, in_text_start, in_text_end, local prev = ImStd.ImTextFindPreviousUtf8Codepoint(text, in_text_start, in_p) local prev_c_len, prev_c = ImStd.ImTextCharFromUtf8(text, prev, in_text_end) - -- Check if the previous character is valid and fits within the range if prev_c ~= 65533 --[[IM_UNICODE_CODEPOINT_INVALID]] and prev_c_len <= (in_p - prev) then return in_p end @@ -5378,7 +5361,7 @@ end -- Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible. --- @param buf char[] function ImStd.ImStrTrimBlanks(buf) - local p = 1 -- buf_begin + local p = 1 -- [Port] buf_begin while buf[p] == 32 or buf[p] == 9 do -- Leading blanks p = p + 1 end @@ -5717,7 +5700,7 @@ local GLocalizationEntriesEnUS = { } -- [Luau] Default platform handlers (upstream: next to the metrics section; defined here so Initialize() can see the local). --- Roblox has no shell: IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS path. Default clipboard/IME handlers are OS-specific: left nil +-- [Port] Roblox has no shell: IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS path. Default clipboard/IME handlers are OS-specific: left nil -- (the backends install their own clipboard handlers). local function Platform_OpenInShellFn_DefaultImpl(ctx, path) return false end @@ -5951,7 +5934,7 @@ end ------------------------------------------------------------------------------- -- [SECTION] SETTINGS --- (in-memory .ini; Roblox has no disk) +-- [Port] (in-memory .ini; Roblox has no disk) ------------------------------------------------------------------------------- -- - UpdateSettings() [Internal] -- - MarkIniSettingsDirty() [Internal] @@ -5982,7 +5965,7 @@ function ImGui.UpdateSettings() if g.SettingsDirtyTimer > 0.0 then g.SettingsDirtyTimer = g.SettingsDirtyTimer - g.IO.DeltaTime if g.SettingsDirtyTimer <= 0.0 then - -- No disk: always let the user know they can call SaveIniSettingsToMemory() + -- [Port] No disk: always let the user know they can call SaveIniSettingsToMemory() g.IO.WantSaveIniSettings = true -- Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves. g.SettingsDirtyTimer = 0.0 end @@ -6060,7 +6043,7 @@ function ImGui.LoadIniSettingsFromDisk(ini_filename) end -- Zero-tolerance, no error reporting, cheap .ini parsing --- Set ini_size==0 (or nil) to use the whole string (Lua strings know their length). +-- [Port] Set ini_size==0 (or nil) to use the whole string (Lua strings know their length). function ImGui.LoadIniSettingsFromMemory(ini_data, ini_size) local g = GImGui assert(g.Initialized) @@ -6112,7 +6095,7 @@ end function ImGui.SaveIniSettingsToDisk(ini_filename) local g = GImGui g.SettingsDirtyTimer = 0.0 - -- Roblox: no disk. Call SaveIniSettingsToMemory() and persist the string yourself (e.g. DataStore). + -- [Port] Roblox: no disk. Call SaveIniSettingsToMemory() and persist the string yourself (e.g. DataStore). end -- Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer @@ -6133,7 +6116,7 @@ function ImGui.CreateNewWindowSettings(name) -- Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier. if not g.IO.ConfigDebugIniSettings then - -- ImHashSkipUncontributingPrefix: skip everything up to the last "###" + -- [Port] ImHashSkipUncontributingPrefix: skip everything up to the last "###" local p = name:match("^.*()###") if p then name = name:sub(p) end end @@ -6318,7 +6301,7 @@ end local function LogTextV_Internal(g, fmt, ...) local s = (select("#", ...) > 0) and string.format(fmt, ...) or fmt if g.LogFile then - print(s) -- TTY (the only "file" available on Roblox) + print(s) -- [Port] TTY (the only "file" available on Roblox) else g.LogBuffer:append(s) end @@ -6334,7 +6317,7 @@ ImGui.LogTextV = ImGui.LogText -- Internal version that takes a position to decide on newline placement and pad items according to their depth. -- We split text into individual lines to add current tree level padding -- FIXME: This code is a little complicated perhaps, considering simplifying the whole system. ---- `text` is a Lua string, `text_begin/text_end` optional 1-based byte range (text_end exclusive). +--- [Port] `text` is a Lua string, `text_begin/text_end` optional 1-based byte range (text_end exclusive). function ImGui.LogRenderedText(ref_pos, text, text_end, text_begin) local g = GImGui local window = g.CurrentWindow @@ -6414,7 +6397,7 @@ end -- Start logging/capturing text output to given file function ImGui.LogToFile(auto_open_depth, filename) - -- Roblox: no file access. Falls back to TTY (output window). + -- [Port] Roblox: no file access. Falls back to TTY (output window). ImGui.LogToTTY(auto_open_depth) end @@ -7039,7 +7022,7 @@ function ImGui.GetWindowContentRegionMax() return window.ContentRegionRect.Max - window.Pos end --- Overloads: IsRectVisible(size) / IsRectVisible(rect_min, rect_max) +-- [Port] Overloads: IsRectVisible(size) / IsRectVisible(rect_min, rect_max) function ImGui.IsRectVisible(a, b) local window = GImGui.CurrentWindow if b == nil then @@ -7560,14 +7543,14 @@ function ImGui.BringWindowToDisplayBehind(window, behind_window) local g = GImGui window = window.RootWindow behind_window = behind_window.RootWindow - local pos_wnd = ImGui.FindWindowDisplayIndex(window) + 1 -- 1-based + local pos_wnd = ImGui.FindWindowDisplayIndex(window) + 1 -- [Port] 1-based local pos_beh = ImGui.FindWindowDisplayIndex(behind_window) + 1 local data = g.Windows.Data if pos_wnd < pos_beh then - for i = pos_wnd, pos_beh - 2 do data[i] = data[i + 1] end -- memmove + for i = pos_wnd, pos_beh - 2 do data[i] = data[i + 1] end -- [Port] memmove data[pos_beh - 1] = window else - for i = pos_wnd, pos_beh + 1, -1 do data[i] = data[i - 1] end -- memmove + for i = pos_wnd, pos_beh + 1, -1 do data[i] = data[i - 1] end -- [Port] memmove data[pos_beh] = window end end @@ -7832,7 +7815,7 @@ function MT.ImGuiWindow:GetIDFromRectangle(r_abs) return ImHashData({ math.floor(r_rel.Min.x), math.floor(r_rel.Min.y), math.floor(r_rel.Max.x), math.floor(r_rel.Max.y) }, 4, seed) end --- Overloads: GetID(str_id) / GetID(str_id_begin, str_id_end) / GetID(int_id) +-- [Port] Overloads: GetID(str_id) / GetID(str_id_begin, str_id_end) / GetID(int_id) --- @param str_or_int string|int --- @param str_end? int # exclusive end (1-based byte position) --- @return ImGuiID @@ -7847,7 +7830,7 @@ end -- Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call -- (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level. -- for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more) --- Overloads: GetIDWithSeed(str, str_end, seed) / GetIDWithSeed(n, seed) +-- [Port] Overloads: GetIDWithSeed(str, str_end, seed) / GetIDWithSeed(n, seed) function ImGui.GetIDWithSeed(a, b, c) local id if type(a) == "number" then @@ -9215,7 +9198,7 @@ local function IsKeyChordPotentiallyCharInput(key_chord) if key == 0 --[[ImGuiKey.None]] then return false end - return g.KeysMayBeCharInput:TestBit(key + 1) -- TestBit requires 1-based index + return g.KeysMayBeCharInput:TestBit(key + 1) -- [Port] TestBit requires 1-based index end -- Request a desired route for an input chord (key + mods). @@ -9670,7 +9653,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) local key = e.Key.Key assert(key ~= 0 --[[ImGuiKey.None]]) - -- TODO: Also gets 0-based index here, consider making key_data storage 1-based + -- [Port] TODO: Also gets 0-based index here, consider making key_data storage 1-based local key_data, key_data_index = ImGui.GetKeyData(g, key) if trickle_fast_inputs and key_data.Down ~= e.Key.Down and (key_changed_mask:TestBit(key_data_index + 1) or mouse_button_changed ~= 0) then @@ -10155,7 +10138,7 @@ end -- Handle resize for: Resize Grips, Borders, Gamepad -- Return true when using auto-fit (double-click on resize grip) --- Returns (ret_auto_fit_mask, border_hovered, border_held) +-- [Port] Returns (ret_auto_fit_mask, border_hovered, border_held) --- @param window ImGuiWindow --- @param resize_grip_count int --- @param resize_grip_col table @@ -11013,7 +10996,7 @@ ImGui.RenderWindowOuterBorders = RenderWindowOuterBorders -- When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead. -- Render title text, collapse button, close button --- Returns the updated 'open' value (nil when there is no close button) +-- [Port] Returns the updated 'open' value (nil when there is no close button) --- @param window ImGuiWindow --- @param title_bar_rect ImRect --- @param name string @@ -11170,7 +11153,7 @@ function ImGui.UpdateWindowSkipRefresh(window) c.ScrollX, c.ScrollY, c.DisplayX, c.DisplayY = window.Scroll.x, window.Scroll.y, ds.x, ds.y return end - -- skip: widgets early-out on SkipItems and Begin() returns visible=false; End() restores it + -- [Port] skip: widgets early-out on SkipItems and Begin() returns visible=false; End() restores it window.CacheSkipItemsBackup = window.SkipItems window.SkipItems = true end @@ -11280,7 +11263,7 @@ end --- @param pos ImVec2 --- @param cond? ImGuiCond function ImGui.SetWindowPos(window, pos, cond) - -- Overloads: SetWindowPos(pos, cond) / SetWindowPos(name, pos, cond) / SetWindowPos(window, pos, cond) + -- [Port] Overloads: SetWindowPos(pos, cond) / SetWindowPos(name, pos, cond) / SetWindowPos(window, pos, cond) if type(window) == "string" then window = ImGui.FindWindowByName(window) if window == nil then return end @@ -11418,7 +11401,7 @@ function ImGui.GetWindowSize() return ImGui.GetCurrentWindowRead().Size end --- Overloads: SetWindowFocus() / SetWindowFocus(name). Passing nil name removes focus. +-- [Port] Overloads: SetWindowFocus() / SetWindowFocus(name). Passing nil name removes focus. --- @param name? string function ImGui.SetWindowFocus(...) if select("#", ...) == 0 then @@ -11563,7 +11546,6 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) -- Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument. local ImGuiChildFlags_SupportedMask_ = bit32.bor(1 --[[ImGuiChildFlags.Borders]], 2 --[[ImGuiChildFlags.AlwaysUseWindowPadding]], 4 --[[ImGuiChildFlags.ResizeX]], 8 --[[ImGuiChildFlags.ResizeY]], 16 --[[ImGuiChildFlags.AutoResizeX]], 32 --[[ImGuiChildFlags.AutoResizeY]], 64 --[[ImGuiChildFlags.AlwaysAutoResize]], 128 --[[ImGuiChildFlags.FrameStyle]], 256 --[[ImGuiChildFlags.NavFlattened]]) - -- IM_UNUSED(ImGuiChildFlags_SupportedMask_) assert(bit32.band(child_flags, bit32.bnot(ImGuiChildFlags_SupportedMask_)) == 0, "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?") assert(bit32.band(window_flags, 64 --[[ImGuiWindowFlags.AlwaysAutoResize]]) == 0, "Cannot specify ImGuiWindowFlags.AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags.AlwaysAutoResize!") if bit32.band(child_flags, 64 --[[ImGuiChildFlags.AlwaysAutoResize]]) ~= 0 then @@ -11677,7 +11659,7 @@ end -- Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'. -- ImGuiChildFlags.Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details! --- `true` is accepted as ImGuiChildFlags.Borders for legacy code. +-- [Port] `true` is accepted as ImGuiChildFlags.Borders for legacy code. --- @param str_id_or_id string|ImGuiID --- @param size_arg? ImVec2 --- @param child_flags? ImGuiChildFlags|bool @@ -11826,7 +11808,7 @@ function ImGui.SetNextWindowClass(window_class) local g = GImGui g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, 8192 --[[ImGuiNextWindowDataFlags.HasWindowClass]]) local wc = ImGuiWindowClass() - for k, v in pairs(window_class) do wc[k] = v end -- C++ copies the struct + for k, v in pairs(window_class) do wc[k] = v end -- [Port] C++ copies the struct g.NextWindowData.WindowClass = wc end @@ -11853,7 +11835,7 @@ function ImGui.SetNextWindowCached(key) end function ImGui.GetWindowDpiScale() - return 1.0 -- Roblox: single viewport, no DPI scaling + return 1.0 -- [Port] Roblox: single viewport, no DPI scaling end function ImGui.GetWindowViewport() @@ -11953,7 +11935,7 @@ function ImGui.IsPopupOpen(id, popup_flags) local g = GImGui if popup_flags == nil then popup_flags = 0 end if type(id) == "string" then - -- str_id overload: with AnyPopupId the id must be 0, otherwise it is hashed with the current window's ID stack + -- [Port] str_id overload: with AnyPopupId the id must be 0, otherwise it is hashed with the current window's ID stack id = (bit32.band(popup_flags, 1024 --[[ImGuiPopupFlags.AnyPopupId]]) ~= 0) and 0 or g.CurrentWindow:GetID(id) end @@ -12083,7 +12065,6 @@ function ImGui.TranslateWindow(window, delta) ImVec2_Copy(window.DC.IdealMaxPos, window.DC.IdealMaxPos + delta) end ---- ImGui::FindWindowByID function ImGui.FindWindowByID(id) local g = GImGui @@ -13088,7 +13069,7 @@ end if bit32.band(flags, 8388608 --[[ImGuiWindowFlags.DockNodeHost]]) == 0 and not window.SkipRefresh then ImGui.PushClipRect(window.InnerClipRect.Min, window.InnerClipRect.Max, true) - -- [Roblox backend] content clip + scroll origin: lets the backend move scrolled content instead of redrawing it + -- [Port] [Roblox backend] content clip + scroll origin: lets the backend move scrolled content instead of redrawing it local dl, cr = window.DrawList, window.DrawList._CmdHeader.ClipRect dl._ContentClipX0, dl._ContentClipY0, dl._ContentClipX1, dl._ContentClipY1 = cr.x, cr.y, cr.z, cr.w dl._ScrollOriginX, dl._ScrollOriginY = window.Pos.x - window.Scroll.x, window.Pos.y - window.Scroll.y @@ -13262,8 +13243,8 @@ function ImGui.End() g.CurrentWindowStack:pop_back() - -- LUA: No "Ternary Operator", since lua (... and (1) or (2)) will eval (1) and (2) no matter what - -- so something like `SetCurrentWindow((g.CurrentWindowStack.Size == 0) and nil or g.CurrentWindowStack:back().Window)` will error + -- [Port] No "Ternary Operator", since lua (... and (1) or (2)) will eval (1) and (2) no matter what + -- [Port] so something like `SetCurrentWindow((g.CurrentWindowStack.Size == 0) and nil or g.CurrentWindowStack:back().Window)` will error if (g.CurrentWindowStack.Size == 0) then SetCurrentWindow(nil) else @@ -13419,7 +13400,7 @@ local function FindHoveredWindowEx(pos, find_first_and_in_any_viewport) if window.HitTestHoleSize.x ~= 0 then local hx, hy = window.Pos.x + window.HitTestHoleOffset.x, window.Pos.y + window.HitTestHoleOffset.y if pos.x >= hx and pos.y >= hy and pos.x < hx + window.HitTestHoleSize.x and pos.y < hy + window.HitTestHoleSize.y then - break -- continue + break -- [Port] continue end end @@ -13763,7 +13744,7 @@ local function LockWheelingWindow(window, wheel_amount) if (g.WheelingWindow == window) then return end - -- IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL") + -- [Port] IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL") g.WheelingWindow = window ImVec2_Copy(g.WheelingWindowRefMousePos, g.IO.MousePos) if window == nil then @@ -13865,7 +13846,6 @@ function ImGui.UpdateMouseWheel() if window == window.RootWindow then local offset = window.Size * (1.0 - scale) * (g.IO.MousePos - window.Pos) / window.Size ImGui.SetWindowPos(window, window.Pos + offset, 0) - -- MarkIniSettingsDirty(window) end return end @@ -14057,7 +14037,7 @@ end local function GetViewportBgFgDrawList(viewport, drawlist_no, drawlist_name) -- Create the draw list on demand, because they are not frequently used for all viewports local g = GImGui - assert(drawlist_no <= 2) -- IM_COUNTOF(viewport->BgFgDrawLists) + assert(drawlist_no <= 2) -- [Port] IM_COUNTOF(viewport->BgFgDrawLists) local draw_list = viewport.BgFgDrawLists[drawlist_no] if draw_list == nil then draw_list = ImDrawList(g.DrawListSharedData) @@ -14216,7 +14196,6 @@ function ImGui.NewFrame() g.MenusIdSubmittedThisFrame:resize(0) -- Calculate frame-rate for the user, as a purely luxurious feature - -- FIXME: are lines below correct and necessary g.FramerateSecPerFrameAccum = g.FramerateSecPerFrameAccum + (g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]) g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % 60 @@ -14550,7 +14529,7 @@ function ImGui.EndFrame() if viewport == nil then viewport = ImGui.GetMainViewport() end - -- IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f) for Viewport 0x%08X", ime_data.WantVisible, ime_data.InputPos.x, ime_data.InputPos.y, viewport.ID) + -- [Port] IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f) for Viewport 0x%08X", ime_data.WantVisible, ime_data.InputPos.x, ime_data.InputPos.y, viewport.ID) g.PlatformIO.Platform_SetImeDataFn(g, viewport, ime_data) end g.WantTextInputNextFrame = ime_data.WantTextInput @@ -14771,7 +14750,6 @@ function ImGui.Shutdown() IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == nil, "Forgot to shutdown Platform backend?") IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == nil, "Forgot to shutdown Renderer backend?") for _, viewport in g.Viewports:iter() do - -- IM_UNUSED(viewport) IM_ASSERT_USER_ERROR(viewport.RendererUserData == nil and viewport.PlatformUserData == nil and viewport.PlatformHandle == nil, "Backend or app forgot to call DestroyPlatformWindows()?") end @@ -15044,7 +15022,7 @@ function ImGui.ColorConvertHSVtoRGB(h, s, v) return p, q, v elseif i == 4 then return t, p, v - else -- i == 5 or default + else -- [Port] i == 5 or default return v, p, q end end @@ -15198,7 +15176,7 @@ local GStyleVarsInfo = { ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextPadding"), -- ImGuiStyleVar.SeparatorTextPadding ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DockingSeparatorSize"), -- ImGuiStyleVar.DockingSeparatorSize } -assert(#GStyleVarsInfo == ImGuiStyleVar.COUNT) -- IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar_COUNT) +assert(#GStyleVarsInfo == ImGuiStyleVar.COUNT) -- [Port] IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar_COUNT) --- @param idx ImGuiStyleVar --- @return ImGuiStyleVarInfo @@ -15221,7 +15199,7 @@ function ImGui.PushStyleVar(idx, val) g.StyleVarStack:push_back(ImGuiStyleMod(idx, var)) if type(val) == "number" then g.Style[var_info.Key] = val - else -- copy into the style's own ImVec2: storing the caller's vector would alias it into the style forever + else -- [Port] copy into the style's own ImVec2: storing the caller's vector would alias it into the style forever var.x = val.x; var.y = val.y end end @@ -15693,7 +15671,7 @@ function ImGui.SetScrollHereY(center_y_ratio) window.ScrollTargetEdgeSnapDist.y = ImMax(0.0, window.WindowPadding.y - spacing_y) end --- Overloads: SetScrollX(scroll_x) / SetScrollX(window, scroll_x) +-- [Port] Overloads: SetScrollX(scroll_x) / SetScrollX(window, scroll_x) --- @param window ImGuiWindow|float --- @param scroll_x float? function ImGui.SetScrollX(window, scroll_x) @@ -15946,7 +15924,7 @@ function ImGui.OpenPopupEx(id, popup_flags) ImVec2_Copy(popup_ref.OpenMousePos, popup_ref.OpenPopupPos) end - -- IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id) + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id) if g.OpenPopupStack.Size < current_stack_size + 1 then g.OpenPopupStack:push_back(popup_ref) return true @@ -16036,7 +16014,7 @@ function ImGui.ClosePopupsOverWindow(ref_window, restore_focus_to_window_under_p end end if popup_count_to_keep < g.OpenPopupStack.Size then -- This test is not required but it allows to set a convenient breakpoint on the statement below - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window and ref_window.Name or "") + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window and ref_window.Name or "") ImGui.ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup) end end @@ -16045,17 +16023,16 @@ end --- @param restore_focus_to_window_under_popup bool function ImGui.ClosePopupToLevel(remaining, restore_focus_to_window_under_popup) local g = GImGui - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup) + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup) assert(remaining >= 0 and remaining < g.OpenPopupStack.Size) - -- if bit32.band(g.DebugLogFlags, ImGuiDebugLogFlags.EventPopup) ~= 0 then - -- for n = remaining + 1, g.OpenPopupStack.Size do - -- local popup = g.OpenPopupStack.Data[n] - -- IMGUI_DEBUG_LOG_POPUP("[popup] - Closing PopupID 0x%08X Window \"%s\"", popup.PopupId, popup.Window and popup.Window.Name or nil) - -- end - -- end + -- [Port] if bit32.band(g.DebugLogFlags, ImGuiDebugLogFlags.EventPopup) ~= 0 then + -- [Port] for n = remaining + 1, g.OpenPopupStack.Size do + -- [Port] local popup = g.OpenPopupStack.Data[n] + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] - Closing PopupID 0x%08X Window \"%s\"", popup.PopupId, popup.Window and popup.Window.Name or nil) + -- [Port] end + -- [Port] end -- Trim open popup stack - -- FIXME: is it safer to full copy here? local prev_popup = g.OpenPopupStack.Data[remaining + 1] g.OpenPopupStack:resize(remaining) @@ -16104,7 +16081,7 @@ function ImGui.CloseCurrentPopup() popup_idx = popup_idx - 1 end - -- IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size, popup_idx) + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size, popup_idx) ImGui.ClosePopupToLevel(popup_idx - 1, true) -- A common pattern is to close a popup when selecting a menu item/selectable that will open another window. @@ -16606,7 +16583,7 @@ end function ImGui.SetNavWindow(window) local g = GImGui if g.NavWindow ~= window then - -- IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")", window and window.Name or "") + -- [Port] IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")", window and window.Name or "") g.NavWindow = window g.NavLastValidSelectionUserData = (-1) --[[ImGuiSelectionUserData_Invalid]] end @@ -16671,7 +16648,7 @@ function ImGui.NavRestoreLayer(layer) local prev_nav_window = g.NavWindow g.NavWindow = ImGui.NavRestoreLastChildNavWindow(g.NavWindow) -- FIXME-NAV: Should clear ongoing nav requests? g.NavLastValidSelectionUserData = (-1) --[[ImGuiSelectionUserData_Invalid]] - -- if (prev_nav_window) IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name) + -- [Port] if (prev_nav_window) IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name) end local window = g.NavWindow if window.NavLastIds[layer] ~= 0 then @@ -16715,7 +16692,7 @@ function ImGui.NavInitWindow(window, force_reinit) if window == window.RootWindow or bit32.band(window.Flags, 67108864 --[[ImGuiWindowFlags.Popup]]) ~= 0 or window.NavLastIds[0] == 0 or force_reinit then init_for_nav = true end - -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d", init_for_nav, window->Name, g.NavLayer) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d", init_for_nav, window->Name, g.NavLayer) if init_for_nav then ImGui.SetNavID(0, g.NavLayer, window.NavRootFocusScopeId, ImRect()) g.NavInitRequest = true @@ -17268,7 +17245,7 @@ function ImGui.NavUpdateCreateMoveRequest() -- (preserve most state, which were already set by the NavMoveRequestForward() function) assert(g.NavMoveDir ~= (-1) --[[ImGuiDir.None]] and g.NavMoveClipDir ~= (-1) --[[ImGuiDir.None]]) assert(bit32.band(g.NavMoveFlags, 128 --[[ImGuiNavMoveFlags.Forwarded]]) ~= 0) - -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir) else -- Initiate directional inputs request g.NavMoveDir = (-1) --[[ImGuiDir.None]] @@ -17300,7 +17277,7 @@ function ImGui.NavUpdateCreateMoveRequest() -- Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match) if g.NavMoveSubmitted and g.NavId == 0 then - -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "", g.NavLayer) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "", g.NavLayer) g.NavInitRequest = true; g.NavInitRequestFromMove = true g.NavInitResult.ID = 0 if g.IO.ConfigNavCursorVisibleAuto then -- NO check for _NoNavInputs here as we assume MoveRequests cannot be created. @@ -17322,7 +17299,7 @@ function ImGui.NavUpdateCreateMoveRequest() inner_rect_rel:Translate(ImVec2(next_scroll.x - window.Scroll.x, next_scroll.y - window.Scroll.y)) if (clamp_x or clamp_y) and not inner_rect_rel:Contains(window.NavRectRel[g.NavLayer]) then - -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n") + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n") local pad_x = ImMin(inner_rect_rel:GetWidth(), window.FontRefSize * 0.5) local pad_y = ImMin(inner_rect_rel:GetHeight(), window.FontRefSize * 0.5) -- Terrible approximation for the intent of starting navigation from first fully visible item inner_rect_rel.Min.x = clamp_x and (inner_rect_rel.Min.x + pad_x) or -3.4028234663853e+38 --[[FLT_MAX]] @@ -17966,7 +17943,7 @@ function ImGui.NavInitRequestApplyResult() -- Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) -- FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently. - -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) ImGui.SetNavID(result.ID, g.NavLayer, result.FocusScopeId, result.RectRel) g.NavIdIsAlive = true -- Mark as alive from previous frame as we got a result if result.SelectionUserData ~= (-1) --[[ImGuiSelectionUserData_Invalid]] then @@ -18008,7 +17985,7 @@ function ImGui.NavMoveRequestApplyResult() ImGui.SetNavCursorVisibleAfterMove() end ImGui.NavClearPreferredPosForAxis(axis) -- On a failed move, clear preferred pos for this axis. - -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n") + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n") return end @@ -18040,7 +18017,7 @@ function ImGui.NavMoveRequestApplyResult() end if g.NavWindow ~= result.Window then - -- IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name) + -- [Port] IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name) g.NavWindow = result.Window g.NavLastValidSelectionUserData = (-1) --[[ImGuiSelectionUserData_Invalid]] end @@ -18067,7 +18044,7 @@ function ImGui.NavMoveRequestApplyResult() end -- Apply new NavID/Focus - -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) local root_for_nav = g.NavWindow.RootWindowForNav local preferred_scoring_pos_rel = ImVec2() ImVec2_Copy(preferred_scoring_pos_rel, root_for_nav.NavPreferredScoringPosRel[g.NavLayer]) @@ -18291,7 +18268,7 @@ function ImGui.SetCurrentViewport(current_window, viewport) g.CurrentDpiScale = viewport and viewport.DpiScale or 1.0 g.CurrentViewport = viewport assert(g.CurrentDpiScale > 0.0 and g.CurrentDpiScale < 99.0) -- Typical correct values would be between 1.0f and 4.0f - -- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X", current_window and current_window.Name or "NULL", viewport and viewport.ID or 0) + -- [Port] IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X", current_window and current_window.Name or "NULL", viewport and viewport.ID or 0) if g.IO.ConfigDpiScaleFonts then g.Style.FontScaleDpi = g.CurrentDpiScale @@ -18595,7 +18572,7 @@ function ImGui.UpdateViewportsNewFrame() -- Erase unused viewports if n > 1 and viewport.LastFrameActive < g.FrameCount - 2 then ImGui.DestroyViewport(viewport) - -- n stays the same because we removed an element + -- [Port] n stays the same because we removed an element else local platform_funcs_available = viewport.PlatformWindowCreated @@ -18638,7 +18615,7 @@ function ImGui.UpdateViewportsNewFrame() viewport:UpdateWorkRect() -- Garbage collect transient buffers of recently BG/FG drawlists - for dl_n = 1, 2 do -- IM_COUNTOF(viewport->BgFgDrawLists) + for dl_n = 1, 2 do -- [Port] IM_COUNTOF(viewport->BgFgDrawLists) if viewport.BgFgDrawListsLastTimeActive[dl_n] < memory_compact_start_time and viewport.BgFgDrawLists[dl_n] ~= nil then IM_DELETE(viewport.BgFgDrawLists, dl_n) end @@ -18910,7 +18887,6 @@ function ImGui.DestroyViewport(viewport) assert(not g.PlatformIO.Viewports:contains(viewport)) assert(g.Viewports.Data[viewport.Idx] == viewport) g.Viewports:erase(viewport.Idx) - -- IM_DELETE(viewport) end -- FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten. @@ -19049,7 +19025,6 @@ function ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) -- Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM if window.Viewport.PlatformRequestMove then ImVec2_Copy(window.Pos, window.Viewport.Pos) - -- ImGui.MarkIniSettingsDirty(window) elseif window.Viewport.Pos.x ~= window.Pos.x or window.Viewport.Pos.y ~= window.Pos.y then viewport_rect_changed = true ImVec2_Copy(window.Viewport.Pos, window.Pos) @@ -19058,7 +19033,6 @@ function ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) if window.Viewport.PlatformRequestResize then ImVec2_Copy(window.Size, window.Viewport.Size) ImVec2_Copy(window.SizeFull, window.Viewport.Size) - -- ImGui.MarkIniSettingsDirty(window) elseif window.Viewport.Size.x ~= window.Size.x or window.Viewport.Size.y ~= window.Size.y then viewport_rect_changed = true ImVec2_Copy(window.Viewport.Size, window.Size) @@ -19215,7 +19189,7 @@ function ImGui.UpdatePlatformWindows() local title_end = ImGui.FindRenderedTextEnd(title) local title_hash = ImHashStr(title, title_end - title_begin) if viewport.LastNameHash ~= title_hash then - -- This still creates new strings + -- [Port] This still creates new strings g.PlatformIO.Platform_SetWindowTitle(viewport, string.sub(title, title_begin, title_end - 1)) viewport.LastNameHash = title_hash end @@ -19269,7 +19243,6 @@ function ImGui.RenderPlatformWindowsDefault(platform_render_arg, renderer_render -- Skip the main viewport (index 1 in Lua), which is always fully handled by the application! local platform_io = ImGui.GetPlatformIO() - -- First pass: render all windows for i = 2, platform_io.Viewports.Size do local viewport = platform_io.Viewports.Data[i] if bit32.band(viewport.Flags, 4096 --[[ImGuiViewportFlags.IsMinimized]]) == 0 then @@ -19282,7 +19255,6 @@ function ImGui.RenderPlatformWindowsDefault(platform_render_arg, renderer_render end end - -- Second pass: swap buffers for all windows for i = 2, platform_io.Viewports.Size do local viewport = platform_io.Viewports.Data[i] if bit32.band(viewport.Flags, 4096 --[[ImGuiViewportFlags.IsMinimized]]) == 0 then @@ -19975,7 +19947,7 @@ function MT.ImGuiTextFilter:Clear() self.InputBuf[1] = 0; self:Build() end function MT.ImGuiTextFilter:IsActive() return self._Items.Size ~= 0 end -- Parse filter and split into a format optimal for PassFilter() --- Items are { Text = string (lowercased), CountInclude = int } +-- [Port] Items are { Text = string (lowercased), CountInclude = int } function MT.ImGuiTextFilter:Build() local items = self._Items items:resize(0) @@ -19984,9 +19956,9 @@ function MT.ImGuiTextFilter:Build() local n = 0 while self.InputBuf[n + 1] ~= nil and self.InputBuf[n + 1] ~= 0 do n = n + 1 end local buf = ImGui._ByteArrayToString(self.InputBuf, 1, n + 1) - local buf_e = n + 1 -- exclusive, 1-based + local buf_e = n + 1 -- [Port] exclusive, 1-based local word_b = 1 - local seq_start_idx = -1 -- 1-based index into items, -1 = none + local seq_start_idx = -1 -- [Port] 1-based index into items, -1 = none while word_b < buf_e do -- Trim blanks while word_b < buf_e and ImCharIsBlankA(string.byte(buf, word_b)) do @@ -20080,7 +20052,7 @@ local function GetSkipItemForListClipping() end --- `offset` is a 0-based count of leading ranges to leave alone +-- [Port] `offset` is a 0-based count of leading ranges to leave alone local function ImGuiListClipper_SortAndFuseRanges(ranges, offset) if offset == nil then offset = 0 end if ranges.Size - offset <= 1 then return end @@ -20263,7 +20235,7 @@ local function ImGuiListClipper_StepInternal(clipper) -- Step 1: Let the clipper infer height from first range if clipper.ItemsHeight <= 0.0 then assert(data.StepNo == 1) - -- (no float precision mitigation needed: Luau numbers are doubles) + -- [Port] (no float precision mitigation needed: Luau numbers are doubles) clipper.ItemsHeight = (window.DC.CursorPos.y - clipper.StartPosY) / (clipper.DisplayEnd - clipper.DisplayStart) if clipper.ItemsHeight == 0.0 and clipper.ItemsCount == 2147483647 --[[INT_MAX]] then -- Accept that no item have been submitted if in indeterminate mode. return false @@ -20603,7 +20575,7 @@ function ImGui.ErrorRecoveryTryToRecoverWindowState(state_in) -- IM_ASSERT(g.FocusScopeStack.Size == state_in.SizeOfFocusScopeStack) end --- Lines are stored in g.DebugLogBuf (one chunk per call) +-- [Port] Lines are stored in g.DebugLogBuf (one chunk per call) function ImGui.DebugLog(fmt, ...) ImGui.DebugLogV(fmt, ...) end @@ -20619,7 +20591,7 @@ function ImGui.DebugLogV(fmt, ...) end local str = prefix .. ((select("#", ...) > 0) and string.format(fmt, ...) or fmt) g.DebugLogBuf:append(str) - -- Line index (upstream: g.DebugLogIndex). Lines are complete strings without '\n'. + -- [Port] Line index (upstream: g.DebugLogIndex). Lines are complete strings without '\n'. local lines = g.DebugLogLines for part, nl in string.gmatch(str, "([^\n]*)(\n?)") do lines[#lines] = lines[#lines] .. part @@ -20757,7 +20729,7 @@ do --[[ [SECTION] METRICS/DEBUGGER WINDOW, DEBUG LOG, ID STACK TOOL, FONT DEBUG -- [SECTION] Font atlas / font debugging ------------------------------------------------------------------------------- --- byte buffers for InputText (same as the demo's DemoBuf/DemoBufStr; kept here so the library doesn't need the demo) +-- [Port] byte buffers for InputText (same as the demo's DemoBuf/DemoBufStr; kept here so the library doesn't need the demo) local function DemoBuf(str, size) local t = {} for i = 1, #str do t[i] = string.byte(str, i) end @@ -20811,7 +20783,7 @@ function ImGui.DebugRenderKeyboardPreview(draw_list) local start_pos = ImVec2(board_min.x + 5.0 - key_step.x, board_min.y) local K = ImGuiKey - local keys_to_display = { -- { Row, Col, Label, Key } + local keys_to_display = { -- [Port] { Row, Col, Label, Key } { 0, 0, "", K.Tab }, { 0, 1, "Q", K.Q }, { 0, 2, "W", K.W }, { 0, 3, "E", K.E }, { 0, 4, "R", K.R }, { 1, 0, "", K.CapsLock }, { 1, 1, "A", K.A }, { 1, 2, "S", K.S }, { 1, 3, "D", K.D }, { 1, 4, "F", K.F }, { 2, 0, "", K.LeftShift }, { 2, 1, "Z", K.Z }, { 2, 2, "X", K.X }, { 2, 3, "C", K.C }, { 2, 4, "V", K.V }, @@ -20933,7 +20905,7 @@ function ImGui.DebugNodeFontGlyphsForSrcMask(font, baked, src_mask) local glyph_col = ImGui.GetColorU32(0 --[[ImGuiCol.Text]]) local cell_size = baked.Size * 1 local cell_spacing = ImGui.GetStyle().ItemSpacing.y - -- [port] only scans loaded codepoints (IndexLookup range) instead of the whole 0..0xFFFF range + -- [Port] only scans loaded codepoints (IndexLookup range) instead of the whole 0..0xFFFF range local max_c = baked.IndexLookup.Size - 1 local base = 0 while base <= max_c do @@ -20991,7 +20963,7 @@ local function CalcFontGlyphSrcOverlapMask(atlas, font, codepoint) local src = font.Sources.Data[src_n + 1] local loader = src.FontLoader or atlas.FontLoader if not (loader.FontSrcContainsGlyph ~= nil and loader.FontSrcContainsGlyph(atlas, src, codepoint)) then - break -- continue + break -- [Port] continue end mask = bit32.bor(mask, bit32.lshift(1, src_n)) count = count + 1 @@ -21086,7 +21058,7 @@ function ImGui.DebugNodeFont(font) if ImGui.TreeNode("Glyphs", "Baked at { %.2fpx, d.%.2f }: %d glyphs%s", baked.Size, baked.RasterizerDensity, baked.Glyphs.Size, (baked.LastUsedFrame < (builder.FrameCount or 0) - 1) and " *Unused*" or "") then if ImGui.SmallButton("Load all") then - for c = 0, 0x7F do baked:FindGlyph(c) end -- [port] ASCII only: loading the whole BMP in Luau stalls for seconds + for c = 0, 0x7F do baked:FindGlyph(c) end -- [Port] ASCII only: loading the whole BMP in Luau stalls for seconds end local surface_sqrt = math.floor(math.sqrt(baked.MetricsTotalSurface)) ImGui.Text("Ascent: %f, Descent: %f, Ascent-Descent: %f", baked.Ascent, baked.Descent, baked.Ascent - baked.Descent) @@ -21276,7 +21248,7 @@ function ImGui.ShowDebugLogWindow(p_open) g.DebugLogFlags = bit32.band(g.DebugLogFlags, bit32.bnot(L.EventClipper)) local lines = g.DebugLogLines local count = #lines - if lines[count] == "" then count = count - 1 end -- trailing partial line + if lines[count] == "" then count = count - 1 end -- [Port] trailing partial line local clipper = ImGuiListClipper() clipper:Begin(count) while clipper:Step() do @@ -21303,9 +21275,9 @@ function ImGui.DebugTextUnformattedWithLocateItem(line_begin, line_end) while p <= line_end - 10 do repeat -- [Luau] 1-based (C: p <= line_end - 10 with 0-based offsets) local b0, b1 = string.byte(line_begin, p, p + 1) local hex = string.match(line_begin, "^%x+", p + 2) - if b0 ~= 48 or (b1 ~= 120 and b1 ~= 88) or hex == nil or string.find(string.sub(line_begin, p + 10, p + 10), "^%x") then -- '0', 'x', 'X' + if b0 ~= 48 or (b1 ~= 120 and b1 ~= 88) or hex == nil or string.find(string.sub(line_begin, p + 10, p + 10), "^%x") then -- [Port] '0', 'x', 'X' p = p + 1 - break -- continue + break -- [Port] continue end local id = tonumber(hex, 16) -- [Luau] sscanf("%X") local p0 = ImGui.CalcTextSizeEx(line_begin, 1, p) @@ -21314,7 +21286,7 @@ function ImGui.DebugTextUnformattedWithLocateItem(line_begin, line_end) if ImGui.IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true) then ImGui.DebugLocateItemOnHover(id) end - p = p + 11 -- p += 10, then the loop's p++ + p = p + 11 -- [Port] p += 10, then the loop's p++ until true end end @@ -21494,7 +21466,7 @@ function ImGui.UpdateDebugToolItemPathQuery() end -- [DEBUG] ID Stack tool: hooks called by GetID() family functions --- `data_id` is the string/number that was hashed. +-- [Port] `data_id` is the string/number that was hashed. function ImGui.DebugHookIdInfo(id, data_type, data_id) local g = ImGui.GetCurrentContext() local query = PathQuery(g) @@ -21686,7 +21658,7 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) local pcmd = draw_list.CmdBuffer.Data[cmd_n] if pcmd.UserCallback then ImGui.BulletText("Callback %s, user_data %s", tostring(pcmd.UserCallback), tostring(pcmd.UserCallbackData)) - break -- continue + break -- [Port] continue end local texid_desc = FormatTextureRefForDebugDisplay(pcmd.TexRef) @@ -21698,7 +21670,7 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) ImGui.DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg.ShowDrawCmdMesh, cfg.ShowDrawCmdBoundingBoxes) end if not pcmd_node_open then - break -- continue + break -- [Port] continue end -- Calculate approximate coverage area (touched pixel count) @@ -22272,7 +22244,7 @@ function ImGui.ShowMetricsWindow(p_open) for i = 1, g.PlatformIO.Monitors.Size do ImGui.DebugNodePlatformMonitor(g.PlatformIO.Monitors.Data[i], "Monitor", i - 1) if ImGui.IsItemHovered() then - cfg.HighlightMonitorIdx = i - 1 -- 0-based, like Monitors:index_from_ptr() + cfg.HighlightMonitorIdx = i - 1 -- [Port] 0-based, like Monitors:index_from_ptr() end end if g.FallbackMonitor then ImGui.DebugNodePlatformMonitor(g.FallbackMonitor, "Fallback", 0) end @@ -22507,7 +22479,7 @@ function ImGui.ShowMetricsWindow(p_open) if ImGui.IsMousePosValid() then ImGui.Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y) else ImGui.Text("Mouse pos: ") end ImGui.Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y) ImGui.Text("Mouse down:") - local count = 5 --[[ImGuiMouseButton.COUNT]] -- IM_COUNTOF(io.MouseDown) + local count = 5 --[[ImGuiMouseButton.COUNT]] -- [Port] IM_COUNTOF(io.MouseDown) for i = 0, count - 1 do if ImGui.IsMouseDown(i) then ImGui.SameLine(); ImGui.Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]) end end ImGui.Text("Mouse clicked:") for i = 0, count - 1 do if ImGui.IsMouseClicked(i) then ImGui.SameLine(); ImGui.Text("b%d (%d)", i, io.MouseClickedCount[i]) end end @@ -22668,7 +22640,7 @@ function ImGui.DebugBreakButton(label, description_of_location) end end --[[ [SECTION] METRICS/DEBUGGER WINDOW, DEBUG LOG, ID STACK TOOL, FONT DEBUG ]] -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value end __FILES['imgui_demo.lua'] = function() @@ -23865,7 +23837,7 @@ S.DemoWindowWidgetsColorAndPickers = { color = ImVec4(114.0 / 255.0, 144.0 / 255.0, 154.0 / 255.0, 200.0 / 255.0), base_flags = ImGuiColorEditFlags.None, saved_palette_init = true, - saved_palette = {}, -- 32 x ImVec4, 1-based + saved_palette = {}, -- [Port] 32 x ImVec4, 1-based backup_color = ImVec4(), no_border = false, ref_color = false, @@ -24075,7 +24047,7 @@ end S.DemoWindowWidgetsComboBoxes = { flags = 0, item_selected_idx = 0, -- Here we store our selection data as an index. - filter = nil, -- ImGuiTextFilter, created lazily + filter = nil, -- [Port] ImGuiTextFilter, created lazily item_current_2 = 0, item_current_3 = -1, -- If the selection isn't within 0..count, Combo won't display a preview item_current_4 = 0, @@ -24193,7 +24165,7 @@ S.DemoWindowWidgetsDataTypes = { s16_v = 32767, u16_v = 65535, s32_v = -1, - u32_v = 4294967295, -- (ImU32)-1 + u32_v = 4294967295, -- [Port] (ImU32)-1 s64_v = -1, u64_v = 18446744073709551615, -- (ImU64)-1 [Port] Lua numbers are doubles: 64-bit values are exact only within +-2^53 f32_v = 0.123, @@ -24231,15 +24203,15 @@ function DemoWindowWidgetsDataTypes() local u8_zero, u8_one, u8_fifty, u8_min, u8_max = 0, 1, 50, 0, 255 local s16_zero, s16_one, s16_fifty, s16_min, s16_max = 0, 1, 50, -32768, 32767 local u16_zero, u16_one, u16_fifty, u16_min, u16_max = 0, 1, 50, 0, 65535 - local s32_zero, s32_one, s32_fifty, s32_min, s32_max, s32_hi_a, s32_hi_b = 0, 1, 50, -1073741824, 1073741823, 1073741823 - 100, 1073741823 -- INT_MIN/2, INT_MAX/2 - local u32_zero, u32_one, u32_fifty, u32_min, u32_max, u32_hi_a, u32_hi_b = 0, 1, 50, 0, 2147483647, 2147483647 - 100, 2147483647 -- UINT_MAX/2 + local s32_zero, s32_one, s32_fifty, s32_min, s32_max, s32_hi_a, s32_hi_b = 0, 1, 50, -1073741824, 1073741823, 1073741823 - 100, 1073741823 -- [Port] INT_MIN/2, INT_MAX/2 + local u32_zero, u32_one, u32_fifty, u32_min, u32_max, u32_hi_a, u32_hi_b = 0, 1, 50, 0, 2147483647, 2147483647 - 100, 2147483647 -- [Port] UINT_MAX/2 local s64_zero, s64_one, s64_fifty, s64_min, s64_max, s64_hi_a, s64_hi_b = 0, 1, 50, LLONG_MIN / 2, LLONG_MAX / 2, LLONG_MAX / 2 - 100, LLONG_MAX / 2 local u64_zero, u64_one, u64_fifty, u64_min, u64_max, u64_hi_a, u64_hi_b = 0, 1, 50, 0, ULLONG_MAX / 2, ULLONG_MAX / 2 - 100, ULLONG_MAX / 2 local f32_zero, f32_one, f32_lo_a, f32_hi_a = 0.0, 1.0, -10000000000.0, 10000000000.0 local f64_zero, f64_one, f64_lo_a, f64_hi_a = 0.0, 1.0, -1000000000000000.0, 1000000000000000.0 -- State - -- (see S.DemoWindowWidgetsDataTypes) + -- [Port] (see S.DemoWindowWidgetsDataTypes) local drag_speed = 0.2 IMGUI_DEMO_MARKER("Widgets/Data Types/Drags") @@ -24458,7 +24430,6 @@ function DemoWindowWidgetsDragAndDrop() local drop_target_flags = bit32.bor(1024 --[[ImGuiDragDropFlags.AcceptBeforeDelivery]], 4096 --[[ImGuiDragDropFlags.AcceptNoPreviewTooltip]]) local payload = ImGui.AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, drop_target_flags) if payload then - -- IM_UNUSED(payload) ImGui.SetMouseCursor(10 --[[ImGuiMouseCursor.NotAllowed]]) ImGui.SetTooltip("Cannot drop here!") end @@ -24874,7 +24845,7 @@ end S.DemoWindowWidgetsPlotting = { animate = true, arr = { 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2 }, - values = {}, -- 90 zeros, filled below + values = {}, -- [Port] 90 zeros, filled below values_offset = 0, refresh_time = 0.0, phase = 0.0, @@ -25798,7 +25769,7 @@ S.DemoWindowWidgetsSelectionAndMultiSelect = { show_in_table = false, show_color_button = true, flags = bit32.bor(ImGuiMultiSelectFlags.ClearOnEscape, ImGuiMultiSelectFlags.BoxSelect1d), - widget_type = 0, -- WidgetType_Selectable + widget_type = 0, -- [Port] WidgetType_Selectable items = ImVector(), items_next_id = 0, selection = ExampleSelectionWithDeletion(), @@ -26190,7 +26161,7 @@ function DemoWindowWidgetsSelectionAndMultiSelect(demo_data) if ImGui.TreeNode("Multi-Select (advanced)") then IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (advanced)") -- Options - local WidgetType_Selectable, WidgetType_TreeNode = 0, 1 -- enum WidgetType + local WidgetType_Selectable, WidgetType_TreeNode = 0, 1 -- [Port] enum WidgetType local st = s.advanced if ImGui.TreeNode("Options") then @@ -26787,22 +26758,22 @@ S.DemoWindowWidgetsTextInput = { "\tlock cmpxchg8b eax\n", 1024 * 16), flags = ImGuiInputTextFlags.AllowTabInput, }, - -- "Filtered Text Input" + -- [Port] "Filtered Text Input" filtered = { buf1 = ImGui.NewTextBuffer("", 32), buf2 = ImGui.NewTextBuffer("", 32), buf3 = ImGui.NewTextBuffer("", 32), buf4 = ImGui.NewTextBuffer("", 32), buf5 = ImGui.NewTextBuffer("", 32), buf6 = ImGui.NewTextBuffer("", 32), buf7 = ImGui.NewTextBuffer("", 32), }, - -- "Password Input" + -- [Port] "Password Input" password = { password = ImGui.NewTextBuffer("password123", 64) }, - -- "Completion, History, Edit Callbacks" + -- [Port] "Completion, History, Edit Callbacks" callbacks = { buf1 = ImGui.NewTextBuffer("", 64), buf2 = ImGui.NewTextBuffer("", 64), buf3 = ImGui.NewTextBuffer("", 64), edit_count = 0, }, -- "Resize Callback" resize = { flags = ImGuiInputTextFlags.None, my_str = ImVector() }, - -- "Eliding, Alignment" + -- [Port] "Eliding, Alignment" eliding = { buf1 = ImGui.NewTextBuffer("/path/to/some/folder/with/long/filename.cpp", 128), flags = ImGuiInputTextFlags.ElideLeft }, -- "Miscellaneous" misc = { buf1 = ImGui.NewTextBuffer("", 16), flags = ImGuiInputTextFlags.EscapeClearsAll }, @@ -27092,7 +27063,7 @@ end ------------------------------------------------------------------------------- S.DemoWindowWidgetsTreeNodes = { - base_flags = bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DefaultOpen), -- "Hierarchy Lines" + base_flags = bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DefaultOpen), -- [Port] "Hierarchy Lines" selection_mask = 0x00, base_flags_2 = bit32.bor(ImGuiTreeNodeFlags.OpenOnArrow, ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.SpanAvailWidth), -- "Advanced" align_label_with_current_x_position = false, @@ -27425,7 +27396,7 @@ S.DemoWindowLayout = { -- Widgets Width f = 0.0, show_indented_items = true, - -- Basic Horizontal Layout + -- [Port] Basic Horizontal Layout c1 = false, c2 = false, c3 = false, c4 = false, f0 = 1.0, f1 = 2.0, f2 = 3.0, item = -1, @@ -27450,7 +27421,7 @@ S.DemoWindowLayout = { -- Text Clipping size = ImVec2(100.0, 100.0), offset = ImVec2(30.0, 30.0), - -- Overlap Mode + -- [Port] Overlap Mode enable_allow_overlap = true, } @@ -28289,14 +28260,14 @@ end ------------------------------------------------------------------------------- S.DemoWindowPopups = { - selected_fish = -1, -- static int selected_fish = -1; - toggles = { true, false, false, false, false }, -- static bool toggles[] = { true, false, false, false, false }; - selected = -1, -- static int selected = -1; - value = 0.5, -- static float value = 0.5f; - name = ImGui.NewTextBuffer("Label1", 32), -- static char name[32] = "Label1"; - dont_ask_me_next_time = false, -- static bool dont_ask_me_next_time = false; - item = 1, -- static int item = 1; - color = { 0.4, 0.7, 0.0, 0.5 }, -- static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; + selected_fish = -1, -- [Port] static int selected_fish = -1; + toggles = { true, false, false, false, false }, -- [Port] static bool toggles[] = { true, false, false, false, false }; + selected = -1, -- [Port] static int selected = -1; + value = 0.5, -- [Port] static float value = 0.5f; + name = ImGui.NewTextBuffer("Label1", 32), -- [Port] static char name[32] = "Label1"; + dont_ask_me_next_time = false, -- [Port] static bool dont_ask_me_next_time = false; + item = 1, -- [Port] static int item = 1; + color = { 0.4, 0.7, 0.0, 0.5 }, -- [Port] static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; } function DemoWindowPopups() local s = S.DemoWindowPopups @@ -28593,7 +28564,7 @@ end -- This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID. -- But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex) -- If you don't use sorting, you will generally never care about giving column an ID! --- enum MyItemColumnID +-- [Port] enum MyItemColumnID MyItemColumnID_ID = 0 MyItemColumnID_Name = 1 MyItemColumnID_Action = 2 @@ -28675,7 +28646,7 @@ S.EditTableSizingFlags = { policies = nil } -- [Port] p_flags -> takes flags, returns the new flags. function EditTableSizingFlags(p_flags) local s = S.EditTableSizingFlags - -- struct EnumDesc { ImGuiTableFlags Value; const char* Name; const char* Tooltip; }; + -- [Port] struct EnumDesc { ImGuiTableFlags Value; const char* Name; const char* Tooltip; }; if s.policies == nil then s.policies = { @@ -28766,7 +28737,7 @@ end -- [SECTION] DemoWindowTables() ------------------------------------------------------------------------------- -S.DemoWindowTables = { -- statics of DemoWindowTables(), one sub-table per TreeNode +S.DemoWindowTables = { -- [Port] statics of DemoWindowTables(), one sub-table per TreeNode disable_indent = false, BordersBackground = { flags = bit32.bor(ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg), @@ -28791,14 +28762,14 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su flags2 = bit32.bor(ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg), cell_padding = ImVec2(0.0, 0.0), show_widget_frame_bg = true, - text_bufs = {}, -- 1-based, cell + 1 + text_bufs = {}, -- [Port] 1-based, cell + 1 init = true, }, SizingPolicies = { flags1 = bit32.bor(ImGuiTableFlags.BordersV, ImGuiTableFlags.BordersOuterH, ImGuiTableFlags.RowBg, ImGuiTableFlags.ContextMenuInBody), sizing_policy_flags = { ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.SizingFixedSame, ImGuiTableFlags.SizingStretchProp, ImGuiTableFlags.SizingStretchSame }, flags = bit32.bor(ImGuiTableFlags.ScrollY, ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg, ImGuiTableFlags.Resizable), - contents_type = 0, -- CT_ShowWidth + contents_type = 0, -- [Port] CT_ShowWidth column_count = 3, text_buf = ImGui.NewTextBuffer("", 32), }, @@ -28833,7 +28804,7 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su table_flags = bit32.bor(ImGuiTableFlags.BordersV, ImGuiTableFlags.BordersOuterH, ImGuiTableFlags.Resizable, ImGuiTableFlags.RowBg, ImGuiTableFlags.NoBordersInBody), tree_node_flags_base = bit32.bor(ImGuiTreeNodeFlags.SpanAllColumns, ImGuiTreeNodeFlags.DefaultOpen, ImGuiTreeNodeFlags.DrawLinesFull), MyTreeNode = nil, -- [Port] local struct, created once on first use - nodes = { -- 1-based; ChildIdx stays 0-based like upstream + nodes = { -- [Port] 1-based; ChildIdx stays 0-based like upstream { Name = "Root with Long Name", Type = "Folder", Size = -1, ChildIdx = 1, ChildCount = 3 }, -- 0 { Name = "Music", Type = "Folder", Size = -1, ChildIdx = 4, ChildCount = 2 }, -- 1 { Name = "Textures", Type = "Folder", Size = -1, ChildIdx = 6, ChildCount = 3 }, -- 2 @@ -28854,7 +28825,7 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su AngledHeaders = { table_flags = bit32.bor(ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY, ImGuiTableFlags.BordersOuter, ImGuiTableFlags.BordersInnerH, ImGuiTableFlags.Hideable, ImGuiTableFlags.Resizable, ImGuiTableFlags.Reorderable, ImGuiTableFlags.HighlightHoveredColumn), column_flags = bit32.bor(ImGuiTableColumnFlags.AngledHeader, ImGuiTableColumnFlags.WidthFixed), - bools = {}, -- 1-based, filled with false on first use + bools = {}, -- [Port] 1-based, filled with false on first use frozen_cols = 1, frozen_rows = 2, }, @@ -28883,11 +28854,11 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY, ImGuiTableFlags.SizingFixedFit), columns_base_flags = ImGuiTableColumnFlags.None, - contents_type = 5, -- CT_SelectableSpanRow + contents_type = 5, -- [Port] CT_SelectableSpanRow freeze_cols = 1, freeze_rows = 1, - items_count = 0, -- IM_COUNTOF(template_items_names) * 2, set below - outer_size_value = nil, -- ImVec2(0.0f, TEXT_BASE_HEIGHT * 12), set lazily (needs font) + items_count = 0, -- [Port] IM_COUNTOF(template_items_names) * 2, set below + outer_size_value = nil, -- [Port] ImVec2(0.0f, TEXT_BASE_HEIGHT * 12), set lazily (needs font) row_min_height = 0.0, -- Auto inner_width_with_scroll = 0.0, -- Auto-extend outer_size_enabled = true, @@ -29007,7 +28978,7 @@ function DemoWindowTables() if ImGui.TreeNode("Borders, background") then IMGUI_DEMO_MARKER("Tables/Borders, background") -- Expose a few Borders related flags interactively - local CT_Text, CT_FillButton = 0, 1 -- enum ContentsType + local CT_Text, CT_FillButton = 0, 1 -- [Port] enum ContentsType local s = s.BordersBackground PushStyleCompact() @@ -29370,7 +29341,7 @@ function DemoWindowTables() "This section allows you to interact and see the effect of various sizing policies " .. "depending on whether Scroll is enabled and the contents of your columns.") - local CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText = 0, 1, 2, 3, 4, 5 -- enum ContentsType + local CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText = 0, 1, 2, 3, 4, 5 -- [Port] enum ContentsType PushStyleCompact() ImGui.PushID("Advanced") @@ -29913,7 +29884,7 @@ function DemoWindowTables() ImGui.TableHeadersRow() -- Simple storage to output a dummy file-system. - -- struct MyTreeNode { Name, Type, Size, ChildIdx, ChildCount } (see s.nodes) + -- [Port] struct MyTreeNode { Name, Type, Size, ChildIdx, ChildCount } (see s.nodes) local MyTreeNode = s.MyTreeNode if MyTreeNode == nil then -- [Port] local struct with a static method, created once and kept in statics MyTreeNode = {} @@ -30349,7 +30320,7 @@ function DemoWindowTables() IMGUI_DEMO_MARKER("Tables/Advanced") local s = s.Advanced - local CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow = 0, 1, 2, 3, 4, 5 -- enum ContentsType + local CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow = 0, 1, 2, 3, 4, 5 -- [Port] enum ContentsType local contents_type_names = { "Text", "Button", "SmallButton", "FillButton", "Selectable", "Selectable (span row)" } if s.outer_size_value == nil then s.outer_size_value = ImVec2(0.0, TEXT_BASE_HEIGHT * 12) end -- static float row_min_height = 0.0f -- Auto @@ -30869,7 +30840,7 @@ function DemoWindowInputs() end ImGui.Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y) ImGui.Text("Mouse down:") - for i = 0, 5 --[[ImGuiMouseButton.COUNT]] - 1 do if ImGui.IsMouseDown(i) then ImGui.SameLine(); ImGui.Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]) end end -- IM_COUNTOF(io.MouseDown), 0-based + for i = 0, 5 --[[ImGuiMouseButton.COUNT]] - 1 do if ImGui.IsMouseDown(i) then ImGui.SameLine(); ImGui.Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]) end end -- [Port] IM_COUNTOF(io.MouseDown), 0-based ImGui.Text("Mouse wheel: %.1f", io.MouseWheel) ImGui.Text("Mouse clicked count:") for i = 0, 5 --[[ImGuiMouseButton.COUNT]] - 1 do if io.MouseClickedCount[i] > 0 then ImGui.SameLine(); ImGui.Text("b%d: %d", i, io.MouseClickedCount[i]) end end @@ -31343,12 +31314,12 @@ function GetTreeLinesFlagsName(flags) end S.ShowStyleEditor = { - ref_saved_style = nil, -- static ImGuiStyle ref_saved_style; (created lazily) + ref_saved_style = nil, -- [Port] static ImGuiStyle ref_saved_style; (created lazily) init = true, output_dest = 0, output_only_modified = true, alpha_flags = 0, - filter = nil, -- static ImGuiTextFilter filter; (created lazily) + filter = nil, -- [Port] static ImGuiTextFilter filter; (created lazily) } -- We omit the ImGui:: prefix in this function, as we don't expect user to be copy and pasting this code. -- [Port] Lua has no `using namespace`: calls keep the ImGui. prefix @@ -31877,17 +31848,17 @@ ExampleAppConsoleMT = {} ExampleAppConsoleMT.__index = ExampleAppConsoleMT function ExampleAppConsole() local self = setmetatable({}, ExampleAppConsoleMT) - self.InputBuf = nil -- char InputBuf[256] - self.Items = ImVector() -- ImVector - self.Commands = ImVector() -- ImVector - self.History = ImVector() -- ImVector + self.InputBuf = nil -- [Port] char InputBuf[256] + self.Items = ImVector() -- [Port] ImVector + self.Commands = ImVector() -- [Port] ImVector + self.History = ImVector() -- [Port] ImVector self.HistoryPos = 0 -- -1: new line, 0..History.Size-1 browsing history. self.Filter = ImGuiTextFilter() self.AutoScroll = false self.ScrollToBottom = false self:ClearLog() - self.InputBuf = ImGui.NewTextBuffer("", 256) -- memset(InputBuf, 0, sizeof(InputBuf)) + self.InputBuf = ImGui.NewTextBuffer("", 256) -- [Port] memset(InputBuf, 0, sizeof(InputBuf)) self.HistoryPos = -1 -- "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches. @@ -32128,7 +32099,7 @@ function ExampleAppConsoleMT:TextEditCallback(data) local word_end = data.CursorPos local word_start = word_end while word_start > 0 do - local c = data.Buf[word_start] -- word_start[-1] + local c = data.Buf[word_start] -- [Port] word_start[-1] if c == 32 or c == 9 or c == 44 or c == 59 then -- ' ', '\t', ',', ';' break end @@ -32216,7 +32187,7 @@ function ExampleAppConsoleMT:TextEditCallback(data) end S.ShowExampleAppConsole = { - console = nil, -- ExampleAppConsole, created on first use + console = nil, -- [Port] ExampleAppConsole, created on first use } function ShowExampleAppConsole(p_open) local s = S.ShowExampleAppConsole @@ -32229,7 +32200,7 @@ end ------------------------------------------------------------------------------- S.ShowExampleAppImageViewer = { - image_viewer = nil, -- ExampleImageViewerData, created on first use + image_viewer = nil, -- [Port] ExampleImageViewerData, created on first use } function ShowExampleAppImageViewer(p_open) local s = S.ShowExampleAppImageViewer @@ -32389,7 +32360,7 @@ end -- Demonstrate creating a simple log window with basic filtering. S.ShowExampleAppLog = { - log = nil, -- ExampleAppLog, created on first use + log = nil, -- [Port] ExampleAppLog, created on first use counter = 0, } function ShowExampleAppLog(p_open) @@ -32710,7 +32681,7 @@ end -- Demonstrate creating a simple property editor. S.ShowExampleAppPropertyEditor = { - property_editor = nil, -- ExampleAppPropertyEditor, created on first use + property_editor = nil, -- [Port] ExampleAppPropertyEditor, created on first use demo_data = nil, -- [Port] fallback when called without demo_data } function ShowExampleAppPropertyEditor(p_open, demo_data) @@ -33102,7 +33073,7 @@ S.ShowExampleAppCustomRendering = { opt_enable_grid = true, opt_enable_context_menu = true, adding_line = false, - -- BG/FG draw lists + -- [Port] BG/FG draw lists draw_bg = true, draw_fg = true, } @@ -33823,9 +33794,9 @@ end S.ShowExampleAppDocuments = { app = ExampleAppDocuments(), - opt_target = nil, -- set below to Target_Tab + opt_target = nil, -- [Port] set below to Target_Tab opt_reorderable = true, - opt_fitting_flags = nil, -- set below to ImGuiTabBarFlags.FittingPolicyDefault_ + opt_fitting_flags = nil, -- [Port] set below to ImGuiTabBarFlags.FittingPolicyDefault_ } function ShowExampleAppDocuments(p_open) local s = S.ShowExampleAppDocuments @@ -34561,14 +34532,14 @@ FONT_ATLAS_DEFAULT_TEX_DATA_H = 27 local IM_DRAWLIST_TEX_LINES_WIDTH_MAX = 32 -- The maximum line width to bake anti-aliased textures for. local writef64, writeu32, readf64, readu32 = buffer.writef64, buffer.writeu32, buffer.readf64, buffer.readu32 --- Write vertex i (1-based) of a VtxBuffer.Buf +-- [Port] Write vertex i (1-based) of a VtxBuffer.Buf local function WV(b, i, x, y, u, v, col) local o = (i - 1) * 36 writef64(b, o, x); writef64(b, o + 8, y); writef64(b, o + 16, u); writef64(b, o + 24, v); writeu32(b, o + 32, col) end -local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -- ((ImU16)-1) -local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE -- ((ImU16)-2) +local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -- [Port] ((ImU16)-1) +local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE -- [Port] ((ImU16)-2) --- @param str string --- @return table @@ -34906,7 +34877,7 @@ function ImGui.ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, end end --- Rotate and translate vertices [vert_start_idx, vert_end_idx) (1-based, like _VtxCurrentIdx) +-- [Port] Rotate and translate vertices [vert_start_idx, vert_end_idx) (1-based, like _VtxCurrentIdx) function ImGui.ShadeVertsTransformPos(draw_list, vert_start_idx, vert_end_idx, pivot_in, cos_a, sin_a, pivot_out) local data = draw_list.VtxBuffer.Buf local pix, piy, pox, poy = pivot_in.x, pivot_in.y, pivot_out.x, pivot_out.y @@ -35895,7 +35866,7 @@ local function ImGui_ImplStbTrueType_FontSrcData() } end --- Need this in Lua since I don't want to include 'stbrp' just for context constructor +-- [Port] Need this in Lua since I don't want to include 'stbrp' just for context constructor -- in ImFontAtlasBuilder def code. The cpp code has 'stbrp_context_opaque' which I don't/can't have here --- @param atlas ImFontAtlas local function ImGui_ImplStbTrueType_LoaderInit(atlas) @@ -35903,7 +35874,7 @@ local function ImGui_ImplStbTrueType_LoaderInit(atlas) end local function ImGui_ImplStbTrueType_FontSrcInit(atlas, src) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) --- @type ImGui_ImplStbTrueType_FontSrcData? local bd_font_data = ImGui_ImplStbTrueType_FontSrcData() @@ -35938,12 +35909,12 @@ local function ImGui_ImplStbTrueType_FontSrcInit(atlas, src) end local function ImGui_ImplStbTrueType_FontSrcDestroy(atlas, src) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) src.FontLoaderData = nil end local function ImGui_ImplStbTrueType_FontSrcContainsGlyph(atlas, src, codepoint) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) local bd_font_data = src.FontLoaderData assert(bd_font_data ~= nil) @@ -35952,7 +35923,7 @@ local function ImGui_ImplStbTrueType_FontSrcContainsGlyph(atlas, src, codepoint) end local function ImGui_ImplStbTrueType_FontBakedInit(atlas, src, baked) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) local bd_font_data = src.FontLoaderData if (src.MergeMode == false) then @@ -36131,14 +36102,14 @@ function ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, ba local loader = src.FontLoader and src.FontLoader or atlas.FontLoader loader_data_size = loader_data_size + loader.FontBakedSrcLoaderDataSize end - -- baked.FontLoaderDatas = (loader_data_size > 0) and IM_ALLOC(loader_data_size) or nil + -- [Port] baked.FontLoaderDatas = (loader_data_size > 0) and IM_ALLOC(loader_data_size) or nil -- local loader_data_p = baked->FontLoaderDatas for _, src in font.Sources:iter() do local loader = src.FontLoader and src.FontLoader or atlas.FontLoader if (loader.FontBakedInit) then loader.FontBakedInit(atlas, src, baked--[[, loader_data_p--]]) end - -- loader_data_p += loader->FontBakedSrcLoaderDataSize + -- [Port] loader_data_p += loader->FontBakedSrcLoaderDataSize end ImFontAtlasBuildSetupFontBakedBlanks(atlas, baked) @@ -36202,7 +36173,7 @@ function ImFontAtlasBakedDiscard(atlas, font, baked) end end - -- char* loader_data_p = (char*)baked->FontLoaderDatas + -- [Port] char* loader_data_p = (char*)baked->FontLoaderDatas for _, src in font.Sources:iter() do local loader = src.FontLoader and src.FontLoader or atlas.FontLoader if loader.FontBakedDestroy then @@ -36299,13 +36270,13 @@ end --- @param atlas ImFontAtlas --- @param src ImFontConfig function ImFontAtlasFontDestroySourceData(atlas, src) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) - -- if src.FontDataOwnedByAtlas then + -- [Port] if src.FontDataOwnedByAtlas then -- IM_FREE(src.FontData) -- end src.FontData = nil - -- if src.GlyphExcludeRanges then + -- [Port] if src.GlyphExcludeRanges then -- IM_FREE(src.GlyphExcludeRanges) -- end src.GlyphExcludeRanges = nil @@ -36317,7 +36288,7 @@ end --- @param font ImFont --- @param src ImFontConfig function ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) assert(font.Sources:contains(src)) -- Find Fallback character. Actual glyph loaded in GetFontBaked(). @@ -36472,7 +36443,7 @@ local function ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas) end local function ImFontAtlasBuildUpdatePointers(atlas) - -- for _, font in atlas.Fonts:iter() do + -- [Port] for _, font in atlas.Fonts:iter() do -- font.Sources:resize(0) -- end -- for _, src in atlas.Sources:iter() do @@ -36650,7 +36621,7 @@ function ImFontAtlasPackInit(atlas) end --- @param atlas ImFontAtlas --- #define IM_DRAWLIST_CORNER_POINTS_MAX (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4 + 3) // Max number of points in corner profiles +-- [Port] #define IM_DRAWLIST_CORNER_POINTS_MAX (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4 + 3) // Max number of points in corner profiles -- [Luau] ImVec2 line_normals[] / float line_distances[] / ImVec2 points[] are flat 1-based scratch arrays (x, y, distance). local corner_points_x, corner_points_y = {}, {} local corner_normals_x, corner_normals_y, corner_distances = {}, {}, {} @@ -36696,7 +36667,7 @@ local function InitCornerGeometry(cx, cy, rounding, circle_segment_max_error, li local inv_d = ImRsqrtPrecise(d2) line_normals_x[i] = diff_y * inv_d -- Normal points outwards line_normals_y[i] = -diff_x * inv_d - line_distances[i] = -(points_x[i] * line_normals_x[i] + points_y[i] * line_normals_y[i]) -- -ImDot() + line_distances[i] = -(points_x[i] * line_normals_x[i] + points_y[i] * line_normals_y[i]) -- [Port] -ImDot() end return num_points - 1 @@ -36719,12 +36690,12 @@ local function SampleCornerFillOrStroke(x, y, thickness, line_normals_x, line_no local aa_width = 1.0 if thickness == 0.0 then -- Fill - return math.floor(ImClamp(1.0 - (d + aa_width * 0.5) / aa_width, 0.0, 1.0) * 255.0) -- (ImU8) + return math.floor(ImClamp(1.0 - (d + aa_width * 0.5) / aa_width, 0.0, 1.0) * 255.0) -- [Port] (ImU8) else -- Stroke local outer = 1.0 - (d + aa_width * 0.5) / aa_width local inner = (d + thickness + aa_width * 0.5) / aa_width - return math.floor(ImClamp(ImMin(inner, outer), 0.0, 1.0) * 255.0) -- (ImU8) + return math.floor(ImClamp(ImMin(inner, outer), 0.0, 1.0) * 255.0) -- [Port] (ImU8) end end @@ -36888,7 +36859,7 @@ function ImFontAtlasBuildUpdateTexDataLines(atlas) -- Calculate super sampled line textures for smaller line widths to make transition between sizes smoother. -- Calculate ramp used for all the textures. - local ramp = {} -- ImU8[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT], 0-based + local ramp = {} -- [Port] ImU8[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT], 0-based for n = 0, 4 --[[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT]] - 1 do ramp[n] = math.floor((n / 4 --[[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT]]) * 255.0) end @@ -37149,7 +37120,7 @@ function ImFontAtlasBuildMain(atlas) end -- [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs - -- ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); + -- [Port] ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); -- if atlas.RendererHasTextures == false then -- ~ImGuiBackendFlags.RendererHasTextures -- ImFontAtlasBuildLegacyPreloadAllGlyphRanges(atlas) -- end @@ -37355,7 +37326,7 @@ end --- @param c ImWchar --- @return ImFontGlyph? function MT.ImFontBaked:FindGlyphNoFallback(c) - if c < self.IndexLookup.Size then -- IM_LIKELY + if c < self.IndexLookup.Size then -- [Port] IM_LIKELY local i = self.IndexLookup.Data[c + 1] if i == IM_FONTGLYPH_INDEX_NOT_FOUND then return nil @@ -37388,7 +37359,7 @@ function MT.ImFont:IsGlyphRangeUnused(c_begin, c_last) local page_begin = math.floor(c_begin / 8192) local page_last = math.floor(c_last / 8192) for page_n = page_begin, page_last do - if bit32.rshift(page_n, 3) < (65535 --[[IM_UNICODE_CODEPOINT_MAX]] + 1) / 8192 / 8 then -- sizeof(Used8kPagesMap) + if bit32.rshift(page_n, 3) < (65535 --[[IM_UNICODE_CODEPOINT_MAX]] + 1) / 8192 / 8 then -- [Port] sizeof(Used8kPagesMap) if bit32.band(self.Used8kPagesMap[bit32.rshift(page_n, 3) + 1] or 0, bit32.lshift(1, bit32.band(page_n, 7))) ~= 0 then return false end @@ -37497,7 +37468,7 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) local codepoint = glyph.Codepoint ImFontBaked_BuildGrowIndex(baked, codepoint + 1) baked.IndexAdvanceX.Data[codepoint + 1] = glyph.AdvanceX - baked.IndexLookup.Data[codepoint + 1] = glyph_idx -- (ImU16) + baked.IndexLookup.Data[codepoint + 1] = glyph_idx -- [Port] (ImU16) local page_n = math.floor(codepoint / 8192) baked.OwnerFont.Used8kPagesMap[bit32.rshift(page_n, 3) + 1] = bit32.bor(baked.OwnerFont.Used8kPagesMap[bit32.rshift(page_n, 3) + 1], bit32.lshift(1, bit32.band(page_n, 7))) @@ -37511,7 +37482,7 @@ end --- @param codepoint ImWchar --- @param advance_x float function ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, advance_x) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) if (src ~= nil) then -- Clamp & recenter if needed local ref_size = baked.OwnerFont.Sources[1].SizePixels @@ -37578,7 +37549,7 @@ end --- @return ImWchar --- @nodiscard local function ImFontAtlas_FontHookRemapCodepoint(atlas, font, c) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) if next(font.RemapPairs) ~= nil then -- [Luau] font->RemapPairs.Data.Size != 0 (RemapPairs is a hash table) local ret = font.RemapPairs[c] return (ret ~= nil) and ret or c @@ -37649,7 +37620,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) end end - -- loader_user_data_p = loader_user_data_p + loader.FontBakedSrcLoaderDataSize + -- [Port] loader_user_data_p = loader_user_data_p + loader.FontBakedSrcLoaderDataSize src_n = src_n + 1 end @@ -37760,7 +37731,7 @@ end --- @param c unsigned_int function ImTextClassifierSetCharClass(bits, codepoint_min, codepoint_end, char_class, c) assert(c >= codepoint_min and c < codepoint_end) - -- IM_UNUSED(codepoint_end) + -- [Port] IM_UNUSED(codepoint_end) c = c - codepoint_min local shift = bit32.lshift(bit32.band(c, 15), 1) bits[bit32.rshift(c, 4) + 1] = bit32.bor(bit32.band(bits[bit32.rshift(c, 4) + 1], bit32.bnot(bit32.lshift(0x03, shift))), bit32.lshift(char_class, shift)) @@ -37822,7 +37793,6 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt end -- [Luau] memo per baked font and string: CalcTextSize() and RenderText() of wrapped text ask for the same wrap points -- (same text/pos/width) every frame. The result only depends on these inputs and the (immutable once loaded) glyph advances. - -- ponytail: whole-memo reset at WRAP_MEMO_MAX strings, LRU if dynamic text churns it local memo = baked._WrapMemo if memo == nil or baked._WrapMemoN >= WRAP_MEMO_MAX then memo = {}; baked._WrapMemo = memo; baked._WrapMemoN = 0 @@ -38002,7 +37972,7 @@ local TEXT_SIZE_CACHE_MAX = 4096 function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags) local text_is_str = type(text) == "string" -- [Luau] cache for the common case (whole string, single pass, no wrap/limit): per baked font, text -> unscaled width, line count. - -- Advances of a baked font never change once loaded, so entries stay valid. ponytail: whole-cache reset at TEXT_SIZE_CACHE_MAX entries, LRU if dynamic text churns it + -- Advances of a baked font never change once loaded, so entries stay valid. local cache_key = nil local wrap_cache = nil local text_len1 = text_is_str and #text + 1 or -1 @@ -38433,7 +38403,7 @@ function MT.ImFontAtlas:AddFontFromFileTTF(filename, size_pixels, font_cfg_templ local data, data_size = ImStd.ImFileLoadToMemory(filename, "rb") if not data then if (font_cfg_template == nil or (bit32.band(font_cfg_template.Flags, 2 --[[ImFontFlags.NoLoadError]]) == 0)) then - -- IMGUI_DEBUG_LOG("While loading '%s'\n", filename) + -- [Port] IMGUI_DEBUG_LOG("While loading '%s'\n", filename) IM_ASSERT_USER_ERROR(0, "Could not load font file!") end @@ -38636,7 +38606,7 @@ local function ImAlphaMultiply(col, alpha_mul) return bit32.bor(bit32.band(col, bit32.bnot(4278190080 --[[IM_COL32_A_MASK]])), bit32.lshift(a, 24 --[[IM_COL32_A_SHIFT]])) end --- #define _GetStrokePos(_FLAGS, _DEFAULT_STROKE_POS) +-- [Port] #define _GetStrokePos(_FLAGS, _DEFAULT_STROKE_POS) local function _GetStrokePos(flags, default_stroke_pos) local stroke_pos = bit32.band(flags, 917504 --[[ImDrawFlags.StrokeMask_]]) if stroke_pos ~= 0 then return stroke_pos end @@ -38771,7 +38741,7 @@ function MT.ImDrawListSharedData:SetCircleTessellationMaxError(max_error) assert(max_error > 0) self.CircleTessellationMaxError = max_error - for i = 1, 64 do -- IM_COUNTOF(CircleSegmentCounts) + for i = 1, 64 do -- [Port] IM_COUNTOF(CircleSegmentCounts) local radius = (i - 1) self.CircleSegmentCounts[i] = (i > 1) and IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, self.CircleTessellationMaxError) or 48 --[[IM_DRAWLIST_ARCFAST_SAMPLE_MAX]] end @@ -38793,7 +38763,7 @@ end -- Initialize before use in a new frame. We always have a command ready in the buffer. -- In the majority of cases, you would want to call PushClipRect() and PushTexture() after this. function MT.ImDrawList:_ResetForNewFrame() - self._ContentClipX0 = nil -- set again by Begin() (Roblox backend scroll reuse) + self._ContentClipX0 = nil -- [Port] set again by Begin() (Roblox backend scroll reuse) if self._Splitter._Count > 1 then self._Splitter:Merge(self) end @@ -38814,7 +38784,7 @@ function MT.ImDrawList:_ResetForNewFrame() self._ClipRectStack:resize(0) self._TextureStack:resize(0) self._CallbacksDataBuf:resize(0) - self._DrawFlagsStack.Size = 0 -- _DrawFlagsStack.clear() (ImSmallStack_) + self._DrawFlagsStack.Size = 0 -- [Port] _DrawFlagsStack.clear() (ImSmallStack_) self._Path:resize(0) self.CmdBuffer:push_back(ImDrawCmd()) @@ -38835,7 +38805,7 @@ function MT.ImDrawList:_ClearFreeMemory() self._ClipRectStack:clear() self._TextureStack:clear() self._CallbacksDataBuf:clear() - self._DrawFlagsStack.Size = 0 -- _DrawFlagsStack.clear() (ImSmallStack_) + self._DrawFlagsStack.Size = 0 -- [Port] _DrawFlagsStack.clear() (ImSmallStack_) self._Path:clear() self._Splitter:ClearFreeMemory() end @@ -38917,7 +38887,7 @@ function MT.ImDrawList:AddCallback(callback, userdata, userdata_size) -- [Lua] No raw bytes: the "copy" is a shallow copy of a table userdata (other values are immutable and stored as is), -- so later changes to the caller's table don't affect this command. userdata_size is only recorded. assert(userdata ~= nil) - assert(userdata_size < 2147483648) -- (1u << 31) + assert(userdata_size < 2147483648) -- [Port] (1u << 31) curr_cmd.UserCallbackData = nil -- Will be resolved during Render() curr_cmd.UserCallbackDataSize = userdata_size curr_cmd.UserCallbackDataOffset = self._CallbacksDataBuf.Size -- 0-based @@ -39066,7 +39036,7 @@ end ------------------------------------------------------------------------------- -- FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap.. ------------------------------------------------------------------------------- --- Lua: channels swap ImVector objects with the draw list (C++ memcpy of the vector headers). +-- [Port] channels swap ImVector objects with the draw list (C++ memcpy of the vector headers). -- Channel 0 holds nothing while it is the current channel (its buffers live in the draw list). -- Copy ClipRect, TexRef, VtxOffset (TexRef is assigned by reference, never mutated) @@ -39111,7 +39081,7 @@ function MT.ImDrawListSplitter:Split(draw_list, channels_count) -- Channels[] hold storage that we'll swap with draw_list._CmdBuffer/_IdxBuffer -- The content of Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. -- When we switch to the next channel, we'll copy draw_list._CmdBuffer/_IdxBuffer into Channels[0] and then Channels[1] into draw_list.CmdBuffer/_IdxBuffer - -- Channel 0 is the draw list itself (memset to 0 in C++) + -- [Port] Channel 0 is the draw list itself (memset to 0 in C++) local channels = self._Channels.Data channels[1] = { _CmdBuffer = nil, _IdxBuffer = nil } for i = 2, channels_count do @@ -39183,7 +39153,7 @@ function MT.ImDrawListSplitter:Merge(draw_list) local src_cmds = ch._CmdBuffer.Data for n = 1, ch._CmdBuffer.Size do dst_cmds[cmd_write] = src_cmds[n] - src_cmds[n] = nil -- ownership moved to the draw list + src_cmds[n] = nil -- [Port] ownership moved to the draw list cmd_write = cmd_write + 1 end end @@ -39283,7 +39253,7 @@ end function MT.ImDrawList:PushDrawFlag(flags, enabled) assert(bit32.band(flags, bit32.bnot(8286704 --[[ImDrawFlags.AllowInPushScope_]])) == 0) assert(bit32.band(flags, 917504 --[[ImDrawFlags.StrokeMask_]]) == 0 or bit32.band(flags, 917504 --[[ImDrawFlags.StrokeMask_]]) == 917504 --[[ImDrawFlags.StrokeLegacy]]) - IM_ASSERT_USER_ERROR_RET(self._DrawFlagsStack.Size < 3, "PushDrawFlag() has a depth limit. Contact us.") -- _DrawFlagsStack.capacity() == 3 + IM_ASSERT_USER_ERROR_RET(self._DrawFlagsStack.Size < 3, "PushDrawFlag() has a depth limit. Contact us.") -- [Port] _DrawFlagsStack.capacity() == 3 self._DrawFlagsStack:push_back(self.Flags) if enabled then self.Flags = bit32.bor(self.Flags, flags) @@ -39489,7 +39459,7 @@ local function _SelectLineTexture(self, screen_thickness, flags) end -- Scale the fringe so that the texture matches the line thickness. - local tex_uvs = self._Data.TexUvLines[texture_idx] -- 0-based table + local tex_uvs = self._Data.TexUvLines[texture_idx] -- [Port] 0-based table return tex_uvs.x, tex_uvs.z, tex_uvs.y, tex_uvs.z, self._FringeScale * screen_thickness * tex_uvs.w -- tex_uvs.w = 1 / thickness else -- For no anti-alias we use fully opaque texture, and no fringe expansion. @@ -39543,7 +39513,7 @@ function MT.ImDrawList:_AddPolyline(points, points_count, col, thickness, flags, local dy = p1.y - p0.y local d2 = dx * dx + dy * dy local inv_len = 0.0 - if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- ImRsqrtPrecise() + if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- [Port] ImRsqrtPrecise() normals_x[i] = -dy * inv_len normals_y[i] = dx * inv_len sqr_lengths[i] = d2 @@ -39555,7 +39525,7 @@ function MT.ImDrawList:_AddPolyline(points, points_count, col, thickness, flags, local dy = p1.y - p0.y local d2 = dx * dx + dy * dy local inv_len = 0.0 - if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- ImRsqrtPrecise() + if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- [Port] ImRsqrtPrecise() normals_x[points_count] = -dy * inv_len normals_y[points_count] = dx * inv_len sqr_lengths[points_count] = d2 @@ -39618,8 +39588,8 @@ function MT.ImDrawList:_AddPolyline(points, points_count, col, thickness, flags, local vb = self.VtxBuffer.Buf local ib = self.IdxBuffer.Data - local vw = self._VtxWritePtr -- 1-based write position in VtxBuffer - local iw = self._IdxWritePtr -- 1-based write position in IdxBuffer + local vw = self._VtxWritePtr -- [Port] 1-based write position in VtxBuffer + local iw = self._IdxWritePtr -- [Port] 1-based write position in IdxBuffer local vtx_idx = self._VtxCurrentIdx local first_vtx_offset = vw local first_vtx_idx = vtx_idx -- [Luau] VtxBuffer position of index 'n' is first_vtx_offset + (n - first_vtx_idx) @@ -39914,7 +39884,7 @@ function MT.ImDrawList:AddConvexPolyFilled(points, points_count, col, flags) local dy = p1.y - p0.y local d2 = dx * dx + dy * dy if d2 > 0.0 then - local inv_len = 1.0 / math.sqrt(d2) -- ImRsqrtPrecise() + local inv_len = 1.0 / math.sqrt(d2) -- [Port] ImRsqrtPrecise() dx = dx * inv_len dy = dy * inv_len end @@ -40103,7 +40073,7 @@ local function PathRectXY(self, ax, ay, bx, by, rounding, flags) if not rounding then rounding = 0.0 end if not flags then flags = 0 end - local has_rounding = rounding >= 0.25 * self._FringeScale -- IM_HAS_ROUNDING(rounding) + local has_rounding = rounding >= 0.25 * self._FringeScale -- [Port] IM_HAS_ROUNDING(rounding) if has_rounding then if bit32.band(flags, 496 --[[ImDrawFlags.RoundMask_]]) == 0 then flags = bit32.bor(flags, 240 --[[ImDrawFlags.RoundAll]]) @@ -40158,7 +40128,7 @@ local function _AddLineXY(self, p1x, p1y, p2x, p2y, col, thickness, flags) local dir_y = p2y - p1y local d2 = dir_x * dir_x + dir_y * dir_y local inv_len = 0.0 - if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- ImRsqrtPrecise() + if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- [Port] ImRsqrtPrecise() dir_x = dir_x * inv_len dir_y = dir_y * inv_len local norm_x = -dir_y @@ -40323,7 +40293,7 @@ function MT.ImDrawList:AddLineH(min_x, max_x, y, col, thickness, flags) top_y = top_y - thickness end - local is_truncated = min_x % 1 == 0 and max_x % 1 == 0 and top_y % 1 == 0 and thickness % 1 == 0 -- IM_IS_TRUNCATED4() + local is_truncated = min_x % 1 == 0 and max_x % 1 == 0 and top_y % 1 == 0 and thickness % 1 == 0 -- [Port] IM_IS_TRUNCATED4() if self._FringeScaleIsInteger and is_truncated and bit32.band(flags, 2048 --[[ImDrawFlags.CapSquare]]) == 0 then if thickness < self._FringeScale then if thickness < (1.0 / 255.0) * self._FringeScale then @@ -40379,7 +40349,7 @@ function MT.ImDrawList:AddLineV(x, min_y, max_y, col, thickness, flags) left_x = left_x - thickness end - local is_truncated = left_x % 1 == 0 and min_y % 1 == 0 and max_y % 1 == 0 and thickness % 1 == 0 -- IM_IS_TRUNCATED4() + local is_truncated = left_x % 1 == 0 and min_y % 1 == 0 and max_y % 1 == 0 and thickness % 1 == 0 -- [Port] IM_IS_TRUNCATED4() if self._FringeScaleIsInteger and is_truncated and bit32.band(flags, 2048 --[[ImDrawFlags.CapSquare]]) == 0 then if thickness < self._FringeScale then if thickness < (1.0 / 255.0) * self._FringeScale then @@ -40423,7 +40393,7 @@ end -- [Luau] _AddRectBaked() taking p_min/p_max as scalars @native local function _AddRectBakedXY(self, p_min_x, p_min_y, p_max_x, p_max_y, col, r, t, tex_uvs, flags) - local uv_l, uv_t, uv_r, uv_b = tex_uvs.x, tex_uvs.y, tex_uvs.z, tex_uvs.w -- uv_tl = (l,t), uv_tr = (r,t), uv_br = (r,b), uv_bl = (l,b) + local uv_l, uv_t, uv_r, uv_b = tex_uvs.x, tex_uvs.y, tex_uvs.z, tex_uvs.w -- [Port] uv_tl = (l,t), uv_tr = (r,t), uv_br = (r,b), uv_bl = (l,b) local idx_allocated = 8 * 2 * 3 local vtx_allocated = 8 * 4 @@ -40519,7 +40489,7 @@ function MT.ImDrawList:_AddRectBaked(p_min, p_max, col, r, t, tex_uvs, flags) _AddRectBakedXY(self, p_min.x, p_min.y, p_max.x, p_max.y, col, r, t, tex_uvs, flags) end -local corner_offset_x = { 1, -1, -1, 1 } -- static const ImVec2 corner_offset[4] = { {1,1}, {-1,1}, {-1,-1}, {1,-1} }; +local corner_offset_x = { 1, -1, -1, 1 } -- [Port] static const ImVec2 corner_offset[4] = { {1,1}, {-1,1}, {-1,-1}, {1,-1} }; local corner_offset_y = { 1, 1, -1, -1 } local corner_flags = { ImDrawFlags.RoundTopLeft, ImDrawFlags.RoundTopRight, ImDrawFlags.RoundBottomRight, ImDrawFlags.RoundBottomLeft } local corner_pos_x, corner_pos_y = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } -- [Luau] scratch @@ -40691,7 +40661,7 @@ function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags) end local fringe_scale = self._FringeScale - local has_rounding = rounding >= 0.25 * fringe_scale -- IM_HAS_ROUNDING(rounding) + local has_rounding = rounding >= 0.25 * fringe_scale -- [Port] IM_HAS_ROUNDING(rounding) -- Calculate the outer boundary of the rectangle based on the stroke position. local offset = 0.0 -- Inside @@ -40726,7 +40696,7 @@ function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags) outer_rounding = ImMin(outer_rounding, ImAbs(height) * (((bit32.band(flags, 80 --[[ImDrawFlags.RoundLeft]]) == 80 --[[ImDrawFlags.RoundLeft]]) or (bit32.band(flags, 160 --[[ImDrawFlags.RoundRight]]) == 160 --[[ImDrawFlags.RoundRight]])) and 0.5 or 1.0) - 1.0) end - local is_truncated = outer_min_x % 1 == 0 and outer_min_y % 1 == 0 and outer_max_x % 1 == 0 and outer_max_y % 1 == 0 and outer_rounding % 1 == 0 and thickness % 1 == 0 -- IM_IS_TRUNCATED4() x2 + local is_truncated = outer_min_x % 1 == 0 and outer_min_y % 1 == 0 and outer_max_x % 1 == 0 and outer_max_y % 1 == 0 and outer_rounding % 1 == 0 and thickness % 1 == 0 -- [Port] IM_IS_TRUNCATED4() x2 if self._FringeScaleIsInteger and is_truncated then local s_rounding = ImTrunc64(outer_rounding * self._InvFringeScale) local s_thickness = ImTrunc64(thickness * self._InvFringeScale) @@ -40822,7 +40792,7 @@ end @native local function _AddRectFilledBakedXY(self, p_min_x, p_min_y, p_max_x, p_max_y, col, r, tex_uvs, flags) -- 9-slice with corner mirroring - local uv_l, uv_t, uv_r, uv_b = tex_uvs.x, tex_uvs.y, tex_uvs.z, tex_uvs.w -- uv_tl = (l,t), uv_tr = (r,t), uv_br = (r,b), uv_bl = (l,b) + local uv_l, uv_t, uv_r, uv_b = tex_uvs.x, tex_uvs.y, tex_uvs.z, tex_uvs.w -- [Port] uv_tl = (l,t), uv_tr = (r,t), uv_br = (r,b), uv_bl = (l,b) PrimReserve(self, 9 * 2 * 3, 4 * 4) @@ -40930,8 +40900,8 @@ function MT.ImDrawList:AddRectFilled(p_min, p_max, col, rounding, flags) end -- When rounding non-integer and under threshold, has_rounding may be false but still affect is_truncated. Likely not worth catering for. - local has_rounding = bit32.band(flags, 496 --[[ImDrawFlags.RoundMask_]]) ~= 256 --[[ImDrawFlags.RoundNone]] and rounding >= 0.25 * fringe_scale -- IM_HAS_ROUNDING(rounding) - local is_truncated = ax % 1 == 0 and ay % 1 == 0 and bx % 1 == 0 and by % 1 == 0 and rounding % 1 == 0 -- IM_IS_TRUNCATED4() && IM_IS_TRUNCATED() + local has_rounding = bit32.band(flags, 496 --[[ImDrawFlags.RoundMask_]]) ~= 256 --[[ImDrawFlags.RoundNone]] and rounding >= 0.25 * fringe_scale -- [Port] IM_HAS_ROUNDING(rounding) + local is_truncated = ax % 1 == 0 and ay % 1 == 0 and bx % 1 == 0 and by % 1 == 0 and rounding % 1 == 0 -- [Port] IM_IS_TRUNCATED4() && IM_IS_TRUNCATED() if self._FringeScaleIsInteger and is_truncated then -- Fast path for the non-AA non-rounded rect. @@ -41373,7 +41343,7 @@ local AddText_clip_rect = ImVec4() @native function MT.ImDrawList:AddText(font, font_size, pos, col, text, text_begin, text_end, wrap_width, cpu_fine_clip_rect) - -- Overload: AddText(pos, col, text, text_end?) + -- [Port] Overload: AddText(pos, col, text, text_end?) if type(font) == "table" and type(font[1]) == "number" then font, font_size, pos, col, text, text_begin, text_end, wrap_width, cpu_fine_clip_rect = nil, 0.0, font, font_size, pos, 1, col, 0.0, nil if text_end == nil then text_end = #text + 1 end @@ -41506,7 +41476,7 @@ function MT.ImDrawList:_CalcCircleAutoSegmentCount(radius) -- Automatic segment count local radius_idx = ImFloor(radius + 0.999) + 1 -- ceil to never reduce accuracy - if radius_idx >= 1 and radius_idx <= 64 then -- IM_COUNTOF(_Data->CircleSegmentCounts) + if radius_idx >= 1 and radius_idx <= 64 then -- [Port] IM_COUNTOF(_Data->CircleSegmentCounts) return self._Data.CircleSegmentCounts[radius_idx] -- Use cached value else return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, self._Data.CircleTessellationMaxError) @@ -41546,7 +41516,7 @@ function MT.ImDrawList:PopClipRect() local stack = self._ClipRectStack assert(stack.Size > 0) stack.Size = stack.Size - 1 -- [Luau] inline pop_back() - if (stack.Size == 0) then -- LUA: No "Ternary Operator" + if (stack.Size == 0) then -- [Port] No "Ternary Operator" ImVec4_Copy(self._CmdHeader.ClipRect, self._Data.ClipRectFullscreen) else ImVec4_Copy(self._CmdHeader.ClipRect, stack.Data[stack.Size]) @@ -41565,7 +41535,7 @@ function MT.ImDrawList:GetClipRectMax() local cr = self._ClipRectStack:back(); r -- [Luau] scalar center (cx, cy); assigned to the forward-declared local, _PathArcToFastEx() wraps it @native function _PathArcToFastExXY(self, cx, cy, radius, a_min_sample, a_max_sample, a_step) - if not (radius >= 0.25 * self._FringeScale) then -- !IM_HAS_ROUNDING(radius) + if not (radius >= 0.25 * self._FringeScale) then -- [Port] !IM_HAS_ROUNDING(radius) PathLineToXY(self, cx, cy) return end @@ -41671,7 +41641,7 @@ end -- 0: East, 3: South, 6: West, 9: North, 12: East @native function MT.ImDrawList:PathArcToFast(center, radius, a_min_of_12, a_max_of_12) - if not (radius >= 0.25 * self._FringeScale) then -- !IM_HAS_ROUNDING(radius) + if not (radius >= 0.25 * self._FringeScale) then -- [Port] !IM_HAS_ROUNDING(radius) self._Path:push_back(center) return end @@ -41685,7 +41655,7 @@ end --- @param a_max float --- @param num_segments int function MT.ImDrawList:_PathArcToN(center, radius, a_min, a_max, num_segments) - if not (radius >= 0.25 * self._FringeScale) then -- !IM_HAS_ROUNDING(radius) + if not (radius >= 0.25 * self._FringeScale) then -- [Port] !IM_HAS_ROUNDING(radius) self._Path:push_back(center) return end @@ -41713,7 +41683,7 @@ end function MT.ImDrawList:PathArcTo(center, radius, a_min, a_max, num_segments) if num_segments == nil then num_segments = 0 end - if not (radius >= 0.25 * self._FringeScale) then -- !IM_HAS_ROUNDING(radius) + if not (radius >= 0.25 * self._FringeScale) then -- [Port] !IM_HAS_ROUNDING(radius) self._Path:push_back(center) return end @@ -41792,8 +41762,6 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b y = IM_TRUNC(y) end - -- if not text_end then - -- end local line_height = size local baked = self:GetFontBaked(size) @@ -41913,7 +41881,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b if gi ~= nil and gi ~= IM_FONTGLYPH_INDEX_NOT_FOUND and gi ~= IM_FONTGLYPH_INDEX_UNUSED then glyph = glyphs[gi] else - glyph = baked:FindGlyph(c) -- may load the glyph and grow the tables + glyph = baked:FindGlyph(c) -- [Port] may load the glyph and grow the tables lookup, lookup_n, glyphs = baked.IndexLookup.Data, baked.IndexLookup.Size, baked.Glyphs.Data end @@ -41988,7 +41956,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b draw_list:PrimUnreserve(idx_count_max, vtx_count_max) draw_list:AddDrawCmd() - return self:RenderText(draw_list, size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, flags) -- was `goto begin` + return self:RenderText(draw_list, size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, flags) -- [Port] was `goto begin` end -- Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action. @@ -42021,7 +41989,7 @@ end --- @param color ImU32 --- @param dir ImGuiDir --- @param scale? float -local arrow_a, arrow_b, arrow_c = ImVec2(), ImVec2(), ImVec2() -- scratch: the path is consumed by AddTriangleFilled before returning +local arrow_a, arrow_b, arrow_c = ImVec2(), ImVec2(), ImVec2() -- [Port] scratch: the path is consumed by AddTriangleFilled before returning function ImGui.RenderArrow(draw_list, pos, color, dir, scale) if scale == nil then scale = 1.0 end @@ -42297,7 +42265,7 @@ function ImGui.RenderRectFilledWithHole(draw_list, outer, inner, col, rounding) end ------------------------------------------------------------------------------- --- Extra path functions (elliptical arc, bezier curves) and concave fill +-- [Port] Extra path functions (elliptical arc, bezier curves) and concave fill ------------------------------------------------------------------------------- function MT.ImDrawList:PathEllipticalArcTo(center, radius, rot, a_min, a_max, num_segments) @@ -42410,7 +42378,7 @@ local function ImTriangulatorNode_Unlink(tri, n) tri.Prev[tri.Next[n]] = tri.Pre local function ImTriangulator_IsReflex(a, b, c) return ((b.x - a.x) * (c.y - b.y)) - ((c.x - b.x) * (b.y - a.y)) < 0.0 end local function ImTriangulatorNodeSpan() - return { Data = {}, Size = 0 } -- Data: node handles, 1-based + return { Data = {}, Size = 0 } -- [Port] Data: node handles, 1-based end MT.ImTriangulatorNodeSpan = {} MT.ImTriangulatorNodeSpan.__index = MT.ImTriangulatorNodeSpan @@ -42422,7 +42390,7 @@ function MT.ImTriangulatorNodeSpan:find_erase_unsorted(idx) for i = self.Size, 1 local function ImTriangulator() return setmetatable({ _TrianglesLeft = 0, - _Nodes = 0, -- node handle (head of the circular list) + _Nodes = 0, -- [Port] node handle (head of the circular list) _Ears = setmetatable(ImTriangulatorNodeSpan(), MT.ImTriangulatorNodeSpan), _Reflexes = setmetatable(ImTriangulatorNodeSpan(), MT.ImTriangulatorNodeSpan), Type = {}, Index = {}, Pos = {}, Next = {}, Prev = {}, -- [Luau] ImTriangulatorNode fields, one array each @@ -42853,7 +42821,7 @@ function stb_decompress(output, i, length) end end -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value end __FILES['imgui_h.lua'] = function() @@ -42873,7 +42841,7 @@ __FILES['imgui_h.lua'] = function() -- Index of this file: -- [SECTION] Forward declarations and basic types --- [SECTION] METATABLE MANAGEMENT +-- [Port] [SECTION] METATABLE MANAGEMENT -- [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> -- [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) -- [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) @@ -42892,7 +42860,7 @@ __FILES['imgui_h.lua'] = function() local type = type -- [Luau] builtin (FASTCALL); ImGui._GetTypeFunc() kept for compatibility local rawget = rawget; local rawset = rawset --- [LuaBitOp](https://bitop.luajit.org/semantics.html) +-- [Port] [LuaBitOp](https://bitop.luajit.org/semantics.html) local bitAnd = bit32.band; local bitOr = bit32.bor local bitLShift = bit32.lshift @@ -42997,10 +42965,10 @@ IM_FREE = ImGui.MemFree IM_DELETE = function(owner, field) if owner[field] ~= nil then owner[field] = nil; ImGui.MemFree(owner, field); end end ------------------------------------------------------------------------------- --- [SECTION] METATABLE MANAGEMENT +-- [Port] [SECTION] METATABLE MANAGEMENT ------------------------------------------------------------------------------- ---- File-scope metatable storage +--- [Port] File-scope metatable storage local MT = {} function ImGui.GetMetatables() return MT end @@ -43012,7 +42980,7 @@ function IM_ASSERT(_EXPR, _MSG) assert((_EXPR), _MSG) end IM_ASSERT_PARANOID = IM_ASSERT -- A primary data type ---- Note that `S64` and `U64` are not supported +--- [Port] Note that `S64` and `U64` are not supported --- @enum ImGuiDataType ImGuiDataType = { @@ -43193,7 +43161,7 @@ function ImVec2_SubVA(v, sub_x, sub_y) return v.x - sub_x, v.y - sub_y end function ImVec2_MulVX(a, scalar) return a.x * scalar, a.y * scalar end ---- An inlined version of `ImVec2_Copy` currently for use in certain ImVector `push_back` +--- [Port] An inlined version of `ImVec2_Copy` currently for use in certain ImVector `push_back` local function ImVec2_TCopy(t, k, v) local dest = t[k]; dest.x = v.x; dest.y = v.y; end -- ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type] @@ -43242,7 +43210,7 @@ function ImVec4_Copy(dest, src) dest.x = src.x; dest.y = src.y; dest.z = src.z; ------------------------------------------------------------------------------- -- ImVector<> ---- A compact ImVector clone +--- [Port] A compact ImVector clone --- @class ImVector --- @field Data T[] # 1-based table --- @field Size int # >= 0 @@ -43250,22 +43218,22 @@ function ImVec4_Copy(dest, src) dest.x = src.x; dest.y = src.y; dest.z = src.z; --- @field _CopyFunc function local IM_VECTOR = {} --- Support 1-based number key indexing while keep method accessing speed +-- [Port] Support 1-based number key indexing while keep method accessing speed --- @param t ImVector --- @param k string|int --- @return any IM_VECTOR.__index = function(t, k) - local m = IM_VECTOR[k] -- methods first (hot path) + local m = IM_VECTOR[k] -- [Port] methods first (hot path) if m ~= nil then return m end - if k == "Data" then return nil end -- Data has already been discarded - return t.Data[IM_ASSERT(k >= 1 and k <= t.Size) or k] -- if the mt access turns out nil, the k must be int index into Data + if k == "Data" then return nil end -- [Port] Data has already been discarded + return t.Data[IM_ASSERT(k >= 1 and k <= t.Size) or k] -- [Port] if the mt access turns out nil, the k must be int index into Data end --- @param t ImVector --- @param k int --- @param v any IM_VECTOR.__newindex = function(t, k, v) - if k == "Data" then rawset(t, "Data", v); return; end -- set new Data. old Data is already discarded + if k == "Data" then rawset(t, "Data", v); return; end -- [Port] set new Data. old Data is already discarded assert(k >= 1 and k <= t.Size) t.Data[k] = v end @@ -43328,10 +43296,10 @@ end function IM_VECTOR:swap(other) self.Size, other.Size = other.Size, self.Size; self.Capacity, other.Capacity = other.Capacity, self.Capacity; self.Data, other.Data = other.Data, self.Data end function IM_VECTOR:contains(v) for i = 1, self.Size do if self.Data[i] == v then return true end end return false end --- NOTE: This currently does not use type-aware copy! +-- [Port] NOTE: This currently does not use type-aware copy! function IM_VECTOR:insert(pos, value) assert(pos >= 1 and pos <= self.Size + 1); if self.Size == self.Capacity then self:reserve(_grow_capacity(self, self.Size + 1)) end; for i = self.Size, pos, -1 do self.Data[i + 1] = self.Data[i] end self.Data[pos] = value self.Size = self.Size + 1 return value end --- NOTE: This currently does not copy type related info! +-- [Port] NOTE: This currently does not copy type related info! --- @nodiscard function IM_VECTOR:copy() local v = ImVector(); v:resize(self.Size) @@ -43340,7 +43308,7 @@ function IM_VECTOR:copy() return v end --- Not keeping value-key records inside `ImVector`, instead just find it +-- [Port] Not keeping value-key records inside `ImVector`, instead just find it --- @return int # 0-based index function IM_VECTOR:index_from_ptr(p) local data = self.Data; for i = 1, self.Size do if p == data[i] then return i - 1 end end @@ -43458,7 +43426,7 @@ function ImDrawChannel() return { _CmdBuffer = ImVector(), _IdxBuffer = ImVector --- @return ImDrawListSplitter --- @nodiscard -MT.ImDrawListSplitter = {} -- methods in imgui_draw.lua +MT.ImDrawListSplitter = {} -- [Port] methods in imgui_draw.lua MT.ImDrawListSplitter.__index = MT.ImDrawListSplitter function ImDrawListSplitter() return setmetatable({ _Current = 0, _Count = 0, _Channels = ImVector() }, MT.ImDrawListSplitter) end @@ -44204,7 +44172,7 @@ function ImGuiIO() -- - Suggested use, e.g. io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map to SHIFT modifier ConfigDebugDrawListDefaultsToStrokeLegacy = false, -- false -- Default all ImDrawList to ImDrawList_StrokeLegacy mode, mimicking pre-1.93.0 rendering. - IniFilename = "imgui.ini", -- Roblox: no disk access, only used as a flag (nil disables .ini handling) + IniFilename = "imgui.ini", -- [Port] no disk access, only used as a flag (nil disables .ini handling) IniSavingRate = 5.0, -- = 5.0f -- Minimum time between saving positions/sizes to .ini file, in seconds. LogFilename = "imgui_log.txt", -- = "imgui_log.txt"-- Path to .log file (default parameter to ImGui.LogToFile when no file is specified). WantSaveIniSettings = false, -- When manual .ini load/save is active (io.IniFilename == nil), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! @@ -44971,7 +44939,7 @@ ImGuiKey = { RightCtrl = 531, RightShift = 532, RightAlt = 533, RightSuper = 534, Menu = 535, - -- 0 ~ 9 (upstream ImGuiKey_0..ImGuiKey_9: K0..K9 in this port, ImGuiKey["0"]..ImGuiKey["9"] are aliases) + -- [Port] 0 ~ 9 (upstream ImGuiKey_0..ImGuiKey_9: K0..K9 in this port, ImGuiKey["0"]..ImGuiKey["9"] are aliases) K0 = 536, K1 = 537, K2 = 538, K3 = 539, K4 = 540, K5 = 541, K6 = 542, K7 = 543, K8 = 544, K9 = 545, ["0"] = 536, ["1"] = 537, ["2"] = 538, ["3"] = 539, ["4"] = 540, ["5"] = 541, ["6"] = 542, ["7"] = 543, ["8"] = 544, ["9"] = 545, @@ -45393,7 +45361,7 @@ ImGuiInputTextFlags = { --- @class ImGuiInputTextCallbackData --- @return ImGuiInputTextCallbackData --- Buf is a 1-based zero-terminated byte table; positions (CursorPos, pos...) are 0-based byte offsets like upstream. +-- [Port] Buf is a 1-based zero-terminated byte table; positions (CursorPos, pos...) are 0-based byte offsets like upstream. MT.ImGuiInputTextCallbackData = {} MT.ImGuiInputTextCallbackData.__index = MT.ImGuiInputTextCallbackData function ImGuiInputTextCallbackData() @@ -45403,7 +45371,7 @@ end function MT.ImGuiInputTextCallbackData:DeleteChars(pos, bytes_count) assert(pos + bytes_count <= self.BufTextLen) local buf = self.Buf - local n = self.BufTextLen - bytes_count - pos + 1 -- includes zero terminator + local n = self.BufTextLen - bytes_count - pos + 1 -- [Port] includes zero terminator for i = 1, n do buf[pos + i] = buf[pos + bytes_count + i] end if self.CursorPos >= pos + bytes_count then @@ -45424,10 +45392,10 @@ function MT.ImGuiInputTextCallbackData:InsertChars(pos, new_text) -- We support partial insertion local avail = self.BufSize - 1 - self.BufTextLen if not is_resizable and new_text_len > avail then - new_text_len = avail -- ponytail: truncates by bytes, not to the closest UTF-8 codepoint + new_text_len = avail end if new_text_len <= 0 then return end - -- ponytail: CallbackResize buffer growth not supported, text is truncated at BufSize instead + if self.BufTextLen + new_text_len + 1 > self.BufSize then new_text_len = self.BufSize - 1 - self.BufTextLen if new_text_len <= 0 then return end @@ -45661,7 +45629,7 @@ end -- Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() --- @class ImGuiPayload ---- Drag and drop payload. `Data` is any Lua value (C++ stores raw bytes); `DataSize` kept for API parity. +--- [Port] Drag and drop payload. `Data` is any Lua value (C++ stores raw bytes); `DataSize` kept for API parity. local IM_PAYLOAD = {} IM_PAYLOAD.__index = IM_PAYLOAD function IM_PAYLOAD:Clear() ImGuiPayload_Clear(self) end @@ -45839,52 +45807,2361 @@ function ImGuiMultiSelectIO() return { Requests = ImVector(ImGuiSelectionRequest, ImGuiSelectionRequest_Copy), RangeSrcItem = -1, NavIdItem = -1, NavIdSelected = false, RangeSrcReset = false, ItemsCount = 0 } end --- ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage: see [SECTION] Widgets: Multi-Select helpers in imgui_widgets.lua +-- [Port] ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage: see [SECTION] Widgets: Multi-Select helpers in imgui_widgets.lua -- (constructors and methods are defined there, like upstream's out-of-line definitions in imgui_widgets.cpp). --- @class ImGuiSettingsHandler ---- Fns take (ctx, handler, ...) like upstream. ReadOpenFn(ctx, handler, name) returns entry; ReadLineFn(ctx, handler, entry, line); +--- [Port] Fns take (ctx, handler, ...) like upstream. ReadOpenFn(ctx, handler, name) returns entry; ReadLineFn(ctx, handler, entry, line); --- WriteAllFn(ctx, handler, buf: ImGuiTextBuffer) function ImGuiSettingsHandler() return { TypeName = nil, TypeHash = 0, ClearAllFn = nil, ReadInitFn = nil, ReadOpenFn = nil, ReadLineFn = nil, ApplyAllFn = nil, WriteAllFn = nil, CleanupFn = nil, UserData = nil } end -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value end __FILES['imgui_impl_roblox.lua'] = function() ---- ImGui Backend for Roblox ---- - Renderer: exact software rasterizer (1:1 with imgui's triangles) into 256x256 EditableImage tiles at native ---- screen resolution; only tiles whose content changed are redrawn/uploaded (see RenderDrawData). ---- - Platform: UserInputService ---- - Files: an in-memory file system (VFS), pre-filled with the fonts from imgui_impl_roblox_fonts.lua ---- Requires "Allow Mesh / Image APIs" (EditableImage) in game settings. +local Raster, Textures, Layers, Overlays, Render, Parallel +do +-- Software rasterizer: pure buffer code shared by the backend and the parallel worker (inlined into ImGuiWorker). +-- Target: RGBA8 row-major (ImU32 is already R | G<<8 | B<<16 | A<<24), non-premultiplied "over" onto transparent. +local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 +local readf64 = buffer.readf64 +local band, rshift = bit32.band, bit32.rshift +local readi32 = buffer.readi32 + +local M = { + TILE = 128, + -- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs. + -- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2), tex id (-1: none), clip x0 y0 x1 y1, + -- bounds x0 y0 x1 y1 (screen pixels, i32), then raw vertices (VTX bytes: x y u v f64, col u32): a at REC_A, + -- c at REC_C, b at REC_B. + -- T job: tox toy (f64), x0 y0 nr count (i32), nr x rect x0 y0 x1 y1 (i32, tile pixels), count x P offset (i32). + VTX = 36, REC = 148, REC_A = 40, REC_C = 76, REC_B = 112, JOB = 32, +} +local TILE = M.TILE + +local TargetBuffer: buffer, TargetWidth = buffer.create(0), 0 +local PrevRow = buffer.create(1024) + +-- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else +-- remembers this row. u32 loop, not readstring ==: that allocated a string per row. +@native +local function RowRepeats(o: number, len: number, has_prev: boolean): boolean + if has_prev then + local same = true + for k = 0, len - 4, 4 do + if readu32(TargetBuffer, o + k) ~= readu32(PrevRow, k) then + same = false + break + end + end + if same then return true end + end + if buffer.len(PrevRow) < len then PrevRow = buffer.create(len) end + buffer.copy(PrevRow, 0, TargetBuffer, o, len) + return false +end +local RectColumns = table.create(256, 0) + +-- FillSpan and DrawTriangle's flat path inline this math with per-span constants: keep them in sync. +@native +local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number, b: number, a: number) + if a >= 255 then + writeu32(TargetBuffer, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080) + return + end + if a <= 0 then return end + local d = readu32(TargetBuffer, o) + if d < 16777216 then + writeu32(TargetBuffer, o, + floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216) + return + end + local sa = a / 255 + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + local ns = 1 - sa + writeu32(TargetBuffer, o, + floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256 + floor(b * sa + db * ns + 0.5) * 65536 + + 4278190080) + else + local k = rshift(d, 24) * ((1 - sa) / 255) + local oa = sa + k + local inv = 1 / oa + writeu32(TargetBuffer, o, floor((r * sa + dr * k) * inv + 0.5) + floor((g * sa + dg * k) * inv + 0.5) * 256 + + floor((b * sa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + end +end + +@native +local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number, + b: number, a: number) + if a <= 0 then return end + local w4 = (x1 - x0 - 1) * 4 + if a >= 255 then + local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080 + local first = (y0 * TargetWidth + x0) * 4 + for o = first, first + w4, 4 do writeu32(TargetBuffer, o, packed) end + for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end + return + end + local packed0 = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216 + local sa = a / 255 + local ns = 1 - sa + local c1 = ns / 255 + local rs, gs, bs = r * sa, g * sa, b * sa + local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination + for y = y0, y1 - 1 do + local o0 = (y * TargetWidth + x0) * 4 + for o = o0, o0 + w4, 4 do + local d = readu32(TargetBuffer, o) + if d == last_d then + writeu32(TargetBuffer, o, last_v) + elseif d < 16777216 then + writeu32(TargetBuffer, o, packed0) + else + last_d = d + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + last_v = floor(rs + dr * ns + 0.5) + floor(gs + dg * ns + 0.5) * 256 + + floor(bs + db * ns + 0.5) * 65536 + 4278190080 + else + local k = rshift(d, 24) * c1 + local oa = sa + k + local inv = 1 / oa + last_v = floor((rs + dr * k) * inv + 0.5) + floor((gs + dg * k) * inv + 0.5) * 256 + + floor((bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 + end + writeu32(TargetBuffer, o, last_v) + end + end + end +end + +@native +local function UnpackColor(col: number) + return col % 256, floor(col / 256) % 256, floor(col / 65536) % 256, floor(col / 16777216) % 256 +end + +@native +local function SampleTexture(t, u: number, v: number) + local tw, th = t.Width, t.Height + local tx, ty = floor(u * tw), floor(v * th) + if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end + if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end + local o = (ty * tw + tx) * 4 + local tb = t.Buffer + return readu8(tb, o), readu8(tb, o + 1), readu8(tb, o + 2), readu8(tb, o + 3) +end + +@native +local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, u0: number, v0: number, + u1: number, v1: number, col: number, t, cx0: number, cy0: number, cx1: number, cy1: number) + local r, g, b, a = UnpackColor(col) + if a == 0 then return end + local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0) + local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1) + if px0 >= px1 or py0 >= py1 then return end + + if not t or (u0 == u1 and v0 == v1) then + if t then + local tr, tg, tb, ta = SampleTexture(t, u0, v0) + r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255 + end + if a <= 0 then return end + if a >= 255 or px1 - px0 < 32 then + FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a) + return + end + -- Wide translucent rect: rows usually blend over identical rows, so copy the previous row's result + local len = (px1 - px0) * 4 + local prev_o = 0 + for y = py0, py1 - 1 do + local o = (y * TargetWidth + px0) * 4 + if RowRepeats(o, len, y > py0) then + buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len) + else + FillSpan(TargetBuffer, y, y + 1, px0, px1, r, g, b, a) + end + prev_o = o + end + return + end + + local du, dv = (u1 - u0) / (x1 - x0), (v1 - v0) / (y1 - y0) + local tw: number, th: number, tbuf: buffer, dbuf: buffer = t.Width, t.Height, t.Buffer, TargetBuffer + local r255, g255, b255, a255 = r / 255, g / 255, b / 255, a / 255 + local ncol = px1 - px0 + local cols = RectColumns + for c = 1, ncol do + local tx = floor((u0 + (px0 + c - 1 + 0.5 - x0) * du) * tw) + if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end + cols[c] = tx * 4 + end + for y = py0, py1 - 1 do + local ty = floor((v0 + (y + 0.5 - y0) * dv) * th) + if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end + local trow4 = ty * tw * 4 + local o = (y * TargetWidth + px0) * 4 + for c = 1, ncol do + local tv = readu32(tbuf, trow4 + cols[c]) + if tv >= 16777216 then + local sa = rshift(tv, 24) * a255 + local sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, + band(rshift(tv, 16), 255) * b255 + if sa >= 255 then + writeu32(dbuf, o, floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + 4278190080) + else + BlendPixel(dbuf, o, sr, sg, sb, sa) + end + end + o = o + 4 + end + end +end + +@native +local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, vc: number, t, cx0: number, cy0: number, + cx1: number, cy1: number, ox: number, oy: number) + local x0, y0 = readf64(vbuf, va) - ox, readf64(vbuf, va + 8) - oy + local x1, y1 = readf64(vbuf, vb) - ox, readf64(vbuf, vb + 8) - oy + local x2, y2 = readf64(vbuf, vc) - ox, readf64(vbuf, vc + 8) - oy + local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0) + if area == 0 then return end + if area < 0 then + vb, vc = vc, vb + x1, y1, x2, y2 = x2, y2, x1, y1 + area = -area + end + + local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1) + local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1) + if minx > maxx or miny > maxy then return end + + local A0, B0 = y1 - y2, x2 - x1 + local C0 = -(A0 * x1 + B0 * y1) + local A1, B1 = y2 - y0, x0 - x2 + local C1 = -(A1 * x2 + B1 * y2) + local A2, B2 = y0 - y1, x1 - x0 + local C2 = -(A2 * x0 + B2 * y0) + local tl0 = A0 > 0 or (A0 == 0 and B0 > 0) + local tl1 = A1 > 0 or (A1 == 0 and B1 > 0) + local tl2 = A2 > 0 or (A2 == 0 and B2 > 0) + + local inv = 1 / area + local n0, n1, n2 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0 + local ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32)) + local rb, gb, bb, ab = UnpackColor(readu32(vbuf, vb + 32)) + local rc, gc, bc, ac = UnpackColor(readu32(vbuf, vc + 32)) + local ua, vva, ub, vvb, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vb + 16), + readf64(vbuf, vb + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) + + local textured = t and not (ua == ub and ua == uc and vva == vvb and vva == vvc) + if t and not textured then -- constant uv (atlas white pixel): fold the texel into the vertex colours + local tr, tg, tb, ta = SampleTexture(t, ua, vva) + ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255 + rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255 + rc, gc, bc, ac = rc * tr / 255, gc * tg / 255, bc * tb / 255, ac * ta / 255 + end + local flat = not textured and ra == rb and ra == rc and ga == gb and ga == gc and ba == bb and ba == bc and aa == ab + and aa == ac + if flat and aa <= 0 then return end + local f_opaque, f_packed, f_sa, f_ns, f_c1, f_rs, f_gs, f_bs = false, 0, 0, 0, 0, 0, 0, 0 + if flat then + f_opaque = aa >= 255 + f_packed = floor(ra + 0.5) + floor(ga + 0.5) * 256 + floor(ba + 0.5) * 65536 + + (f_opaque and 4278190080 or floor(aa + 0.5) * 16777216) + f_sa = aa / 255 + f_ns = 1 - f_sa + f_c1 = f_ns / 255 + f_rs, f_gs, f_bs = ra * f_sa, ga * f_sa, ba * f_sa + end + + for y = miny, maxy do + local py = y + 0.5 + local xl, xr = minx, maxx + local e0, e1, e2 = B0 * py + C0, B1 * py + C1, B2 * py + C2 + -- (e * n is -e / A within an ulp; the 1e-6 margin covers that, and the exact tests below decide) + if A0 > 0 then + xl = max(xl, floor(e0 * n0 - 0.500001)) + elseif A0 < 0 then + xr = min(xr, ceil(e0 * n0 - 0.499999)) + end + if A1 > 0 then + xl = max(xl, floor(e1 * n1 - 0.500001)) + elseif A1 < 0 then + xr = min(xr, ceil(e1 * n1 - 0.499999)) + end + if A2 > 0 then + xl = max(xl, floor(e2 * n2 - 0.500001)) + elseif A2 < 0 then + xr = min(xr, ceil(e2 * n2 - 0.499999)) + end + + while xl <= xr do + local px = xl + 0.5 + local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2 + if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then + break + end + xl += 1 + end + while xr > xl do + local px = xr + 0.5 + local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2 + if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then + break + end + xr -= 1 + end + if xl > xr then continue end + local o = (y * TargetWidth + xl) * 4 + if flat then + local o1 = o + (xr - xl) * 4 + if f_opaque then + for oo = o, o1, 4 do writeu32(dbuf, oo, f_packed) end + continue + end + local last_d, last_v = -1, 0 + for oo = o, o1, 4 do + local d = readu32(dbuf, oo) + if d == last_d then + writeu32(dbuf, oo, last_v) + elseif d < 16777216 then + writeu32(dbuf, oo, f_packed) + else + last_d = d + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + last_v = floor(f_rs + dr * f_ns + 0.5) + floor(f_gs + dg * f_ns + 0.5) * 256 + + floor(f_bs + db * f_ns + 0.5) * 65536 + 4278190080 + else + local k = rshift(d, 24) * f_c1 + local oa = f_sa + k + local inv = 1 / oa + last_v = floor((f_rs + dr * k) * inv + 0.5) + floor((f_gs + dg * k) * inv + 0.5) * 256 + + floor((f_bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 + end + writeu32(dbuf, oo, last_v) + end + end + continue + end + for x = xl, xr do + local px = x + 0.5 + local w0, w1, w2 = (A0 * px + e0) * inv, (A1 * px + e1) * inv, (A2 * px + e2) * inv + local a = w0 * aa + w1 * ab + w2 * ac + if textured then + local r = w0 * ra + w1 * rb + w2 * rc + local g = w0 * ga + w1 * gb + w2 * gc + local b = w0 * ba + w1 * bb + w2 * bc + local tr, tg, tb, ta = SampleTexture(t, w0 * ua + w1 * ub + w2 * uc, w0 * vva + w1 * vvb + w2 * vvc) + BlendPixel(dbuf, o, r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255) + elseif a > 0 then + BlendPixel(dbuf, o, w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc, + w0 * ba + w1 * bb + w2 * bc, a) + end + o += 4 + end + end +end + +-- Linear gradient quad, constant uv. kind 1: along y (ca top, cb bottom), 2: along x. Same pixels as the triangles. +@native +local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, ca: number, + cb: number, kind: number, t, u: number, v: number, cx0: number, cy0: number, cx1: number, cy1: number) + local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0) + local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1) + if px0 >= px1 or py0 >= py1 then return end + local ra, ga, ba, aa = UnpackColor(ca) + local rb, gb, bb, ab = UnpackColor(cb) + if t then + local tr, tg, tb, ta = SampleTexture(t, u, v) + ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255 + rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255 + end + if kind == 1 then + local inv = 1 / (y1 - y0) + for y = py0, py1 - 1 do + local f = (y + 0.5 - y0) * inv + local nf = 1 - f + FillSpan(TargetBuffer, y, y + 1, px0, px1, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, + aa * nf + ab * f) + end + else + local inv = 1 / (x1 - x0) + local len = (px1 - px0) * 4 + local opaque = aa >= 255 and ab >= 255 + local prev_o = 0 + for y = py0, py1 - 1 do + local o = (y * TargetWidth + px0) * 4 + if y > py0 and (opaque or RowRepeats(o, len, true)) + or (y == py0 and not opaque and RowRepeats(o, len, false)) then + buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len) + else + local oo = o + for x = px0, px1 - 1 do + local f = (x + 0.5 - x0) * inv + local nf = 1 - f + BlendPixel(TargetBuffer, oo, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f) + oo = oo + 4 + end + end + prev_o = o + end + end +end + +function M.SetTarget(buf: buffer, width: number) + TargetBuffer, TargetWidth = buf, width +end + +@native +function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number) + local rw = rx1 - rx0 + if rw == TargetWidth then + buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4) + else + for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4, 0, rw * 4) end + end +end + +@native +function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: number) + for y = 0, rh - 1 do + buffer.copy(dst, y * rw * 4, TargetBuffer, ((ry0 + y) * TargetWidth + rx0) * 4, rw * 4) + end +end + +-- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2 +@native +local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, tox: number, toy: number, + cx0: number, cy0: number, cx1: number, cy1: number) + if kind == 0 then + DrawTriangle(TargetBuffer, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, tox, toy) + return + end + local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox, + readf64(vbuf, vc + 8) - toy + if kind == 1 then + DrawRect(TargetBuffer, ax, ay, cx, cy, readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16), + readf64(vbuf, vc + 24), readu32(vbuf, va + 32), t, cx0, cy0, cx1, cy1) + else + DrawRectGradient(TargetBuffer, ax, ay, cx, cy, readu32(vbuf, va + 32), readu32(vbuf, vc + 32), kind - 1, t, + readf64(vbuf, va + 16), readf64(vbuf, va + 24), cx0, cy0, cx1, cy1) + end +end +M.DrawPrim = DrawPrim + +-- Packed tile jobs -> one exact-size buffer per rect, in job order (worker + main-thread fallback) +local Scratch = buffer.create(TILE * TILE * 4) +@native +function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } + local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect + local REC_A, REC_B, REC_C = M.REC_A, M.REC_B, M.REC_C + M.SetTarget(Scratch, TILE) + local out, no = {}, 0 + local o = 0 + while o < tlen do + local tox, toy = readf64(T, o), readf64(T, o + 8) + local x0, y0, nr, count = readi32(T, o + 16), readi32(T, o + 20), readi32(T, o + 24), readi32(T, o + 28) + local ro = o + 32 + local po = ro + nr * 16 + o = po + count * 4 + for r = 0, nr - 1 do + local rx0, ry0, rx1, ry1 = readi32(T, ro + r * 16), readi32(T, ro + r * 16 + 4), + readi32(T, ro + r * 16 + 8), readi32(T, ro + r * 16 + 12) + ClearRect(rx0, ry0, rx1, ry1) + for k = 0, count - 1 do + local q = readi32(T, po + k * 4) + local cx0, cy0 = max(readi32(P, q + 8) - x0, rx0), max(readi32(P, q + 12) - y0, ry0) + local cx1, cy1 = min(readi32(P, q + 16) - x0, rx1), min(readi32(P, q + 20) - y0, ry1) + if cx0 >= cx1 or cy0 >= cy1 or readi32(P, q + 24) - x0 >= rx1 or readi32(P, q + 28) - y0 >= ry1 + or readi32(P, q + 32) - x0 <= rx0 or readi32(P, q + 36) - y0 <= ry0 then + continue + end + local tid, t = readi32(P, q + 4), nil + if tid >= 0 then t = textures[tid] end + DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, tox, toy, cx0, cy0, cx1, cy1) + end + local rw, rh = rx1 - rx0, ry1 - ry0 + local sub = buffer.create(rw * rh * 4) + CopySubRect(sub, rx0, ry0, rw, rh) + no += 1 + out[no] = sub + end + end + return out +end + +Raster = M +end +do +-- Texture records, the module-wide EditableImage budget, profiling labels and stage timing stats. + + +local AssetService = game:GetService("AssetService") +local writeu32 = buffer.writeu32 +local TILE = Raster.TILE + +local M = {} + +-- One table, not locals: shared by every context and module. FreeTile is set by layers.lua (Evict needs it). +local EditableImages = { + Cap = 64 * 1024 * 1024, Bytes = 0, Count = 0, ImageBytes = setmetatable({}, { __mode = "k" }), + Pool = {}, PoolMax = 16, + Backends = setmetatable({}, { __mode = "k" }), + LastTextureId = 0, KEEP_FRAMES = 30, + StageTiming = false, +} +M.EditableImages = EditableImages + +local ProfileBegin, ProfileEnd = debug.profilebegin, debug.profileend +local Profiling = false +function M.PB(name) if Profiling then ProfileBegin(name) end end +function M.PE() if Profiling then ProfileEnd() end end +function M.SetProfiling(enabled) Profiling = enabled and true or false end +function M.IsProfiling() return Profiling end + +-- StageTiming on: RenderDrawData accumulates os.clock per stage into StageFrame (GetStats().Frame) +function EditableImages.BeginStage() EditableImages.StageStart = os.clock() end +function EditableImages.EndStage(stage) + local f = EditableImages.StageFrame + if f then f[stage] += os.clock() - EditableImages.StageStart end +end +function EditableImages.AddStat(name, n) + local f = EditableImages.StageFrame + if f then f[name] += n end +end + +function M.GetBackendData() + return ImGui.GetCurrentContext() and ImGui.GetIO().BackendPlatformUserData or nil +end + +@native +local function CopyTexturePixels(tex, dst, x, y, w, h) + local bpp, tex_w = tex.BytesPerPixel, tex.Width + for row = 0, h - 1 do + local src, src_base = tex:GetPixelsAt(x, y + row) + local dst_off = ((y + row) * tex_w + x) * 4 + if bpp == 4 then + for i = 0, w - 1 do + local s = src_base + i * 4 + writeu32(dst, dst_off + i * 4, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216) + end + else -- Alpha8: white with alpha + for i = 0, w - 1 do + writeu32(dst, dst_off + i * 4, 16777215 + src[src_base + i] * 16777216) + end + end + end +end + +-- Shared by every context: a font atlas shared between contexts is created under one, drawn under the others +local Records = {} +M.Records = Records + +local function CreateTextureRecord(tex) + local t = { Buffer = buffer.create(tex.Width * tex.Height * 4), Width = tex.Width, Height = tex.Height } + CopyTexturePixels(tex, t.Buffer, 0, 0, tex.Width, tex.Height) + EditableImages.LastTextureId += 1 + Records[EditableImages.LastTextureId] = t + tex.BackendUserData = EditableImages.LastTextureId + tex:SetTexID(EditableImages.LastTextureId) + tex:SetStatus(0 --[[ImTextureStatus.OK]]) +end + +function M.UpdateTexture(tex) + if tex.Status == 2 --[[ImTextureStatus.WantCreate]] then + CreateTextureRecord(tex) + elseif tex.Status == 3 --[[ImTextureStatus.WantUpdates]] then + local t = Records[tex.BackendUserData] + if t == nil or t.Width ~= tex.Width or t.Height ~= tex.Height then + CreateTextureRecord(tex) + return + end + for _, r in tex.Updates:iter() do + CopyTexturePixels(tex, t.Buffer, r.x, r.y, r.w, r.h) + end + t.V = (t.V or 0) + 1 -- parallel workers hold copies, resent when this changes + tex:SetStatus(0 --[[ImTextureStatus.OK]]) + elseif tex.Status == 4 --[[ImTextureStatus.WantDestroy]] then + if tex.BackendUserData then + Records[tex.BackendUserData] = nil + tex.BackendUserData = nil + end + tex:SetTexID((-1) --[[ImTextureID_Invalid]]) + tex:SetStatus(1 --[[ImTextureStatus.Destroyed]]) + end +end + +-- User texture from RGBA8 pixels. Ids are never reused, so cached tiles can't show a stale image. +function ImGui_ImplRoblox_CreateTexture(pixels, w, h) + EditableImages.LastTextureId += 1 + Records[EditableImages.LastTextureId] = { Buffer = pixels, Width = w, Height = h } + return ImTextureRef(EditableImages.LastTextureId) +end + +function ImGui_ImplRoblox_DestroyTexture(tex_ref) + Records[tex_ref._TexID] = nil +end + +-- Every EditableImage goes through Create/Destroy, counted against Cap. Over the cap (or CreateEditableImage failing): +-- evict idle tiles, retry once; still nothing -> nil, the caller skips the tile this frame. +function EditableImages.Create(w, h) + local need = w * h * 4 + if need > EditableImages.Cap then return nil end + for attempt = 1, 2 do + if EditableImages.Bytes + need <= EditableImages.Cap then + local ok, img = pcall(AssetService.CreateEditableImage, AssetService, { Size = Vector2.new(w, h) }) + if ok and img then + EditableImages.ImageBytes[img] = need + EditableImages.Bytes += need + EditableImages.Count += 1 + return img + end + if attempt == 1 then EditableImages.Evict(math.huge) end -- engine refused: free everything evictable + elseif attempt == 1 then + EditableImages.Evict(EditableImages.Bytes + need - EditableImages.Cap) + end + end + return nil +end + +function EditableImages.Destroy(img) + local s = EditableImages.ImageBytes[img] + if s then + EditableImages.ImageBytes[img] = nil + EditableImages.Bytes -= s + EditableImages.Count -= 1 + end + img:Destroy() +end + +-- The free list first, then idle tiles (not shown, not used this frame) of every context +function EditableImages.Evict(need) + local freed = 0 + while freed < need and #EditableImages.Pool > 0 do + local t = table.remove(EditableImages.Pool) + EditableImages.Destroy(t.Image) + t.Label:Destroy() + freed += TILE * TILE * 4 + end + if freed >= need then return end + for BackendData in EditableImages.Backends do + for _, set in pairs(BackendData.Layers) do + for kind = 1, 3 do + local l = set[kind] + if l then + for k, t in pairs(l.Tiles) do + if t.Used ~= BackendData.FrameNo and not (t.Visible and l.Visible) then + EditableImages.FreeTile(l, k) + freed += TILE * TILE * 4 + end + end + end + end + end + end +end + +Textures = M +end +do +-- Layers and tiles (one Frame per draw list and kind, TILE x TILE EditableImages); draw list snapshot/compare + + + +local floor, max = math.floor, math.max +local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64 +local TILE = Raster.TILE +local EditableImages = Textures.EditableImages + +local M = {} +-- content up to this far off screen is kept, so dragging a window past the edge doesn't redraw it +local CLIP_PAD = 2048 +M.CLIP_PAD = CLIP_PAD +-- per draw command, filled by CollectPrims for Snapshot: no primitive clipped, layer kind, bounds of its primitives +local CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1 = {}, {}, {}, {}, {}, {} +M.CmdUnclipped, M.CmdKind, M.CmdBoundsX0, M.CmdBoundsY0, M.CmdBoundsX1, M.CmdBoundsY1 = + CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1 +-- free per-tile primitive lists, 4 at a time +EditableImages.ListPool = {} + +-- Kinds: 1 = before the window content (background, title bar, scrollbar), 2 = content (at the scroll origin in a +-- ClipsDescendants frame, so scrolling just moves it), 3 = drawn after content, not clipped to it (menu bar). +local function NewFrame(parent, clips) + local frame = Instance.new("Frame") + frame.Name = "Layer" + frame.BackgroundTransparency = 1 + frame.BorderSizePixel = 0 + frame.Size = UDim2.fromOffset(0, 0) + frame.ClipsDescendants = clips + frame.Visible = false + frame.Parent = parent + return frame +end + +function M.GetLayer(BackendData, draw_list, kind) + local set = BackendData.Layers[draw_list] + if not set then + set = { LastUsed = 0 } + BackendData.Layers[draw_list] = set + end + local layer = set[kind] + if layer then return layer end + local root, frame + if kind == 2 then + root = NewFrame(BackendData.Gui, true) + frame = NewFrame(root, false) + frame.Visible = true + else + frame = NewFrame(BackendData.Gui, false) + root = frame + end + layer = { + Root = root, Frame = frame, Tiles = {}, + TileHash1 = {}, TileHash2 = {}, TileCounts = {}, TileLists = {}, + TileListHash1 = {}, TileListHash2 = {}, TileListFlat = {}, TileX = {}, TileY = {}, + Touched = {}, TouchedCount = 0, + Visible = false, X = false, Y = false, Z = -1, + ClipX0 = false, ClipY0 = false, ClipX1 = false, ClipY1 = false, + } + set[kind] = layer + return layer +end + +function M.HideLayer(layer) + if layer.Visible then + layer.Visible = false + layer.Root.Visible = false + end +end + +-- recycle: to EditableImages.Pool. Its label stays parented (hidden): Studio reparenting costs far more than a +-- property set, and a scrolling layer's next tile usually goes back into the same frame +function EditableImages.FreeTile(layer, key, recycle) + local tile = layer.Tiles[key] + if recycle and #EditableImages.Pool < EditableImages.PoolMax then + table.insert(EditableImages.Pool, tile) + else + EditableImages.Destroy(tile.Image) + tile.Label:Destroy() + end + layer.Tiles[key] = nil + if EditableImages.StageTiming then EditableImages.AddStat("TilesFreed", 1) end + if (layer.TileCounts[key] or 0) > 0 then return end -- touched this frame: its primitive list is still needed + local lp = EditableImages.ListPool + if layer.TileLists[key] and #lp < 256 then + lp[#lp + 1] = layer.TileLists[key] + lp[#lp + 1] = layer.TileListHash1[key] + lp[#lp + 1] = layer.TileListHash2[key] + lp[#lp + 1] = layer.TileListFlat[key] + end + layer.TileLists[key], layer.TileListHash1[key], layer.TileListHash2[key], layer.TileListFlat[key] = + nil, nil, nil, nil + layer.TileHash1[key], layer.TileHash2[key], layer.TileCounts[key], layer.TileX[key], layer.TileY[key] = + nil, nil, nil, nil, nil +end + +function M.GetTile(BackendData, layer, key, tx, ty) + local tile = layer.Tiles[key] + if tile then return tile end + local scale = BackendData.Scale + local old = table.remove(EditableImages.Pool) + local label, img + if old then + label, img = old.Label, old.Image + else + img = EditableImages.Create(TILE, TILE) + if not img then return nil end -- over the budget even after eviction: the caller skips this tile this frame + label = Instance.new("ImageLabel") + label.Name = "Tile" + label.BackgroundTransparency = 1 + label.BorderSizePixel = 0 + label.ResampleMode = Enum.ResamplerMode.Pixelated + label.ImageContent = Content.fromObject(img) + label.Visible = false + end + if not old or old.Scale ~= scale then label.Size = UDim2.fromOffset(TILE / scale, TILE / scale) end + label.Position = UDim2.fromOffset(tx * TILE / scale, ty * TILE / scale) + if not old or old.Active ~= BackendData.TilesActive then label.Active = BackendData.TilesActive end + if not old or old.Parent ~= layer.Frame then label.Parent = layer.Frame end + -- Content*: content bounds; Valid*: where Buffer == image pixels. A recycled tile keeps both (they still describe + -- its image): its first draw is a full one (DrawnCount -1) that only clears old + new content bounds. + if old then + tile = old + tile.Hash1, tile.Hash2, tile.Visible, tile.Used, tile.Deferred, tile.DrawnCount = + -1, -1, false, BackendData.FrameNo, nil, -1 + tile.Scale, tile.Active, tile.Parent = scale, BackendData.TilesActive, layer.Frame + else + tile = { + Image = img, Label = label, Buffer = buffer.create(TILE * TILE * 4), + Hash1 = -1, Hash2 = -1, Visible = false, Used = BackendData.FrameNo, + ContentX0 = TILE, ContentY0 = TILE, ContentX1 = 0, ContentY1 = 0, + ValidX0 = 0, ValidY0 = 0, ValidX1 = TILE, ValidY1 = TILE, + Scale = scale, Active = BackendData.TilesActive, Parent = layer.Frame, + DrawnCount = -1, DrawnHash1 = {}, DrawnHash2 = {}, DrawnFlat = {}, + DrawnX0 = {}, DrawnY0 = {}, DrawnX1 = {}, DrawnY1 = {}, + } + end + layer.Tiles[key] = tile + if EditableImages.StageTiming then EditableImages.AddStat("TilesCreated", 1) end + return tile +end + +function M.DestroyLayerSet(set) + for kind = 1, 3 do + local layer = set[kind] + if layer then + for _, tile in pairs(layer.Tiles) do EditableImages.Destroy(tile.Image) end + for _, t in EditableImages.Pool do + if t.Parent == layer.Frame then + t.Label.Parent = nil + t.Parent = nil + end + end + layer.Root:Destroy() + end + end +end + +function M.DestroyTiles(BackendData) + for _, set in pairs(BackendData.Layers) do M.DestroyLayerSet(set) end + BackendData.Layers = {} +end + +-- Snapshot compared exactly with the next frame's list: 1 = identical (only restack), 2 = moved by whole pixels +-- (only move the layers), 0 = changed. Per command: clip (4 f64), ElemCount, IdxOffset, VtxOffset (u32), tex id +-- (f64), kind (u8), unclipped (u8), bounds of its primitives (4 x i32). +local CMD_STRIDE = 70 + +@native +function M.Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) + local nv = draw_list.VtxBuffer.Size * 36 --[[VTX_STRIDE]] + local idx, ni = draw_list.IdxBuffer.Data, draw_list.IdxBuffer.Size + local ncmd = draw_list.CmdBuffer.Size + local sv, si, sc = set.SnapVtx, set.SnapIdx, set.SnapCmds + if not sv or buffer.len(sv) < nv then + sv = buffer.create(max(nv, 64) * 2) + set.SnapVtx = sv + end + if not si then + si = {} + set.SnapIdx = si + end + if not sc or buffer.len(sc) < ncmd * CMD_STRIDE then + sc = buffer.create(max(ncmd, 4) * CMD_STRIDE * 2) + set.SnapCmds = sc + end + buffer.copy(sv, 0, draw_list.VtxBuffer.Buf, 0, nv) + table.move(idx, 1, ni, 1, si) + local o, ci = 0, 0 + for _, pcmd in draw_list.CmdBuffer:iter() do + if pcmd.UserCallback ~= nil then + set.SnapOK = false + return + end + local c = pcmd.ClipRect + writef64(sc, o, c.x) + writef64(sc, o + 8, c.y) + writef64(sc, o + 16, c.z) + writef64(sc, o + 24, c.w) + writeu32(sc, o + 32, pcmd.ElemCount) + writeu32(sc, o + 36, pcmd.IdxOffset) + writeu32(sc, o + 40, pcmd.VtxOffset) + writef64(sc, o + 44, pcmd:GetTexID()) + ci += 1 + buffer.writeu8(sc, o + 52, CmdKind[ci] or 0) + buffer.writeu8(sc, o + 53, CmdUnclipped[ci] and 1 or 0) + if CmdUnclipped[ci] then + buffer.writei32(sc, o + 54, CmdBoundsX0[ci]) + buffer.writei32(sc, o + 58, CmdBoundsY0[ci]) + buffer.writei32(sc, o + 62, CmdBoundsX1[ci]) + buffer.writei32(sc, o + 66, CmdBoundsY1[ci]) + end + o += CMD_STRIDE + end + set.SnapVtxBytes, set.SnapIdxCount, set.SnapCmdCount = nv, ni, ncmd + set.SnapOriginX, set.SnapOriginY, set.SnapScreenW, set.SnapScreenH = ox, oy, ScreenWidth, ScreenHeight + set.SnapHasContent = draw_list._ContentClipX0 ~= nil + set.SnapContentX0, set.SnapContentY0, set.SnapContentX1, set.SnapContentY1 = + draw_list._ContentClipX0 or 0, draw_list._ContentClipY0 or 0, draw_list._ContentClipX1 or 0, + draw_list._ContentClipY1 or 0 + set.SnapScrollX, set.SnapScrollY = draw_list._ScrollOriginX or 0, draw_list._ScrollOriginY or 0 + set.SnapOK = true +end + +-- a + d == b exactly, with no rounding in a + d (so every later "x - origin" gives the same result as before the move) +@native +local function ShiftedExact(a, d, b) + local s = a + d + if s ~= b then return false end + local bb = s - a + return (a - (s - bb)) + (d - bb) == 0 +end + +@native +function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) + if not set or not set.SnapOK then return 0 end + local nv = draw_list.VtxBuffer.Size * 36 --[[VTX_STRIDE]] + local ni, ncmd = draw_list.IdxBuffer.Size, draw_list.CmdBuffer.Size + if nv ~= set.SnapVtxBytes or ni ~= set.SnapIdxCount or ncmd ~= set.SnapCmdCount or ox ~= set.SnapOriginX + or oy ~= set.SnapOriginY or ScreenWidth ~= set.SnapScreenW or ScreenHeight ~= set.SnapScreenH then + return 0 + end + if (draw_list._ContentClipX0 ~= nil) ~= set.SnapHasContent then return 0 end + local vb, sv = draw_list.VtxBuffer.Buf, set.SnapVtx + if nv == 0 then return 1 end + -- translation from the first vertex: whole pixels only, and only with DisplayPos at 0 (so it stays exact) + local dx, dy = readf64(vb, 0) - readf64(sv, 0), readf64(vb, 8) - readf64(sv, 8) + if dx ~= dx or dy ~= dy then return 0 end + if dx == 0 and dy == 0 then + -- u32 loop, not readstring ==: that allocated 2 vertex-buffer strings per list per frame (GC spikes) + for o = 0, nv - 4, 4 do if readu32(vb, o) ~= readu32(sv, o) then return 0 end end + else + if dx ~= floor(dx) or dy ~= floor(dy) or ox ~= 0 or oy ~= 0 or not set.SnapLimitFree then return 0 end + -- everything must stay as far from the clip limits as before (nothing newly clamped) + if set.SnapExtentX0 + dx < -CLIP_PAD or set.SnapExtentY0 + dy < -CLIP_PAD + or set.SnapExtentX1 + dx > ScreenWidth + CLIP_PAD or set.SnapExtentY1 + dy > ScreenHeight + CLIP_PAD then + return 0 + end + end + local idx, si = draw_list.IdxBuffer.Data, set.SnapIdx + for i = 1, ni do if idx[i] ~= si[i] then return 0 end end + local sc, o = set.SnapCmds, 0 + local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1, + draw_list._ContentClipY1 + local seen_content = false + for _, pcmd in draw_list.CmdBuffer:iter() do + if pcmd.UserCallback ~= nil then return 0 end + if pcmd.ElemCount ~= readu32(sc, o + 32) or pcmd.IdxOffset ~= readu32(sc, o + 36) + or pcmd.VtxOffset ~= readu32(sc, o + 40) or pcmd:GetTexID() ~= readf64(sc, o + 44) then + return 0 + end + local c = pcmd.ClipRect + if dx == 0 and dy == 0 then + if c.x ~= readf64(sc, o) or c.y ~= readf64(sc, o + 8) or c.z ~= readf64(sc, o + 16) + or c.w ~= readf64(sc, o + 24) then + return 0 + end + elseif not (ShiftedExact(readf64(sc, o), dx, c.x) and ShiftedExact(readf64(sc, o + 8), dy, c.y) + and ShiftedExact(readf64(sc, o + 16), dx, c.z) and ShiftedExact(readf64(sc, o + 24), dy, c.w)) then + -- an unchanged clip rect (e.g. the viewport) is fine if it clips none of this command's primitives + if c.x ~= readf64(sc, o) or c.y ~= readf64(sc, o + 8) or c.z ~= readf64(sc, o + 16) + or c.w ~= readf64(sc, o + 24) + or buffer.readu8(sc, o + 53) == 0 then return 0 end + if buffer.readi32(sc, o + 54) + dx < floor(c.x) or buffer.readi32(sc, o + 58) + dy < floor(c.y) + or buffer.readi32(sc, o + 62) + dx > floor(c.z) + or buffer.readi32(sc, o + 66) + dy > floor(c.w) then return 0 end + end + if pcmd.ElemCount > 0 then + local kind = 1 + if ccx0 and c.x >= ccx0 and c.y >= ccy0 and c.z <= ccx1 and c.w <= ccy1 then + kind = 2 + seen_content = true + elseif seen_content then kind = 3 end + if kind ~= buffer.readu8(sc, o + 52) then return 0 end + end + o += CMD_STRIDE + end + if dx == 0 and dy == 0 then + if set.SnapHasContent and (draw_list._ContentClipX0 ~= set.SnapContentX0 + or draw_list._ContentClipY0 ~= set.SnapContentY0 or draw_list._ContentClipX1 ~= set.SnapContentX1 + or draw_list._ContentClipY1 ~= set.SnapContentY1 or draw_list._ScrollOriginX ~= set.SnapScrollX + or draw_list._ScrollOriginY ~= set.SnapScrollY) then return 0 end + return 1 + end + if set.SnapHasContent and not (ShiftedExact(set.SnapContentX0, dx, draw_list._ContentClipX0) + and ShiftedExact(set.SnapContentY0, dy, draw_list._ContentClipY0) + and ShiftedExact(set.SnapContentX1, dx, draw_list._ContentClipX1) + and ShiftedExact(set.SnapContentY1, dy, draw_list._ContentClipY1) + and ShiftedExact(set.SnapScrollX, dx, draw_list._ScrollOriginX) + and ShiftedExact(set.SnapScrollY, dy, draw_list._ScrollOriginY)) then return 0 end + for v = 0, nv - 36 --[[VTX_STRIDE]], 36 --[[VTX_STRIDE]] do + if not ShiftedExact(readf64(sv, v), dx, readf64(vb, v)) + or not ShiftedExact(readf64(sv, v + 8), dy, readf64(vb, v + 8)) + or readf64(vb, v + 16) ~= readf64(sv, v + 16) or readf64(vb, v + 24) ~= readf64(sv, v + 24) + or readu32(vb, v + 32) ~= readu32(sv, v + 32) then return 0 end + end + return 2, dx, dy +end + +function M.ShiftLayer(layer, dx, dy, scale) + layer.X += dx + layer.Y += dy + local root = layer.Root + if root ~= layer.Frame then + layer.ClipX0 += dx + layer.ClipY0 += dy + layer.ClipX1 += dx + layer.ClipY1 += dy + root.Position = UDim2.fromOffset(layer.ClipX0 / scale, layer.ClipY0 / scale) + else + root.Position = UDim2.fromOffset(layer.X / scale, layer.Y / scale) + end +end + +Layers = M +end +do +-- Overlays: user Instances placed inside a window (SetOverlay), stacked right above its layers and moving with it. + + +local M = {} + +local function OverlayHolder(BackendData, draw_list, clip) + local hs = BackendData.OverlayHolders[draw_list] + if not hs then + hs = {} + BackendData.OverlayHolders[draw_list] = hs + end + local h = hs[clip] + if not h then + h = Instance.new("Frame") + h.Name = clip and "OverlayClip" or "Overlay" + h.BackgroundTransparency = 1 + h.BorderSizePixel = 0 + h.ClipsDescendants = clip + h.Size = UDim2.fromOffset(0, 0) + h.Parent = BackendData.Gui + hs[clip] = h + end + return h +end + +local OverlayUsed = {} +function M.PlaceOverlays(BackendData, draw_list, z, ox, oy) + local list = BackendData.Overlays[draw_list] + local hs = BackendData.OverlayHolders[draw_list] + if not list then + if hs then for _, h in pairs(hs) do h.Visible = false end end + return z + end + local scale, frame_no = BackendData.Scale, BackendData.FrameNo + z += 1 + local used = OverlayUsed + table.clear(used) + for _, o in ipairs(list) do + local clip = o.Clip and draw_list._ContentClipX0 ~= nil + local h = OverlayHolder(BackendData, draw_list, clip) + local hx, hy = 0, 0 + if clip then + hx, hy = draw_list._ContentClipX0 - ox, draw_list._ContentClipY0 - oy + if not used[h] then + h.Position = UDim2.fromOffset(hx / scale, hy / scale) + h.Size = UDim2.fromOffset((draw_list._ContentClipX1 - draw_list._ContentClipX0) / scale, + (draw_list._ContentClipY1 - draw_list._ContentClipY0) / scale) + end + elseif not used[h] then + h.Position = UDim2.fromOffset(0, 0) + end + used[h] = true + h.ZIndex = z + h.Visible = true + local f = o.Frame + if f.Parent ~= h then f.Parent = h end + f.Position = UDim2.fromOffset((o.X - ox - hx) / scale, (o.Y - oy - hy) / scale) + f.Size = UDim2.fromOffset(o.W / scale, o.H / scale) + f.Visible = true + BackendData.OverlayShown[f] = frame_no + end + if hs then for _, h in pairs(hs) do if not used[h] then h.Visible = false end end end + return z +end + +--- Show `frame` this frame at (x, y, w, h) (imgui coordinates) inside the current window. Call every frame it should +--- be visible; frames not submitted are hidden. clip: clip to the window's content area (scrolls with it). +function ImGui_ImplRoblox_SetOverlay(frame, x, y, w, h, clip) + local BackendData = Textures.GetBackendData() + local dl = ImGui.GetWindowDrawList() + local list = BackendData.Overlays[dl] + if not list then + list = {} + BackendData.Overlays[dl] = list + end + list[#list + 1] = { Frame = frame, X = x, Y = y, W = w, H = h, Clip = clip ~= false } +end + +Overlays = M +end +do +-- Rendering: collect primitives, hash them into tiles, redraw + upload changed tiles (RenderDrawData). + + + + + +local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max +local readu32, readf64 = buffer.readu32, buffer.readf64 +local SetTarget, ClearRect, DrawPrim, CopySubRect = Raster.SetTarget, Raster.ClearRect, Raster.DrawPrim, + Raster.CopySubRect +local TILE = Raster.TILE +local TILE_SIZE = Vector2.new(TILE, TILE) +local EditableImages, PB, PE, GetBackendData, UpdateTexture = Textures.EditableImages, Textures.PB, Textures.PE, + Textures.GetBackendData, Textures.UpdateTexture +local GetLayer, HideLayer, GetTile, DestroyLayerSet, Snapshot, CompareDrawList, ShiftLayer = Layers.GetLayer, + Layers.HideLayer, Layers.GetTile, Layers.DestroyLayerSet, Layers.Snapshot, Layers.CompareDrawList, Layers.ShiftLayer +local CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1 = Layers.CmdUnclipped, Layers.CmdKind, + Layers.CmdBoundsX0, Layers.CmdBoundsY0, Layers.CmdBoundsX1, Layers.CmdBoundsY1 +local CLIP_PAD = Layers.CLIP_PAD +local PlaceOverlays = Overlays.PlaceOverlays + +local M = {} +-- Parallel executor state; parallel.lua adds its functions. On: enabled; Active: used by the current RenderDrawData. +local Parallel = { On = false, Active = false } +M.Parallel = Parallel + +local P1, P2 = 2147483647, 2147483629 -- two independent 31 bit hashes per tile (collision odds ~2^-62) +local LAYER_KEEP_FRAMES = 120 +local MAX_DEFER_FRAMES = 8 -- a changed tile is redrawn at the latest this many frames later, even over the budget + +local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient = {}, {}, {}, {}, {}, {} +local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = {}, {}, {}, {} +local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = {}, {}, {}, {} +local PrimTexId, PrimVtxBuffer, PrimKind = {}, {}, {} +local LayerPrims1, LayerPrims2, LayerPrims3 = {}, {}, {} +M.PrimA, M.PrimB, M.PrimC, M.PrimD = PrimA, PrimB, PrimC, PrimD +M.PrimTexture, M.PrimGradient = PrimTexture, PrimGradient +M.PrimClipX0, M.PrimClipY0, M.PrimClipX1, M.PrimClipY1 = PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 +M.PrimBoundsX0, M.PrimBoundsY0, M.PrimBoundsX1, M.PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 +M.PrimTexId, M.PrimVtxBuffer = PrimTexId, PrimVtxBuffer + +-- Adds [a, c) x [b, d) to the n dirty rects DX0..DY1 (merged unless that wastes area), returns the count +EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1 = {}, {}, {}, {} +@native +function EditableImages.AddRect(n: number, a: number, b: number, c: number, d: number): number + if a >= c or b >= d then return n end + local X0, Y0, X1, Y1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1 + local best, best_grow = 1, math.huge + for i = 1, n do + local e, f, g, h = X0[i], Y0[i], X1[i], Y1[i] + local ux0, uy0, ux1, uy1 = min(a, e), min(b, f), max(c, g), max(d, h) + local box, own = (ux1 - ux0) * (uy1 - uy0), (g - e) * (h - f) + local ov = max(min(c, g) - max(a, e), 0) * max(min(d, h) - max(b, f), 0) + -- waste outside both rects vs. apart: the overlap twice + a primitive pass and an upload (~2048 px) + if box - ((c - a) * (d - b) + own - ov) <= ov + 2048 then + X0[i], Y0[i], X1[i], Y1[i] = ux0, uy0, ux1, uy1 + return n + end + if box - own < best_grow then best, best_grow = i, box - own end + end + if n < 4 then + n += 1 + X0[n], Y0[n], X1[n], Y1[n] = a, b, c, d + else + X0[best], Y0[best], X1[best], Y1[best] = min(a, X0[best]), min(b, Y0[best]), max(c, X1[best]), max(d, Y1[best]) + end + return n +end + +@native +local function HashVertex(h1: number, h2: number, vbuf: buffer, v: number, ox: number, oy: number) + local x, y = readf64(vbuf, v) - ox, readf64(vbuf, v + 8) - oy + local uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24) + local c = readu32(vbuf, v + 32) + h1 = (h1 * 48271 + x * 4096 + y) % P1 + h1 = (h1 * 48271 + uv * 4096 + c) % P1 + h2 = (h2 * 16807 + y * 4093 + x) % P2 + h2 = (h2 * 16807 + uv * 65521 + c * 3) % P2 + return h1, h2 +end + +@native +local function HashTiles(layer, plist, np, lx0, ly0, ox, oy) + local TileHash1, TileHash2, TileCounts, TileLists, Touched = + layer.TileHash1, layer.TileHash2, layer.TileCounts, layer.TileLists, layer.Touched + local TileListHash1, TileListHash2, TileListFlat = layer.TileListHash1, layer.TileListHash2, layer.TileListFlat + for k = 1, layer.TouchedCount do TileCounts[Touched[k]] = 0 end + local TouchedCount = 0 + local CurKey, CurCount, CurHash1, CurHash2, CurList, CurListHash1, CurListHash2, CurListFlat = + nil, 0, 0, 0, nil, nil, nil, nil + local TileXs, TileYs = layer.TileX, layer.TileY + for pi = 1, np do + local p = plist[pi] + local tex_id = PrimTexId[p] + -- hash the clipped bounds, not the clip: a window clipped by the fixed viewport stays hash-stable when moved + local cx0, cy0, cx1, cy1 = PrimBoundsX0[p] - lx0, PrimBoundsY0[p] - ly0, PrimBoundsX1[p] - lx0, + PrimBoundsY1[p] - ly0 + local vbuf = PrimVtxBuffer[p] + local va, vd = PrimA[p], PrimD[p] + -- flat rect: hash its clipped rect per tile, so resizing only changes the tiles its edges cross + local FlatRect, RectColor, RectUV = false, 0, 0 + if vd and not PrimGradient[p] then + local u0, v0 = readf64(vbuf, va + 16), readf64(vbuf, va + 24) + local vc = PrimC[p] + if not PrimTexture[p] or (u0 == readf64(vbuf, vc + 16) and v0 == readf64(vbuf, vc + 24)) then + FlatRect, RectColor, RectUV = true, readu32(vbuf, va + 32), u0 * 8192 + v0 + end + end + local h1, h2 = 0, 0 + local FlatSig = -1 + if FlatRect then FlatSig = ((RectColor * 8191 + RectUV * 4096) % P1 * 64 + tex_id) % P1 end + if not FlatRect then + h1 = ((cx0 * 8191 + cy0) * 8191 + cx1) % P1 + h2 = ((cy1 * 8191 + cx1) * 8191 + cy0 + tex_id) % P2 + local vax, vay = lx0 + ox, ly0 + oy + if vd then + -- axis aligned quad: CollectPrims checked that TR/BL follow from TL/BR (+ kind) + h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay) + h1, h2 = HashVertex(h1, h2, vbuf, PrimC[p], vax, vay) + local gk = PrimGradient[p] + if gk then + h1 = (h1 * 48271 + gk) % P1 + h2 = (h2 * 16807 + gk * 3) % P2 + end + else + h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay) + h1, h2 = HashVertex(h1, h2, vbuf, PrimB[p], vax, vay) + h1, h2 = HashVertex(h1, h2, vbuf, PrimC[p], vax, vay) + end + end + for ty = floor((PrimBoundsY0[p] - ly0) / TILE), floor((PrimBoundsY1[p] - 1 - ly0) / TILE) do + for tx = floor((PrimBoundsX0[p] - lx0) / TILE), floor((PrimBoundsX1[p] - 1 - lx0) / TILE) do + if FlatRect then + local tx0, ty0 = tx * TILE, ty * TILE + local ix0, iy0 = max(cx0 - tx0, 0), max(cy0 - ty0, 0) + local ix1, iy1 = min(cx1 - tx0, TILE), min(cy1 - ty0, TILE) + local r = ((ix0 * 131 + iy0) * 131 + ix1) * 131 + iy1 + h1 = ((r * 48271 + RectColor) % P1 * 48271 + RectUV * 4096 + 7) % P1 + h2 = ((r * 16807 + RectColor + tex_id) % P2 * 16807 + RectUV * 65521 + 11) % P2 + end + -- unique for |tx|, |ty| < 32768 (content tiles go negative) + local key = (ty + 32768) * 65536 + tx + 32768 + if key ~= CurKey then + if CurKey then + TileCounts[CurKey], TileHash1[CurKey], TileHash2[CurKey] = CurCount, CurHash1, CurHash2 + end + CurKey = key + CurCount = TileCounts[key] + if not CurCount or CurCount == 0 then + CurCount, CurHash1, CurHash2 = 0, 0, 0 + if not TileLists[key] then + local ListPool = EditableImages.ListPool + local m = #ListPool + if m >= 4 then + TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key] = + ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m] + ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m] = nil, nil, nil, nil + else + TileLists[key] = {} + TileListHash1[key] = {} + TileListHash2[key] = {} + TileListFlat[key] = {} + end + end + TouchedCount = TouchedCount + 1 + Touched[TouchedCount] = key + TileXs[key], TileYs[key] = tx, ty + else + CurHash1, CurHash2 = TileHash1[key], TileHash2[key] + end + CurList, CurListHash1, CurListHash2, CurListFlat = + TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key] + end + CurCount += 1 + CurList[CurCount], CurListHash1[CurCount], CurListHash2[CurCount], CurListFlat[CurCount] = + p, h1, h2, FlatSig + CurHash1 = (CurHash1 * 48271 + h1) % P1 + CurHash2 = (CurHash2 * 16807 + h2 + CurCount) % P2 + end + end + end + if CurKey then TileCounts[CurKey], TileHash1[CurKey], TileHash2[CurKey] = CurCount, CurHash1, CurHash2 end + layer.TouchedCount = TouchedCount + return TouchedCount +end + +local function PlaceLayer(layer, scale, lx0, ly0, z, clip_x0, clip_y0, clip_x1, clip_y1) + local root = layer.Root + if root ~= layer.Frame then + if layer.ClipX0 ~= clip_x0 or layer.ClipY0 ~= clip_y0 or layer.ClipX1 ~= clip_x1 or layer.ClipY1 ~= clip_y1 then + layer.ClipX0, layer.ClipY0, layer.ClipX1, layer.ClipY1 = clip_x0, clip_y0, clip_x1, clip_y1 + root.Position = UDim2.fromOffset(clip_x0 / scale, clip_y0 / scale) + root.Size = UDim2.fromOffset((clip_x1 - clip_x0) / scale, (clip_y1 - clip_y0) / scale) + layer.X = false + end + if layer.X ~= lx0 or layer.Y ~= ly0 then + layer.X, layer.Y = lx0, ly0 + layer.Frame.Position = UDim2.fromOffset((lx0 - clip_x0) / scale, (ly0 - clip_y0) / scale) + end + elseif layer.X ~= lx0 or layer.Y ~= ly0 then + layer.X, layer.Y = lx0, ly0 + root.Position = UDim2.fromOffset(lx0 / scale, ly0 / scale) + end + if layer.Z ~= z then + layer.Z = z + root.ZIndex = z + end + if not layer.Visible then + layer.Visible = true + root.Visible = true + end +end + +local function SweepTiles(BackendData, layer, TouchedCount, lx0, ly0, clip_x0, clip_y0, clip_x1, clip_y1) + local TileCounts, Touched = layer.TileCounts, layer.Touched + -- content layer: only tiles inside its clip frame are kept, so scrolling holds the visible tiles + a few spares + local FrameNo, VisibleCount, SpareCap = BackendData.FrameNo, TouchedCount, TouchedCount + if layer.Root ~= layer.Frame then + for kk = 1, TouchedCount do + local key = Touched[kk] + local x0, y0 = lx0 + layer.TileX[key] * TILE, ly0 + layer.TileY[key] * TILE + if x0 >= clip_x1 or y0 >= clip_y1 or x0 + TILE <= clip_x0 or y0 + TILE <= clip_y0 then + TileCounts[key] = 0 + VisibleCount -= 1 + end + end + SpareCap = min(VisibleCount, 4) + end + -- unused tiles stay for a quick scroll back: at most SpareCap of them, for at most KEEP_FRAMES + local spare = 0 + for key, tile in pairs(layer.Tiles) do + if not TileCounts[key] or TileCounts[key] == 0 then + if tile.Visible then + tile.Visible = false + tile.Label.Visible = false + tile.Hash1 = -1 + tile.DrawnCount = -1 + end + spare += 1 + if spare > SpareCap or FrameNo - tile.Used > EditableImages.KEEP_FRAMES then + EditableImages.FreeTile(layer, key, true) + end + end + end +end + +@native +local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, vy0, vx1, vy1) + local qx0, qy0, qx1, qy1 = tile.ValidX0, tile.ValidY0, tile.ValidX1, tile.ValidY1 + local list, ListHash1, ListHash2 = layer.TileLists[key], layer.TileListHash1[key], layer.TileListHash2[key] + local DrawnHash1, DrawnHash2, DrawnX0, DrawnY0, DrawnX1, DrawnY1, DrawnCount = + tile.DrawnHash1, tile.DrawnHash2, tile.DrawnX0, tile.DrawnY0, tile.DrawnX1, tile.DrawnY1, + tile.DrawnCount + local nx0, ny0, nx1, ny1 = TILE, TILE, 0, 0 + for k = 1, count do + local p = list[k] + local a, b = PrimBoundsX0[p] - x0, PrimBoundsY0[p] - y0 + local c, d = PrimBoundsX1[p] - x0, PrimBoundsY1[p] - y0 + if a < nx0 then nx0 = a end + if b < ny0 then ny0 = b end + if c > nx1 then nx1 = c end + if d > ny1 then ny1 = d end + end + nx0, ny0, nx1, ny1 = max(nx0, 0), max(ny0, 0), min(nx1, TILE), min(ny1, TILE) + local DX0, DY0, DX1, DY1, AddRect = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, + EditableImages.DY1, EditableImages.AddRect + local DirtyCount = 0 + if force or DrawnCount < 0 then + -- outside the old + new content bounds the valid part is already transparent + DirtyCount = AddRect(AddRect(0, tile.ContentX0, tile.ContentY0, tile.ContentX1, tile.ContentY1), nx0, + ny0, nx1, ny1) + else + -- partial redraw: a pixel no changed primitive (old or new) touches is covered by the same primitives in the + -- same order, so only the bounds of the changed ones are redrawn + local i, lim = 1, min(DrawnCount, count) + while i <= lim and DrawnHash1[i] == ListHash1[i] and DrawnHash2[i] == ListHash2[i] do i += 1 end + local j = 0 + while j <= lim - i and DrawnHash1[DrawnCount - j] == ListHash1[count - j] + and DrawnHash2[DrawnCount - j] == ListHash2[count - j] do + j += 1 + end + local of, lf = tile.DrawnFlat, layer.TileListFlat[key] + local paired = DrawnCount - j - i == count - j - i + for k = i, count - j do + local p = list[k] + local a, b, c, d = max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0), + min(PrimBoundsX1[p] - x0, TILE), min(PrimBoundsY1[p] - y0, TILE) + local oa, ob, oc, od = DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k] + if paired and lf[k] >= 0 and lf[k] == of[k] then + -- same flat rect, new bounds: only the strips between the old and new edges can differ + local uy0, uy1 = min(b, ob), max(d, od) + local ux0, ux1 = min(a, oa), max(c, oc) + if a ~= oa then DirtyCount = AddRect(DirtyCount, ux0, uy0, max(a, oa), uy1) end + if c ~= oc then DirtyCount = AddRect(DirtyCount, min(c, oc), uy0, ux1, uy1) end + if b ~= ob then DirtyCount = AddRect(DirtyCount, ux0, uy0, ux1, max(b, ob)) end + if d ~= od then DirtyCount = AddRect(DirtyCount, ux0, min(d, od), ux1, uy1) end + else + DirtyCount = AddRect(DirtyCount, a, b, c, d) + if k <= DrawnCount - j then DirtyCount = AddRect(DirtyCount, oa, ob, oc, od) end + end + end + for k = count - j + 1, DrawnCount - j do + DirtyCount = AddRect(DirtyCount, DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k]) + end + end + -- clip D to V, then add the exposed part that isn't valid. cut: part of D inside the valid rect was clipped away + local cut, RectCount = false, 0 + for r = 1, DirtyCount do + local a, b, c, d = DX0[r], DY0[r], DX1[r], DY1[r] + local ix0, iy0, ix1, iy1 = max(a, qx0), max(b, qy0), min(c, qx1), min(d, qy1) + if ix0 < ix1 and iy0 < iy1 and (ix0 < vx0 or iy0 < vy0 or ix1 > vx1 or iy1 > vy1) then cut = true end + a, b, c, d = max(a, vx0), max(b, vy0), min(c, vx1), min(d, vy1) + if a < c and b < d then + RectCount += 1 + DX0[RectCount], DY0[RectCount], DX1[RectCount], DY1[RectCount] = a, b, c, d + end + end + if exposed then + local ex0, ey0, ex1, ey1 = vx0, vy0, vx1, vy1 + if qx0 <= vx0 and qx1 >= vx1 then + if qy0 <= vy0 and qy1 > vy0 then ey0 = qy1 elseif qy1 >= vy1 and qy0 < vy1 then ey1 = qy0 end + elseif qy0 <= vy0 and qy1 >= vy1 then + if qx0 <= vx0 and qx1 > vx0 then ex0 = qx1 elseif qx1 >= vx1 and qx0 < vx1 then ex1 = qx0 end + end + RectCount = AddRect(RectCount, ex0, ey0, ex1, ey1) + end + if cut then + qx0, qy0, qx1, qy1 = vx0, vy0, vx1, vy1 + elseif exposed then + if (qx0 == vx0 and qx1 == vx1 and qy0 <= vy1 and vy0 <= qy1) + or (qy0 == vy0 and qy1 == vy1 and qx0 <= vx1 and vx0 <= qx1) + or (qx0 >= vx0 and qy0 >= vy0 and qx1 <= vx1 and qy1 <= vy1) then + qx0, qy0, qx1, qy1 = min(qx0, vx0), min(qy0, vy0), max(qx1, vx1), max(qy1, vy1) + else + qx0, qy0, qx1, qy1 = vx0, vy0, vx1, vy1 + end + end + tile.ValidX0, tile.ValidY0, tile.ValidX1, tile.ValidY1 = qx0, qy0, qx1, qy1 + tile.ContentX0, tile.ContentY0, tile.ContentX1, tile.ContentY1 = nx0, ny0, nx1, ny1 + local DrawnFlat, ListFlat = tile.DrawnFlat, layer.TileListFlat[key] + for k = 1, count do + local p = list[k] + DrawnHash1[k], DrawnHash2[k], DrawnFlat[k] = ListHash1[k], ListHash2[k], ListFlat[k] + DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k] = + max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0), min(PrimBoundsX1[p] - x0, TILE), + min(PrimBoundsY1[p] - y0, TILE) + end + tile.DrawnCount = count + return RectCount +end + +@native +local function RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1) + ClearRect(rx0, ry0, rx1, ry1) + for k = 1, count do + local p = list[k] + local cx0, cy0 = max(PrimClipX0[p] - x0, rx0), max(PrimClipY0[p] - y0, ry0) + local cx1, cy1 = min(PrimClipX1[p] - x0, rx1), min(PrimClipY1[p] - y0, ry1) + if cx0 >= cx1 or cy0 >= cy1 or PrimBoundsX0[p] - x0 >= rx1 or PrimBoundsY0[p] - y0 >= ry1 + or PrimBoundsX1[p] - x0 <= rx0 or PrimBoundsY1[p] - y0 <= ry0 then + continue + end + local kind, gk = 0, PrimGradient[p] + if PrimD[p] then kind = gk and gk + 1 or 1 end + DrawPrim(kind, PrimTexture[p], PrimVtxBuffer[p], PrimA[p], PrimB[p], PrimC[p], tox, toy, cx0, cy0, cx1, cy1) + end +end + +-- WritePixelsBuffer needs the exact size: partial upload buffers are reused by size +local SubBuffers, SubBufferCount = {}, 0 +local function UploadRect(img, buf, rx0, ry0, rx1, ry1) + local rw, rh = rx1 - rx0, ry1 - ry0 + if rw == TILE and rh == TILE then + img:WritePixelsBuffer(Vector2.zero, TILE_SIZE, buf) + return + end + local sk = rw * 1024 + rh + local sub = SubBuffers[sk] + if not sub then + if SubBufferCount >= 256 then + table.clear(SubBuffers) + SubBufferCount = 0 + end + sub = buffer.create(rw * rh * 4) + SubBuffers[sk] = sub + SubBufferCount += 1 + end + CopySubRect(sub, rx0, ry0, rw, rh) + img:WritePixelsBuffer(Vector2.new(rx0, ry0), Vector2.new(rw, rh), sub) +end + +local function RedrawTile(BackendData, layer, key, tile, count, x0, y0, ox, oy, force, exposed, vx0, vy0, vx1, vy1) + BackendData.RedrawStarted = true + BackendData.FrameTiles += 1 + tile.Deferred = 0 + tile.Hash1, tile.Hash2 = layer.TileHash1[key], layer.TileHash2[key] + local RectCount = DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, vy0, vx1, vy1) + local list = layer.TileLists[key] + local tox, toy = ox + x0, oy + y0 + local Timing = EditableImages.StageTiming and EditableImages.StageFrame + if Timing and RectCount > 0 then Timing.TilesRasterized += 1 end + -- parallel: rasterized + uploaded later in the frame (pixels outside the rects are never read) + if Parallel.Active and RectCount > 0 then + Parallel.Tile(tile.Image, list, count, x0, y0, tox, toy, RectCount) + return + end + SetTarget(tile.Buffer, TILE) + local DX0, DY0, DX1, DY1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1 + for r = 1, RectCount do + local rx0, ry0, rx1, ry1 = DX0[r], DY0[r], DX1[r], DY1[r] + RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1) + PB("ImGui upload") + local t_up = Timing and os.clock() + if Timing then + Timing.PixelsRasterized += (rx1 - rx0) * (ry1 - ry0) + Timing.Uploads += 1 + end + UploadRect(tile.Image, tile.Buffer, rx0, ry0, rx1, ry1) + if Timing then Timing.Upload += os.clock() - t_up end + PE() + end +end + +local function DrawLayer(BackendData, layer, plist, np, lx0, ly0, ox, oy, force, z, clip_x0, clip_y0, clip_x1, clip_y1) + PB("ImGui tile hash") + if EditableImages.StageTiming then EditableImages.BeginStage() end + local TouchedCount = HashTiles(layer, plist, np, lx0, ly0, ox, oy) + if EditableImages.StageTiming then EditableImages.EndStage("Hash") end + PE() + + PlaceLayer(layer, BackendData.Scale, lx0, ly0, z, clip_x0, clip_y0, clip_x1, clip_y1) + + PB("ImGui raster+upload") + if EditableImages.StageTiming then EditableImages.BeginStage() end + SweepTiles(BackendData, layer, TouchedCount, lx0, ly0, clip_x0, clip_y0, clip_x1, clip_y1) + local TileCounts, Touched, TileHash1, TileHash2 = layer.TileCounts, layer.Touched, layer.TileHash1, layer.TileHash2 + local content = layer.Root ~= layer.Frame + local FrameNo, deferred = BackendData.FrameNo, false + for kk = 1, TouchedCount do + local key = Touched[kk] + local count = TileCounts[key] + if not count or count == 0 then continue end -- outside the content clip, or list freed + local tx, ty = layer.TileX[key], layer.TileY[key] + local tile = GetTile(BackendData, layer, key, tx, ty) + if not tile then continue end + tile.Used = FrameNo + local x0, y0 = lx0 + tx * TILE, ly0 + ty * TILE + -- redraws are clipped to the visible part; a part scrolled into view that isn't valid is redrawn then + local vx0, vy0, vx1, vy1 = 0, 0, TILE, TILE + if content then + vx0, vy0, vx1, vy1 = max(clip_x0 - x0, 0), max(clip_y0 - y0, 0), min(clip_x1 - x0, TILE), min(clip_y1 - y0, + TILE) + end + local exposed = vx0 < tile.ValidX0 or vy0 < tile.ValidY0 or vx1 > tile.ValidX1 or vy1 > tile.ValidY1 + local dirty = force or exposed or tile.Hash1 ~= TileHash1[key] or tile.Hash2 ~= TileHash2[key] + if dirty and BackendData.RedrawStarted and (tile.Deferred or 0) < MAX_DEFER_FRAMES + and ((BackendData.RedrawBudget > 0 and os.clock() - BackendData.FrameStartTime >= BackendData.RedrawBudget) + or (BackendData.TileLimit and BackendData.FrameTiles >= BackendData.TileLimit)) then + -- over budget (TileLimit: t_pixels hook): keep the old pixels (the stored hashes describe them) + tile.Deferred = (tile.Deferred or 0) + 1 + if force then + tile.Hash1 = -1 + tile.DrawnCount = -1 + end + deferred = true + dirty = false + end + if dirty then RedrawTile(BackendData, layer, key, tile, count, x0, y0, ox, oy, force, exposed, vx0, vy0, vx1, vy1) end + -- a deferred tile that was hidden holds old pixels: stays hidden until drawn + if not tile.Visible and (tile.Deferred or 0) == 0 then + tile.Visible = true + tile.Label.Visible = true + end + end + if EditableImages.StageTiming then + EditableImages.EndStage("Raster") + end + PE() + return deferred +end + +local function UpdateTextures(draw_data) + PB("ImGui textures") + if draw_data.Textures ~= nil then + for _, tex in draw_data.Textures:iter() do + if tex.Status ~= 0 --[[ImTextureStatus.OK]] then + -- WantUpdates only writes regions no tile has sampled yet: no redraw needed + UpdateTexture(tex) + end + end + end + PE() +end + +local function RenderRateAllows(BackendData, draw_data) + local rate = BackendData.RenderRate + if BackendData.BusyRenderRate > 0 then + local g = ImGui.GetCurrentContext() + local busy = g.WheelingWindow ~= nil or g.MovingWindow ~= nil -- (io.MouseWheel is already cleared by EndFrame) + if not busy and g.ActiveId ~= 0 then + local w = g.ActiveIdWindow + local cur = g.MouseCursor + busy = (cur >= 2 --[[ImGuiMouseCursor.ResizeAll]] and cur <= 6 --[[ImGuiMouseCursor.ResizeNWSE]]) + or (w ~= nil and (g.ActiveId == ImGui.GetWindowScrollbarID(w, 1 --[[ImGuiAxis.X]]) + or g.ActiveId == ImGui.GetWindowScrollbarID(w, 2 --[[ImGuiAxis.Y]]))) + end + if busy and (rate <= 0 or BackendData.BusyRenderRate < rate) then rate = BackendData.BusyRenderRate end + end + if rate > 0 then + local now = os.clock() + -- skipped: kept pending, Heartbeat draws it if no new frame comes + if now + 0.002 < BackendData.NextRender then + BackendData.Pending = draw_data + return false + end + BackendData.NextRender = math.max(BackendData.NextRender + 1 / rate, now) + end + return true +end + +local function ReuseDrawList(BackendData, set, draw_list, same, sdx, sdy, z, ox, oy, ScreenWidth, ScreenHeight) + for kind = 1, 3 do + local layer = set[kind] + if layer and layer.Visible then + if same == 2 then ShiftLayer(layer, sdx, sdy, BackendData.Scale) end + z += 1 + if layer.Z ~= z then + layer.Z = z + layer.Root.ZIndex = z + end + end + end + if same == 2 then + Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) + set.SnapExtentX0 += sdx + set.SnapExtentY0 += sdy + set.SnapExtentX1 += sdx + set.SnapExtentY1 += sdy + end + set.LastUsed = BackendData.FrameNo + return PlaceOverlays(BackendData, draw_list, z, ox, oy) +end + +-- Collects primitives into Prim* (from n + 1) and commands into Cmd*; returns n, LimitFree and the extents +@native +local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, LimitX1, LimitY1) + local vbuf, idx = draw_list.VtxBuffer.Buf, draw_list.IdxBuffer.Data + local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1, + draw_list._ContentClipY1 + local SeenContent = false + local ex0, ey0, ex1, ey1 = math.huge, math.huge, -math.huge, -math.huge + local LimitFree = true + if ccx0 then + local a, b, c, d = floor(ccx0 - ox), floor(ccy0 - oy), floor(ccx1 - ox), floor(ccy1 - oy) + if a < LimitX0 or b < LimitY0 or c > LimitX1 or d > LimitY1 then LimitFree = false end + ex0, ey0, ex1, ey1 = min(ex0, a), min(ey0, b), max(ex1, c), max(ey1, d) + end + local ci = 0 + for _, pcmd in draw_list.CmdBuffer:iter() do + ci += 1 + CmdUnclipped[ci], CmdKind[ci] = false, 0 + if pcmd.UserCallback ~= nil then + pcmd.UserCallback(draw_list, pcmd) + elseif pcmd.ElemCount > 0 then + local clip = pcmd.ClipRect + local rcx0, rcy0, rcx1, rcy1 = floor(clip.x - ox), floor(clip.y - oy), floor(clip.z - ox), + floor(clip.w - oy) + if rcx0 < LimitX0 or rcy0 < LimitY0 or rcx1 > LimitX1 or rcy1 > LimitY1 then LimitFree = false end + if rcx0 < ex0 then ex0 = rcx0 end + if rcy0 < ey0 then ey0 = rcy0 end + if rcx1 > ex1 then ex1 = rcx1 end + if rcy1 > ey1 then ey1 = rcy1 end + local cx0, cy0 = max(rcx0, LimitX0), max(rcy0, LimitY0) + local cx1, cy1 = min(rcx1, LimitX1), min(rcy1, LimitY1) + local kind = 1 + if ccx0 and clip.x >= ccx0 and clip.y >= ccy0 and clip.z <= ccx1 and clip.w <= ccy1 then + kind = 2 + SeenContent = true + if clip.x == ccx0 and clip.y == ccy0 and clip.z == ccx1 and clip.w == ccy1 then + -- clipped by the layer's clip frame instead: partly visible rows stay hash-stable while scrolling + cx0, cy0, cx1, cy1 = LimitX0, LimitY0, LimitX1, LimitY1 + end + elseif SeenContent then + kind = 3 + end + CmdKind[ci] = kind + local CmdFree, cex0, cey0, cex1, cey1 = + cx1 > cx0 and cy1 > cy0, math.huge, math.huge, -math.huge, -math.huge + if cx1 > cx0 and cy1 > cy0 then + local tex_id = pcmd:GetTexID() + local t = BackendData.Textures[tex_id] + local vo = pcmd.VtxOffset + local i, last = pcmd.IdxOffset + 1, pcmd.IdxOffset + pcmd.ElemCount + while i <= last do + local ia, ic = idx[i], idx[i + 2] + local va, vb, vc = (vo + ia - 1) * 36 --[[VTX_STRIDE]], (vo + idx[i + 1] - 1) * 36 --[[VTX_STRIDE]], + (vo + ic - 1) * 36 --[[VTX_STRIDE]] + local vd = false + local gk = false + local pax, pay = readf64(vbuf, va), readf64(vbuf, va + 8) + local pbx, pby = readf64(vbuf, vb), readf64(vbuf, vb + 8) + local pcx, pcy = readf64(vbuf, vc), readf64(vbuf, vc + 8) + local bx0, by0, bx1, by1 + if i + 5 <= last and idx[i + 3] == ia and idx[i + 4] == ic then + local d = (vo + idx[i + 5] - 1) * 36 --[[VTX_STRIDE]] + local pdx, pdy = readf64(vbuf, d), readf64(vbuf, d + 8) + if pay == pby and pbx == pcx and pcy == pdy and pdx == pax and pax < pbx and pay < pdy then + local col, colb, colc, cold = readu32(vbuf, va + 32), readu32(vbuf, vb + 32), + readu32(vbuf, vc + 32), readu32(vbuf, d + 32) + local tax, tay = readf64(vbuf, va + 16), readf64(vbuf, va + 24) + local tbx, tby = readf64(vbuf, vb + 16), readf64(vbuf, vb + 24) + local tcx, tcy = readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) + local tdx, tdy = readf64(vbuf, d + 16), readf64(vbuf, d + 24) + if colb == col and colc == col and cold == col then + if tbx == tcx and tby == tay and tdx == tax and tdy == tcy then vd = d end + elseif tax == tbx and tax == tcx and tax == tdx and tay == tby and tay == tcy + and tay == tdy then + if colb == col and cold == colc then + vd = d + gk = 1 + elseif cold == col and colb == colc then + vd = d + gk = 2 + end + end + if vd then + bx0, by0 = ceil(pax - ox - 0.5), ceil(pay - oy - 0.5) + bx1, by1 = ceil(pcx - ox - 0.5), ceil(pcy - oy - 0.5) + end + end + end + if vd then + i = i + 6 + else + bx0, by0 = floor(min(pax, pbx, pcx) - ox), floor(min(pay, pby, pcy) - oy) + bx1, by1 = ceil(max(pax, pbx, pcx) - ox) + 1, ceil(max(pay, pby, pcy) - oy) + 1 + i = i + 3 + end + if bx0 < cx0 or by0 < cy0 or bx1 > cx1 or by1 > cy1 then CmdFree = false end + if bx0 < cex0 then cex0 = bx0 end + if by0 < cey0 then cey0 = by0 end + if bx1 > cex1 then cex1 = bx1 end + if by1 > cey1 then cey1 = by1 end + if bx0 < ex0 then ex0 = bx0 end + if by0 < ey0 then ey0 = by0 end + if bx1 > ex1 then ex1 = bx1 end + if by1 > ey1 then ey1 = by1 end + if bx0 < LimitX0 or by0 < LimitY0 or bx1 > LimitX1 or by1 > LimitY1 then LimitFree = false end + if bx0 < cx0 then bx0 = cx0 end + if by0 < cy0 then by0 = cy0 end + if bx1 > cx1 then bx1 = cx1 end + if by1 > cy1 then by1 = cy1 end + if bx0 < bx1 and by0 < by1 then + n = n + 1 + PrimA[n], PrimB[n], PrimC[n], PrimD[n], PrimTexture[n], PrimGradient[n], PrimTexId[n], + PrimVtxBuffer[n] = va, vb, vc, vd, t, gk, tex_id, vbuf + PrimClipX0[n], PrimClipY0[n], PrimClipX1[n], PrimClipY1[n] = cx0, cy0, cx1, cy1 + PrimBoundsX0[n], PrimBoundsY0[n], PrimBoundsX1[n], PrimBoundsY1[n] = bx0, by0, bx1, by1 + PrimKind[n] = kind + end + end + end + if cex0 > cex1 then cex0, cey0, cex1, cey1 = 0, 0, 0, 0 end + CmdUnclipped[ci] = CmdFree + CmdBoundsX0[ci], CmdBoundsY0[ci], CmdBoundsX1[ci], CmdBoundsY1[ci] = cex0, cey0, cex1, cey1 + end + end + return n, LimitFree, ex0, ey0, ex1, ey1 +end + +@native +local function DrawLists(BackendData, draw_list, first, n, z, ox, oy, force, LimitX0, LimitY0, LimitX1, LimitY1) + local set = BackendData.Layers[draw_list] + local ListDeferred = false + local Kind1Count, Kind2Count, Kind3Count = 0, 0, 0 + local Kind1X, Kind1Y, Kind3X, Kind3Y = math.huge, math.huge, math.huge, math.huge + for p = first, n do + local k = PrimKind[p] + if k == 1 then + Kind1Count += 1 + LayerPrims1[Kind1Count] = p + if PrimBoundsX0[p] < Kind1X then Kind1X = PrimBoundsX0[p] end + if PrimBoundsY0[p] < Kind1Y then Kind1Y = PrimBoundsY0[p] end + elseif k == 2 then + Kind2Count += 1 + LayerPrims2[Kind2Count] = p + else + Kind3Count += 1 + LayerPrims3[Kind3Count] = p + if PrimBoundsX0[p] < Kind3X then Kind3X = PrimBoundsX0[p] end + if PrimBoundsY0[p] < Kind3Y then Kind3Y = PrimBoundsY0[p] end + end + end + if Kind1Count > 0 then + z += 1 + if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 1), LayerPrims1, Kind1Count, Kind1X, Kind1Y, ox, + oy, force, z) then + ListDeferred = true + end + elseif set and set[1] then HideLayer(set[1]) end + if Kind2Count > 0 then + local ccx0 = draw_list._ContentClipX0 + local ContentX0, ContentY0, ContentX1, ContentY1 + if ccx0 then + ContentX0, ContentY0 = max(floor(ccx0 - ox), LimitX0), max(floor(draw_list._ContentClipY0 - oy), LimitY0) + ContentX1, ContentY1 = min(floor(draw_list._ContentClipX1 - ox), LimitX1), + min(floor(draw_list._ContentClipY1 - oy), LimitY1) + end + z += 1 + if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 2), LayerPrims2, Kind2Count, + floor(draw_list._ScrollOriginX - ox), floor(draw_list._ScrollOriginY - oy), ox, oy, force, z, + ContentX0, ContentY0, ContentX1, ContentY1) then ListDeferred = true end + elseif set and set[2] then HideLayer(set[2]) end + if Kind3Count > 0 then + z += 1 + if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 3), LayerPrims3, Kind3Count, Kind3X, Kind3Y, ox, + oy, force, z) then + ListDeferred = true + end + elseif set and set[3] then HideLayer(set[3]) end + return z, ListDeferred +end + +-- Overlay frames are only hidden (the user owns them); unused layers hidden, long unused ones freed +local function SweepLayers(BackendData, FrameNo) + for frame, shown in pairs(BackendData.OverlayShown) do + if shown ~= FrameNo then + frame.Visible = false + BackendData.OverlayShown[frame] = nil + end + end + table.clear(BackendData.Overlays) + + for draw_list, set in pairs(BackendData.Layers) do + if set.LastUsed ~= FrameNo then + set.SnapOK = false + for kind = 1, 3 do if set[kind] then HideLayer(set[kind]) end end + if FrameNo - set.LastUsed > LAYER_KEEP_FRAMES then + DestroyLayerSet(set) + BackendData.Layers[draw_list] = nil + end + end + end +end + +function M.RenderDrawData(draw_data) + local BackendData = GetBackendData() + PB("ImGui RenderDrawData") + BackendData.FrameStartTime = os.clock() + if EditableImages.StageTiming then + EditableImages.StageFrame = { Compare = 0, Collect = 0, Hash = 0, Raster = 0, Upload = 0, Other = 0, Total = 0, + TilesRasterized = 0, PixelsRasterized = 0, Uploads = 0, TilesCreated = 0, TilesFreed = 0 } end + BackendData.FrameTiles = 0 + -- the first dirty tile of a frame is always redrawn (progress), the rest within the budget + BackendData.RedrawStarted = false + BackendData.Stale = nil + + UpdateTextures(draw_data) + if not RenderRateAllows(BackendData, draw_data) then + PE() + return + end + + local ScreenWidth, ScreenHeight = floor(draw_data.DisplaySize.x), floor(draw_data.DisplaySize.y) + if ScreenWidth <= 0 or ScreenHeight <= 0 then + PE() + return + end + local ox, oy = draw_data.DisplayPos.x, draw_data.DisplayPos.y + local LimitX0, LimitY0, LimitX1, LimitY1 = -CLIP_PAD, -CLIP_PAD, ScreenWidth + CLIP_PAD, ScreenHeight + CLIP_PAD + BackendData.FrameNo += 1 + local FrameNo = BackendData.FrameNo + local force = BackendData.ForceRedraw + BackendData.ForceRedraw = false + Parallel.Active = Parallel.On and not Parallel.Config.Inline + + local n = 0 + local z = 0 + local AnyDeferred = false + for _, draw_list in draw_data.CmdLists:iter() do + PB("ImGui unchanged check") + if EditableImages.StageTiming then EditableImages.BeginStage() end + local set = BackendData.Layers[draw_list] + local same, sdx, sdy = 0, 0, 0 + if not force then same, sdx, sdy = CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) end + if same ~= 0 then + z = ReuseDrawList(BackendData, set, draw_list, same, sdx, sdy, z, ox, oy, ScreenWidth, ScreenHeight) + if EditableImages.StageTiming then EditableImages.EndStage("Compare") end + PE() + continue + end + if EditableImages.StageTiming then EditableImages.EndStage("Compare") end + PE() + + PB("ImGui collect") + if EditableImages.StageTiming then EditableImages.BeginStage() end + local first = n + 1 + local LimitFree, ex0, ey0, ex1, ey1 + n, LimitFree, ex0, ey0, ex1, ey1 = CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, LimitX1, + LimitY1) + if EditableImages.StageTiming then EditableImages.EndStage("Collect") end + PE() + + local ListDeferred + z, ListDeferred = DrawLists(BackendData, draw_list, first, n, z, ox, oy, force, LimitX0, LimitY0, LimitX1, + LimitY1) + set = BackendData.Layers[draw_list] + -- deferred tiles: not "unchanged" next frame, so they get redrawn + if set then + set.LastUsed = FrameNo + if ListDeferred then set.SnapOK = false else + Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) + set.SnapLimitFree = LimitFree + set.SnapExtentX0, set.SnapExtentY0, set.SnapExtentX1, set.SnapExtentY1 = ex0, ey0, ex1, ey1 + end + end + if ListDeferred then AnyDeferred = true end + z = PlaceOverlays(BackendData, draw_list, z, ox, oy) + end + + SweepLayers(BackendData, FrameNo) + -- drop references so old vertex tables can be collected + for k = n + 1, BackendData.LastPrimCount do PrimTexture[k], PrimVtxBuffer[k] = nil, nil end + BackendData.LastPrimCount = n + -- Tiles left for later: if the app doesn't submit a new frame, Heartbeat finishes them from this draw data + if AnyDeferred then + BackendData.Stale = draw_data + BackendData.StaleHeartbeat = BackendData.HeartbeatCount + end + if Parallel.Active then + Parallel.Flush() + end + if EditableImages.StageTiming and EditableImages.StageFrame then + local f = EditableImages.StageFrame + f.Raster -= f.Upload + f.Total = os.clock() - BackendData.FrameStartTime + f.Other = f.Total - f.Compare - f.Collect - f.Hash - f.Raster - f.Upload + BackendData.FrameStats = f + end + PE() +end + +Render = M +end +do +-- Parallel executor (opt-in, EnableParallel): Tile packs each dirty tile per Actor, Flush sends the batch while the +-- dispatch window (PreAnimation .. Finish) is open, else rasterizes it at once; Finish uploads every result. + + + + +local Players = game:GetService("Players") +local EditableImages, Records = Textures.EditableImages, Textures.Records +local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient = Render.PrimA, Render.PrimB, Render.PrimC, Render.PrimD, + Render.PrimTexture, Render.PrimGradient +local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = Render.PrimClipX0, Render.PrimClipY0, Render.PrimClipX1, + Render.PrimClipY1 +local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = Render.PrimBoundsX0, Render.PrimBoundsY0, + Render.PrimBoundsX1, Render.PrimBoundsY1 +local PrimTexId, PrimVtxBuffer = Render.PrimTexId, Render.PrimVtxBuffer + +local M = Render.Parallel +local writei32, writef64, copy = buffer.writei32, buffer.writef64, buffer.copy +local RasterJobs = Raster.RasterJobs +local VTX, REC, REC_A, REC_B, REC_C, JOB = Raster.VTX, Raster.REC, Raster.REC_A, Raster.REC_B, Raster.REC_C, Raster.JOB +assert(VTX == VTX_STRIDE, "raster.lua: vertex layout differs from ImDrawVert") + +-- Sync / SyncDrop / Inline: test hooks (inline "workers"; drop half their results; bypass the executor) +M.Config = { Actors = 4, MinTiles = 4, MinPixels = 16384, MaxBytesPerPixel = 3, Sync = false, SyncDrop = false, + Inline = false, Worker = nil } +M.Stats = { + ParallelFlushes = 0, SerialFlushes = 0, Tiles = 0, Fallbacks = 0, Late = 0, Pack = 0, Flush = 0, Finish = 0, + SendBytes = 0, TexSends = 0, TexBytes = 0, Rects = 0, Recv = 0, RecvBytes = 0, +} +local Stats = M.Stats + +local NA = 1 +local Pb, Pn, Tb, Tn, load, used = {}, {}, {}, {}, {}, {} +local stamp, poff, stamp_base = {}, {}, 0 +local free_batches, free_bufs, free_bytes = {}, {}, 0 +local function newBatch() + return table.remove(free_batches) + or { N = 0, Px = 0, Img = {}, Actor = {}, NR = {}, Rect = {}, P = {}, T = {}, TL = {}, Res = {} } +end +local function takeBuf(len: number): buffer + local l = free_bufs[len] + local b = l and table.remove(l) + if b then + free_bytes -= len + return b + end + return buffer.create(len) +end +local function giveBuf(b: buffer) + local len = buffer.len(b) + local l = free_bufs[len] + if not l then + l = {} + free_bufs[len] = l + end + if #l < 8 and free_bytes + len <= 4194304 then + l[#l + 1] = b + free_bytes += len + end +end +local jobs = newBatch() +local NO_TEX = {} +local cur = {} +local pending, by_id, batch_no = {}, {}, 0 +local open = false +local actors, ready, conns, folder = {}, false, {}, nil +local sent = {} + +local function grow(b: buffer, need: number): buffer + local n = buffer.len(b) + if need <= n then + return b + end + while n < need do + n *= 2 + end + local nb = buffer.create(n) + copy(nb, 0, b) + return nb +end + +local function reset() + for a = 1, NA do + Pn[a], Tn[a], load[a] = 0, 0, 0 + if used[a] then + table.clear(used[a]) + end + end + stamp_base += 64 + jobs = newBatch() +end + +-- One dirty tile (rects in EditableImages.DX0..DY1[1..nr], primitives list[1..count]) -> the least loaded Actor +@native +function M.Tile(img, list, count: number, x0: number, y0: number, tox: number, toy: number, nr: number) + local t0 = os.clock() + local DX0, DY0, DX1, DY1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1 + local area = 0 + for r = 1, nr do + area += (DX1[r] - DX0[r]) * (DY1[r] - DY0[r]) + end + local a = 1 + for i = 2, NA do + if load[i] < load[a] then + a = i + end + end + load[a] += area + 200 + jobs.Px += area + local j = jobs.N + 1 + jobs.N = j + jobs.Img[j], jobs.Actor[j], jobs.NR[j] = img, a, nr + Stats.Rects += nr + local R = jobs.Rect + local ri = #R + for r = 1, nr do + R[ri + 1], R[ri + 2], R[ri + 3], R[ri + 4] = DX0[r], DY0[r], DX1[r], DY1[r] + ri += 4 + end + + local T, to = grow(Tb[a], Tn[a] + JOB + nr * 16 + count * 4), Tn[a] + Tb[a] = T + writef64(T, to, tox) + writef64(T, to + 8, toy) + writei32(T, to + 16, x0) + writei32(T, to + 20, y0) + writei32(T, to + 24, nr) + writei32(T, to + 28, count) + to += JOB + for r = 1, nr do + writei32(T, to, DX0[r]) + writei32(T, to + 4, DY0[r]) + writei32(T, to + 8, DX1[r]) + writei32(T, to + 12, DY1[r]) + to += 16 + end + local P, pn = grow(Pb[a], Pn[a] + count * REC), Pn[a] + Pb[a] = P + local st = stamp_base + a + local u = used[a] + for k = 1, count do + local p = list[k] + if stamp[p] ~= st then + stamp[p], poff[p] = st, pn + local d, t = PrimD[p], PrimTexture[p] + local gk = PrimGradient[p] + writei32(P, pn, d and (gk and gk + 1 or 1) or 0) + writei32(P, pn + 4, t and PrimTexId[p] or -1) + if t then + u[t] = PrimTexId[p] + end + writei32(P, pn + 8, PrimClipX0[p]) + writei32(P, pn + 12, PrimClipY0[p]) + writei32(P, pn + 16, PrimClipX1[p]) + writei32(P, pn + 20, PrimClipY1[p]) + writei32(P, pn + 24, PrimBoundsX0[p]) + writei32(P, pn + 28, PrimBoundsY0[p]) + writei32(P, pn + 32, PrimBoundsX1[p]) + writei32(P, pn + 36, PrimBoundsY1[p]) + local vb = PrimVtxBuffer[p] + copy(P, pn + REC_A, vb, PrimA[p], VTX) + copy(P, pn + REC_C, vb, PrimC[p], VTX) + if not d then + copy(P, pn + REC_B, vb, PrimB[p], VTX) + end + pn += REC + end + writei32(T, to, poff[p]) + to += 4 + end + Pn[a], Tn[a] = pn, to + Stats.Pack += os.clock() - t0 +end + +local function upload(b) + local alive, R, ri = EditableImages.ImageBytes, b.Rect, 0 + table.clear(cur) + for j = 1, b.N do + local a = b.Actor[j] + local outs, c = b.Res[a], cur[a] or 0 + local img = b.Img[j] + for _ = 1, b.NR[j] do + c += 1 + if alive[img] then + local x0, y0 = R[ri + 1], R[ri + 2] + img:WritePixelsBuffer(Vector2.new(x0, y0), Vector2.new(R[ri + 3] - x0, R[ri + 4] - y0), outs[c]) + end + ri += 4 + end + cur[a] = c + end +end + +-- Uploads every pending batch (late worker results rasterized here) and closes the dispatch window +function M.Finish() + open = false + if #pending == 0 then + return + end + local t0 = os.clock() + for _, b in pending do + for a = 1, NA do + if b.TL[a] > 0 and not b.Res[a] then + b.Res[a] = RasterJobs(b.P[a], b.T[a], b.TL[a], Records) + if b.Sent then + Stats.Fallbacks += 1 + end + end + end + upload(b) + by_id[b.Id] = nil + for a = 1, NA do + if b.P[a] then + giveBuf(b.P[a]) + giveBuf(b.T[a]) + end + end + b.N, b.Px, b.Sent = 0, 0, false + table.clear(b.Img) + table.clear(b.Actor) + table.clear(b.NR) + table.clear(b.Rect) + table.clear(b.P) + table.clear(b.T) + table.clear(b.TL) + table.clear(b.Res) + if #free_batches < 8 then + free_batches[#free_batches + 1] = b + end + end + table.clear(pending) + Stats.Finish += os.clock() - t0 +end + +function M.Flush() + local n = jobs.N + if n == 0 then + if not open then + M.Finish() + end + return + end + local t0 = os.clock() + local cfg = M.Config + local par = open and (cfg.Sync or ready) and n >= cfg.MinTiles and jobs.Px >= cfg.MinPixels + if par and cfg.MaxBytesPerPixel > 0 then + local bytes = 0 + for a = 1, NA do + bytes += Pn[a] + Tn[a] + end + par = bytes <= cfg.MaxBytesPerPixel * jobs.Px + end + batch_no += 1 + local b = jobs + b.Id, b.Sent = batch_no, par + for a = 1, NA do + local tl = Tn[a] + b.TL[a] = tl + if tl == 0 then + continue + end + if not par then + b.Res[a] = RasterJobs(Pb[a], Tb[a], tl, Records) + continue + end + -- recycled copies rounded up to 4 KB (SendMessage copies the whole buffer) + local P, T = takeBuf(Pn[a] + 4095 - (Pn[a] + 4095) % 4096), takeBuf(tl + 4095 - (tl + 4095) % 4096) + copy(P, 0, Pb[a], 0, Pn[a]) + copy(T, 0, Tb[a], 0, tl) + b.P[a], b.T[a] = P, T + + local tex, s = NO_TEX, sent[a] + for rec, id in used[a] do + local v = rec.V or 0 + if s[rec] ~= v then + if tex == NO_TEX then + tex = {} + end + s[rec] = v + tex[#tex + 1] = { id, rec.Buffer, rec.Width, rec.Height } + Stats.TexSends += 1 + Stats.TexBytes += buffer.len(rec.Buffer) + end + end + Stats.SendBytes += Pn[a] + tl + if cfg.Sync then + if not (cfg.SyncDrop and a % 2 == 0) then + b.Res[a] = RasterJobs(P, T, tl, Records) + end + else + actors[a]:SendMessage("job", batch_no, P, T, tex, tl) + end + end + if par then + Stats.ParallelFlushes += 1 + else + Stats.SerialFlushes += 1 + end + Stats.Tiles += n + by_id[batch_no] = b + pending[#pending + 1] = b + reset() + Stats.Flush += os.clock() - t0 + if not open then + M.Finish() + end +end + +function M.BeginFrame() + open = true +end + +local function setActors(n) + NA = n + for a = 1, n do + Pb[a] = Pb[a] or buffer.create(4096) + Tb[a] = Tb[a] or buffer.create(1024) + used[a] = used[a] or {} + sent[a] = setmetatable({}, { __mode = "k" }) + end + reset() +end +setActors(1) + +function M.Disable() + M.Finish() + for _, c in conns do + c:Disconnect() + end + table.clear(conns) + if folder then + folder:Destroy() + folder = nil + end + table.clear(actors) + ready, open = false, false + M.On, M.Active = false, false +end + +function M.Enable(opts) + M.Disable() + for k, v in opts or {} do + M.Config[k] = v + end + local cfg = M.Config + setActors(math.max(1, cfg.Actors)) + M.On = true + if cfg.Sync then + return + end + local RunService = game:GetService("RunService") + -- bundle: script is the library ModuleScript (e.g. ImGui.Impl under the typed module) + local template = cfg.Worker or script:FindFirstChild("Worker") + or (script.Parent and script.Parent:FindFirstChild("Worker")) + assert(template, "ImGui_ImplRoblox.EnableParallel: no Worker LocalScript (build/ImGuiWorker.client.luau) as a" + .. " child of the ImGui module; or pass { Worker = ... }") + folder = Instance.new("Folder") + folder.Name = "ImGuiRasterActors" + for a = 1, NA do + local actor = Instance.new("Actor") + actor.Name = "Raster" .. a + local done = Instance.new("BindableEvent") + done.Name = "Done" + done.Parent = actor + table.insert(conns, done.Event:Connect(function(id, outs) + local t0, b = os.clock(), by_id[id] + if b then + b.Res[a] = outs + else + Stats.Late += 1 + end + for _, o in outs do + Stats.RecvBytes += buffer.len(o) + end + Stats.Recv += os.clock() - t0 + end)) + local w = template:Clone() + w.Parent = actor + actor.Parent = folder + actors[a] = actor + end + folder.Parent = Players.LocalPlayer:WaitForChild("PlayerScripts") + ready = false + table.insert(conns, RunService.PreAnimation:Connect(function() + if not ready then + ready = true + for _, act in actors do + if not act:GetAttribute("Ready") then + ready = false + end + end + end + open = true + end)) + table.insert(conns, RunService.PostSimulation:Connect(M.Finish)) +end + +Parallel = M +end +-- ImGui backend for Roblox: platform, input, files, Init/Shutdown and the public API; rendering in render.lua. +-- Requires "Allow Mesh / Image APIs" (EditableImage) in game settings. + + + + local UserInputService = game:GetService("UserInputService") local Players = game:GetService("Players") -local AssetService = game:GetService("AssetService") -local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max -local readu8, readu32, writeu32, readstring = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.readstring -local readf64 = buffer.readf64 -local band, rshift = bit32.band, bit32.rshift +local floor, min = math.floor, math.min +local EditableImages, PB, PE = Textures.EditableImages, Textures.PB, Textures.PE +local ImGui_ImplRoblox_GetBackendData = Textures.GetBackendData +local ImGui_ImplRoblox_RenderDrawData = Render.RenderDrawData +local DestroyTiles = Layers.DestroyTiles -local ImGui_ImplRoblox_GetBackendData -local ImGui_ImplRoblox_UpdateTexture -local ImGui_ImplRoblox_RenderDrawData -local ImGui_ImplRoblox_Shutdown - -local KEY_MAP = {} -- Enum.KeyCode -> ImGuiKey +local KEY_MAP = {} do local names = { - Return = "Enter", Escape = "Escape", Backspace = "Backspace", Tab = "Tab", Space = "Space", KeypadEnter = "KeypadEnter", + Return = "Enter", Escape = "Escape", Backspace = "Backspace", Tab = "Tab", Space = "Space", + KeypadEnter = "KeypadEnter", Up = "UpArrow", Down = "DownArrow", Left = "LeftArrow", Right = "RightArrow", Home = "Home", End = "End", PageUp = "PageUp", PageDown = "PageDown", Insert = "Insert", Delete = "Delete", LeftControl = "LeftCtrl", RightControl = "RightCtrl", LeftShift = "LeftShift", RightShift = "RightShift", LeftAlt = "LeftAlt", RightAlt = "RightAlt", LeftSuper = "LeftSuper", RightSuper = "RightSuper", - Quote = "Apostrophe", Comma = "Comma", Minus = "Minus", Period = "Period", Slash = "Slash", Semicolon = "Semicolon", - Equals = "Equal", LeftBracket = "LeftBracket", BackSlash = "Backslash", RightBracket = "RightBracket", Backquote = "GraveAccent", + Quote = "Apostrophe", Comma = "Comma", Minus = "Minus", Period = "Period", Slash = "Slash", + Semicolon = "Semicolon", + Equals = "Equal", LeftBracket = "LeftBracket", BackSlash = "Backslash", RightBracket = "RightBracket", + Backquote = "GraveAccent", CapsLock = "CapsLock", KeypadPeriod = "KeypadDecimal", KeypadDivide = "KeypadDivide", KeypadMultiply = "KeypadMultiply", KeypadMinus = "KeypadSubtract", KeypadPlus = "KeypadAdd", KeypadEquals = "KeypadEqual", @@ -45902,19 +48179,20 @@ do end end --- Roblox has no "text input" event, so characters come from KeyCode.Value (ASCII for printable keys) + a US layout shift table. +-- No text input event: characters come from KeyCode.Value (printable ASCII) + a US layout shift table local SHIFTED = { - ["1"] = "!", ["2"] = "@", ["3"] = "#", ["4"] = "$", ["5"] = "%", ["6"] = "^", ["7"] = "&", ["8"] = "*", ["9"] = "(", ["0"] = ")", - ["-"] = "_", ["="] = "+", ["["] = "{", ["]"] = "}", ["\\"] = "|", [";"] = ":", ["'"] = "\"", [","] = "<", ["."] = ">", ["/"] = "?", ["`"] = "~", + ["1"] = "!", ["2"] = "@", ["3"] = "#", ["4"] = "$", ["5"] = "%", ["6"] = "^", ["7"] = "&", ["8"] = "*", ["9"] = "(", + ["0"] = ")", + ["-"] = "_", ["="] = "+", ["["] = "{", ["]"] = "}", ["\\"] = "|", [";"] = ":", ["'"] = "\"", [","] = "<", + ["."] = ">", ["/"] = "?", ["`"] = "~", } local MOUSE_BUTTONS = { - [Enum.UserInputType.MouseButton1] = 0, -- ImGuiMouseButton.Left - [Enum.UserInputType.MouseButton2] = 1, -- ImGuiMouseButton.Right - [Enum.UserInputType.MouseButton3] = 2, -- ImGuiMouseButton.Middle + [Enum.UserInputType.MouseButton1] = 0, + [Enum.UserInputType.MouseButton2] = 1, + [Enum.UserInputType.MouseButton3] = 2, } ---- @return boolean ctrl, boolean shift, boolean alt local function ImGui_ImplRoblox_UpdateKeyModifiers() local io = ImGui.GetIO() local K = Enum.KeyCode @@ -45928,11 +48206,6 @@ local function ImGui_ImplRoblox_UpdateKeyModifiers() return ctrl, shift, alt end ---- @return table? -function ImGui_ImplRoblox_GetBackendData() - return ImGui.GetCurrentContext() and ImGui.GetIO().BackendPlatformUserData or nil -end - local function ImGui_ImplRoblox_UpdateMonitors(w, h) local platform_io = ImGui.GetPlatformIO() platform_io.Monitors:resize(0) @@ -45944,24 +48217,14 @@ local function ImGui_ImplRoblox_UpdateMonitors(w, h) platform_io.Monitors:push_back(imgui_monitor) end ---------------------------------------------------------- --- PLATFORM DATA & CALLBACKS ---------------------------------------------------------- - -- Games can't touch the OS clipboard, so copy/paste only works inside ImGui -local clipboard = "" -local function ImGui_ImplRoblox_PlatformSetClipboardText(ctx, text) clipboard = text end -local proxy_focused = false -local function ImGui_ImplRoblox_PlatformGetClipboardText(ctx) if proxy_focused then return "" end return clipboard end +local Clipboard = "" +local function ImGui_ImplRoblox_PlatformSetClipboardText(ctx, text) Clipboard = text end +local ProxyFocused = false +local function ImGui_ImplRoblox_PlatformGetClipboardText(ctx) if ProxyFocused then return "" end return Clipboard end ---------------------------------------------------------- --- FILE SYSTEM (in-memory, Roblox has no file access) ---------------------------------------------------------- +local VFS = {} -local VFS = {} -- path -> string of raw bytes - ---- Registers a file so ImGui can load it, e.g. ImGui_ImplRoblox.AddFile("fonts/MyFont.ttf", bytes) ---- then io.Fonts:AddFontFromFileTTF("fonts/MyFont.ttf", 16) local function ImGui_ImplRoblox_AddFile(path, bytes) VFS[path] = bytes end for path, hex in pairs(IM_INCLUDE("imgui_impl_roblox_fonts.lua")) do @@ -45993,1208 +48256,7 @@ function ImStd.ImFileLoadToMemory(filename, mode) return file_data, size end ---------------------------------------------------------- --- TEXTURE MANAGEMENT ---------------------------------------------------------- - --- Copies a region of ImTextureData pixels (1-based byte table) into our RGBA8 buffer -@native -local function CopyTexturePixels(tex, dst, x, y, w, h) - local bpp, tex_w = tex.BytesPerPixel, tex.Width - for row = 0, h - 1 do - local src, src_base = tex:GetPixelsAt(x, y + row) - local dst_off = ((y + row) * tex_w + x) * 4 - if bpp == 4 then - for i = 0, w - 1 do - local s = src_base + i * 4 - writeu32(dst, dst_off + i * 4, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216) - end - else -- Alpha8: white with alpha - for i = 0, w - 1 do - writeu32(dst, dst_off + i * 4, 16777215 + src[src_base + i] * 16777216) - end - end - end -end - -function ImGui_ImplRoblox_UpdateTexture(tex) - local bd = ImGui_ImplRoblox_GetBackendData() - if tex.Status == 2 --[[ImTextureStatus.WantCreate]] then - local t = { Buffer = buffer.create(tex.Width * tex.Height * 4), Width = tex.Width, Height = tex.Height } - CopyTexturePixels(tex, t.Buffer, 0, 0, tex.Width, tex.Height) - - bd.TextureCount = bd.TextureCount + 1 - bd.Textures[bd.TextureCount] = t - tex.BackendUserData = bd.TextureCount - tex:SetTexID(bd.TextureCount) - tex:SetStatus(0 --[[ImTextureStatus.OK]]) - elseif tex.Status == 3 --[[ImTextureStatus.WantUpdates]] then - local t = bd.Textures[tex.BackendUserData] - assert(t ~= nil) - for _, r in tex.Updates:iter() do - CopyTexturePixels(tex, t.Buffer, r.x, r.y, r.w, r.h) - end - tex:SetStatus(0 --[[ImTextureStatus.OK]]) - elseif tex.Status == 4 --[[ImTextureStatus.WantDestroy]] then - if tex.BackendUserData then - bd.Textures[tex.BackendUserData] = nil - tex.BackendUserData = nil - end - tex:SetTexID((-1) --[[ImTextureID_Invalid]]) - tex:SetStatus(1 --[[ImTextureStatus.Destroyed]]) - end -end - ---- User texture from RGBA8 pixels (e.g. EditableImage:ReadPixelsBuffer()). Returns an ImTextureRef for ---- ImGui.Image / draw_list:AddImage. Ids are never reused, so cached tiles can't show a stale image. -function ImGui_ImplRoblox_CreateTexture(pixels, w, h) - local bd = ImGui_ImplRoblox_GetBackendData() - bd.TextureCount = bd.TextureCount + 1 - bd.Textures[bd.TextureCount] = { Buffer = pixels, Width = w, Height = h } - return ImTextureRef(bd.TextureCount) -end - -function ImGui_ImplRoblox_DestroyTexture(tex_ref) - ImGui_ImplRoblox_GetBackendData().Textures[tex_ref._TexID] = nil -end - ---------------------------------------------------------- --- RENDERING (software rasterizer into tile buffers) ---------------------------------------------------------- --- Buffer layout: 4 bytes per pixel, R G B A, row-major, 0-based offsets. ImU32 colours are already R | G<<8 | B<<16 | A<<24. --- Blending is non-premultiplied "over" with a transparent (alpha 0) background, so the game stays visible behind ImGui. - -local buf, buf_w -- buffer/width of the tile being drawn -local rect_cols = table.create(256, 0) -- scratch: texel column offsets for DrawRect -local sub_bufs, n_sub_bufs = {}, 0 -- scratch: partial tile upload buffers by size -local TILE_SIZE -- Vector2, set below - --- Blends one pixel (r, g, b, a are 0..255). One u32 read/write, one division in the general case. --- FillSpan below inlines the same math with per-span constants - keep the two in sync. -@native -local function BlendPixel(o, r, g, b, a) - if a >= 255 then - writeu32(buf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080) - return - end - if a <= 0 then return end - local d = readu32(buf, o) - local da = rshift(d, 24) - if da == 0 then - writeu32(buf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216) - return - end - local sa = a / 255 - local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) - if da == 255 then - local ns = 1 - sa - writeu32(buf, o, floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256 + floor(b * sa + db * ns + 0.5) * 65536 + 4278190080) - else - local k = da * ((1 - sa) / 255) - local oa = sa + k - local inv = 1 / oa - writeu32(buf, o, floor((r * sa + dr * k) * inv + 0.5) + floor((g * sa + dg * k) * inv + 0.5) * 256 - + floor((b * sa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) - end -end - --- Fills pixels [x0, x1) of row y with one colour -@native -local function FillSpan(y, x0, x1, r, g, b, a) - if a <= 0 then return end - local o0 = (y * buf_w + x0) * 4 - local o1 = o0 + (x1 - x0 - 1) * 4 - if a >= 255 then - local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080 - for o = o0, o1, 4 do writeu32(buf, o, packed) end - return - end - local packed0 = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216 - local sa = a / 255 - local ns = 1 - sa - local c1 = ns / 255 - local rs, gs, bs = r * sa, g * sa, b * sa - local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination - for o = o0, o1, 4 do - local d = readu32(buf, o) - local da = rshift(d, 24) - if d == last_d then - writeu32(buf, o, last_v) - elseif da == 0 then - writeu32(buf, o, packed0) - else - last_d = d - local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) - if da == 255 then - last_v = floor(rs + dr * ns + 0.5) + floor(gs + dg * ns + 0.5) * 256 + floor(bs + db * ns + 0.5) * 65536 + 4278190080 - else - local k = da * c1 - local oa = sa + k - local inv = 1 / oa - last_v = floor((rs + dr * k) * inv + 0.5) + floor((gs + dg * k) * inv + 0.5) * 256 - + floor((bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 - end - writeu32(buf, o, last_v) - end - end -end - -@native -local function UnpackColor(col) - return col % 256, floor(col / 256) % 256, floor(col / 65536) % 256, floor(col / 16777216) % 256 -end - --- Nearest texel at (u, v) as r, g, b, a (0..255) -@native -local function SampleTexture(t, u, v) - local tw, th = t.Width, t.Height - local tx, ty = floor(u * tw), floor(v * th) - if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end - if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end - local o = (ty * tw + tx) * 4 - local tb = t.Buffer - return readu8(tb, o), readu8(tb, o + 1), readu8(tb, o + 2), readu8(tb, o + 3) -end - --- Axis aligned, single colour quad (rects, glyphs, images). Pixel centers inside [x0, x1) x [y0, y1) are drawn. -@native -local function DrawRect(x0, y0, x1, y1, u0, v0, u1, v1, col, t, cx0, cy0, cx1, cy1) - local r, g, b, a = UnpackColor(col) - if a == 0 then return end - local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0) - local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1) - if px0 >= px1 or py0 >= py1 then return end - - if not t or (u0 == u1 and v0 == v1) then - if t then - local tr, tg, tb, ta = SampleTexture(t, u0, v0) - r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255 - end - if a <= 0 then return end - -- Rows of a flat rect usually blend over identical rows: when this row's destination equals the previous - -- row's (exact string compare), the result is identical too, so memcpy the previous row's result. - local len = (px1 - px0) * 4 - local prev_dst, prev_o = nil, 0 - for y = py0, py1 - 1 do - local o = (y * buf_w + px0) * 4 - if a >= 255 then - if prev_dst then buffer.copy(buf, o, buf, prev_o, len) else FillSpan(y, px0, px1, r, g, b, a); prev_dst = true end - else - local dst = readstring(buf, o, len) - if dst == prev_dst then - buffer.copy(buf, o, buf, prev_o, len) - else - FillSpan(y, px0, px1, r, g, b, a) - prev_dst = dst - end - end - prev_o = o - end - return - end - - local du, dv = (u1 - u0) / (x1 - x0), (v1 - v0) / (y1 - y0) - local tw, th, tbuf = t.Width, t.Height, t.Buffer - local r255, g255, b255, a255 = r / 255, g / 255, b / 255, a / 255 - -- The texel column only depends on x: compute it once per column instead of once per pixel - local ncol = px1 - px0 - local cols = rect_cols - for c = 1, ncol do - local tx = floor((u0 + (px0 + c - 1 + 0.5 - x0) * du) * tw) - if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end - cols[c] = tx * 4 - end - for y = py0, py1 - 1 do - local ty = floor((v0 + (y + 0.5 - y0) * dv) * th) - if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end - local trow4 = ty * tw * 4 - local o = (y * buf_w + px0) * 4 - for c = 1, ncol do - local to = trow4 + cols[c] - local ta = readu8(tbuf, to + 3) - if ta > 0 then - local sa = ta * a255 - local sr, sg, sb = readu8(tbuf, to) * r255, readu8(tbuf, to + 1) * g255, readu8(tbuf, to + 2) * b255 - if sa >= 255 then -- (BlendPixel's opaque case, inlined: most glyph texels) - writeu32(buf, o, floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + 4278190080) - else - BlendPixel(o, sr, sg, sb, sa) - end - end - o = o + 4 - end - end -end - --- Generic triangle: per-vertex colour + uv, top-left fill rule, clipped to [cx0, cx1) x [cy0, cy1) -@native -local function DrawTriangle(vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, ox, oy) - local x0, y0 = readf64(vbuf, va) - ox, readf64(vbuf, va + 8) - oy - local x1, y1 = readf64(vbuf, vb) - ox, readf64(vbuf, vb + 8) - oy - local x2, y2 = readf64(vbuf, vc) - ox, readf64(vbuf, vc + 8) - oy - local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0) - if area == 0 then return end - if area < 0 then -- make the winding consistent so "inside" means all edge functions >= 0 - vb, vc = vc, vb - x1, y1, x2, y2 = x2, y2, x1, y1 - area = -area - end - - local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1) - local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1) - if minx > maxx or miny > maxy then return end - - -- Edge functions E(p) = A*px + B*py + C, w0 is opposite va, w1 opposite vb, w2 opposite vc - local A0, B0 = y1 - y2, x2 - x1; local C0 = -(A0 * x1 + B0 * y1) - local A1, B1 = y2 - y0, x0 - x2; local C1 = -(A1 * x2 + B1 * y2) - local A2, B2 = y0 - y1, x1 - x0; local C2 = -(A2 * x0 + B2 * y0) - local tl0 = A0 > 0 or (A0 == 0 and B0 > 0) - local tl1 = A1 > 0 or (A1 == 0 and B1 > 0) - local tl2 = A2 > 0 or (A2 == 0 and B2 > 0) - - local inv = 1 / area - local ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32)) - local rb, gb, bb, ab = UnpackColor(readu32(vbuf, vb + 32)) - local rc, gc, bc, ac = UnpackColor(readu32(vbuf, vc + 32)) - local ua, vva, ub, vvb, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vb + 16), readf64(vbuf, vb + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) - - local textured = t and not (ua == ub and ua == uc and vva == vvb and vva == vvc) - if t and not textured then -- constant uv (e.g. the atlas white pixel): fold the texel into the vertex colours - local tr, tg, tb, ta = SampleTexture(t, ua, vva) - ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255 - rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255 - rc, gc, bc, ac = rc * tr / 255, gc * tg / 255, bc * tb / 255, ac * ta / 255 - end - local flat = not textured and ra == rb and ra == rc and ga == gb and ga == gc and ba == bb and ba == bc and aa == ab and aa == ac - if flat and aa <= 0 then return end - - for y = miny, maxy do - local py = y + 0.5 - -- Narrow the x range of this row using the edges (expanded by one pixel, exact test below) - local xl, xr = minx, maxx - local e0, e1, e2 = B0 * py + C0, B1 * py + C1, B2 * py + C2 - if A0 ~= 0 then local xe = -e0 / A0 - 0.5; if A0 > 0 then xl = max(xl, floor(xe)) else xr = min(xr, ceil(xe)) end end - if A1 ~= 0 then local xe = -e1 / A1 - 0.5; if A1 > 0 then xl = max(xl, floor(xe)) else xr = min(xr, ceil(xe)) end end - if A2 ~= 0 then local xe = -e2 / A2 - 0.5; if A2 > 0 then xl = max(xl, floor(xe)) else xr = min(xr, ceil(xe)) end end - - local row = y * buf_w - for x = xl, xr do - local px = x + 0.5 - local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2 - if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then - local o = (row + x) * 4 - if flat then - BlendPixel(o, ra, ga, ba, aa) - else - w0, w1, w2 = w0 * inv, w1 * inv, w2 * inv - local r = w0 * ra + w1 * rb + w2 * rc - local g = w0 * ga + w1 * gb + w2 * gc - local b = w0 * ba + w1 * bb + w2 * bc - local a = w0 * aa + w1 * ab + w2 * ac - if textured then - local tr, tg, tb, ta = SampleTexture(t, w0 * ua + w1 * ub + w2 * uc, w0 * vva + w1 * vvb + w2 * vvc) - r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255 - end - BlendPixel(o, r, g, b, a) - end - end - end - end -end - --- Layers: every ImDrawList (one per top level window, popup, tooltip, plus the viewport bg/fg lists) gets its own --- Frame, stacked by draw order. A layer is covered by TILE x TILE EditableImages (one ImageLabel each) placed --- relative to the layer's origin (top-left of its content). Primitives are hashed into tiles in layer-relative --- coordinates, so moving a window only moves its Frame: no tile changes, nothing re-rasterized or uploaded. --- Only tiles whose hash changed are redrawn; the hash covers everything that affects a tile's pixels. -local TILE = 128 -TILE_SIZE = Vector2.new(TILE, TILE) -local P1, P2 = 2147483647, 2147483629 -- two independent 31 bit hashes per tile (collision odds ~2^-62) -local KEY_W = 64 -- tile key = ty * KEY_W + tx (layers up to 16384 px wide) -local CLIP_PAD = 2048 -- content up to this far off screen is kept, so dragging a window past the edge doesn't redraw it -local LAYER_KEEP_FRAMES = 120 -- unused layers are destroyed after this many rendered frames -local MAX_DEFER_FRAMES = 8 -- a tile is redrawn at the latest this many frames after it changed, even over the redraw budget - --- Primitive arrays (reused between frames, no per-frame allocation) -local pr_a, pr_b, pr_c, pr_d, pr_t, pr_g = {}, {}, {}, {}, {}, {} -- vertices (pr_d == false -> triangle), texture, gradient kind -local pr_cx0, pr_cy0, pr_cx1, pr_cy1 = {}, {}, {}, {} -- clip (screen pixels) -local pr_bx0, pr_by0, pr_bx1, pr_by1 = {}, {}, {}, {} -- clipped bounds (screen pixels) -local pr_tex = {} -- texture id -local pr_vb = {} -- vertex buffer (draw list VtxBuffer.Buf) -local pr_k = {} -- layer kind (1..3) -local plist1, plist2, plist3 = {}, {}, {} -- primitive indices per layer kind -local cm_free, cm_kind, cm_x0, cm_y0, cm_x1, cm_y1 = {}, {}, {}, {}, {}, {} -- per draw command (collect -> Snapshot) - -@native -local function HashVertex(h1, h2, vbuf, v, ox, oy) - local x, y = readf64(vbuf, v) - ox, readf64(vbuf, v + 8) - oy - local uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24) - local c = readu32(vbuf, v + 32) - h1 = (h1 * 48271 + x * 4096 + y) % P1 - h1 = (h1 * 48271 + uv * 4096) % P1 - h1 = (h1 * 48271 + c) % P1 - h2 = (h2 * 16807 + y * 4093 + x) % P2 - h2 = (h2 * 16807 + uv * 65521) % P2 - h2 = (h2 * 16807 + c) % P2 - return h1, h2 -end - --- Axis aligned quad with a linear colour gradient and constant uv (ColorPicker hue/SV/alpha bars, AddRectFilledMultiColor). --- kind 1: colour varies along y (ca top, cb bottom), kind 2: along x (ca left, cb right). Same pixels as the two triangles. -@native -local function DrawRectGradient(x0, y0, x1, y1, ca, cb, kind, t, u, v, cx0, cy0, cx1, cy1) - local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0) - local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1) - if px0 >= px1 or py0 >= py1 then return end - local ra, ga, ba, aa = UnpackColor(ca) - local rb, gb, bb, ab = UnpackColor(cb) - if t then - local tr, tg, tb, ta = SampleTexture(t, u, v) - ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255 - rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255 - end - if kind == 1 then - local inv = 1 / (y1 - y0) - for y = py0, py1 - 1 do - local f = (y + 0.5 - y0) * inv - local nf = 1 - f - FillSpan(y, px0, px1, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f) - end - else - -- Every row gets the same colours: when a row's destination equals the previous row's, copy its result - local inv = 1 / (x1 - x0) - local len = (px1 - px0) * 4 - local opaque = aa >= 255 and ab >= 255 - local prev_dst, prev_o = nil, 0 - for y = py0, py1 - 1 do - local o = (y * buf_w + px0) * 4 - local dst = (not opaque) and readstring(buf, o, len) or true - if prev_dst ~= nil and dst == prev_dst then - buffer.copy(buf, o, buf, prev_o, len) - else - local oo = o - for x = px0, px1 - 1 do - local f = (x + 0.5 - x0) * inv - local nf = 1 - f - BlendPixel(oo, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f) - oo = oo + 4 - end - prev_dst = dst - end - prev_o = o - end - end -end - --- Layer kinds per draw list: 1 = drawn before the window content (background, title bar, borders, scrollbar), --- 2 = window content (positioned at the scroll origin inside a ClipsDescendants frame, so scrolling just moves it), --- 3 = anything not clipped to the content drawn after content started (menu bar, overlays). Stacked 1 < 2 < 3. -local function NewFrame(parent, clips) - local frame = Instance.new("Frame") - frame.Name = "Layer" - frame.BackgroundTransparency = 1 - frame.BorderSizePixel = 0 - frame.Size = UDim2.fromOffset(0, 0) - frame.ClipsDescendants = clips - frame.Visible = false - frame.Parent = parent - return frame -end - -local function GetLayer(bd, draw_list, kind) - local set = bd.Layers[draw_list] - if not set then set = { LastUsed = 0 }; bd.Layers[draw_list] = set end - local layer = set[kind] - if layer then return layer end - local root, frame - if kind == 2 then - root = NewFrame(bd.Gui, true) - frame = NewFrame(root, false); frame.Visible = true - else - frame = NewFrame(bd.Gui, false); root = frame - end - layer = { Root = root, Frame = frame, Tiles = {}, TH1 = {}, TH2 = {}, TN = {}, TL = {}, TL1 = {}, TL2 = {}, TLF = {}, TX = {}, TY = {}, Touched = {}, NTouched = 0, - Visible = false, X = false, Y = false, Z = -1, CX0 = false, CY0 = false, CX1 = false, CY1 = false } - set[kind] = layer - return layer -end - -local function HideLayer(layer) - if layer.Visible then layer.Visible = false; layer.Root.Visible = false end -end - -local function GetTile(bd, layer, key, tx, ty) - local tile = layer.Tiles[key] - if tile then return tile end - local img = AssetService:CreateEditableImage({ Size = Vector2.new(TILE, TILE) }) - assert(img, "imgui_impl_roblox: EditableImage memory budget exceeded") - local label = Instance.new("ImageLabel") - label.Name = "Tile" .. key - label.BackgroundTransparency = 1 - label.BorderSizePixel = 0 - local scale = bd.Scale - label.Size = UDim2.fromOffset(TILE / scale, TILE / scale) - label.Position = UDim2.fromOffset(tx * TILE / scale, ty * TILE / scale) - label.ResampleMode = Enum.ResamplerMode.Pixelated - label.ImageContent = Content.fromObject(img) - label.Visible = false - label.Active = bd.TilesActive - label.Parent = layer.Frame - tile = { Image = img, Label = label, Buffer = buffer.create(TILE * TILE * 4), H1 = -1, H2 = -1, Visible = false, BX0 = TILE, BY0 = TILE, BX1 = 0, BY1 = 0, - ON = -1, OH1 = {}, OH2 = {}, OF = {}, OB0 = {}, OB1 = {}, OB2 = {}, OB3 = {} } -- last drawn primitive list (hashes, bounds in tile) - layer.Tiles[key] = tile - return tile -end - -local function DestroyLayerSet(set) - for kind = 1, 3 do - local layer = set[kind] - if layer then - for _, tile in pairs(layer.Tiles) do tile.Image:Destroy() end - layer.Root:Destroy() - end - end -end - -local function DestroyTiles(bd) - for _, set in pairs(bd.Layers) do DestroyLayerSet(set) end - bd.Layers = {} -end - --- Snapshot of everything in a draw list that affects its layers, compared exactly with the next frame's list: --- 1 = identical (only restack), 2 = everything moved by the same whole pixels (dx, dy) (only move the layers: a window --- being dragged), 0 = changed (full path). Compared in place (no strings built): early exit at the first difference. -local writef64 = buffer.writef64 -local CMD_STRIDE = 70 -- clip (4 f64), ElemCount, IdxOffset, VtxOffset (u32), tex id (f64), kind (u8), free (u8), bounds of its primitives (4 x i32) - -@native -local function Snapshot(set, draw_list, ox, oy, sw, sh) - local nv = draw_list.VtxBuffer.Size * 36 --[[VTX_STRIDE]] - local idx, ni = draw_list.IdxBuffer.Data, draw_list.IdxBuffer.Size - local ncmd = draw_list.CmdBuffer.Size - local sv, si, sc = set.SV, set.SI, set.SC - if not sv or buffer.len(sv) < nv then sv = buffer.create(max(nv, 64) * 2); set.SV = sv end - if not si or buffer.len(si) < ni * 4 then si = buffer.create(max(ni, 16) * 8); set.SI = si end - if not sc or buffer.len(sc) < ncmd * CMD_STRIDE then sc = buffer.create(max(ncmd, 4) * CMD_STRIDE * 2); set.SC = sc end - buffer.copy(sv, 0, draw_list.VtxBuffer.Buf, 0, nv) - for i = 1, ni do writeu32(si, (i - 1) * 4, idx[i]) end - local o, ci = 0, 0 - for _, pcmd in draw_list.CmdBuffer:iter() do - if pcmd.UserCallback ~= nil then set.SnapOK = false; return end - local c = pcmd.ClipRect - writef64(sc, o, c.x); writef64(sc, o + 8, c.y); writef64(sc, o + 16, c.z); writef64(sc, o + 24, c.w) - writeu32(sc, o + 32, pcmd.ElemCount); writeu32(sc, o + 36, pcmd.IdxOffset); writeu32(sc, o + 40, pcmd.VtxOffset) - writef64(sc, o + 44, pcmd:GetTexID()) - ci += 1 - buffer.writeu8(sc, o + 52, cm_kind[ci] or 0); buffer.writeu8(sc, o + 53, cm_free[ci] and 1 or 0) - if cm_free[ci] then - buffer.writei32(sc, o + 54, cm_x0[ci]); buffer.writei32(sc, o + 58, cm_y0[ci]); buffer.writei32(sc, o + 62, cm_x1[ci]); buffer.writei32(sc, o + 66, cm_y1[ci]) - end - o += CMD_STRIDE - end - set.SVN, set.SIN, set.SCN = nv, ni, ncmd - set.SOX, set.SOY, set.SSW, set.SSH = ox, oy, sw, sh - set.SCC = draw_list._ContentClipX0 ~= nil - set.SCX0, set.SCY0, set.SCX1, set.SCY1 = draw_list._ContentClipX0 or 0, draw_list._ContentClipY0 or 0, draw_list._ContentClipX1 or 0, draw_list._ContentClipY1 or 0 - set.SSX, set.SSY = draw_list._ScrollOriginX or 0, draw_list._ScrollOriginY or 0 - set.SnapOK = true -end - --- a + d == b exactly, with no rounding in a + d (so every later "x - origin" gives the same result as before the move) -@native -local function ShiftedExact(a, d, b) - local s = a + d - if s ~= b then return false end - local bb = s - a - return (a - (s - bb)) + (d - bb) == 0 -end - -@native -local function CompareDrawList(set, draw_list, ox, oy, sw, sh) - if not set or not set.SnapOK then return 0 end - local nv = draw_list.VtxBuffer.Size * 36 --[[VTX_STRIDE]] - local ni, ncmd = draw_list.IdxBuffer.Size, draw_list.CmdBuffer.Size - if nv ~= set.SVN or ni ~= set.SIN or ncmd ~= set.SCN or ox ~= set.SOX or oy ~= set.SOY or sw ~= set.SSW or sh ~= set.SSH then return 0 end - if (draw_list._ContentClipX0 ~= nil) ~= set.SCC then return 0 end - local vb, sv = draw_list.VtxBuffer.Buf, set.SV - if nv == 0 then return 1 end - -- translation from the first vertex: whole pixels only, and only with DisplayPos at 0 (so it stays exact) - local dx, dy = readf64(vb, 0) - readf64(sv, 0), readf64(vb, 8) - readf64(sv, 8) - if dx ~= dx or dy ~= dy then return 0 end - if dx ~= 0 or dy ~= 0 then - if dx ~= floor(dx) or dy ~= floor(dy) or ox ~= 0 or oy ~= 0 or not set.SLimFree then return 0 end - -- everything must stay as far from the clip limits as before (nothing newly clamped) - if set.SEX0 + dx < -CLIP_PAD or set.SEY0 + dy < -CLIP_PAD or set.SEX1 + dx > sw + CLIP_PAD or set.SEY1 + dy > sh + CLIP_PAD then return 0 end - end - local idx, si = draw_list.IdxBuffer.Data, set.SI - for i = 1, ni do if idx[i] ~= readu32(si, (i - 1) * 4) then return 0 end end - local sc, o = set.SC, 0 - local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1, draw_list._ContentClipY1 - local seen_content = false - for _, pcmd in draw_list.CmdBuffer:iter() do - if pcmd.UserCallback ~= nil then return 0 end - if pcmd.ElemCount ~= readu32(sc, o + 32) or pcmd.IdxOffset ~= readu32(sc, o + 36) or pcmd.VtxOffset ~= readu32(sc, o + 40) or pcmd:GetTexID() ~= readf64(sc, o + 44) then return 0 end - local c = pcmd.ClipRect - if dx == 0 and dy == 0 then - if c.x ~= readf64(sc, o) or c.y ~= readf64(sc, o + 8) or c.z ~= readf64(sc, o + 16) or c.w ~= readf64(sc, o + 24) then return 0 end - elseif not (ShiftedExact(readf64(sc, o), dx, c.x) and ShiftedExact(readf64(sc, o + 8), dy, c.y) - and ShiftedExact(readf64(sc, o + 16), dx, c.z) and ShiftedExact(readf64(sc, o + 24), dy, c.w)) then - -- An unchanged clip rect (e.g. the viewport) is fine if it clipped none of this command's primitives before - -- the move and still clips none after it - if c.x ~= readf64(sc, o) or c.y ~= readf64(sc, o + 8) or c.z ~= readf64(sc, o + 16) or c.w ~= readf64(sc, o + 24) - or buffer.readu8(sc, o + 53) == 0 then return 0 end - if buffer.readi32(sc, o + 54) + dx < floor(c.x) or buffer.readi32(sc, o + 58) + dy < floor(c.y) - or buffer.readi32(sc, o + 62) + dx > floor(c.z) or buffer.readi32(sc, o + 66) + dy > floor(c.w) then return 0 end - end - -- same layer kind as before (same rule as the collect pass) - if pcmd.ElemCount > 0 then - local kind = 1 - if ccx0 and c.x >= ccx0 and c.y >= ccy0 and c.z <= ccx1 and c.w <= ccy1 then kind = 2; seen_content = true - elseif seen_content then kind = 3 end - if kind ~= buffer.readu8(sc, o + 52) then return 0 end - end - o += CMD_STRIDE - end - if dx == 0 and dy == 0 then - if set.SCC and (draw_list._ContentClipX0 ~= set.SCX0 or draw_list._ContentClipY0 ~= set.SCY0 or draw_list._ContentClipX1 ~= set.SCX1 - or draw_list._ContentClipY1 ~= set.SCY1 or draw_list._ScrollOriginX ~= set.SSX or draw_list._ScrollOriginY ~= set.SSY) then return 0 end - for v = 0, nv - 36 --[[VTX_STRIDE]], 36 --[[VTX_STRIDE]] do - if readf64(vb, v) ~= readf64(sv, v) or readf64(vb, v + 8) ~= readf64(sv, v + 8) or readf64(vb, v + 16) ~= readf64(sv, v + 16) - or readf64(vb, v + 24) ~= readf64(sv, v + 24) or readu32(vb, v + 32) ~= readu32(sv, v + 32) then return 0 end - end - return 1 - end - if set.SCC and not (ShiftedExact(set.SCX0, dx, draw_list._ContentClipX0) and ShiftedExact(set.SCY0, dy, draw_list._ContentClipY0) - and ShiftedExact(set.SCX1, dx, draw_list._ContentClipX1) and ShiftedExact(set.SCY1, dy, draw_list._ContentClipY1) - and ShiftedExact(set.SSX, dx, draw_list._ScrollOriginX) and ShiftedExact(set.SSY, dy, draw_list._ScrollOriginY)) then return 0 end - for v = 0, nv - 36 --[[VTX_STRIDE]], 36 --[[VTX_STRIDE]] do - if not ShiftedExact(readf64(sv, v), dx, readf64(vb, v)) or not ShiftedExact(readf64(sv, v + 8), dy, readf64(vb, v + 8)) - or readf64(vb, v + 16) ~= readf64(sv, v + 16) or readf64(vb, v + 24) ~= readf64(sv, v + 24) or readu32(vb, v + 32) ~= readu32(sv, v + 32) then return 0 end - end - return 2, dx, dy -end - --- A window moved by whole pixels: its tiles are unchanged, only the layer frames move -local function ShiftLayer(layer, dx, dy, scale) - layer.X += dx; layer.Y += dy - local root = layer.Root - if root ~= layer.Frame then - layer.CX0 += dx; layer.CY0 += dy; layer.CX1 += dx; layer.CY1 += dy - root.Position = UDim2.fromOffset(layer.CX0 / scale, layer.CY0 / scale) - else - root.Position = UDim2.fromOffset(layer.X / scale, layer.Y / scale) - end -end - --- Overlays: user Instances (e.g. a Frame holding a ViewportFrame) placed inside a window, registered every frame with --- ImGui_ImplRoblox.SetOverlay() while that window is current. They stack right above the window's layers, move with --- it, and (clip = true) are clipped to the window's content area like its widgets. -local function OverlayHolder(bd, draw_list, clip) - local hs = bd.OverlayHolders[draw_list] - if not hs then hs = {}; bd.OverlayHolders[draw_list] = hs end - local h = hs[clip] - if not h then - h = Instance.new("Frame") - h.Name = clip and "OverlayClip" or "Overlay" - h.BackgroundTransparency = 1 - h.BorderSizePixel = 0 - h.ClipsDescendants = clip - h.Size = UDim2.fromOffset(0, 0) - h.Parent = bd.Gui - hs[clip] = h - end - return h -end - -local function PlaceOverlays(bd, draw_list, z, ox, oy) - local list = bd.Overlays[draw_list] - local hs = bd.OverlayHolders[draw_list] - if not list then - if hs then for _, h in pairs(hs) do h.Visible = false end end - return z - end - local scale, frame_no = bd.Scale, bd.FrameNo - z += 1 - local used = {} - for _, o in ipairs(list) do - local clip = o.Clip and draw_list._ContentClipX0 ~= nil - local h = OverlayHolder(bd, draw_list, clip) - local hx, hy = 0, 0 - if clip then - hx, hy = draw_list._ContentClipX0 - ox, draw_list._ContentClipY0 - oy - if not used[h] then - h.Position = UDim2.fromOffset(hx / scale, hy / scale) - h.Size = UDim2.fromOffset((draw_list._ContentClipX1 - draw_list._ContentClipX0) / scale, (draw_list._ContentClipY1 - draw_list._ContentClipY0) / scale) - end - elseif not used[h] then - h.Position = UDim2.fromOffset(0, 0) - end - used[h] = true - h.ZIndex = z - h.Visible = true - local f = o.Frame - if f.Parent ~= h then f.Parent = h end - f.Position = UDim2.fromOffset((o.X - ox - hx) / scale, (o.Y - oy - hy) / scale) - f.Size = UDim2.fromOffset(o.W / scale, o.H / scale) - f.Visible = true - bd.OverlayShown[f] = frame_no - end - if hs then for _, h in pairs(hs) do if not used[h] then h.Visible = false end end end - return z -end - ---- Show `frame` this frame at (x, y, w, h) (imgui coordinates) inside the current window. Call every frame it should ---- be visible; frames not submitted are hidden. clip: clip to the window's content area (scrolls with it). -function ImGui_ImplRoblox_SetOverlay(frame, x, y, w, h, clip) - local bd = ImGui_ImplRoblox_GetBackendData() - local dl = ImGui.GetWindowDrawList() - local list = bd.Overlays[dl] - if not list then list = {}; bd.Overlays[dl] = list end - list[#list + 1] = { Frame = frame, X = x, Y = y, W = w, H = h, Clip = clip ~= false } -end - --- MicroProfiler labels, enabled with ImGui_ImplRoblox.SetProfiling(true) -local profilebegin, profileend = debug.profilebegin, debug.profileend -local profiling = false -local function PB(name) if profiling then profilebegin(name) end end -local function PE() if profiling then profileend() end end - -@native -local function DrawLayer(bd, layer, plist, np, lx0, ly0, ox, oy, force, z, clip_x0, clip_y0, clip_x1, clip_y1) - local scale = bd.Scale - local deferred = false - -- Pass 2: hash primitives into layer-relative tiles - PB("ImGui tile hash") - local th1, th2, tn, tl, touched = layer.TH1, layer.TH2, layer.TN, layer.TL, layer.Touched - local tl1, tl2, tlf = layer.TL1, layer.TL2, layer.TLF -- per-tile list of the primitives' hashes (for partial redraws) - for k = 1, layer.NTouched do tn[touched[k]] = 0 end - local nt = 0 - for pi = 1, np do - local p = plist[pi] - local tex_id = pr_tex[p] - -- The clip rect only affects pixels inside the primitive's bounds, so hash the clipped bounds (relative) - -- instead of the clip itself: a window clipped by the (fixed) viewport rect stays hash-stable when moved. - local cx0, cy0, cx1, cy1 = pr_bx0[p] - lx0, pr_by0[p] - ly0, pr_bx1[p] - lx0, pr_by1[p] - ly0 - local vbuf = pr_vb[p] - local va, vd = pr_a[p], pr_d[p] - -- Flat rect (single colour, no gradient, constant uv): its pixels in a tile are exactly its clipped pixel rect - -- inside that tile filled with one colour, so hash that per tile instead of the vertices. Resizing a window - -- then only changes the tiles its edges cross, not every tile its background covers. - local flat_rect, rcol, ruv = false, 0, 0 - if vd and not pr_g[p] then - local u0, v0 = readf64(vbuf, va + 16), readf64(vbuf, va + 24) - local vc = pr_c[p] - if not pr_t[p] or (u0 == readf64(vbuf, vc + 16) and v0 == readf64(vbuf, vc + 24)) then - flat_rect, rcol, ruv = true, readu32(vbuf, va + 32), u0 * 8192 + v0 - end - end - local h1, h2 = 0, 0 - local fsig = -1 -- flat rect: colour/uv/texture without the geometry (-1: not a flat rect) - if flat_rect then fsig = ((rcol * 8191 + ruv * 4096) % P1 * 64 + tex_id) % P1 end - if not flat_rect then - h1 = ((cx0 * 8191 + cy0) * 8191 + cx1) % P1 - h2 = ((cy1 * 8191 + cx1) * 8191 + cy0 + tex_id) % P2 - local vax, vay = lx0 + ox, ly0 + oy - if vd then - -- Axis aligned quad: the collect pass checked that TR/BL (positions, uvs, colours) follow from TL/BR - -- (and the gradient kind), so TL + BR + kind determine its pixels - h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay) - h1, h2 = HashVertex(h1, h2, vbuf, pr_c[p], vax, vay) - local gk = pr_g[p] - if gk then h1 = (h1 * 48271 + gk) % P1; h2 = (h2 * 16807 + gk * 3) % P2 end - else - h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay) - h1, h2 = HashVertex(h1, h2, vbuf, pr_b[p], vax, vay) - h1, h2 = HashVertex(h1, h2, vbuf, pr_c[p], vax, vay) - end - end - for ty = floor((pr_by0[p] - ly0) / TILE), floor((pr_by1[p] - 1 - ly0) / TILE) do - for tx = floor((pr_bx0[p] - lx0) / TILE), floor((pr_bx1[p] - 1 - lx0) / TILE) do - if flat_rect then - local tx0, ty0 = tx * TILE, ty * TILE - local ix0, iy0 = max(cx0 - tx0, 0), max(cy0 - ty0, 0) - local ix1, iy1 = min(cx1 - tx0, TILE), min(cy1 - ty0, TILE) - local r = ((ix0 * 131 + iy0) * 131 + ix1) * 131 + iy1 - h1 = ((r * 48271 + rcol) % P1 * 48271 + ruv * 4096 + 7) % P1 - h2 = ((r * 16807 + rcol + tex_id) % P2 * 16807 + ruv * 65521 + 11) % P2 - end - local key = ty * KEY_W + tx - local k = tn[key] - if not k or k == 0 then - k = 0 - th1[key], th2[key] = 0, 0 - if not tl[key] then tl[key] = {}; tl1[key] = {}; tl2[key] = {}; tlf[key] = {} end - nt = nt + 1 - touched[nt] = key - layer.TX[key], layer.TY[key] = tx, ty - end - k = k + 1 - tn[key] = k - tl[key][k] = p - tl1[key][k], tl2[key][k], tlf[key][k] = h1, h2, fsig - th1[key] = (th1[key] * 48271 + h1) % P1 - th2[key] = (th2[key] * 16807 + h2 + k) % P2 - end - end - end - layer.NTouched = nt - PE() - - -- Place the layer (this is all a window move costs) - local root = layer.Root - if root ~= layer.Frame then - -- content: clip frame at the content clip rect, tiles frame at the scroll origin relative to it - if layer.CX0 ~= clip_x0 or layer.CY0 ~= clip_y0 or layer.CX1 ~= clip_x1 or layer.CY1 ~= clip_y1 then - layer.CX0, layer.CY0, layer.CX1, layer.CY1 = clip_x0, clip_y0, clip_x1, clip_y1 - root.Position = UDim2.fromOffset(clip_x0 / scale, clip_y0 / scale) - root.Size = UDim2.fromOffset((clip_x1 - clip_x0) / scale, (clip_y1 - clip_y0) / scale) - layer.X = false - end - if layer.X ~= lx0 or layer.Y ~= ly0 then - layer.X, layer.Y = lx0, ly0 - layer.Frame.Position = UDim2.fromOffset((lx0 - clip_x0) / scale, (ly0 - clip_y0) / scale) - end - elseif layer.X ~= lx0 or layer.Y ~= ly0 then - layer.X, layer.Y = lx0, ly0 - root.Position = UDim2.fromOffset(lx0 / scale, ly0 / scale) - end - if layer.Z ~= z then layer.Z = z; root.ZIndex = z end - if not layer.Visible then layer.Visible = true; root.Visible = true end - - -- Pass 3: redraw + upload changed tiles, hide unused ones - PB("ImGui raster+upload") - for key, tile in pairs(layer.Tiles) do - if not tn[key] or tn[key] == 0 then - if tile.Visible then tile.Visible = false; tile.Label.Visible = false; tile.H1 = -1; tile.ON = -1 end - end - end - for kk = 1, nt do - local key = touched[kk] - local count = tn[key] - local tx, ty = layer.TX[key], layer.TY[key] - local tile = GetTile(bd, layer, key, tx, ty) - local dirty = force or tile.H1 ~= th1[key] or tile.H2 ~= th2[key] - if dirty and bd.RedrawStarted and (tile.Deferred or 0) < MAX_DEFER_FRAMES - and ((bd.RedrawBudget > 0 and os.clock() - bd.FrameT0 >= bd.RedrawBudget) or (bd.TileLimit and bd.FrameTiles >= bd.TileLimit)) then -- (TileLimit: test hook, tools/test/scripts/t_pixels.luau) - -- Over this frame's redraw budget: keep showing the old pixels, redraw on a following frame. The tile's - -- stored hashes/list still describe what it shows, so the next comparison is against the real content. - tile.Deferred = (tile.Deferred or 0) + 1 - if force then tile.H1 = -1; tile.ON = -1 end -- full redraw later (force doesn't persist) - deferred = true - dirty = false - end - if dirty then - bd.RedrawStarted = true - bd.FrameTiles += 1 - tile.Deferred = 0 - tile.H1, tile.H2 = th1[key], th2[key] - local x0, y0 = lx0 + tx * TILE, ly0 + ty * TILE - local x1, y1 = x0 + TILE, y0 + TILE - buf, buf_w = tile.Buffer, TILE - local list, lh1, lh2 = tl[key], tl1[key], tl2[key] - local oh1, oh2, ob0, ob1, ob2, ob3, on = tile.OH1, tile.OH2, tile.OB0, tile.OB1, tile.OB2, tile.OB3, tile.ON - -- New content bounds (union of the primitives' bounds in this tile) - local nx0, ny0, nx1, ny1 = TILE, TILE, 0, 0 - for k = 1, count do - local p = list[k] - local a, b = pr_bx0[p] - x0, pr_by0[p] - y0 - local c, d = pr_bx1[p] - x0, pr_by1[p] - y0 - if a < nx0 then nx0 = a end - if b < ny0 then ny0 = b end - if c > nx1 then nx1 = c end - if d > ny1 then ny1 = d end - end - nx0, ny0, nx1, ny1 = max(nx0, 0), max(ny0, 0), min(nx1, TILE), min(ny1, TILE) - local rx0, ry0, rx1, ry1 - if force or on < 0 then - -- Dirty region = old content bounds + new content bounds. Outside it the tile is already - -- transparent, so only this region is cleared and uploaded (edge tiles are often mostly empty). - rx0, ry0, rx1, ry1 = min(nx0, tile.BX0), min(ny0, tile.BY0), max(nx1, tile.BX1), max(ny1, tile.BY1) - else - -- Partial redraw: the primitives before the first and after the last changed one are the same as last - -- time. A pixel that no changed primitive (old or new) touches is covered by the same primitives in the - -- same order, so it is already correct: only the bounds of the changed ones are cleared and redrawn. - local i, lim = 1, min(on, count) - while i <= lim and oh1[i] == lh1[i] and oh2[i] == lh2[i] do i += 1 end - local j = 0 - while j <= lim - i and oh1[on - j] == lh1[count - j] and oh2[on - j] == lh2[count - j] do j += 1 end - rx0, ry0, rx1, ry1 = TILE, TILE, 0, 0 - local of, lf = tile.OF, tlf[key] - local paired = on - j - i == count - j - i - for k = i, count - j do - local p = list[k] - local a, b, c, d = max(pr_bx0[p] - x0, 0), max(pr_by0[p] - y0, 0), min(pr_bx1[p] - x0, TILE), min(pr_by1[p] - y0, TILE) - local oa, ob, oc, od = ob0[k], ob1[k], ob2[k], ob3[k] - if paired and lf[k] >= 0 and lf[k] == of[k] then - -- Same flat rect (colour/uv/texture) with new bounds: pixels inside both are unchanged, only the - -- strips between the old and new edges can differ (e.g. a window background growing on resize) - local uy0, uy1 = min(b, ob), max(d, od) - local ux0, ux1 = min(a, oa), max(c, oc) - if a ~= oa then ux0 = min(a, oa); local e = max(a, oa); rx0 = min(rx0, ux0); rx1 = max(rx1, e); ry0 = min(ry0, uy0); ry1 = max(ry1, uy1) end - if c ~= oc then local e = min(c, oc); rx0 = min(rx0, e); rx1 = max(rx1, max(c, oc)); ry0 = min(ry0, uy0); ry1 = max(ry1, uy1) end - if b ~= ob then ry0 = min(ry0, min(b, ob)); ry1 = max(ry1, max(b, ob)); rx0 = min(rx0, ux0); rx1 = max(rx1, ux1) end - if d ~= od then ry0 = min(ry0, min(d, od)); ry1 = max(ry1, max(d, od)); rx0 = min(rx0, ux0); rx1 = max(rx1, ux1) end - else - if a < rx0 then rx0 = a end - if b < ry0 then ry0 = b end - if c > rx1 then rx1 = c end - if d > ry1 then ry1 = d end - if k <= on - j then - if oa < rx0 then rx0 = oa end - if ob < ry0 then ry0 = ob end - if oc > rx1 then rx1 = oc end - if od > ry1 then ry1 = od end - end - end - end - for k = count - j + 1, on - j do -- old middle longer than the new one - if ob0[k] < rx0 then rx0 = ob0[k] end - if ob1[k] < ry0 then ry0 = ob1[k] end - if ob2[k] > rx1 then rx1 = ob2[k] end - if ob3[k] > ry1 then ry1 = ob3[k] end - end - end - tile.BX0, tile.BY0, tile.BX1, tile.BY1 = nx0, ny0, nx1, ny1 - -- Remember this list for the next partial redraw - for k = 1, count do - local p = list[k] - oh1[k], oh2[k], tile.OF[k] = lh1[k], lh2[k], tlf[key][k] - ob0[k], ob1[k], ob2[k], ob3[k] = max(pr_bx0[p] - x0, 0), max(pr_by0[p] - y0, 0), min(pr_bx1[p] - x0, TILE), min(pr_by1[p] - y0, TILE) - end - tile.ON = count - local rw = rx1 - rx0 - if rw == TILE then - buffer.fill(buf, ry0 * TILE * 4, 0, (ry1 - ry0) * TILE * 4) - else - for y = ry0, ry1 - 1 do buffer.fill(buf, (y * TILE + rx0) * 4, 0, rw * 4) end - end - local tox, toy = ox + x0, oy + y0 - for k = 1, count do - local p = list[k] - -- clip to the dirty region (only those pixels are redrawn) - local cx0, cy0 = max(pr_cx0[p] - x0, rx0), max(pr_cy0[p] - y0, ry0) - local cx1, cy1 = min(pr_cx1[p] - x0, rx1), min(pr_cy1[p] - y0, ry1) - if cx0 >= cx1 or cy0 >= cy1 or pr_bx0[p] - x0 >= rx1 or pr_by0[p] - y0 >= ry1 or pr_bx1[p] - x0 <= rx0 or pr_by1[p] - y0 <= ry0 then continue end - local va, vc, vd, vbuf = pr_a[p], pr_c[p], pr_d[p], pr_vb[p] - if vd then - local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox, readf64(vbuf, vc + 8) - toy - local gk = pr_g[p] - if gk then - DrawRectGradient(ax, ay, cx, cy, readu32(vbuf, va + 32), readu32(vbuf, vc + 32), gk, pr_t[p], readf64(vbuf, va + 16), readf64(vbuf, va + 24), cx0, cy0, cx1, cy1) - else - DrawRect(ax, ay, cx, cy, readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24), readu32(vbuf, va + 32), pr_t[p], cx0, cy0, cx1, cy1) - end - else - DrawTriangle(vbuf, va, pr_b[p], vc, pr_t[p], cx0, cy0, cx1, cy1, tox, toy) - end - end - PB("ImGui upload") - if rw == TILE and ry0 == 0 and ry1 == TILE then - tile.Image:WritePixelsBuffer(Vector2.zero, TILE_SIZE, buf) - elseif rw > 0 and ry1 > ry0 then - local rh = ry1 - ry0 - local sk = rw * 1024 + rh -- partial upload buffers are reused (WritePixelsBuffer needs the exact size) - local sub = sub_bufs[sk] - if not sub then - if n_sub_bufs >= 256 then table.clear(sub_bufs); n_sub_bufs = 0 end - sub = buffer.create(rw * rh * 4); sub_bufs[sk] = sub; n_sub_bufs += 1 - end - for y = 0, rh - 1 do buffer.copy(sub, y * rw * 4, buf, ((ry0 + y) * TILE + rx0) * 4, rw * 4) end - tile.Image:WritePixelsBuffer(Vector2.new(rx0, ry0), Vector2.new(rw, rh), sub) - end - PE() - end - if not tile.Visible and (tile.Deferred or 0) == 0 then -- (a deferred tile that was hidden holds old pixels: stays hidden until drawn) - tile.Visible = true - tile.Label.Visible = true - end - end - PE() - return deferred -end - -@native -function ImGui_ImplRoblox_RenderDrawData(draw_data) - local bd = ImGui_ImplRoblox_GetBackendData() - PB("ImGui RenderDrawData") - bd.FrameT0 = os.clock() - bd.FrameTiles = 0 - bd.RedrawStarted = false -- the first dirty tile of a frame is always redrawn (progress), the rest within the budget - bd.Stale = nil - - PB("ImGui textures") - if draw_data.Textures ~= nil then - for _, tex in draw_data.Textures:iter() do - if tex.Status ~= 0 --[[ImTextureStatus.OK]] then - -- No redraw needed for WantUpdates: it only writes texture portions which have never been used before - -- (new glyphs/rects), so no existing tile samples them. Created textures get a new (never reused) id. - ImGui_ImplRoblox_UpdateTexture(tex) - end - end - end - PE() - - -- Render rate cap: textures are always updated (imgui expects it), tiles only at bd.RenderRate Hz - -- Optional lower cap while scrolling / resizing / moving a window (SetBusyRenderRate, off by default) - local rate = bd.RenderRate - if bd.BusyRenderRate > 0 then - local g = ImGui.GetCurrentContext() - local busy = g.WheelingWindow ~= nil or g.MovingWindow ~= nil -- (io.MouseWheel is already cleared by EndFrame) - if not busy and g.ActiveId ~= 0 then - local w = g.ActiveIdWindow - local cur = g.MouseCursor -- ResizeAll..ResizeNWSE while a resize grip/border is held - busy = (cur >= 2 --[[ImGuiMouseCursor.ResizeAll]] and cur <= 6 --[[ImGuiMouseCursor.ResizeNWSE]]) - or (w ~= nil and (g.ActiveId == ImGui.GetWindowScrollbarID(w, 1 --[[ImGuiAxis.X]]) or g.ActiveId == ImGui.GetWindowScrollbarID(w, 2 --[[ImGuiAxis.Y]]))) - end - if busy and (rate <= 0 or bd.BusyRenderRate < rate) then rate = bd.BusyRenderRate end - end - if rate > 0 then - local now = os.clock() - -- Skipped: kept pending, so if no new frame comes (the app stopped rendering) Heartbeat still draws it - if now + 0.002 < bd.NextRender then bd.Pending = draw_data; PE(); return end - bd.NextRender = math.max(bd.NextRender + 1 / rate, now) - end - - local sw, sh = floor(draw_data.DisplaySize.x), floor(draw_data.DisplaySize.y) - if sw <= 0 or sh <= 0 then PE(); return end - local ox, oy = draw_data.DisplayPos.x, draw_data.DisplayPos.y - local lim_x0, lim_y0, lim_x1, lim_y1 = -CLIP_PAD, -CLIP_PAD, sw + CLIP_PAD, sh + CLIP_PAD - bd.FrameNo += 1 - local frame_no = bd.FrameNo - local force = bd.ForceRedraw - bd.ForceRedraw = false - - local n = 0 - local z = 0 - local any_deferred = false - for _, draw_list in draw_data.CmdLists:iter() do - -- Unchanged draw list (same vertices, indices, commands, origin and scroll): its layers are already correct, - -- only restack them. Moved by whole pixels (a dragged window): only move its layers. Either way no collect + hash. - PB("ImGui unchanged check") - local set = bd.Layers[draw_list] - local same, sdx, sdy = 0, 0, 0 - if not force then same, sdx, sdy = CompareDrawList(set, draw_list, ox, oy, sw, sh) end - if same ~= 0 then - for kind = 1, 3 do - local layer = set[kind] - if layer and layer.Visible then - if same == 2 then ShiftLayer(layer, sdx, sdy, bd.Scale) end - z += 1 - if layer.Z ~= z then layer.Z = z; layer.Root.ZIndex = z end - end - end - if same == 2 then - Snapshot(set, draw_list, ox, oy, sw, sh) - set.SEX0 += sdx; set.SEY0 += sdy; set.SEX1 += sdx; set.SEY1 += sdy - end - set.LastUsed = frame_no - z = PlaceOverlays(bd, draw_list, z, ox, oy) - PE() - continue - end - PE() - -- Pass 1: collect this list's primitives and their bounds - PB("ImGui collect") - local first = n + 1 - local vbuf, idx = draw_list.VtxBuffer.Buf, draw_list.IdxBuffer.Data - local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1, draw_list._ContentClipY1 - local content_x0, content_y0, content_x1, content_y1 - if ccx0 then - content_x0, content_y0 = max(floor(ccx0 - ox), lim_x0), max(floor(ccy0 - oy), lim_y0) - content_x1, content_y1 = min(floor(ccx1 - ox), lim_x1), min(floor(ccy1 - oy), lim_y1) - end - local seen_content = false - -- extents of everything clamped by the clip limits below (lim_free: nothing was), for the move fast path - local ex0, ey0, ex1, ey1 = math.huge, math.huge, -math.huge, -math.huge - local lim_free = true - if ccx0 then - local a, b, c, d = floor(ccx0 - ox), floor(ccy0 - oy), floor(ccx1 - ox), floor(ccy1 - oy) - if a < lim_x0 or b < lim_y0 or c > lim_x1 or d > lim_y1 then lim_free = false end - ex0, ey0, ex1, ey1 = min(ex0, a), min(ey0, b), max(ex1, c), max(ey1, d) - end - local ci = 0 - for _, pcmd in draw_list.CmdBuffer:iter() do - ci += 1 - cm_free[ci], cm_kind[ci] = false, 0 - if pcmd.UserCallback ~= nil then - pcmd.UserCallback(draw_list, pcmd) - elseif pcmd.ElemCount > 0 then - local clip = pcmd.ClipRect - local rcx0, rcy0, rcx1, rcy1 = floor(clip.x - ox), floor(clip.y - oy), floor(clip.z - ox), floor(clip.w - oy) - if rcx0 < lim_x0 or rcy0 < lim_y0 or rcx1 > lim_x1 or rcy1 > lim_y1 then lim_free = false end - if rcx0 < ex0 then ex0 = rcx0 end - if rcy0 < ey0 then ey0 = rcy0 end - if rcx1 > ex1 then ex1 = rcx1 end - if rcy1 > ey1 then ey1 = rcy1 end - local cx0, cy0 = max(rcx0, lim_x0), max(rcy0, lim_y0) - local cx1, cy1 = min(rcx1, lim_x1), min(rcy1, lim_y1) - local kind = 1 - if ccx0 and clip.x >= ccx0 and clip.y >= ccy0 and clip.z <= ccx1 and clip.w <= ccy1 then - kind = 2; seen_content = true - if clip.x == ccx0 and clip.y == ccy0 and clip.z == ccx1 and clip.w == ccy1 then - -- clipped by the layer's clip frame instead: partly visible rows stay hash-stable while scrolling - cx0, cy0, cx1, cy1 = lim_x0, lim_y0, lim_x1, lim_y1 - end - elseif seen_content then - kind = 3 - end - cm_kind[ci] = kind - local cfree, cex0, cey0, cex1, cey1 = cx1 > cx0 and cy1 > cy0, math.huge, math.huge, -math.huge, -math.huge - if cx1 > cx0 and cy1 > cy0 then - local tex_id = pcmd:GetTexID() - local t = bd.Textures[tex_id] - local vo = pcmd.VtxOffset - local i, last = pcmd.IdxOffset + 1, pcmd.IdxOffset + pcmd.ElemCount - while i <= last do - local ia, ic = idx[i], idx[i + 2] - -- byte offsets of the vertices (index is 1-based) - local va, vb, vc = (vo + ia - 1) * 36 --[[VTX_STRIDE]], (vo + idx[i + 1] - 1) * 36 --[[VTX_STRIDE]], (vo + ic - 1) * 36 --[[VTX_STRIDE]] - local vd = false - local gk = false - local pax, pay = readf64(vbuf, va), readf64(vbuf, va + 8) - local pbx, pby = readf64(vbuf, vb), readf64(vbuf, vb + 8) - local pcx, pcy = readf64(vbuf, vc), readf64(vbuf, vc + 8) - local bx0, by0, bx1, by1 - if i + 5 <= last and idx[i + 3] == ia and idx[i + 4] == ic then - local d = (vo + idx[i + 5] - 1) * 36 --[[VTX_STRIDE]] - local pdx, pdy = readf64(vbuf, d), readf64(vbuf, d + 8) - -- axis aligned quad (TL, TR, BR, BL) - if pay == pby and pbx == pcx and pcy == pdy and pdx == pax and pax < pbx and pay < pdy then - local col, colb, colc, cold = readu32(vbuf, va + 32), readu32(vbuf, vb + 32), readu32(vbuf, vc + 32), readu32(vbuf, d + 32) - local tax, tay = readf64(vbuf, va + 16), readf64(vbuf, va + 24) - local tbx, tby = readf64(vbuf, vb + 16), readf64(vbuf, vb + 24) - local tcx, tcy = readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) - local tdx, tdy = readf64(vbuf, d + 16), readf64(vbuf, d + 24) - if colb == col and colc == col and cold == col then - if tbx == tcx and tby == tay and tdx == tax and tdy == tcy then vd = d end - elseif tax == tbx and tax == tcx and tax == tdx and tay == tby and tay == tcy and tay == tdy then - -- constant uv, linear gradient: vertical (top/bottom pairs equal) or horizontal (left/right pairs equal) - if colb == col and cold == colc then vd = d; gk = 1 - elseif cold == col and colb == colc then vd = d; gk = 2 end - end - if vd then - bx0, by0 = ceil(pax - ox - 0.5), ceil(pay - oy - 0.5) - bx1, by1 = ceil(pcx - ox - 0.5), ceil(pcy - oy - 0.5) - end - end - end - if vd then - i = i + 6 - else - bx0, by0 = floor(min(pax, pbx, pcx) - ox), floor(min(pay, pby, pcy) - oy) - bx1, by1 = ceil(max(pax, pbx, pcx) - ox) + 1, ceil(max(pay, pby, pcy) - oy) + 1 - i = i + 3 - end - if bx0 < cx0 or by0 < cy0 or bx1 > cx1 or by1 > cy1 then cfree = false end - if bx0 < cex0 then cex0 = bx0 end - if by0 < cey0 then cey0 = by0 end - if bx1 > cex1 then cex1 = bx1 end - if by1 > cey1 then cey1 = by1 end - if bx0 < ex0 then ex0 = bx0 end - if by0 < ey0 then ey0 = by0 end - if bx1 > ex1 then ex1 = bx1 end - if by1 > ey1 then ey1 = by1 end - if bx0 < lim_x0 or by0 < lim_y0 or bx1 > lim_x1 or by1 > lim_y1 then lim_free = false end - if bx0 < cx0 then bx0 = cx0 end - if by0 < cy0 then by0 = cy0 end - if bx1 > cx1 then bx1 = cx1 end - if by1 > cy1 then by1 = cy1 end - if bx0 < bx1 and by0 < by1 then - n = n + 1 - pr_a[n], pr_b[n], pr_c[n], pr_d[n], pr_t[n], pr_g[n], pr_tex[n], pr_vb[n] = va, vb, vc, vd, t, gk, tex_id, vbuf - pr_cx0[n], pr_cy0[n], pr_cx1[n], pr_cy1[n] = cx0, cy0, cx1, cy1 - pr_bx0[n], pr_by0[n], pr_bx1[n], pr_by1[n] = bx0, by0, bx1, by1 - pr_k[n] = kind - end - end - end - if cex0 > cex1 then cex0, cey0, cex1, cey1 = 0, 0, 0, 0 end -- (no primitives) - cm_free[ci] = cfree - cm_x0[ci], cm_y0[ci], cm_x1[ci], cm_y1[ci] = cex0, cey0, cex1, cey1 - end - end - PE() - - -- Split into layer kinds and place each one - set = bd.Layers[draw_list] - local list_deferred = false - local nk1, nk2, nk3 = 0, 0, 0 - local o1x, o1y, o3x, o3y = math.huge, math.huge, math.huge, math.huge - for p = first, n do - local k = pr_k[p] - if k == 1 then - nk1 += 1; plist1[nk1] = p - if pr_bx0[p] < o1x then o1x = pr_bx0[p] end - if pr_by0[p] < o1y then o1y = pr_by0[p] end - elseif k == 2 then - nk2 += 1; plist2[nk2] = p - else - nk3 += 1; plist3[nk3] = p - if pr_bx0[p] < o3x then o3x = pr_bx0[p] end - if pr_by0[p] < o3y then o3y = pr_by0[p] end - end - end - if nk1 > 0 then - z += 1 - if DrawLayer(bd, GetLayer(bd, draw_list, 1), plist1, nk1, o1x, o1y, ox, oy, force, z) then list_deferred = true end - elseif set and set[1] then HideLayer(set[1]) end - if nk2 > 0 then - z += 1 - if DrawLayer(bd, GetLayer(bd, draw_list, 2), plist2, nk2, floor(draw_list._ScrollOriginX - ox), floor(draw_list._ScrollOriginY - oy), ox, oy, force, z, - content_x0, content_y0, content_x1, content_y1) then list_deferred = true end - elseif set and set[2] then HideLayer(set[2]) end - if nk3 > 0 then - z += 1 - if DrawLayer(bd, GetLayer(bd, draw_list, 3), plist3, nk3, o3x, o3y, ox, oy, force, z) then list_deferred = true end - elseif set and set[3] then HideLayer(set[3]) end - set = bd.Layers[draw_list] - -- (deferred tiles: not "unchanged" next frame even if the draw list is, so they get redrawn) - if set then - set.LastUsed = frame_no - if list_deferred then set.SnapOK = false else - Snapshot(set, draw_list, ox, oy, sw, sh) - set.SLimFree = lim_free - set.SEX0, set.SEY0, set.SEX1, set.SEY1 = ex0, ey0, ex1, ey1 - end - end - if list_deferred then any_deferred = true end - z = PlaceOverlays(bd, draw_list, z, ox, oy) - end - - -- Overlay frames not submitted this frame are hidden (never destroyed: the user owns them) - for frame, shown in pairs(bd.OverlayShown) do - if shown ~= frame_no then frame.Visible = false; bd.OverlayShown[frame] = nil end - end - table.clear(bd.Overlays) - - -- Hide layers not drawn this frame; free long unused ones (closed windows, old tooltips) - for draw_list, set in pairs(bd.Layers) do - if set.LastUsed ~= frame_no then - set.SnapOK = false -- hidden now: must go through the full path when shown again - for kind = 1, 3 do if set[kind] then HideLayer(set[kind]) end end - if frame_no - set.LastUsed > LAYER_KEEP_FRAMES then - DestroyLayerSet(set) - bd.Layers[draw_list] = nil - end - end - end - - -- drop references so old vertex tables can be collected - for k = n + 1, bd.LastPrimCount do pr_t[k], pr_vb[k] = nil, nil end - bd.LastPrimCount = n - -- Tiles left for later: if the app doesn't submit a new frame, Heartbeat finishes them from this draw data - if any_deferred then bd.Stale = draw_data; bd.StaleHB = bd.HB end - PE() -end - ---------------------------------------------------------- --- CORE LIFECYCLE ---------------------------------------------------------- - ---- @param parent Instance? # where the ScreenGui goes, defaults to the local player's PlayerGui ---- @param render_scale number? # imgui pixels per Roblox UI point (defaults to 1). Roblox UI points are scaled by the ---- # OS display scale, so on a 150% display pass 1.5 to render at physical resolution ---- # (imgui then looks the same size as a desktop imgui app). Change later with SetRenderScale(). +-- render_scale: imgui pixels per Roblox UI point (default 1; 1.5 on a 150% display = physical resolution) function ImGui_ImplRoblox_Init(parent, render_scale) local io = ImGui.GetIO() @@ -47206,16 +48268,20 @@ function ImGui_ImplRoblox_Init(parent, render_scale) gui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling -- layers (one Frame per draw list) stack by ZIndex gui.Parent = parent or Players.LocalPlayer:WaitForChild("PlayerGui") - local bd = { + local BackendData = { Time = os.clock(), Gui = gui, Connections = {}, - Textures = {}, TextureCount = 0, MouseX = -1, MouseY = -1, - Layers = {}, Overlays = {}, OverlayHolders = {}, OverlayShown = {}, FrameNo = 0, Scale = render_scale or 1, TilesActive = false, RenderRate = 60, BusyRenderRate = 0, RedrawBudget = 0, HB = 0, NextRender = 0, LastPrimCount = 0, ForceRedraw = true, + Textures = Textures.Records, MouseX = -1, MouseY = -1, + Layers = {}, Overlays = {}, OverlayHolders = {}, OverlayShown = {}, FrameNo = 0, Scale = render_scale or 1, + TilesActive = false, RenderRate = 60, BusyRenderRate = 0, RedrawBudget = 0, HeartbeatCount = 0, + NextRender = 0, LastPrimCount = 0, ForceRedraw = true, } - io.BackendPlatformUserData = bd + io.BackendPlatformUserData = BackendData + EditableImages.Backends[BackendData] = true io.BackendPlatformName = "imgui_impl_roblox" io.BackendRendererName = "imgui_impl_roblox" - io.BackendFlags = bit32.bor(io.BackendFlags, 16 --[[ImGuiBackendFlags.RendererHasTextures]], 8 --[[ImGuiBackendFlags.RendererHasVtxOffset]]) + io.BackendFlags = bit32.bor(io.BackendFlags, 16 --[[ImGuiBackendFlags.RendererHasTextures]], + 8 --[[ImGuiBackendFlags.RendererHasVtxOffset]]) local platform_io = ImGui.GetPlatformIO() platform_io.Platform_SetClipboardTextFn = ImGui_ImplRoblox_PlatformSetClipboardText @@ -47224,7 +48290,7 @@ function ImGui_ImplRoblox_Init(parent, render_scale) local screen = gui.AbsoluteSize ImGui_ImplRoblox_UpdateMonitors(screen.X, screen.Y) - local function connect(signal, fn) table.insert(bd.Connections, signal:Connect(fn)) end + local function connect(signal, fn) table.insert(BackendData.Connections, signal:Connect(fn)) end connect(UserInputService.InputBegan, function(input, game_processed) local io = ImGui.GetIO() @@ -47232,20 +48298,20 @@ function ImGui_ImplRoblox_Init(parent, render_scale) if button then io:AddMouseSourceEvent(0 --[[ImGuiMouseSource.Mouse]]) io:AddMouseButtonEvent(button, true) - elseif input.UserInputType == Enum.UserInputType.Keyboard and (not game_processed or proxy_focused) then + elseif input.UserInputType == Enum.UserInputType.Keyboard and (not game_processed or ProxyFocused) then local ctrl, shift, alt = ImGui_ImplRoblox_UpdateKeyModifiers() local key = KEY_MAP[input.KeyCode] if key then io:AddKeyEvent(key, true) end - if proxy_focused and (key == 523 --[[ImGuiKey.Backspace]] or key == 522 --[[ImGuiKey.Delete]]) then ImGui_ImplRoblox_GetBackendData().DeleteKeySeen = true end + if ProxyFocused and (key == 523 --[[ImGuiKey.Backspace]] or key == 522 --[[ImGuiKey.Delete]]) then + ImGui_ImplRoblox_GetBackendData().DeleteKeySeen = true + end - -- Text: printable ASCII keys, skipped while Ctrl/Alt are held (shortcuts) local v = input.KeyCode.Value if v >= 32 and v < 127 and not (ctrl or alt) then local c = string.char(v) if shift then c = SHIFTED[c] or c:upper() end - -- While the proxy may own text input, hold the char: NewFrame uses the proxy's text if it changed - -- (correct layout/unicode), otherwise these. So typing works even if the proxy silently lost focus. - if proxy_focused then table.insert(ImGui_ImplRoblox_GetBackendData().PendingChars, string.byte(c)) + -- while the proxy may own input, hold the char: NewFrame types it only if the proxy didn't deliver text + if ProxyFocused then table.insert(ImGui_ImplRoblox_GetBackendData().PendingChars, string.byte(c)) else io:AddInputCharacter(string.byte(c)) end end end @@ -47269,36 +48335,36 @@ function ImGui_ImplRoblox_Init(parent, render_scale) end end) - bd.PendingChars = {} + BackendData.PendingChars = {} - -- Render rate cap trailing edge: the last frame submitted is always drawn, even if it was skipped and the app - -- then stopped calling NewFrame (e.g. it rendered one empty frame to hide its windows) + -- Render rate cap trailing edge: the last frame submitted is always drawn, even if the app then stopped rendering connect(game:GetService("RunService").Heartbeat, function() - local d = bd.Pending - if d and os.clock() + 0.002 >= bd.NextRender then - bd.Pending = nil + local d = BackendData.Pending + if d and os.clock() + 0.002 >= BackendData.NextRender then + BackendData.Pending = nil ImGui_ImplRoblox_RenderDrawData(d) - elseif bd.Stale and bd.HB > bd.StaleHB then -- deferred tiles of a frame not followed by a new one - ImGui_ImplRoblox_RenderDrawData(bd.Stale) + elseif BackendData.Stale and BackendData.HeartbeatCount > BackendData.StaleHeartbeat then + ImGui_ImplRoblox_RenderDrawData(BackendData.Stale) end - bd.HB += 1 + BackendData.HeartbeatCount += 1 end) connect(UserInputService.WindowFocused, function() ImGui.GetIO():AddFocusEvent(true) end) connect(UserInputService.WindowFocusReleased, function() ImGui.GetIO():AddFocusEvent(false) end) end --- Text proxy (opt-in, ImGui_ImplRoblox.SetTextProxy(true)): a hidden TextBox holds focus while an imgui text field is --- active, so the OS gives us typing (any layout/unicode), paste (Ctrl+V) and copy/cut (Ctrl+C/X of imgui's selection). --- Off: typing comes from KeyCodes (printable ASCII), no OS clipboard. +-- Text proxy (opt-in): a hidden TextBox holds focus while a text field is active (OS typing, paste, copy/cut) function ImGui_ImplRoblox_SetTextProxy(enabled) - local bd = ImGui_ImplRoblox_GetBackendData() + local BackendData = ImGui_ImplRoblox_GetBackendData() if not enabled then - if bd.Proxy then bd.Proxy:Destroy(); bd.Proxy = nil end - proxy_focused = false + if BackendData.Proxy then + BackendData.Proxy:Destroy() + BackendData.Proxy = nil + end + ProxyFocused = false return end - if bd.Proxy then return end + if BackendData.Proxy then return end local proxy = Instance.new("TextBox") proxy.Name = "TextProxy" proxy.BackgroundTransparency = 1 @@ -47310,27 +48376,29 @@ function ImGui_ImplRoblox_SetTextProxy(enabled) proxy.ClearTextOnFocus = false proxy.TextEditable = true proxy.Text = "" - proxy.Parent = bd.Gui - bd.Proxy, bd.ProxyText = proxy, "" - -- Clicking elsewhere (or Roblox taking focus) ends the edit, like clicking outside the field in imgui. - -- (Text is polled in NewFrame instead of using Text changed signals: those are deferred in Roblox.) + proxy.Parent = BackendData.Gui + BackendData.Proxy, BackendData.ProxyText = proxy, "" + -- Text is polled in NewFrame: TextBox change signals are deferred in Roblox proxy.FocusLost:Connect(function() - if bd.ProxyReleasing then return end - -- Roblox drops TextBox focus on any click, including clicks inside imgui (e.g. moving the cursor within the - -- same field). Those must not end the edit: just recapture next frame. Only a click outside imgui ends it. - if ImGui.GetIO().WantCaptureMouse then bd.ProxyLostId = nil; return end - bd.ProxyLostId = bd.ProxyActiveId -- don't recapture for the same field + if BackendData.ProxyReleasing then return end + -- Roblox drops TextBox focus on any click, also inside imgui: only a click outside imgui ends the edit + if ImGui.GetIO().WantCaptureMouse then + BackendData.ProxyLostId = nil + return + end + BackendData.ProxyLostId = BackendData.ProxyActiveId local g = ImGui.GetCurrentContext() - if g and g.ActiveId ~= 0 and g.ActiveId == bd.ProxyActiveId then ImGui.ClearActiveID() end + if g and g.ActiveId ~= 0 and g.ActiveId == BackendData.ProxyActiveId then ImGui.ClearActiveID() end end) end -function ImGui_ImplRoblox_Shutdown() +local function ImGui_ImplRoblox_Shutdown() local io = ImGui.GetIO() - local bd = ImGui_ImplRoblox_GetBackendData() - for _, c in ipairs(bd.Connections) do c:Disconnect() end - DestroyTiles(bd) - bd.Gui:Destroy() + local BackendData = ImGui_ImplRoblox_GetBackendData() + for _, c in ipairs(BackendData.Connections) do c:Disconnect() end + DestroyTiles(BackendData) + EditableImages.Backends[BackendData] = nil + BackendData.Gui:Destroy() io.BackendPlatformUserData = nil io.BackendPlatformName = nil @@ -47341,72 +48409,78 @@ function ImGui_ImplRoblox_Shutdown() ))) end + function ImGui_ImplRoblox_NewFrame() PB("ImGui NewFrame (backend)") local io = ImGui.GetIO() - local bd = ImGui_ImplRoblox_GetBackendData() - if bd.Pending then bd.Pending = nil; table.clear(bd.Overlays) end -- skipped frame superseded (its draw lists get reset) - bd.Stale = nil + local BackendData = ImGui_ImplRoblox_GetBackendData() + if BackendData.Pending then -- skipped frame superseded (its draw lists get reset) + BackendData.Pending = nil + table.clear(BackendData.Overlays) + end + BackendData.Stale = nil - local screen = bd.Gui.AbsoluteSize - local w, h = floor(screen.X * bd.Scale), floor(screen.Y * bd.Scale) - if w ~= bd.ScreenW or h ~= bd.ScreenH then - bd.ScreenW, bd.ScreenH = w, h + local screen = BackendData.Gui.AbsoluteSize + local w, h = floor(screen.X * BackendData.Scale), floor(screen.Y * BackendData.Scale) + if w ~= BackendData.ScreenW or h ~= BackendData.ScreenH then + BackendData.ScreenW, BackendData.ScreenH = w, h ImGui_ImplRoblox_UpdateMonitors(w, h) end ImVec2_CopyV(io.DisplaySize, w, h) local current_time = os.clock() - io.DeltaTime = (current_time > bd.Time) and (current_time - bd.Time) or (1.0 / 60.0) - bd.Time = current_time + io.DeltaTime = (current_time > BackendData.Time) and (current_time - BackendData.Time) or (1.0 / 60.0) + BackendData.Time = current_time local m = UserInputService:GetMouseLocation() - if m.X ~= bd.MouseX or m.Y ~= bd.MouseY then - bd.MouseX, bd.MouseY = m.X, m.Y + if m.X ~= BackendData.MouseX or m.Y ~= BackendData.MouseY then + BackendData.MouseX, BackendData.MouseY = m.X, m.Y io:AddMouseSourceEvent(0 --[[ImGuiMouseSource.Mouse]]) - io:AddMousePosEvent(m.X * bd.Scale, m.Y * bd.Scale) + io:AddMousePosEvent(m.X * BackendData.Scale, m.Y * BackendData.Scale) end - -- Text proxy: focused while an imgui text field is active. proxy_focused only when Roblox really gave it focus, - -- otherwise the KeyCode fallback keeps typing working. - local proxy = bd.Proxy + local proxy = BackendData.Proxy local g = ImGui.GetCurrentContext() local focused_box = proxy and UserInputService:GetFocusedTextBox() if not proxy then - -- text proxy disabled: KeyCode typing only elseif io.WantTextInput and g.ActiveId ~= 0 then - if g.ActiveId ~= bd.ProxyActiveId or g.ActiveIdIsJustActivated or g.IO.MouseClicked[0] then bd.ProxyActiveId = g.ActiveId; bd.ProxyLostId = nil end -- (re)clicking a field recaptures + if g.ActiveId ~= BackendData.ProxyActiveId or g.ActiveIdIsJustActivated or g.IO.MouseClicked[0] then + BackendData.ProxyActiveId = g.ActiveId + BackendData.ProxyLostId = nil + end local mouse_up = not (io.MouseDown[0] or io.MouseDown[1] or io.MouseDown[2]) - if focused_box ~= proxy and mouse_up and bd.ProxyLostId ~= g.ActiveId and (focused_box == nil or not focused_box:IsDescendantOf(game)) then - bd.ProxyText = proxy.Text -- what it already holds is not new input (else re-typing it would collapse imgui's selection) + if focused_box ~= proxy and mouse_up and BackendData.ProxyLostId ~= g.ActiveId + and (focused_box == nil or not focused_box:IsDescendantOf(game)) then + -- what it already holds is not new input (else re-typing it would collapse imgui's selection) + BackendData.ProxyText = proxy.Text proxy:CaptureFocus() focused_box = UserInputService:GetFocusedTextBox() end elseif focused_box == proxy then - bd.ProxyReleasing = true + BackendData.ProxyReleasing = true proxy:ReleaseFocus() - bd.ProxyReleasing = false + BackendData.ProxyReleasing = false focused_box = nil end - proxy_focused = proxy ~= nil and focused_box == proxy + ProxyFocused = proxy ~= nil and focused_box == proxy local used_proxy_text = false - if proxy_focused then - -- 1) whatever the OS put in the proxy since last frame (typing, paste, cut) replaces imgui's selection + if ProxyFocused then local text = proxy.Text - if text ~= bd.ProxyText and text ~= bd.ProxyLastRaw then -- (LastRaw: don't re-send if our reset hasn't applied yet) - bd.ProxyLastRaw = text - -- InputText ignores characters while Ctrl is held (upstream, so shortcuts don't type); a paste arrives with - -- Ctrl still down, so release Ctrl around the characters in the event queue. - local ctrl = io.KeyCtrl or UserInputService:IsKeyDown(Enum.KeyCode.LeftControl) or UserInputService:IsKeyDown(Enum.KeyCode.RightControl) + if text ~= BackendData.ProxyText and text ~= BackendData.ProxyLastRaw then + BackendData.ProxyLastRaw = text + -- InputText ignores chars while Ctrl is held; a paste arrives with Ctrl down, so release it around them + local ctrl = io.KeyCtrl or UserInputService:IsKeyDown(Enum.KeyCode.LeftControl) + or UserInputService:IsKeyDown(Enum.KeyCode.RightControl) if ctrl then io:AddKeyEvent(4096 --[[ImGuiMod_Ctrl]], false) end - local prev = bd.ProxyText or "" + local prev = BackendData.ProxyText or "" if #text < #prev and prev:sub(1, #text) == text and text:sub(-1) ~= "\n" then - -- The TextBox deleted from its own text (Backspace/Delete; Roblox can't hold a real selection in it, so it - -- may remove just 1 char). Apply the deletion with imgui's own selection instead: one Backspace deletes - -- the whole imgui selection, or one char if none. Skipped if imgui already got the key event. - if not bd.DeleteKeySeen then io:AddKeyEvent(523 --[[ImGuiKey.Backspace]], true); io:AddKeyEvent(523 --[[ImGuiKey.Backspace]], false) end + -- the TextBox deleted from its own text (no real selection): one Backspace on imgui's selection + if not BackendData.DeleteKeySeen then + io:AddKeyEvent(523 --[[ImGuiKey.Backspace]], true) + io:AddKeyEvent(523 --[[ImGuiKey.Backspace]], false) + end elseif text ~= "\n" and text ~= "\r" and text ~= "\t" then -- Enter/Tab arrive as key events - local prev = bd.ProxyText or "" + local prev = BackendData.ProxyText or "" if #text > 0 and (prev == "" or text:sub(1, #prev) ~= prev or #text <= #prev) then for _, cp in utf8.codes(text) do io:AddInputCharacter(cp) end elseif #text > #prev then @@ -47415,91 +48489,131 @@ function ImGui_ImplRoblox_NewFrame() end if ctrl then io:AddKeyEvent(4096 --[[ImGuiMod_Ctrl]], true) end used_proxy_text = true - bd.ProxyText = nil + BackendData.ProxyText = nil end - -- 2) mirror imgui's selection, fully selected, so the native Ctrl+C / Ctrl+X copy exactly that local st = g.InputTextState local sel = "" if st and st.ID ~= 0 and st.ID == g.ActiveId and st.Stb and st:HasSelection() then - local a, b = math.min(st.Stb.select_start, st.Stb.select_end), math.max(st.Stb.select_start, st.Stb.select_end) + local a, b = math.min(st.Stb.select_start, st.Stb.select_end), + math.max(st.Stb.select_start, st.Stb.select_end) sel = ImGui._ByteArrayToString(st.TextA.Data, a, b) -- stb positions are 1-based in this port end - if sel ~= bd.ProxyText then + if sel ~= BackendData.ProxyText then proxy.Text = sel - bd.ProxyLastRaw = nil - bd.ProxyText = sel + BackendData.ProxyLastRaw = nil + BackendData.ProxyText = sel end - -- keep imgui's selection fully selected in the proxy, so Ctrl+C copies it and typing/Ctrl+V replaces it + -- mirror imgui's selection, fully selected, so native Ctrl+C copies it and typing/Ctrl+V replaces it local want_sel, want_cur = (#sel > 0) and 1 or -1, #sel + 1 if proxy.SelectionStart ~= want_sel then proxy.SelectionStart = want_sel end if proxy.CursorPosition ~= want_cur then proxy.CursorPosition = want_cur end end - bd.DeleteKeySeen = false + BackendData.DeleteKeySeen = false - -- Held KeyCode chars: dropped if the proxy delivered the text, otherwise typed (proxy didn't really get the keys) - local pending = bd.PendingChars + local pending = BackendData.PendingChars if #pending > 0 then if not used_proxy_text then for _, c in ipairs(pending) do io:AddInputCharacter(c) end end table.clear(pending) end - -- While the mouse is over imgui, make the tiles Active so Roblox stops passing clicks/wheel to the game (camera zoom etc.) + -- Tiles Active while over imgui, so Roblox stops passing clicks/wheel to the game (camera zoom etc.) local want = io.WantCaptureMouse - if want ~= bd.TilesActive then - bd.TilesActive = want - for _, set in pairs(bd.Layers) do for kind = 1, 3 do local layer = set[kind]; if layer then for _, tile in pairs(layer.Tiles) do tile.Label.Active = want end end end end + if want ~= BackendData.TilesActive then + BackendData.TilesActive = want + for _, set in pairs(BackendData.Layers) do + for kind = 1, 3 do + local layer = set[kind] + if layer then for _, tile in pairs(layer.Tiles) do tile.Label.Active = want end end + end + end end PE() end ---- Opt-in: max milliseconds per frame spent redrawing changed tiles (default 0 = no limit, every change is drawn the ---- same frame). With a budget (e.g. 1.5), tiles over it keep ---- their previous pixels and are redrawn on the following frames (each one at most a few frames late), so a big change ---- (resizing a large window, opening one, scrolling a long list) is spread over frames instead of one long frame. +-- Public API (documented in README.md) function ImGui_ImplRoblox_SetRedrawBudget(ms) ImGui_ImplRoblox_GetBackendData().RedrawBudget = (ms or 0) / 1000 end ---- Max tile redraws per second (default 60; 0 = every frame, limited by the redraw budget instead). imgui logic still runs every frame. function ImGui_ImplRoblox_SetRenderRate(hz) ImGui_ImplRoblox_GetBackendData().RenderRate = hz or 0 end ---- Optional: max tile redraws per second while scrolling, resizing or moving a window (0 = off, the default) function ImGui_ImplRoblox_SetBusyRenderRate(hz) ImGui_ImplRoblox_GetBackendData().BusyRenderRate = hz or 0 end ---- Toggle MicroProfiler labels (debug.profilebegin) for the backend -function ImGui_ImplRoblox_SetProfiling(enabled) profiling = enabled and true or false end -local function ImGui_ImplRoblox_IsProfiling() return profiling end +function ImGui_ImplRoblox_SetProfiling(enabled) Textures.SetProfiling(enabled) end +local ImGui_ImplRoblox_IsProfiling = Textures.IsProfiling + +function ImGui_ImplRoblox_SetStageTiming(enabled) + EditableImages.StageTiming = enabled and true or false + if not EditableImages.StageTiming then EditableImages.StageFrame = nil end +end function ImGui_ImplRoblox_SetRenderScale(scale) - local bd = ImGui_ImplRoblox_GetBackendData() - if scale == bd.Scale then return end - bd.Scale = scale - DestroyTiles(bd) - bd.ForceRedraw = true + local BackendData = ImGui_ImplRoblox_GetBackendData() + if scale == BackendData.Scale then return end + BackendData.Scale = scale + DestroyTiles(BackendData) + BackendData.ForceRedraw = true end +function ImGui_ImplRoblox_GetStats() + local BackendData = ImGui_ImplRoblox_GetBackendData() + local tiles = 0 + for _, set in pairs(BackendData.Layers) do + for kind = 1, 3 do if set[kind] then for _ in pairs(set[kind].Tiles) do tiles += 1 end end end + end + return { Tiles = tiles, EditableImages = EditableImages.Count, EditableImageBytes = EditableImages.Bytes, + EditableImageCap = EditableImages.Cap, Instances = #BackendData.Gui:GetDescendants(), + Frame = BackendData.FrameStats, Renders = BackendData.FrameNo } +end + +function ImGui_ImplRoblox_SetEditableImageCap(bytes) + EditableImages.Cap = bytes or 64 * 1024 * 1024 + EditableImages.Evict(EditableImages.Bytes - EditableImages.Cap) +end + +function ImGui_ImplRoblox_EnableParallel(opts) Parallel.Enable(opts) end + +function ImGui_ImplRoblox_DisableParallel() Parallel.Disable() end + +function ImGui_ImplRoblox_FinishParallel() Parallel.Finish() end + +function ImGui_ImplRoblox_BeginParallelFrame() Parallel.BeginFrame() end + +function ImGui_ImplRoblox_GetParallelStats() return Parallel.Stats end + +function ImGui_ImplRoblox_GetParallelConfig() return Parallel.Config end + ImGui_ImplRoblox = { Init = ImGui_ImplRoblox_Init, Shutdown = ImGui_ImplRoblox_Shutdown, NewFrame = ImGui_ImplRoblox_NewFrame, RenderDrawData = ImGui_ImplRoblox_RenderDrawData, AddFile = ImGui_ImplRoblox_AddFile, - SetRenderScale = ImGui_ImplRoblox_SetRenderScale, - SetRenderRate = ImGui_ImplRoblox_SetRenderRate, - SetRedrawBudget = ImGui_ImplRoblox_SetRedrawBudget, - SetOverlay = ImGui_ImplRoblox_SetOverlay, - SetTextProxy = ImGui_ImplRoblox_SetTextProxy, CreateTexture = ImGui_ImplRoblox_CreateTexture, DestroyTexture = ImGui_ImplRoblox_DestroyTexture, + SetOverlay = ImGui_ImplRoblox_SetOverlay, + SetTextProxy = ImGui_ImplRoblox_SetTextProxy, + SetRenderScale = ImGui_ImplRoblox_SetRenderScale, GetRenderScale = function() return ImGui_ImplRoblox_GetBackendData().Scale end, + SetRenderRate = ImGui_ImplRoblox_SetRenderRate, SetBusyRenderRate = ImGui_ImplRoblox_SetBusyRenderRate, + SetRedrawBudget = ImGui_ImplRoblox_SetRedrawBudget, SetProfiling = ImGui_ImplRoblox_SetProfiling, IsProfiling = ImGui_ImplRoblox_IsProfiling, + SetStageTiming = ImGui_ImplRoblox_SetStageTiming, + GetStats = ImGui_ImplRoblox_GetStats, + SetEditableImageCap = ImGui_ImplRoblox_SetEditableImageCap, + EnableParallel = ImGui_ImplRoblox_EnableParallel, + DisableParallel = ImGui_ImplRoblox_DisableParallel, + FinishParallel = ImGui_ImplRoblox_FinishParallel, + BeginParallelFrame = ImGui_ImplRoblox_BeginParallelFrame, + GetParallelStats = ImGui_ImplRoblox_GetParallelStats, + GetParallelConfig = ImGui_ImplRoblox_GetParallelConfig, } return true -- [Roblox] ModuleScripts must return exactly one value @@ -53937,7 +55051,7 @@ __FILES['imgui_internal.lua'] = function() -- [SECTION] ImFontLoader -- [SECTION] ImFontAtlas internal API -- --- PORT: the order of declarations in this file does not strictly follow upstream's imgui_internal.h. +-- [Port] the order of declarations in this file does not strictly follow upstream's imgui_internal.h. --- @meta @@ -53955,11 +55069,10 @@ local t_sort = table.sort --- @alias ImGuiTableColumnIdx ImS16 --- TODO: Implement actual ImString type +-- [Port] TODO: Implement actual ImString type --- @alias ImString char[]|string --- @alias ImStringBuffer char[] --- NOTE: temporary solution --- @param buf char[] --- @param buf_begin int --- @param buf_end int # exclusive @@ -53975,7 +55088,7 @@ end -- Helper: ImPool<> -- Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer, -- Indexes have the same lifetime as the associated object. ---- ImPool: pool of objects keyed by ID. Public indices are 0-based like upstream (Buf is stored 1-based). +--- [Port] ImPool: pool of objects keyed by ID. Public indices are 0-based like upstream (Buf is stored 1-based). --- `ctor` creates a new element. Removed slots are recycled via FreeIdx (-1 = none; free slots chain through `_NextFree`). local IM_POOL = {} IM_POOL.__index = IM_POOL @@ -54010,7 +55123,7 @@ function IM_POOL:Remove(key, p) self.AliveCount = self.AliveCount - 1 end function IM_POOL:Reserve(n) end --- NOTE: removed slots hold `false`; iterate with `for i = 0, pool:GetMapSize() - 1 do local t = pool:GetByIndex(i) if t then ... end end` +-- [Port] NOTE: removed slots hold `false`; iterate with `for i = 0, pool:GetMapSize() - 1 do local t = pool:GetByIndex(i) if t then ... end end` ------------------------------------------------------------------------------- -- [SECTION] Context pointer @@ -54020,7 +55133,7 @@ function IM_POOL:Reserve(n) end --- @type ImGuiContext? local GImGui -- Current implicit context pointer --- Sets local `GImGui` in this file(imgui_internal.lua). +-- [Port] Sets local `GImGui` in this file(imgui_internal.lua). -- This is currently only used in main code `ImGui.SetCurrentContext()` --- @param ctx ImGuiContext? function ImGui._SetCurrentContext_Internal(ctx) @@ -54162,7 +55275,7 @@ ImTrunc64 = _Trunc --- @param f float function ImCeilFast(f) local i - if f >= 0 then i = math.floor(f) else i = math.ceil(f) end -- same as `ImTrunc()` + if f >= 0 then i = math.floor(f) else i = math.ceil(f) end -- [Port] same as `ImTrunc()` if f > i then return i + 1 end return i end @@ -54222,7 +55335,7 @@ function ImStd.ImExponentialMovingAverage(avg, sample, n) return avg end --- Uses `string.match` internally +-- [Port] Uses `string.match` internally --- @param str string function ImAtof(str) return tonumber(string.match(str, "[+-]?%d*%.?%d+")) @@ -54240,7 +55353,6 @@ do local _memmove = function(dest, dest_start, src, src_start, count) if count <= 0 then return end - -- more compact instead of writing separate if-else and for loops local c = (dest == src and dest_start >= src_start) for i = (c and count - 1 or 0), (c and 0 or count - 1), (c and -1 or 1) do dest[dest_start + i] = src[src_start + i] @@ -54248,12 +55360,8 @@ local _memmove = function(dest, dest_start, src, src_start, count) end if table.move then - --- [GMod] Platform specific: the `table.move` polyfill in non-x86-64 currently uses `unpack` which will break if too many elements - -- Remove this check when the polyfill is fixed or removed - if not gmod or (gmod and BRANCH == "x86-64") then - _memmove = function(dest, dest_start, src, src_start, count) - table.move(src, src_start, src_start + count - 1, dest_start, dest) - end + _memmove = function(dest, dest_start, src, src_start, count) + table.move(src, src_start, src_start + count - 1, dest_start, dest) end end @@ -54400,9 +55508,9 @@ function ImStd.ImStrlen(str, begin) assert(false) end --- FIXME: should also accept count? --- FIXME: avoid dynamic type checking? --- string.find with patterns disabled +-- [Port] FIXME: should also accept count? +-- [Port] FIXME: avoid dynamic type checking? +-- [Port] string.find with patterns disabled --- @param str string|char[] --- @param s string|char --- @param start_pos? int @@ -54450,7 +55558,7 @@ IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT = ((IM_DRAWLIST_TEX_LINES_DETAILED_WI -- - The message will always be a string literal, in order to increase likelihood of being display by an assert handler. -- - See 'Demo->Configuration->Error Handling' and ImGuiIO definitions for details on error handling. -- - Read https://github.com/ocornut/imgui/wiki/Error-Handling for details on error handling. --- Upstream: `if (!(expr) && ErrorLog(msg)) IM_ASSERT(0)`. ErrorLog() returns io.ConfigErrorRecoveryEnableAssert. +-- [Port] Upstream: `if (!(expr) && ErrorLog(msg)) IM_ASSERT(0)`. ErrorLog() returns io.ConfigErrorRecoveryEnableAssert. function IM_ASSERT_USER_ERROR(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then if not ImGui.ErrorLog or ImGui.ErrorLog(_MSG) then error(_MSG, 2) end end end -- Recoverable User Error function IM_ASSERT_USER_ERROR_RET(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then error(_MSG, 2) end end @@ -54963,7 +56071,7 @@ end -- Helper: ImBitArray class (wrapper over ImBitArray functions) -- Store 1-bit per value. ---- NOTE: This struct is expensive to create +--- [Port] NOTE: This struct is expensive to create --- @class ImBitArray --- @field Data ImU32[] @@ -55187,7 +56295,7 @@ function ImFontAtlasBuilder() this.PreloadedAllGlyphsRanges = false -- Set when missing ImGuiBackendFlags.RendererHasTextures features forces atlas to preload everything. -- Cache of all ImFontBaked - this.BakedPool = ImVector() -- ImStableVector + this.BakedPool = ImVector() -- [Port] ImStableVector this.BakedMap = {} -- BakedId --> ImFontBaked this.BakedDiscardedCount = 0 @@ -55228,7 +56336,7 @@ end -- [SECTION] Style support ------------------------------------------------------------------------------- ---- `GetVarPtr()` is currently only used on `g.Style` in Dear ImGui, and we don't have pointers! +--- [Port] `GetVarPtr()` is currently only used on `g.Style` in Dear ImGui, and we don't have pointers! --- @class ImGuiStyleVarInfo --- @field Count ImU32 # 1+ --- @field DataType ImGuiDataType @@ -55743,7 +56851,7 @@ local function ImGuiInputTextState() SelectedAllMouseLock = false, -- after a double-click to select all, we ignore further mouse drags to update selection EditedBefore = false, -- edited since activated EditedThisFrame = false, -- edited this frame - ValidatedThisFrame = false, -- validated this frame (e.g. Enter pressed) + ValidatedThisFrame = false, WantReloadUserBuf = false, -- force a reload of user buf so it may be modified externally. may be automatic in future version. LastMoveDirectionLR = 0 --[[ImGuiDir.Left]], -- ImGuiDir_Left or ImGuiDir_Right. track last movement direction so when cursor cross over a word-wrapping boundaries we can display it on either line depending on last move.s ReloadSelectionStart = 0, @@ -56036,7 +57144,7 @@ end ------------------------------------------------------------------------------- -- We always assume that -1 is an invalid value (which works for indices and pointers) --- (ImGuiSelectionUserData_Invalid is defined above with the ImGuiSelectionUserData alias) +-- [Port] (ImGuiSelectionUserData_Invalid is defined above with the ImGuiSelectionUserData alias) -- Temporary storage for multi-select --- @class ImGuiMultiSelectTempData @@ -56177,7 +57285,7 @@ function ImGui.GetMultiSelectState(id) local g = GImGui; return g.MultiSelectSto ------------------------------------------------------------------------------- -- [SECTION] Tab bar, Tab item support --- PORT: public flags from imgui.h + private extensions +-- [Port] public flags from imgui.h + private extensions ------------------------------------------------------------------------------- -- Flags for ImGui.BeginTabBar() @@ -56226,7 +57334,7 @@ ImGuiTabItemFlags = { } ImGuiTabItemFlags.SectionMask_ = bitOr(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing) --- Storage for one active tab item. In this port the label is stored in `Name` (C++ uses NameOffset into TabBar.TabsNames) +-- [Port] Storage for one active tab item. In this port the label is stored in `Name` (C++ uses NameOffset into TabBar.TabsNames) --- @class ImGuiTabItem --- @return ImGuiTabItem function ImGuiTabItem() @@ -56245,7 +57353,7 @@ function ImGuiTabItem() } end --- Storage for a tab bar. Tabs: ImVector of ImGuiTabItem tables (references; "pointers" stay valid across reorders) +-- [Port] Storage for a tab bar. Tabs: ImVector of ImGuiTabItem tables (references; "pointers" stay valid across reorders) --- @class ImGuiTabBar --- @return ImGuiTabBar function ImGuiTabBar() @@ -56277,7 +57385,7 @@ function ImGuiShrinkWidthItem() return { Index = 0, Width = 0.0, InitialWidth = --- @param shared_font_atlas? ImFontAtlas --- @return ImGuiContext --- @nodiscard -function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this structure +function ImGuiContext(shared_font_atlas) local this = { Style = ImGuiStyle(), ColorStack = ImVector(), -- Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() @@ -56515,20 +57623,20 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct ComboPreviewData = ImGuiComboPreviewData(), CurrentTabBar = nil, - TabBars = ImPool(ImGuiTabBar), -- ImPool + TabBars = ImPool(ImGuiTabBar), -- [Port] ImPool -- Docking DockContext = ImGuiDockContext(), DockNodeWindowMenuHandler = nil, DebugHoveredDockNode = nil, -- Hovered dock node. - CurrentTabBarStack = ImVector(), -- ImVector - ShrinkWidthBuffer = ImVector(), -- ImGuiShrinkWidthItem + CurrentTabBarStack = ImVector(), -- [Port] ImVector + ShrinkWidthBuffer = ImVector(), -- [Port] ImGuiShrinkWidthItem -- Multi-Select state BoxSelectState = ImGuiBoxSelectState(), CurrentMultiSelect = nil, MultiSelectTempDataStacked = 0, -- Temporary multi-select data size (because we leave previous instances undestructed, we generally don't use MultiSelectTempData.Size) - MultiSelectTempData = ImVector(), -- ImVector, 1-based - MultiSelectStorage = ImPool(ImGuiMultiSelectState), -- ImPool + MultiSelectTempData = ImVector(), -- [Port] ImVector, 1-based + MultiSelectStorage = ImPool(ImGuiMultiSelectState), -- [Port] ImPool WindowResizeBorderExpectedRect = ImRect(), -- Expected border rect, switch to relative edit if moving WindowResizeRelativeMode = false, @@ -56650,7 +57758,7 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct DebugAllocInfo = ImGuiDebugAllocInfo(), --- Misc - FramerateSecPerFrame = {}, -- size = 60 + FramerateSecPerFrame = {}, -- [Port] size = 60 FramerateSecPerFrameIdx = 0, FramerateSecPerFrameCount = 0, FramerateSecPerFrameAccum = 0, @@ -56660,15 +57768,15 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct WantTextInputNextFrame = -1, -- Copied in EndFrame() from g.PlatformImeData.WantTextInput. Needs to be set for some backends (SDL3) to emit character inputs. TempBuffer = ImVector(), -- Temporary text buffer - -- Tables (imgui_tables.lua) + -- [Port] Tables (imgui_tables.lua) CurrentTable = nil, DebugBreakInTable = 0, -- Set to break in BeginTable() call. TablesTempDataStacked = 0, -- Temporary table data size (because we leave previous instances undestructed, we generally don't use TablesTempData.Size) TablesTempData = ImVector(), -- Temporary table data (buffers reused/shared across instances, support nesting) - Tables = ImPool(), -- ImPool, 0-based indices (imgui_tables.lua) - TablesLastTimeActive = ImVector(), -- [table_idx + 1] = float + Tables = ImPool(), -- [Port] ImPool, 0-based indices (imgui_tables.lua) + TablesLastTimeActive = ImVector(), -- [Port] [table_idx + 1] = float DrawChannelsTempMergeBuffer = ImVector(), - SettingsTables = ImVector(), -- ImChunkStream: plain vector, SettingsOffset = 1-based index + SettingsTables = ImVector(), -- [Port] ImChunkStream: plain vector, SettingsOffset = 1-based index } for i = 0, 59 do this.FramerateSecPerFrame[i] = 0 end @@ -56843,7 +57951,7 @@ local function ImGuiWindowTempData() TreeRecordsClippedNodesY2Mask = nil, -- Store whether we should keep recording Y2. Cleared when passing clip max. Equivalent TreeHasStackDataDepthMask value should always be set. ChildWindows = ImVector(), - CurrentTableIdx = -1, -- 0-based index into g.Tables, -1 if none + CurrentTableIdx = -1, -- [Port] 0-based index into g.Tables, -1 if none CurrentColumns = nil, -- ImGuiOldColumns (legacy Columns API) StateStorage = nil, -- Current persistent per-window storage (store e.g. tree node open/close state) @@ -57041,7 +58149,7 @@ function ImGuiWindow(ctx, name) LastTimeActive = -1.0, -- Last timestamp the window was Active (using float as we don't need high precision there) StateStorage = {}, - ColumnsStorage = ImVector(), -- ImVector + ColumnsStorage = ImVector(), -- [Port] ImVector WriteAccessed = false, -- Set to true when any widget access the current window @@ -57051,7 +58159,7 @@ function ImGuiWindow(ctx, name) HitTestHoleSize = ImVec2(), -- Define an optional rectangular hole where mouse will pass-through the window. NavLastChildNavWindow = nil, -- When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) - NavLastIds = {[0] = 0, [1] = 0}, -- FIXME: 1-based instead + NavLastIds = {[0] = 0, [1] = 0}, -- [Port] FIXME: 1-based instead NavRectRel = {[0] = ImRect(), [1] = ImRect()}, -- Reference rectangle, in window relative space NavPreferredScoringPosRel = {[0] = ImVec2(), [1] = ImVec2()}, -- Preferred X/Y position updated when moving on a given axis, reset to FLT_MAX. NavRootFocusScopeId = 0 -- Focus Scope ID at the time of Begin() @@ -57877,7 +58985,7 @@ function ImGui.GetCurrentTabBar() local g = GImGui; return g.CurrentTabBar end function ImGui.IsItemActiveAsInputText() local g = GImGui; return g.ActiveId ~= 0 and g.ActiveId == g.LastItemData.ID and g.InputTextState.ID == g.LastItemData.ID end -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value end __FILES['imgui_tables.lua'] = function() @@ -58059,22 +59167,22 @@ __FILES['imgui_tables.lua'] = function() -- - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false. ------------------------------------------------------------------------------- --- Port notes: --- - Column indices / display orders / draw channel indices are 0-based VALUES like upstream. --- Per-column arrays (table.Columns, table.DisplayOrderToIndex, table.RowCellData) are Lua tables with 0-based keys. --- table.ColumnsSize mirrors upstream `table->Columns.size()`. --- - ImBitArray masks are Lua tables { [n] = true }. --- - table.ColumnsNames is a Lua array of strings, column.NameOffset is a 0-based index into it (-1 = none). --- - g.SettingsTables is a plain vector of ImGuiTableSettings; table.SettingsOffset is a 1-based index into it (-1 = none). --- Each settings entry owns `Columns` (0-based Lua table of ImGuiTableColumnSettings). --- - ImGuiTableSortSpecs.Specs is a 1-based Lua array of ImGuiTableColumnSortSpecs. +-- [Port] Port notes: +-- [Port] - Column indices / display orders / draw channel indices are 0-based VALUES like upstream. +-- [Port] Per-column arrays (table.Columns, table.DisplayOrderToIndex, table.RowCellData) are Lua tables with 0-based keys. +-- [Port] table.ColumnsSize mirrors upstream `table->Columns.size()`. +-- [Port] - ImBitArray masks are Lua tables { [n] = true }. +-- [Port] - table.ColumnsNames is a Lua array of strings, column.NameOffset is a 0-based index into it (-1 = none). +-- [Port] - g.SettingsTables is a plain vector of ImGuiTableSettings; table.SettingsOffset is a 1-based index into it (-1 = none). +-- [Port] Each settings entry owns `Columns` (0-based Lua table of ImGuiTableColumnSettings). +-- [Port] - ImGuiTableSortSpecs.Specs is a 1-based Lua array of ImGuiTableColumnSortSpecs. --- @type ImGuiContext? local GImGui local MT = ImGui.GetMetatables() --- Sets local `GImGui` in this file(imgui_tables.lua). +-- [Port] Sets local `GImGui` in this file(imgui_tables.lua). -- This is currently only used in main code `ImGui.SetCurrentContext()` --- @param ctx ImGuiContext? function ImGui._SetCurrentContext_Tables(ctx) @@ -58372,7 +59480,7 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi -- Acquire storage for the table local table_ = g.Tables:GetOrAddByKey(id) - if table_.Columns == nil then -- pool created a plain table + if table_.Columns == nil then -- [Port] pool created a plain table for k, v in pairs(ImGuiTable()) do table_[k] = v end end @@ -59876,7 +60984,7 @@ function ImGui.TableReconcileColumns(table_) end -- Remaining entries are matched sequentially. - local dst_idx = 1 -- index in reconcile array (1-based) + local dst_idx = 1 -- [Port] index in reconcile array (1-based) if matches ~= reconcile_requests.Size then for src_n = 0, src_count - 1 do local src_column = src_columns[src_n] @@ -59968,7 +61076,7 @@ function ImGui.TableGetColumnCount() return table_ and table_.ColumnsCount or 0 end --- Overloads: TableGetColumnName(column_n?) / TableGetColumnName(table, column_n) +-- [Port] Overloads: TableGetColumnName(column_n?) / TableGetColumnName(table, column_n) function ImGui.TableGetColumnName(a, b) local table_, column_n if type(a) == "table" then @@ -60886,7 +61994,7 @@ end -- Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd. -- -- This function is particularly tricky to understand.. take a breath. --- (Lua: splitter channel n lives in splitter._Channels.Data[n + 1]; bit arrays are Lua sets) +-- [Port] (Lua: splitter channel n lives in splitter._Channels.Data[n + 1]; bit arrays are Lua sets) local TableMergeDrawChannels_MergeGroups = {} for n = 0, 3 do TableMergeDrawChannels_MergeGroups[n] = { ClipRect = ImRect(), ChannelsCount = 0, ChannelsMask = {} } @@ -61184,7 +62292,7 @@ end -- changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, -- else you may wastefully sort your data every frame! -- Lifetime: don't hold on this table over multiple frames or past any subsequent call to BeginTable()! --- PORT: Specs is a 1-based Lua array. +-- [Port] Specs is a 1-based Lua array. function ImGui.TableGetSortSpecs() local g = GImGui local table_ = g.CurrentTable @@ -61276,7 +62384,7 @@ function ImGui.TableSortSpecsSanitize(table_) -- Clear SortOrder from hidden column and verify that there's no gap or duplicate. local sort_order_count = 0 - local sort_order_set = {} -- C++: ImU64 sort_order_mask + local sort_order_set = {} -- [Port] C++: ImU64 sort_order_mask local sort_order_dup = false for column_n = 0, table_.ColumnsCount - 1 do local column = table_.Columns[column_n] @@ -61291,7 +62399,7 @@ function ImGui.TableSortSpecsSanitize(table_) end end - -- need_fix_linearize: (1 << count) != (mask + 1) <=> the set of sort orders isn't exactly {0..count-1} + -- [Port] need_fix_linearize: (1 << count) != (mask + 1) <=> the set of sort orders isn't exactly {0..count-1} local need_fix_linearize = sort_order_dup for n = 0, sort_order_count - 1 do if not sort_order_set[n] then need_fix_linearize = true end @@ -62475,7 +63583,7 @@ function ImGui.TableRemove(table_) end -- Free up/compact internal Table buffers for when it gets unused --- Overloads: (ImGuiTable) / (ImGuiTableTempData) +-- [Port] Overloads: (ImGuiTable) / (ImGuiTableTempData) function ImGui.TableGcCompactTransientBuffers(t) if not t then return end if t.TableIndex ~= nil then -- ImGuiTableTempData @@ -62553,7 +63661,7 @@ end -- - EndColumns() -- - Columns() ------------------------------------------------------------------------------- --- (Lua: columns.Columns is an ImVector, column n lives in .Data[n + 1]) +-- [Port] (Lua: columns.Columns is an ImVector, column n lives in .Data[n + 1]) function ImGui.GetColumnIndex() local window = ImGui.GetCurrentWindowRead() @@ -62969,7 +64077,7 @@ function ImGui.Columns(columns_count, id, borders) end end -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value end __FILES['imgui_widgets.lua'] = function() @@ -63002,7 +64110,7 @@ __FILES['imgui_widgets.lua'] = function() --- @type ImGuiContext? local GImGui --- Sets local `GImGui` in this file(imgui_widgets.lua). +-- [Port] Sets local `GImGui` in this file(imgui_widgets.lua). -- This is currently only used in main code `ImGui.SetCurrentContext()` --- @param ctx ImGuiContext? function ImGui._SetCurrentContext_Widgets(ctx) @@ -63344,7 +64452,7 @@ function ImGui.BulletText(fmt, ...) ImGui.RenderText(ImVec2(bb.Min.x + (g.FontSize + style.FramePadding.x * 2), bb.Min.y + 0.0), text, 1, text_end, false) end --- va_list variants: identical to the varargs versions in Lua +-- [Port] va_list variants: identical to the varargs versions in Lua ImGui.TextColoredV = ImGui.TextColored ImGui.TextDisabledV = ImGui.TextDisabled ImGui.TextWrappedV = ImGui.TextWrapped @@ -63359,8 +64467,8 @@ ImGui.BulletTextV = ImGui.BulletText -- - Value() ------------------------------------------------------------------------------- --- Value(prefix, b) / Value(prefix, int) / Value(prefix, float, float_format) --- Lua can't tell int from float: integers without float_format print as %d, otherwise %.3f +-- [Port] Value(prefix, b) / Value(prefix, int) / Value(prefix, float, float_format) +-- [Port] Lua can't tell int from float: integers without float_format print as %d, otherwise %.3f function ImGui.Value(prefix, v, float_format) if type(v) == "boolean" then ImGui.Text("%s: %s", prefix, v and "true" or "false") @@ -63460,7 +64568,7 @@ end -- with same ID and different MouseButton (see #8030). You can fix it by: -- (1) switching to use a single ButtonBehavior() with multiple _MouseButton flags. -- or (2) surrounding those calls with PushItemFlag(ImGuiItemFlags.AllowDuplicateId, true); ... PopItemFlag() --- Returns (pressed, hovered, held). +-- [Port] Returns (pressed, hovered, held). --- @param bb ImRect --- @param id ImGuiID --- @param flags? ImGuiButtonFlags @@ -63738,7 +64846,7 @@ function ImGui.ButtonEx(label, size_arg, flags) local label_size = ImGui.CalcTextSize(label, label_end, false) -- [Luau] scalar pos, no temporary ImVec2 - local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y -- Don't modify the cursor! + local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y local frame_padding = style.FramePadding if bit32.band(flags, 32768 --[[ImGuiButtonFlags.AlignTextBaseLine]]) ~= 0 and frame_padding.y < window.DC.CurrLineTextBaseOffset then -- Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos_y = pos_y + window.DC.CurrLineTextBaseOffset - frame_padding.y @@ -64046,7 +65154,7 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ -- As a special thing, we allow scrollbar near the edge of a screen/viewport to be reachable with mouse at the extreme edge (#9276) local bb_hit = ImRect() ImRect_Copy(bb_hit, bb_frame) - ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb_hit, g.Style.WindowBorderSize, 1 --[[ImGuiAxis.X]] + 2 --[[ImGuiAxis.Y]] - axis) -- swap axis here + ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb_hit, g.Style.WindowBorderSize, 1 --[[ImGuiAxis.X]] + 2 --[[ImGuiAxis.Y]] - axis) -- [Port] swap axis here -- Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). ImGui.ItemAdd(bb_frame, id, nil, 2 --[[ImGuiItemFlags.NoNav]]) @@ -64456,7 +65564,7 @@ function ImGui.RadioButtonEx(label, active) return pressed end --- `rawequal` is used here to check if v == v_button +-- [Port] `rawequal` is used here to check if v == v_button --- @param label string --- @param v any --- @param v_button any @@ -65186,7 +66294,7 @@ function ImGui.EndComboPreview() preview_data.WithinPreview = false end --- Getter for the old Combo() API: Lua array of strings (1-based), `idx` is 0-based +-- [Port] Getter for the old Combo() API: Lua array of strings (1-based), `idx` is 0-based local function Items_ArrayGetter(data, idx) return data[idx + 1] end @@ -65216,7 +66324,7 @@ local function Items_SingleStringCount(data) return items_count end --- Normalizes the 3 upstream overloads to (getter, user_data, items_count, height) +-- [Port] Normalizes the 3 upstream overloads to (getter, user_data, items_count, height) -- - (items: string[], items_count?, height?) -- - (items_separated_by_zeros: string, height?) -- - (getter: fun(user_data, idx): string?, user_data, items_count, height?) @@ -65343,9 +66451,9 @@ function ImGui.DataTypeGetInfo(data_type) end -- [Luau] string.format() has no length modifiers (%lld, %I64d...) and formats negative numbers as 64-bit for %u/%x/%X/%o: --- strip modifiers and re-apply C's integer promotion/two's complement for signed types. +-- [Port] strip modifiers and re-apply C's integer promotion/two's complement for signed types. local DataTypeFormatStringCached do -local fmt_info_memo = {} -- format -> { stripped format, is unsigned conversion } +local fmt_info_memo = {} -- [Port] format -> { stripped format, is unsigned conversion } local function GetFormatInfo(format) local info = fmt_info_memo[format] if info == nil then @@ -65357,7 +66465,7 @@ local function GetFormatInfo(format) return info end ---- Lua-string version of DataTypeFormatString() (memoized), used for display. +--- [Port] Lua-string version of DataTypeFormatString() (memoized), used for display. --- @param data_type ImGuiDataType --- @param data number --- @param format string @@ -65371,14 +66479,14 @@ function DataTypeFormatStringCached(data_type, data, format) elseif data_type == 1 --[[ImGuiDataType.U8]] then data = (ImU8)(data) elseif data_type == 2 --[[ImGuiDataType.S16]] then data = (ImS16)(data) elseif data_type == 3 --[[ImGuiDataType.U16]] then data = (ImU16)(data) - elseif data_type == 4 --[[ImGuiDataType.S32]] then -- (signed values are already stored signed) + elseif data_type == 4 --[[ImGuiDataType.S32]] then -- [Port] (signed values are already stored signed) elseif data_type == 5 --[[ImGuiDataType.U32]] then data = (ImU32)(data) elseif data_type == 6 --[[ImGuiDataType.S64]] or data_type == 7 --[[ImGuiDataType.U64]] then - -- (string.format() already prints negative numbers as 64-bit two's complement for %u/%x/%X/%o) + -- [Port] (string.format() already prints negative numbers as 64-bit two's complement for %u/%x/%X/%o) if info[2] then - if data >= 18446744073709551616 then data = -1 end -- (ImU64)-1 rounds to 2^64 in a double: print ULLONG_MAX + if data >= 18446744073709551616 then data = -1 end -- [Port] (ImU64)-1 rounds to 2^64 in a double: print ULLONG_MAX elseif data >= 9223372036854775808 then - data = 9223372036854774784 -- largest double below 2^63 (LLONG_MAX isn't representable) + data = 9223372036854774784 -- [Port] largest double below 2^63 (LLONG_MAX isn't representable) end return FormatCached(info[1], data) else @@ -65397,7 +66505,7 @@ end --- @return int function ImGui.DataTypeFormatString(buf, buf_size, data_type, data, format) local str = DataTypeFormatStringCached(data_type, data, format) - local len = ImMin(#str, buf_size - 1) -- ImFormatString(): truncate and return the written length + local len = ImMin(#str, buf_size - 1) -- [Port] ImFormatString(): truncate and return the written length ImStd.ImStrncpy(buf, 1, { string.byte(str, 1, len) }, 1, len + 1) return len end @@ -65950,7 +67058,7 @@ function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min return data, value_changed end --- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For an Input widget, step and step_fast are optional. +-- [Port] Note: data is passed by value and the new value is returned: Returns (data, value_changed). For an Input widget, step and step_fast are optional. -- Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. --- @param label string --- @param data_type ImGuiDataType @@ -65977,7 +67085,7 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag local data_default = (bit32.band(g.NextItemData.HasFlags, 8 --[[ImGuiNextItemDataFlags.HasRefVal]]) ~= 0) and g.NextItemData.RefVal or g.DataTypeZeroValue - local buf, buf_size = {}, 64 -- char buf[64]; IM_COUNTOF(buf) + local buf, buf_size = {}, 64 -- [Port] char buf[64]; IM_COUNTOF(buf) if bit32.band(flags, 16384 --[[ImGuiInputTextFlags.DisplayEmptyRefVal]]) ~= 0 and ImGui.DataTypeCompare(data_type, data, data_default) == 0 then buf[1] = 0 else @@ -66454,7 +67562,7 @@ local function TempInputIsClampEnabled(flags, data_type, min, max) if bit32.band(flags, 512 --[[ImGuiSliderFlags.ClampOnInput]]) ~= 0 and (min ~= nil or max ~= nil) then local clamp_range_dir = 0 if min ~= nil and max ~= nil then - clamp_range_dir = ImGui.DataTypeCompare(data_type, min, max) -- -1 when min < max, == 0 when min == max + clamp_range_dir = ImGui.DataTypeCompare(data_type, min, max) end if min == nil or max == nil or clamp_range_dir < 0 then return true @@ -66475,7 +67583,7 @@ end --- @param format string --- @param flags ImGuiSliderFlags -- [Luau] memo of string.format(format, value) for drag/slider value text (same values are redrawn every frame). --- ponytail: whole-memo reset at 4096 entries, LRU if values churn + local fmt_memo, fmt_memo_n = {}, 0 local SliderScalar_total_bb, SliderScalar_grab_bb = ImRect(), ImRect() -- [Luau] scratch for SliderScalar()/DragScalar(), never escape local DRAG_TEXT_ALIGN = ImVec2(0.5, 0.5) @@ -66490,7 +67598,7 @@ function FormatCached(format, v) return r end --- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a Drag widget, min and max are optional. +-- [Port] Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a Drag widget, min and max are optional. -- Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. @native function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, flags) @@ -66644,7 +67752,7 @@ function ImGui.DragInt(label, v, v_speed, v_min, v_max, format, flags) return ImGui.DragScalar(label, 4 --[[ImGuiDataType.S32]], v, v_speed, v_min, v_max, format, flags) end --- `v` is mutated in place (1-based), returns value_changed +-- [Port] `v` is mutated in place (1-based), returns value_changed function ImGui.DragScalarN(label, data_type, v, components, v_speed, v_min, v_max, format, flags) if v_speed == nil then v_speed = 1.0 end if flags == nil then flags = 0 end @@ -66923,7 +68031,7 @@ function ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, t, v_min, v_max -- - Not doing a *1.0 multiply at the end of a range as it tends to be lossy. While absolute aiming at a large s64/u64 -- range is going to be imprecise anyway, with this check we at least make the edge values matches expected limits. local v_new_off_f = (SIGNEDTYPE)((v_max - v_min)) * t - result = (TYPE)((SIGNEDTYPE)(v_min) + (SIGNEDTYPE)(v_new_off_f + 0)) -- LUA: + 0 instead of + ((v_min > v_max) and -0.5 or 0.5) + result = (TYPE)((SIGNEDTYPE)(v_min) + (SIGNEDTYPE)(v_new_off_f + 0)) -- [Port] + 0 instead of + ((v_min > v_max) and -0.5 or 0.5) end end @@ -67188,7 +68296,7 @@ function ImGui.SliderBehavior(bb, id, data_type, v, min, max, format, flags, out return v, false end --- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a slider, min and max are required. +-- [Port] Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a slider, min and max are required. -- Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. --- @generic T : number --- @param label string @@ -68231,7 +69339,7 @@ function ImGui.InputTextDeactivateHook(id) assert(state.TextA.Data ~= nil) -- IM_ASSERT(state.TextA[state.TextLen + 1] == 0) g.InputTextDeactivatedState.TextA:resize(state.TextLen + 1) - ImStd.memmove(g.InputTextDeactivatedState.TextA.Data, 1, state.TextA.Data, 1, state.TextLen) -- state.TextLen + 1 + ImStd.memmove(g.InputTextDeactivatedState.TextA.Data, 1, state.TextA.Data, 1, state.TextLen) -- [Port] state.TextLen + 1 end end @@ -68356,7 +69464,7 @@ local function InputTextLineIndexGetPosOffset(g, state, line_index, buf, buf_end end end - local line_no = (it == it_begin) and 0 or (it - 1) -- 0-based (index_from_ptr) + local line_no = (it == it_begin) and 0 or (it - 1) -- [Port] 0-based (index_from_ptr) local line_start = line_index:get_line_begin(1, line_no) local offset = ImVec2() offset.x = InputTextCalcTextSize(g, buf, line_start, cursor_ptr, buf_end, nil, 2 --[[ImDrawTextFlags.WrapKeepBlanks]]).x @@ -68578,7 +69686,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback -- Find initial scroll position for right alignment ImVec2_Copy(state.Scroll, ImVec2(0.0, 0.0)) if bit32.band(flags, 131072 --[[ImGuiInputTextFlags.ElideLeft]]) ~= 0 then - state.Scroll.x = state.Scroll.x + ImMax(0.0, ImGui.CalcTextSize(table.concat(buf)).x - frame_size.x + style.FramePadding.x * 2.0) -- FIXME: no table.concat here + state.Scroll.x = state.Scroll.x + ImMax(0.0, ImGui.CalcTextSize(table.concat(buf)).x - frame_size.x + style.FramePadding.x * 2.0) -- [Port] FIXME: no table.concat here end -- Recycle existing cursor/selection/undo stack but clamp position @@ -69210,7 +70318,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end -- Calculate visibility - local line_visible_n0, line_visible_n1 = 0, 1 -- 0-based like upstream + local line_visible_n0, line_visible_n1 = 0, 1 -- [Port] 0-based like upstream if is_multiline then line_visible_n0, line_visible_n1 = ImGui.CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize) end @@ -69710,7 +70818,7 @@ function ImGui.ColorEdit4(label, col, flags) end elseif bit32.band(flags, 4194304 --[[ImGuiColorEditFlags.DisplayHex]]) ~= 0 and bit32.band(flags, 32 --[[ImGuiColorEditFlags.NoInputs]]) == 0 then -- RGB Hexadecimal Input - -- TODO: resolve sprintf, sscanf requirement. currently this section creates a lot of temp tables and strings... + -- [Port] TODO: resolve sprintf, sscanf requirement. currently this section creates a lot of temp tables and strings... local buf, buf_size = nil, 64 if alpha then local str = ImFormatString("#%02X%02X%02X%02X", ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255), ImClamp(i[3], 0, 255), ImClamp(i[4], 0, 255)) @@ -69868,7 +70976,7 @@ function ImGui.ColorEdit3(label, col, flags) return ImGui.ColorEdit4(label, col, bit32.bor(flags, 2 --[[ImGuiColorEditFlags.NoAlpha]])) end --- `col` mutated in place, returns value_changed +-- [Port] `col` mutated in place, returns value_changed function ImGui.ColorPicker3(label, col, flags) if flags == nil then flags = 0 end local col4 = { col[1], col[2], col[3], 1.0 } @@ -70131,7 +71239,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) -- Convert back color to RGB if value_changed_h or value_changed_sv then if bit32.band(flags, 268435456 --[[ImGuiColorEditFlags.InputRGB]]) ~= 0 then - col[1], col[2], col[3] = ImGui.ColorConvertHSVtoRGB(H, S, V) -- Lua 1-based indexing + col[1], col[2], col[3] = ImGui.ColorConvertHSVtoRGB(H, S, V) -- [Port] Lua 1-based indexing g.ColorEditSavedHue = H g.ColorEditSavedSat = S g.ColorEditSavedID = g.ColorEditCurrentID @@ -70177,7 +71285,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) -- Try to cancel hue wrap (after ColorEdit4 call), if any if value_changed_fix_hue_wrap and bit32.band(flags, 268435456 --[[ImGuiColorEditFlags.InputRGB]]) ~= 0 then - local new_H, new_S, new_V = ImGui.ColorConvertRGBtoHSV(col[1], col[2], col[3]) -- Lua 1-based indexing + local new_H, new_S, new_V = ImGui.ColorConvertRGBtoHSV(col[1], col[2], col[3]) -- [Port] Lua 1-based indexing if new_H <= 0 and H > 0 then if new_V <= 0 and V ~= new_V then @@ -70633,7 +71741,7 @@ end -- - CollapsingHeader() ------------------------------------------------------------------------------- --- va_list variants: identical in Lua (varargs) +-- [Port] va_list variants: identical in Lua (varargs) ImGui.TextColoredV = function(...) return ImGui.TextColored(...) end ImGui.TextDisabledV = function(...) return ImGui.TextDisabled(...) end ImGui.TextWrappedV = function(...) return ImGui.TextWrapped(...) end @@ -70649,7 +71757,7 @@ function ImGui.SetNextItemRefVal(data_type, v) g.NextItemData.RefVal = v end --- Overloads: TreeNode(label) / TreeNode(str_id, fmt, ...) +-- [Port] Overloads: TreeNode(label) / TreeNode(str_id, fmt, ...) --- @param label string @native function ImGui.TreeNode(label, fmt, ...) @@ -70668,7 +71776,7 @@ function ImGui.TreeNodeV(str_id, fmt, ...) return ImGui.TreeNodeExV(str_id, 0, fmt, ...) end --- Overloads: TreeNodeEx(label, flags) / TreeNodeEx(str_id, flags, fmt, ...) +-- [Port] Overloads: TreeNodeEx(label, flags) / TreeNodeEx(str_id, flags, fmt, ...) --- @param label string --- @param flags? ImGuiTreeNodeFlags function ImGui.TreeNodeEx(label, flags, fmt, ...) @@ -71238,7 +72346,7 @@ end -- CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags.NoTreePushOnOpen flag). -- This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags.CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). --- Overloads: CollapsingHeader(label, flags?) -> is_open +-- [Port] Overloads: CollapsingHeader(label, flags?) -> is_open -- CollapsingHeader(label, p_visible: bool, flags?) -> is_open, p_visible -- p_visible == nil : regular collapsing header -- p_visible == true : show a small close button on the corner of the header, clicking the button will set p_visible = false (returned as 2nd value) @@ -71588,7 +72696,7 @@ function ImGui.GetTypingSelectRequest(flags) -- Handle backspace if bit32.band(flags, 1 --[[ImGuiTypingSelectFlags.AllowBackspace]]) ~= 0 and ImGui.IsKeyPressedEx(523 --[[ImGuiKey.Backspace]], 1 --[[ImGuiInputFlags.Repeat]]) then - local p = ImStd.ImTextFindPreviousUtf8Codepoint(data.SearchBuffer, 1, buffer_len + 1) -- 1-based byte position + local p = ImStd.ImTextFindPreviousUtf8Codepoint(data.SearchBuffer, 1, buffer_len + 1) -- [Port] 1-based byte position data.SearchBuffer = string.sub(data.SearchBuffer, 1, p - 1) buffer_len = p - 1 end @@ -71881,7 +72989,7 @@ function ImGui.BeginBoxSelect(scope_rect, window, box_select_id, ms_flags) end end - -- box_select_intersection = BoxSelectRectPrev + BoxSelectRectCurr + -- [Port] box_select_intersection = BoxSelectRectPrev + BoxSelectRectCurr local box_select_intersection_min_x, box_select_intersection_min_y = ImMin(prev.Min.x, curr.Min.x), ImMin(prev.Min.y, curr.Min.y) local box_select_intersection_max_x, box_select_intersection_max_y = ImMax(prev.Max.x, curr.Max.x), ImMax(prev.Max.y, curr.Max.y) if bit32.band(ms_flags, 128 --[[ImGuiMultiSelectFlags.BoxSelect2d]]) ~= 0 then @@ -72568,7 +73676,7 @@ function ImGui.MultiSelectAddSetRange(ms, selected, range_dir, first_item, last_ -- FIXME-OPT: Disabled on 2026/04/09 as this would break with any form of coarse clipping that we don't know about (e.g. TableNextColumn() return value). -- The low-hanging fruit would be to know that ImGuiSelectionUserData are sequential indices, in which case we can trivially compare PrevSubmittedItem + RangeDir == FirstItem. -- User can always perform this merge if required. - -- (#if 0 block not ported) + -- [Port] (#if 0 block not ported) local req = MultiSelectScratchRequest -- ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, (ImS8)range_dir, (range_dir > 0) ? first_item : last_item, (range_dir > 0) ? last_item : first_item } req.Type = 2 --[[ImGuiSelectionRequestType.SetRange]]; req.Selected = selected; req.RangeDirection = range_dir @@ -72680,7 +73788,7 @@ function MT.ImGuiSelectionBasicStorage:GetNextSelectedItem(opaque_it) table.sort(keys, PairComparerByValueInt) -- ~ImGuiStorage::BuildSortByValueInt() PairComparerStorage = nil else - table.sort(keys) -- ImGuiStorage is sorted by key + table.sort(keys) -- [Port] ImGuiStorage is sorted by key end it = 1 end @@ -72837,7 +73945,7 @@ function MT.ImGuiSelectionExternalStorage:ApplyRequests(ms_io) end end -end -- do (Typing-Select, Box-Select, Multi-Select) +end -- [Port] do (Typing-Select, Box-Select, Multi-Select) ------------------------------------------------------------------------------- -- [SECTION] Widgets: ListBox @@ -72906,7 +74014,7 @@ end -- This is merely a helper around BeginListBox(), EndListBox(). -- Considering using those directly to submit custom data or store selection differently. --- Overloads: (label, current_item, items[], items_count?, height_in_items?) or (label, current_item, getter, user_data, items_count, height_in_items?) +-- [Port] Overloads: (label, current_item, items[], items_count?, height_in_items?) or (label, current_item, getter, user_data, items_count, height_in_items?) --- @param current_item int # 0-based --- @return int current_item --- @return bool value_changed @@ -73011,7 +74119,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local v_min = 3.4028234663853e+38 --[[FLT_MAX]] local v_max = -3.4028234663853e+38 --[[FLT_MAX]] for i = 1, values_count do - local v = values_getter(data, i) -- NaN isn't checked here + local v = values_getter(data, i) -- [Port] NaN isn't checked here v_min = ImMin(v_min, v) v_max = ImMax(v_max, v) @@ -73830,7 +74938,7 @@ end do --[[ [SECTION] Widgets: BeginTabBar, EndTabBar, etc. (was imgui_tabs.lua) ]] --- Dear ImGui --- Tab bars & tab items: 1:1 port of imgui_widgets.cpp [SECTION] Widgets: BeginTabBar/BeginTabItem (docking branch) +-- [Port] Tab bars & tab items: 1:1 port of imgui_widgets.cpp [SECTION] Widgets: BeginTabBar/BeginTabItem (docking branch) -- -- Port notes: -- - tab_bar.Tabs is an ImVector of ImGuiTabItem tables (references). C++ pointer arithmetic on the array is replaced by @@ -73883,7 +74991,7 @@ local function GetTabBarRefFromTabBar(tab_bar) return ImGuiPtrOrIndex(tab_bar) end --- Stable sorts (C++ ImQsort is not stable, but the comparers are total orders in practice) +-- [Port] Stable sorts (C++ ImQsort is not stable, but the comparers are total orders in practice) local function SortTabsBySection(tab_bar) table.sort(tab_bar.Tabs.Data, TabItemComparerBySection) end @@ -73915,7 +75023,7 @@ end -- Shrink excess width from a set of item, by removing width from the larger items first. -- Set items Width to -1.0f to disable shrinking this item. --- items: 1-based array of ImGuiShrinkWidthItem, `first` = 1-based index of first item, `count` items +-- [Port] items: 1-based array of ImGuiShrinkWidthItem, `first` = 1-based index of first item, `count` items function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) if count <= 0 then return end if count == 1 then @@ -74138,7 +75246,7 @@ function ImGui.TabBarLayout(tab_bar) local tabs = tab_bar.Tabs local tab_dst_n = 0 local need_sort_by_section = false - local sections = { ImGuiTabBarSection(), ImGuiTabBarSection(), ImGuiTabBarSection() } -- Layout sections: Leading, Central, Trailing (1-based: [1]=Leading,[2]=Central,[3]=Trailing) + local sections = { ImGuiTabBarSection(), ImGuiTabBarSection(), ImGuiTabBarSection() } -- [Port] Layout sections: Leading, Central, Trailing (1-based: [1]=Leading,[2]=Central,[3]=Trailing) for tab_src_n = 0, tabs.Size - 1 do local tab = tabs.Data[tab_src_n + 1] if tab.LastFrameVisible < tab_bar.PrevFrameVisible or tab.WantClose then @@ -74208,7 +75316,7 @@ function ImGui.TabBarLayout(tab_bar) -- Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central -- (whereas our tabs are stored as: leading, central, trailing) - -- (shrink_buffer_indexes holds 0-based offsets) + -- [Port] (shrink_buffer_indexes holds 0-based offsets) local shrink_buffer_indexes = { 0, sections[1].TabCount + sections[3].TabCount, sections[1].TabCount } local swb = g.ShrinkWidthBuffer swb:resize(tabs.Size) @@ -74617,7 +75725,7 @@ function ImGui.TabBarProcessReorder(tab_bar) if bit32.band(tab2.Flags, 32 --[[ImGuiTabItemFlags.NoReorder]]) ~= 0 then return false end if bit32.band(tab1.Flags, 192 --[[ImGuiTabItemFlags.SectionMask_]]) ~= bit32.band(tab2.Flags, 192 --[[ImGuiTabItemFlags.SectionMask_]]) then return false end - -- Move tab1 to tab2's position, shifting the tabs in between + -- [Port] Move tab1 to tab2's position, shifting the tabs in between table.remove(tab_bar.Tabs.Data, tab1_order + 1) table.insert(tab_bar.Tabs.Data, tab2_order + 1, tab1) @@ -75208,10 +76316,10 @@ end __FILES['imstb_rectpack.lua'] = function() --- Dear ImGui --- This is a Lua port of original `imstb_rectpack.h` +-- [Port] This is a Lua port of original `imstb_rectpack.h` --- ALL TABLES IN THIS FILE ARE 1-BASED! --- Avoids table creation when possible +-- [Port] ALL TABLES IN THIS FILE ARE 1-BASED! +-- [Port] Avoids table creation when possible -- [DEAR IMGUI] -- This is a slightly modified version of stb_rect_pack.h 1.01. @@ -75481,7 +76589,7 @@ function stbrp_init_target(context, width, height, nodes, num_nodes) end -- find minimum y position if it starts at x1 --- Returns (min_y, waste_area) +-- [Port] Returns (min_y, waste_area) --- @param c stbrp_context --- @param first stbrp_node --- @param x0 int @@ -75872,7 +76980,7 @@ end __FILES['imstb_textedit.lua'] = function() --- Dear ImGui --- This is a Lua port of original `imstb_textedit.h` +-- [Port] This is a Lua port of original `imstb_textedit.h` -- [DEAR IMGUI] -- This is a slightly modified version of stb_textedit.h 1.14. @@ -75911,7 +77019,7 @@ __FILES['imstb_textedit.lua'] = function() -- -- Uses the C runtime function 'memmove', which you can override -- by defining IMSTB_TEXTEDIT_memmove before the implementation. --- (In this port: ImStb.TEXTEDIT_memmove.) +-- [Port] (In this port: ImStb.TEXTEDIT_memmove.) -- -- -- VERSION HISTORY @@ -76089,7 +77197,7 @@ __FILES['imstb_textedit.lua'] = function() -- efficient, but it's not horrible on modern computers. But you wouldn't -- want to edit million-line files with it. --- ALL TABLES IN THIS FILE ARE 1-BASED! +-- [Port] ALL TABLES IN THIS FILE ARE 1-BASED! -- Character Indexing: -- idx=n, the n'th char (1-based) -- Cursor Indexing: @@ -76328,7 +77436,7 @@ end local stb_text_locate_coord do --- only create once, reuse later +-- [Port] only create once, reuse later local r = StbTexteditRow() --- traverse the layout to locate the nearest character to a display position @@ -76837,7 +77945,7 @@ function stb_textedit_key(str, state, key) if not is_page and state.single_line then -- on windows, up&down in single-line behave like left&right key = bit32.bor(2097153 --[[STB_TEXTEDIT_K_RIGHT]], bit32.band(key, 4194304 --[[STB_TEXTEDIT_K_SHIFT]])) - return stb_textedit_key(str, state, key) -- was `goto retry` + return stb_textedit_key(str, state, key) -- [Port] was `goto retry` end if sel then @@ -76910,7 +78018,7 @@ function stb_textedit_key(str, state, key) if not is_page and state.single_line then -- on windows, up&down become left&right key = bit32.bor(2097152 --[[STB_TEXTEDIT_K_LEFT]], bit32.band(key, 4194304 --[[STB_TEXTEDIT_K_SHIFT]])) - return stb_textedit_key(str, state, key) -- was `goto retry` + return stb_textedit_key(str, state, key) -- [Port] was `goto retry` end if sel then @@ -77414,7 +78522,7 @@ end __FILES['imstb_truetype.lua'] = function() --- Dear ImGui --- This is a Lua port of original `imstb_truetype.h` +-- [Port] This is a Lua port of original `imstb_truetype.h` -- [DEAR IMGUI] -- This is a slightly modified version of stb_truetype.h 1.26. @@ -77491,7 +78599,7 @@ __FILES['imstb_truetype.lua'] = function() -- accurately measures pixel coverage for anti-aliasing, except in the case -- where multiple shapes overlap, in which case it overestimates the AA pixel -- coverage. Thus, anti-aliasing of intersecting shapes may look wrong. --- (This port only implements the new rasterizer.) +-- [Port] (This port only implements the new rasterizer.) -- -- ADDITIONAL DOCUMENTATION -- @@ -77609,7 +78717,7 @@ local STBTT_MS_EID = { -- encodingID for STBTT_PLATFORM_ID_MICROSOFT UNICODE_FULL = 10 } --- original enum doesn't have a name, so we name it +-- [Port] original enum doesn't have a name, so we name it --- @enum STBTT_VTX local STBTT_VTX = { MOVE = 1, @@ -78208,7 +79316,7 @@ local function stbtt_InitFont_internal(info, data, fontstart) info.fdselect = stbtt__new_buf(nil, 0) -- @TODO this should use size from table (not 512MB) - info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- PORT: 64MB here instead of 512MB + info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- [Port] 64MB here instead of 512MB local b = info.cff -- read the header @@ -78499,7 +79607,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) if numberOfContours > 0 then local endPtsOfContours = g + 10 local ins = ttUSHORT(data, endPtsOfContours + numberOfContours * 2) - local points = (endPtsOfContours + numberOfContours * 2 + 2 + ins) + 1 -- 1-based idx + local points = (endPtsOfContours + numberOfContours * 2 + 2 + ins) + 1 -- [Port] 1-based idx local n = 1 + ttUSHORT(data, endPtsOfContours + numberOfContours * 2 - 2) local m = n + 2 * numberOfContours -- a loose bound on how many vertices we might need @@ -78719,7 +79827,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) end -- Append vertices. - if num_vertices == 0 then -- LUA: No malloc + if num_vertices == 0 then -- [Port] No malloc vertices = comp_verts else for i = 1, comp_num_vertices do @@ -78869,7 +79977,7 @@ local function stbtt__run_charstring(info, glyph_index, c) local has_subrs = 0 local clear_stack - local s = {} -- size = 48, 0-based + local s = {} -- [Port] size = 48, 0-based local subr_stack = {} for i = 1, 10 do subr_stack[i] = stbtt__buf() end @@ -79600,8 +80708,8 @@ end local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y) local active = nil - local scanline = {} -- size = result.w, 0-based - local scanline2 = {} -- size = result.w + 1, 0-based + local scanline = {} -- [Port] size = result.w, 0-based + local scanline2 = {} -- [Port] size = result.w + 1, 0-based STBTT__NOTUSED(vsubsample) @@ -79686,7 +80794,7 @@ end --- @param a stbtt__edge --- @param b stbtt__edge local STBTT__COMPARE = function(a, b) - if a.y0 == nil then return false end -- sentinels on the back + if a.y0 == nil then return false end -- [Port] sentinels on the back if b.y0 == nil then return true end return a.y0 < b.y0 end @@ -79895,7 +81003,7 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) local num_contours = n if n == 0 then return nil end - local contour_lengths = {} -- size = n + local contour_lengths = {} -- [Port] size = n -- make two passes through the points so we don't need to realloc for pass = 0, 1 do @@ -80202,15 +81310,15 @@ end __FILES['imstd_minstdio.lua'] = function() --- Dear ImGui --- This is a minimal Lua impl of C-like sscanf, sprintf sub-set +-- [Port] This is a minimal Lua impl of C-like sscanf, sprintf sub-set --- Supports: +-- [Port] Supports: -- - %x, %X, %nx, %nX (where n is a number) -- - %d, %nd, %u, %nu (where n is a number) -- - length modifiers h, hh, l, ll, I64 on integers: ll/I64 = 64-bit range (doubles: exact only within +-2^53) -- - %f, %lf (very limited) -- --- Returns items_matched instead of EOF on error +-- [Port] Returns items_matched instead of EOF on error local _byte = string.byte @@ -80243,7 +81351,7 @@ local function hex_digit_to_int(c) if c >= CHAR_A and c <= CHAR_F then return c - CHAR_A + 10 end end --- we force this behavior by default +-- [Port] we force this behavior by default local function clamp_if_overflow(spec, val, is_64) if spec == CHAR_d or spec == CHAR_x or spec == CHAR_X then local max = is_64 and 9223372036854775807 or 2147483647 --[[INT_MAX]] @@ -80264,7 +81372,7 @@ end --- @param result table # table to store parsed values local function sscanf(buffer, buffer_begin, format, result) local p = buffer_begin - local f = 1 -- format_begin + local f = 1 -- [Port] format_begin local format_len = #format local assigned = 0 local items_matched = 0 @@ -80291,10 +81399,10 @@ local function sscanf(buffer, buffer_begin, format, result) break end - -- encountered % in fmt + -- [Port] encountered % in fmt f = f + 1 - -- %% + -- [Port] %% if _byte(format, f, f) == CHAR_PERCENT then if buffer[p] == CHAR_PERCENT then p = p + 1 @@ -80306,7 +81414,7 @@ local function sscanf(buffer, buffer_begin, format, result) break end - -- handle optional width + -- [Port] handle optional width local width = 0 while isdigit(_byte(format, f, f)) do width = width * 10 + _byte(format, f, f) - CHAR_0 @@ -80316,7 +81424,7 @@ local function sscanf(buffer, buffer_begin, format, result) width = math.huge end - -- length modifiers + -- [Port] length modifiers local n_l = 0 while _byte(format, f, f) == CHAR_l or _byte(format, f, f) == CHAR_h do if _byte(format, f, f) == CHAR_l then n_l = n_l + 1 end @@ -80336,7 +81444,7 @@ local function sscanf(buffer, buffer_begin, format, result) elseif spec == CHAR_d or spec == CHAR_u then base = 10 elseif spec == CHAR_f or spec == CHAR_F then - is_float = true -- TODO: distinguish %lf from %f? + is_float = true -- [Port] TODO: distinguish %lf from %f? else return items_matched end @@ -80356,7 +81464,7 @@ local function sscanf(buffer, buffer_begin, format, result) p = p + 1 end - -- inf, nan are not handled + -- [Port] inf, nan are not handled local p_start = p local int_part = 0 @@ -80384,7 +81492,7 @@ local function sscanf(buffer, buffer_begin, format, result) val = sign * (int_part + frac_part / frac_div) else local sign = 1 - -- optional sign + -- [Port] optional sign if base == 10 then if buffer[p] == CHAR_PLUS then p = p + 1 @@ -80403,7 +81511,6 @@ local function sscanf(buffer, buffer_begin, format, result) end if p == p_start then - -- failed to match return items_matched end @@ -80420,7 +81527,7 @@ local function sscanf(buffer, buffer_begin, format, result) end end if spec == CHAR_u and val < 0 then - val = val + (is_64 and 18446744073709551616 or 4294967296) -- unsigned wrap-around like strtoul() + val = val + (is_64 and 18446744073709551616 or 4294967296) -- [Port] unsigned wrap-around like strtoul() end end @@ -80901,21 +82008,26 @@ return { ImGuiWindowSettings = ImGuiWindowSettings, ImGuiWindowStackData = ImGuiWindowStackData, ImGui_ImplRoblox = ImGui_ImplRoblox, + ImGui_ImplRoblox_BeginParallelFrame = ImGui_ImplRoblox_BeginParallelFrame, ImGui_ImplRoblox_CreateTexture = ImGui_ImplRoblox_CreateTexture, ImGui_ImplRoblox_DestroyTexture = ImGui_ImplRoblox_DestroyTexture, - ImGui_ImplRoblox_GetBackendData = ImGui_ImplRoblox_GetBackendData, + ImGui_ImplRoblox_DisableParallel = ImGui_ImplRoblox_DisableParallel, + ImGui_ImplRoblox_EnableParallel = ImGui_ImplRoblox_EnableParallel, + ImGui_ImplRoblox_FinishParallel = ImGui_ImplRoblox_FinishParallel, + ImGui_ImplRoblox_GetParallelConfig = ImGui_ImplRoblox_GetParallelConfig, + ImGui_ImplRoblox_GetParallelStats = ImGui_ImplRoblox_GetParallelStats, + ImGui_ImplRoblox_GetStats = ImGui_ImplRoblox_GetStats, ImGui_ImplRoblox_Init = ImGui_ImplRoblox_Init, ImGui_ImplRoblox_NewFrame = ImGui_ImplRoblox_NewFrame, - ImGui_ImplRoblox_RenderDrawData = ImGui_ImplRoblox_RenderDrawData, ImGui_ImplRoblox_SetBusyRenderRate = ImGui_ImplRoblox_SetBusyRenderRate, + ImGui_ImplRoblox_SetEditableImageCap = ImGui_ImplRoblox_SetEditableImageCap, ImGui_ImplRoblox_SetOverlay = ImGui_ImplRoblox_SetOverlay, ImGui_ImplRoblox_SetProfiling = ImGui_ImplRoblox_SetProfiling, ImGui_ImplRoblox_SetRedrawBudget = ImGui_ImplRoblox_SetRedrawBudget, ImGui_ImplRoblox_SetRenderRate = ImGui_ImplRoblox_SetRenderRate, ImGui_ImplRoblox_SetRenderScale = ImGui_ImplRoblox_SetRenderScale, + ImGui_ImplRoblox_SetStageTiming = ImGui_ImplRoblox_SetStageTiming, ImGui_ImplRoblox_SetTextProxy = ImGui_ImplRoblox_SetTextProxy, - ImGui_ImplRoblox_Shutdown = ImGui_ImplRoblox_Shutdown, - ImGui_ImplRoblox_UpdateTexture = ImGui_ImplRoblox_UpdateTexture, ImHashData = ImHashData, ImHashStr = ImHashStr, ImHashStrRaw = ImHashStrRaw, @@ -81052,7 +82164,6 @@ return { ShowExampleAppWindowTitles = ShowExampleAppWindowTitles, ShowExampleMenuFile = ShowExampleMenuFile, ShowTableColumnsStatusFlags = ShowTableColumnsStatusFlags, - TILE_SIZE = TILE_SIZE, UINT_MAX = UINT_MAX, VTX_STRIDE = VTX_STRIDE, _PathArcToFastExXY = _PathArcToFastExXY, diff --git a/build/ImGuiTyped.luau b/build/ImGuiTyped.luau index 303e8dc..cfaa28a 100644 --- a/build/ImGuiTyped.luau +++ b/build/ImGuiTyped.luau @@ -991,8 +991,38 @@ export type ImGuiStyleVar = { Alpha: number, DisabledAlpha: number, WindowPaddin export type ImGuiTreeNodeFlags = { None: number, Selected: number, Framed: number, AllowOverlap: number, NoTreePushOnOpen: number, NoAutoOpenOnLog: number, DefaultOpen: number, OpenOnDoubleClick: number, OpenOnArrow: number, Leaf: number, Bullet: number, FramePadding: number, SpanAvailWidth: number, SpanFullWidth: number, SpanLabelWidth: number, SpanAllColumns: number, LabelSpanAllColumns: number, NavLeftJumpsToParent: number, DrawLinesNone: number, DrawLinesFull: number, DrawLinesToNodes: number, NoNavFocus: number, ClipLabelForTrailingButton: number, UpsideDownArrow: number, CollapsingHeader: number, OpenOnMask_: number, DrawLinesMask_: number, [string]: number } export type ImGuiViewportFlags = { None: number, IsPlatformWindow: number, IsPlatformMonitor: number, OwnedByApp: number, NoDecoration: number, NoTaskBarIcon: number, NoFocusOnAppearing: number, NoFocusOnClick: number, NoInputs: number, NoRendererClear: number, NoAutoMerge: number, TopMost: number, CanHostOtherWindows: number, IsMinimized: number, IsFocused: number, [string]: number } export type ImGuiWindowFlags = { None: number, NoTitleBar: number, NoResize: number, NoMove: number, NoScrollbar: number, NoScrollWithMouse: number, NoCollapse: number, AlwaysAutoResize: number, NoBackground: number, NoSavedSettings: number, NoMouseInputs: number, MenuBar: number, HorizontalScrollbar: number, NoFocusOnAppearing: number, NoBringToFrontOnFocus: number, AlwaysVerticalScrollbar: number, AlwaysHorizontalScrollbar: number, NoNavInputs: number, NoNavFocus: number, UnsavedDocument: number, NoDocking: number, DockNodeHost: number, ChildWindow: number, Tooltip: number, Popup: number, Modal: number, ChildMenu: number, NoNav: number, NoDecoration: number, NoInputs: number, [string]: number } +export type ImGuiParallelConfig = { Actors: number?, MinTiles: number?, MinPixels: number?, MaxBytesPerPixel: number?, Worker: any, Sync: boolean?, SyncDrop: boolean?, Inline: boolean?, [string]: any } +export type ImGuiImplRoblox = { + Init: (...any) -> ...any, + Shutdown: (...any) -> ...any, + NewFrame: (...any) -> ...any, + RenderDrawData: (...any) -> ...any, + AddFile: (...any) -> ...any, + CreateTexture: (...any) -> ...any, + DestroyTexture: (...any) -> ...any, + SetOverlay: (...any) -> ...any, + SetTextProxy: (...any) -> ...any, + SetRenderScale: (...any) -> ...any, + GetRenderScale: (...any) -> ...any, + SetRenderRate: (...any) -> ...any, + SetBusyRenderRate: (...any) -> ...any, + SetRedrawBudget: (...any) -> ...any, + SetProfiling: (...any) -> ...any, + IsProfiling: (...any) -> ...any, + SetStageTiming: (...any) -> ...any, + GetStats: (...any) -> ...any, + SetEditableImageCap: (...any) -> ...any, + EnableParallel: (opts: ImGuiParallelConfig?) -> (), + DisableParallel: () -> (), + FinishParallel: () -> (), + BeginParallelFrame: () -> (), + GetParallelStats: () -> { [string]: number }, + GetParallelConfig: () -> ImGuiParallelConfig, + [string]: any, +} export type ImGuiModule = { ImGui: ImGuiAPI, + ImGui_ImplRoblox: ImGuiImplRoblox, ImVec2: (x: number?, y: number?, z: number?, w: number?) -> ImVec2, ImVec4: (x: number?, y: number?, z: number?, w: number?) -> ImVec4, ImDrawFlags: ImDrawFlags, diff --git a/build/ImGuiWorker.client.luau b/build/ImGuiWorker.client.luau new file mode 100644 index 0000000..57415e6 --- /dev/null +++ b/build/ImGuiWorker.client.luau @@ -0,0 +1,497 @@ +--!optimize 2 +-- GENERATED by tools/bundle.py from backends/roblox/worker.luau + raster.lua - do not edit +-- Parallel raster worker (Actor LocalScript). The build inlines raster.lua for the Raster line. +local Actor = script:GetActor() +if not Actor then + return +end + +local Raster = (function() +-- Software rasterizer: pure buffer code shared by the backend and the parallel worker (inlined into ImGuiWorker). +-- Target: RGBA8 row-major (ImU32 is already R | G<<8 | B<<16 | A<<24), non-premultiplied "over" onto transparent. +local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 +local readf64 = buffer.readf64 +local band, rshift = bit32.band, bit32.rshift +local readi32 = buffer.readi32 + +local M = { + TILE = 128, + -- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs. + -- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2), tex id (-1: none), clip x0 y0 x1 y1, + -- bounds x0 y0 x1 y1 (screen pixels, i32), then raw vertices (VTX bytes: x y u v f64, col u32): a at REC_A, + -- c at REC_C, b at REC_B. + -- T job: tox toy (f64), x0 y0 nr count (i32), nr x rect x0 y0 x1 y1 (i32, tile pixels), count x P offset (i32). + VTX = 36, REC = 148, REC_A = 40, REC_C = 76, REC_B = 112, JOB = 32, +} +local TILE = M.TILE + +local TargetBuffer: buffer, TargetWidth = buffer.create(0), 0 +local PrevRow = buffer.create(1024) + +-- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else +-- remembers this row. u32 loop, not readstring ==: that allocated a string per row. +@native +local function RowRepeats(o: number, len: number, has_prev: boolean): boolean + if has_prev then + local same = true + for k = 0, len - 4, 4 do + if readu32(TargetBuffer, o + k) ~= readu32(PrevRow, k) then + same = false + break + end + end + if same then return true end + end + if buffer.len(PrevRow) < len then PrevRow = buffer.create(len) end + buffer.copy(PrevRow, 0, TargetBuffer, o, len) + return false +end +local RectColumns = table.create(256, 0) + +-- FillSpan and DrawTriangle's flat path inline this math with per-span constants: keep them in sync. +@native +local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number, b: number, a: number) + if a >= 255 then + writeu32(TargetBuffer, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080) + return + end + if a <= 0 then return end + local d = readu32(TargetBuffer, o) + if d < 16777216 then + writeu32(TargetBuffer, o, + floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216) + return + end + local sa = a / 255 + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + local ns = 1 - sa + writeu32(TargetBuffer, o, + floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256 + floor(b * sa + db * ns + 0.5) * 65536 + + 4278190080) + else + local k = rshift(d, 24) * ((1 - sa) / 255) + local oa = sa + k + local inv = 1 / oa + writeu32(TargetBuffer, o, floor((r * sa + dr * k) * inv + 0.5) + floor((g * sa + dg * k) * inv + 0.5) * 256 + + floor((b * sa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + end +end + +@native +local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number, + b: number, a: number) + if a <= 0 then return end + local w4 = (x1 - x0 - 1) * 4 + if a >= 255 then + local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080 + local first = (y0 * TargetWidth + x0) * 4 + for o = first, first + w4, 4 do writeu32(TargetBuffer, o, packed) end + for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end + return + end + local packed0 = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216 + local sa = a / 255 + local ns = 1 - sa + local c1 = ns / 255 + local rs, gs, bs = r * sa, g * sa, b * sa + local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination + for y = y0, y1 - 1 do + local o0 = (y * TargetWidth + x0) * 4 + for o = o0, o0 + w4, 4 do + local d = readu32(TargetBuffer, o) + if d == last_d then + writeu32(TargetBuffer, o, last_v) + elseif d < 16777216 then + writeu32(TargetBuffer, o, packed0) + else + last_d = d + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + last_v = floor(rs + dr * ns + 0.5) + floor(gs + dg * ns + 0.5) * 256 + + floor(bs + db * ns + 0.5) * 65536 + 4278190080 + else + local k = rshift(d, 24) * c1 + local oa = sa + k + local inv = 1 / oa + last_v = floor((rs + dr * k) * inv + 0.5) + floor((gs + dg * k) * inv + 0.5) * 256 + + floor((bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 + end + writeu32(TargetBuffer, o, last_v) + end + end + end +end + +@native +local function UnpackColor(col: number) + return col % 256, floor(col / 256) % 256, floor(col / 65536) % 256, floor(col / 16777216) % 256 +end + +@native +local function SampleTexture(t, u: number, v: number) + local tw, th = t.Width, t.Height + local tx, ty = floor(u * tw), floor(v * th) + if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end + if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end + local o = (ty * tw + tx) * 4 + local tb = t.Buffer + return readu8(tb, o), readu8(tb, o + 1), readu8(tb, o + 2), readu8(tb, o + 3) +end + +@native +local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, u0: number, v0: number, + u1: number, v1: number, col: number, t, cx0: number, cy0: number, cx1: number, cy1: number) + local r, g, b, a = UnpackColor(col) + if a == 0 then return end + local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0) + local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1) + if px0 >= px1 or py0 >= py1 then return end + + if not t or (u0 == u1 and v0 == v1) then + if t then + local tr, tg, tb, ta = SampleTexture(t, u0, v0) + r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255 + end + if a <= 0 then return end + if a >= 255 or px1 - px0 < 32 then + FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a) + return + end + -- Wide translucent rect: rows usually blend over identical rows, so copy the previous row's result + local len = (px1 - px0) * 4 + local prev_o = 0 + for y = py0, py1 - 1 do + local o = (y * TargetWidth + px0) * 4 + if RowRepeats(o, len, y > py0) then + buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len) + else + FillSpan(TargetBuffer, y, y + 1, px0, px1, r, g, b, a) + end + prev_o = o + end + return + end + + local du, dv = (u1 - u0) / (x1 - x0), (v1 - v0) / (y1 - y0) + local tw: number, th: number, tbuf: buffer, dbuf: buffer = t.Width, t.Height, t.Buffer, TargetBuffer + local r255, g255, b255, a255 = r / 255, g / 255, b / 255, a / 255 + local ncol = px1 - px0 + local cols = RectColumns + for c = 1, ncol do + local tx = floor((u0 + (px0 + c - 1 + 0.5 - x0) * du) * tw) + if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end + cols[c] = tx * 4 + end + for y = py0, py1 - 1 do + local ty = floor((v0 + (y + 0.5 - y0) * dv) * th) + if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end + local trow4 = ty * tw * 4 + local o = (y * TargetWidth + px0) * 4 + for c = 1, ncol do + local tv = readu32(tbuf, trow4 + cols[c]) + if tv >= 16777216 then + local sa = rshift(tv, 24) * a255 + local sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, + band(rshift(tv, 16), 255) * b255 + if sa >= 255 then + writeu32(dbuf, o, floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + 4278190080) + else + BlendPixel(dbuf, o, sr, sg, sb, sa) + end + end + o = o + 4 + end + end +end + +@native +local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, vc: number, t, cx0: number, cy0: number, + cx1: number, cy1: number, ox: number, oy: number) + local x0, y0 = readf64(vbuf, va) - ox, readf64(vbuf, va + 8) - oy + local x1, y1 = readf64(vbuf, vb) - ox, readf64(vbuf, vb + 8) - oy + local x2, y2 = readf64(vbuf, vc) - ox, readf64(vbuf, vc + 8) - oy + local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0) + if area == 0 then return end + if area < 0 then + vb, vc = vc, vb + x1, y1, x2, y2 = x2, y2, x1, y1 + area = -area + end + + local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1) + local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1) + if minx > maxx or miny > maxy then return end + + local A0, B0 = y1 - y2, x2 - x1 + local C0 = -(A0 * x1 + B0 * y1) + local A1, B1 = y2 - y0, x0 - x2 + local C1 = -(A1 * x2 + B1 * y2) + local A2, B2 = y0 - y1, x1 - x0 + local C2 = -(A2 * x0 + B2 * y0) + local tl0 = A0 > 0 or (A0 == 0 and B0 > 0) + local tl1 = A1 > 0 or (A1 == 0 and B1 > 0) + local tl2 = A2 > 0 or (A2 == 0 and B2 > 0) + + local inv = 1 / area + local n0, n1, n2 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0 + local ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32)) + local rb, gb, bb, ab = UnpackColor(readu32(vbuf, vb + 32)) + local rc, gc, bc, ac = UnpackColor(readu32(vbuf, vc + 32)) + local ua, vva, ub, vvb, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vb + 16), + readf64(vbuf, vb + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) + + local textured = t and not (ua == ub and ua == uc and vva == vvb and vva == vvc) + if t and not textured then -- constant uv (atlas white pixel): fold the texel into the vertex colours + local tr, tg, tb, ta = SampleTexture(t, ua, vva) + ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255 + rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255 + rc, gc, bc, ac = rc * tr / 255, gc * tg / 255, bc * tb / 255, ac * ta / 255 + end + local flat = not textured and ra == rb and ra == rc and ga == gb and ga == gc and ba == bb and ba == bc and aa == ab + and aa == ac + if flat and aa <= 0 then return end + local f_opaque, f_packed, f_sa, f_ns, f_c1, f_rs, f_gs, f_bs = false, 0, 0, 0, 0, 0, 0, 0 + if flat then + f_opaque = aa >= 255 + f_packed = floor(ra + 0.5) + floor(ga + 0.5) * 256 + floor(ba + 0.5) * 65536 + + (f_opaque and 4278190080 or floor(aa + 0.5) * 16777216) + f_sa = aa / 255 + f_ns = 1 - f_sa + f_c1 = f_ns / 255 + f_rs, f_gs, f_bs = ra * f_sa, ga * f_sa, ba * f_sa + end + + for y = miny, maxy do + local py = y + 0.5 + local xl, xr = minx, maxx + local e0, e1, e2 = B0 * py + C0, B1 * py + C1, B2 * py + C2 + -- (e * n is -e / A within an ulp; the 1e-6 margin covers that, and the exact tests below decide) + if A0 > 0 then + xl = max(xl, floor(e0 * n0 - 0.500001)) + elseif A0 < 0 then + xr = min(xr, ceil(e0 * n0 - 0.499999)) + end + if A1 > 0 then + xl = max(xl, floor(e1 * n1 - 0.500001)) + elseif A1 < 0 then + xr = min(xr, ceil(e1 * n1 - 0.499999)) + end + if A2 > 0 then + xl = max(xl, floor(e2 * n2 - 0.500001)) + elseif A2 < 0 then + xr = min(xr, ceil(e2 * n2 - 0.499999)) + end + + while xl <= xr do + local px = xl + 0.5 + local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2 + if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then + break + end + xl += 1 + end + while xr > xl do + local px = xr + 0.5 + local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2 + if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then + break + end + xr -= 1 + end + if xl > xr then continue end + local o = (y * TargetWidth + xl) * 4 + if flat then + local o1 = o + (xr - xl) * 4 + if f_opaque then + for oo = o, o1, 4 do writeu32(dbuf, oo, f_packed) end + continue + end + local last_d, last_v = -1, 0 + for oo = o, o1, 4 do + local d = readu32(dbuf, oo) + if d == last_d then + writeu32(dbuf, oo, last_v) + elseif d < 16777216 then + writeu32(dbuf, oo, f_packed) + else + last_d = d + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + last_v = floor(f_rs + dr * f_ns + 0.5) + floor(f_gs + dg * f_ns + 0.5) * 256 + + floor(f_bs + db * f_ns + 0.5) * 65536 + 4278190080 + else + local k = rshift(d, 24) * f_c1 + local oa = f_sa + k + local inv = 1 / oa + last_v = floor((f_rs + dr * k) * inv + 0.5) + floor((f_gs + dg * k) * inv + 0.5) * 256 + + floor((f_bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 + end + writeu32(dbuf, oo, last_v) + end + end + continue + end + for x = xl, xr do + local px = x + 0.5 + local w0, w1, w2 = (A0 * px + e0) * inv, (A1 * px + e1) * inv, (A2 * px + e2) * inv + local a = w0 * aa + w1 * ab + w2 * ac + if textured then + local r = w0 * ra + w1 * rb + w2 * rc + local g = w0 * ga + w1 * gb + w2 * gc + local b = w0 * ba + w1 * bb + w2 * bc + local tr, tg, tb, ta = SampleTexture(t, w0 * ua + w1 * ub + w2 * uc, w0 * vva + w1 * vvb + w2 * vvc) + BlendPixel(dbuf, o, r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255) + elseif a > 0 then + BlendPixel(dbuf, o, w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc, + w0 * ba + w1 * bb + w2 * bc, a) + end + o += 4 + end + end +end + +-- Linear gradient quad, constant uv. kind 1: along y (ca top, cb bottom), 2: along x. Same pixels as the triangles. +@native +local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, ca: number, + cb: number, kind: number, t, u: number, v: number, cx0: number, cy0: number, cx1: number, cy1: number) + local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0) + local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1) + if px0 >= px1 or py0 >= py1 then return end + local ra, ga, ba, aa = UnpackColor(ca) + local rb, gb, bb, ab = UnpackColor(cb) + if t then + local tr, tg, tb, ta = SampleTexture(t, u, v) + ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255 + rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255 + end + if kind == 1 then + local inv = 1 / (y1 - y0) + for y = py0, py1 - 1 do + local f = (y + 0.5 - y0) * inv + local nf = 1 - f + FillSpan(TargetBuffer, y, y + 1, px0, px1, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, + aa * nf + ab * f) + end + else + local inv = 1 / (x1 - x0) + local len = (px1 - px0) * 4 + local opaque = aa >= 255 and ab >= 255 + local prev_o = 0 + for y = py0, py1 - 1 do + local o = (y * TargetWidth + px0) * 4 + if y > py0 and (opaque or RowRepeats(o, len, true)) + or (y == py0 and not opaque and RowRepeats(o, len, false)) then + buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len) + else + local oo = o + for x = px0, px1 - 1 do + local f = (x + 0.5 - x0) * inv + local nf = 1 - f + BlendPixel(TargetBuffer, oo, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f) + oo = oo + 4 + end + end + prev_o = o + end + end +end + +function M.SetTarget(buf: buffer, width: number) + TargetBuffer, TargetWidth = buf, width +end + +@native +function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number) + local rw = rx1 - rx0 + if rw == TargetWidth then + buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4) + else + for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4, 0, rw * 4) end + end +end + +@native +function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: number) + for y = 0, rh - 1 do + buffer.copy(dst, y * rw * 4, TargetBuffer, ((ry0 + y) * TargetWidth + rx0) * 4, rw * 4) + end +end + +-- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2 +@native +local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, tox: number, toy: number, + cx0: number, cy0: number, cx1: number, cy1: number) + if kind == 0 then + DrawTriangle(TargetBuffer, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, tox, toy) + return + end + local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox, + readf64(vbuf, vc + 8) - toy + if kind == 1 then + DrawRect(TargetBuffer, ax, ay, cx, cy, readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16), + readf64(vbuf, vc + 24), readu32(vbuf, va + 32), t, cx0, cy0, cx1, cy1) + else + DrawRectGradient(TargetBuffer, ax, ay, cx, cy, readu32(vbuf, va + 32), readu32(vbuf, vc + 32), kind - 1, t, + readf64(vbuf, va + 16), readf64(vbuf, va + 24), cx0, cy0, cx1, cy1) + end +end +M.DrawPrim = DrawPrim + +-- Packed tile jobs -> one exact-size buffer per rect, in job order (worker + main-thread fallback) +local Scratch = buffer.create(TILE * TILE * 4) +@native +function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } + local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect + local REC_A, REC_B, REC_C = M.REC_A, M.REC_B, M.REC_C + M.SetTarget(Scratch, TILE) + local out, no = {}, 0 + local o = 0 + while o < tlen do + local tox, toy = readf64(T, o), readf64(T, o + 8) + local x0, y0, nr, count = readi32(T, o + 16), readi32(T, o + 20), readi32(T, o + 24), readi32(T, o + 28) + local ro = o + 32 + local po = ro + nr * 16 + o = po + count * 4 + for r = 0, nr - 1 do + local rx0, ry0, rx1, ry1 = readi32(T, ro + r * 16), readi32(T, ro + r * 16 + 4), + readi32(T, ro + r * 16 + 8), readi32(T, ro + r * 16 + 12) + ClearRect(rx0, ry0, rx1, ry1) + for k = 0, count - 1 do + local q = readi32(T, po + k * 4) + local cx0, cy0 = max(readi32(P, q + 8) - x0, rx0), max(readi32(P, q + 12) - y0, ry0) + local cx1, cy1 = min(readi32(P, q + 16) - x0, rx1), min(readi32(P, q + 20) - y0, ry1) + if cx0 >= cx1 or cy0 >= cy1 or readi32(P, q + 24) - x0 >= rx1 or readi32(P, q + 28) - y0 >= ry1 + or readi32(P, q + 32) - x0 <= rx0 or readi32(P, q + 36) - y0 <= ry0 then + continue + end + local tid, t = readi32(P, q + 4), nil + if tid >= 0 then t = textures[tid] end + DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, tox, toy, cx0, cy0, cx1, cy1) + end + local rw, rh = rx1 - rx0, ry1 - ry0 + local sub = buffer.create(rw * rh * 4) + CopySubRect(sub, rx0, ry0, rw, rh) + no += 1 + out[no] = sub + end + end + return out +end + +return M +end)() +local Done = Actor:WaitForChild("Done") +local Textures = {} + +Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength) + for _, Texture in TexUpdates do + Textures[Texture[1]] = { Buffer = Texture[2], Width = Texture[3], Height = Texture[4] } + end + local Results = Raster.RasterJobs(Prims, Tiles, TileLength, Textures) + task.synchronize() + Done:Fire(Id, Results) +end) + +Actor:SetAttribute("Ready", true) diff --git a/build/imgui_love.linemap.json b/build/imgui_love.linemap.json index 325243e..8bed3f2 100644 --- a/build/imgui_love.linemap.json +++ b/build/imgui_love.linemap.json @@ -1 +1 @@ -[[183, "imgui.lua"], [22812, "imgui_demo.lua"], [34670, "imgui_draw.lua"], [42997, "imgui_h.lua"], [45994, "imgui_impl_love.lua"], [46538, "imgui_internal.lua"], [50510, "imgui_tables.lua"], [55602, "imgui_widgets.lua"], [67836, "imstb_rectpack.lua"], [68500, "imstb_textedit.lua"], [70042, "imstb_truetype.lua"], [72830, "imstd_minstdio.lua"]] \ No newline at end of file +[[183, "imgui.lua"], [22784, "imgui_demo.lua"], [34641, "imgui_draw.lua"], [42965, "imgui_h.lua"], [45962, "imgui_impl_love.lua"], [46506, "imgui_internal.lua"], [50472, "imgui_tables.lua"], [55564, "imgui_widgets.lua"], [67798, "imstb_rectpack.lua"], [68462, "imstb_textedit.lua"], [70004, "imstb_truetype.lua"], [72792, "imstd_minstdio.lua"]] \ No newline at end of file diff --git a/build/imgui_love.lua b/build/imgui_love.lua index a8ddc32..cf60f59 100644 --- a/build/imgui_love.lua +++ b/build/imgui_love.lua @@ -421,7 +421,7 @@ __FILES['imgui.lua'] = function() -- - See https://github.com/ocornut/imgui/wiki/Getting-Started, and README.md of this repository. -- - Run and study the examples and demo in imgui_demo.lua to get acquainted with the library. -- - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder --- (backends/imgui_impl_roblox.lua for Roblox, backends/imgui_impl_love.lua for LÖVE). +-- (backends/roblox/imgui_impl_roblox.lua for Roblox, backends/love/imgui_impl_love.lua for LÖVE). -- - Build a single file with tools/bundle.py: build/ImGui.luau (Roblox ModuleScript) or build/imgui_love.lua (LÖVE), -- then require() / load it. All exported names (ImGui, ImVec2, ImVec4, IM_COL32, every ImGui*Flags enum...) are fields of the returned table. -- - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. @@ -524,9 +524,9 @@ __FILES['imgui.lua'] = function() -- ------------------------------------ -- -- A backend implements the usual Dear ImGui contract: Init, NewFrame, RenderDrawData, inputs -> io:AddXXXEvent(), --- texture updates via ImTextureData. Adding another Lua host means a new backends/imgui_impl_.lua. +-- texture updates via ImTextureData. Adding another Lua host means a new backends//imgui_impl_.lua. -- -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for basic instructions. --- -> the backends in backends/imgui_impl_roblox.lua and backends/imgui_impl_love.lua are complete implementations. +-- -> the backends in backends/roblox/imgui_impl_roblox.lua and backends/love/imgui_impl_love.lua are complete implementations. -- -- Basic application/backend skeleton: -- @@ -600,13 +600,12 @@ __FILES['imgui.lua'] = function() -- (Core Code) --- Flags: --- IMGUI_DISABLE_OBSOLETE_FUNCTIONS = true -- This flag is not implemented +-- [Port] IMGUI_DISABLE_OBSOLETE_FUNCTIONS = true -- This flag is not implemented --- NOTE: you must implement ImStd.ImFileOpen if you are not in GMod IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS = true -- Don't implement ImStd.ImFileOpen/ImStd.ImFileClose/ImStd.ImFileRead/ImFileWrite so you can implement them yourself IMGUI_DISABLE_DEBUG_TOOLS = false -- Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty -IMGUI_DISABLE_TIME_FUNCTIONS = false -- Disable setting platform_io.Platform_SessionDate from os.date() in Initialize() +IMGUI_DISABLE_TIME_FUNCTIONS = false -- [Port] Disable setting platform_io.Platform_SessionDate from os.date() in Initialize() -- Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be ~= nil. -- - ImGui.CreateContext() will automatically set this pointer if it is nil. @@ -625,9 +624,9 @@ end ImGui = {} -ImStd = {} -- Contains functions that originally don't belong to cpp namespaces +ImStd = {} -- [Port] Contains functions that originally don't belong to cpp namespaces --- IM_INCLUDE(name) is provided by the bundle (see tools/bundle.py): runs the bundled file once, returns its result. +-- [Port] IM_INCLUDE(name) is provided by the bundle (see tools/bundle.py): runs the bundled file once, returns its result. function ImGui._GetTypeFunc() return type end @@ -656,7 +655,7 @@ function ImGui.MemAlloc(constructor, size) end -- IM_FREE() == ImGui.MemFree() --- This does not set `owner[field]` to nil! +-- [Port] This does not set `owner[field]` to nil! --- @param owner table --- @param field string|int function ImGui.MemFree(owner, field) @@ -718,8 +717,8 @@ IM_INCLUDE"imgui_tables.lua" do --[[ [SECTION] imgui_dragdrop (was imgui_dragdrop.lua) ]] --- Dear ImGui --- Drag and drop: 1:1 port of imgui.cpp [SECTION] DRAG AND DROP (docking branch) --- Payload `Data` is any Lua value (no copy is made). `data_size` is optional and only kept for API parity. +-- [Port] Drag and drop: 1:1 port of imgui.cpp [SECTION] DRAG AND DROP (docking branch) +-- [Port] Payload `Data` is any Lua value (no copy is made). `data_size` is optional and only kept for API parity. ------------------------------------------------------------------------------- -- [SECTION] DRAG AND DROP @@ -1050,15 +1049,15 @@ function ImGui.EndDragDropTarget() if g.DragDropPayload.Delivery then ImGui.ClearDragDrop() end end --- Payload methods (C++ ImGuiPayload members): payload:IsDataType(t) etc. also work through these globals +-- [Port] Payload methods (C++ ImGuiPayload members): payload:IsDataType(t) etc. also work through these globals function ImGui.PayloadIsDataType(payload, t) return ImGuiPayload_IsDataType(payload, t) end end --[[ [SECTION] imgui_dragdrop (was imgui_dragdrop.lua) ]] do --[[ [SECTION] imgui_docking (was imgui_docking.lua) ]] --- Dear ImGui --- Docking: 1:1 port of imgui.cpp [SECTION] DOCKING (docking branch, 1.93 WIP) +-- [Port] Docking: 1:1 port of imgui.cpp [SECTION] DOCKING (docking branch, 1.93 WIP) -- --- Port notes: +-- [Port] Port notes: -- - Main viewport only (no multi-viewports on Roblox): viewport creation/merging code paths are kept where cheap, but -- windows always live in the main viewport. -- - ImGuiDockContext.Nodes (ImGuiStorage in C++) is a Lua table ID -> node. Iterations that upstream does over the @@ -1327,7 +1326,7 @@ end local function IsRectInverted(r) return r.Min.x > r.Max.x or r.Min.y > r.Max.y end ---- Sorted snapshot of node IDs (upstream iterates ImGuiStorage which is sorted by key) +--- [Port] Sorted snapshot of node IDs (upstream iterates ImGuiStorage which is sorted by key) local function DockContextNodesSorted(ctx) local ids = {} for id in pairs(ctx.DockContext.Nodes) do ids[#ids + 1] = id end @@ -1862,7 +1861,7 @@ local function FixLargeWindowsWhenUndocking(size, ref_viewport) end function ImGui.DockContextProcessUndockWindow(ctx, window, clear_persistent_docking_ref) - if clear_persistent_docking_ref == nil then clear_persistent_docking_ref = true end -- C++ default argument + if clear_persistent_docking_ref == nil then clear_persistent_docking_ref = true end -- [Port] C++ default argument if window.DockNode then ImGui.DockNodeRemoveWindow(window.DockNode, window, clear_persistent_docking_ref and 0 or window.DockId) else @@ -2108,7 +2107,7 @@ function ImGui.DockNodeMoveWindows(dst_node, src_node) end -- Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar(). - -- Snapshot: DockNodeAddWindow() won't touch src_node.Windows since window.DockNode is cleared first + -- [Port] Snapshot: DockNodeAddWindow() won't touch src_node.Windows since window.DockNode is cleared first local windows = {} for i = 1, src_node.Windows.Size do windows[i] = src_node.Windows.Data[i] end for _, window in ipairs(windows) do @@ -2807,7 +2806,7 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) end -- If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value - local tabs_unsorted_start = tab_bar.Tabs.Size -- 0-based + local tabs_unsorted_start = tab_bar.Tabs.Size -- [Port] 0-based local tab_n = tab_bar.Tabs.Size - 1 while tab_n >= 0 and bit32.band(tab_bar.Tabs.Data[tab_n + 1].Flags, 8388608 --[[ImGuiTabItemFlags.Unsorted]]) ~= 0 do -- FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting? @@ -3054,12 +3053,12 @@ function ImGui.DockNodeCalcTabBarLayout(node) return out_title_rect, r, window_menu_button_pos, out_close_button_pos end ---- Modifies pos_old/size_old/pos_new/size_new in place (ImVec2 tables) +--- [Port] Modifies pos_old/size_old/pos_new/size_new in place (ImVec2 tables) function ImGui.DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, dir, size_new_desired) local g = ImGui.GetCurrentContext() local dock_spacing = g.Style.ItemInnerSpacing.x local axis = (dir == 0 --[[ImGuiDir.Left]] or dir == 1 --[[ImGuiDir.Right]]) and 1 --[[ImGuiAxis.X]] or 2 --[[ImGuiAxis.Y]] - local a, o = axis, 3 - axis -- the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index + local a, o = axis, 3 - axis -- [Port] the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index pos_new[o] = pos_old[o] size_new[o] = size_old[o] @@ -3544,7 +3543,7 @@ function ImGui.DockNodeTreeUpdateSplitter(node) -- Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally) local axis = node.SplitAxis assert(axis ~= 0 --[[ImGuiAxis.None]]) - local a, o = axis, 3 - axis -- the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index + local a, o = axis, 3 - axis -- [Port] the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index local bb = ImRect(ImVec2(child_0.Pos.x, child_0.Pos.y), ImVec2(child_1.Pos.x, child_1.Pos.y)) bb.Min[a] = bb.Min[a] + child_0.Size[a] bb.Max[o] = bb.Max[o] + child_1.Size[o] @@ -4698,7 +4697,7 @@ DockSettingsHandler_WriteAll = function(ctx, handler, buf) end ------------------------------------------------------------------------------- --- Docking: helpers (imgui_internal.h inlines) + widgets used by docking +-- [Port] Docking: helpers (imgui_internal.h inlines) + widgets used by docking ------------------------------------------------------------------------------- function ImGui.DockNodeGetRootNode(node) @@ -4769,7 +4768,7 @@ function ImGui.RenderArrowDockMenu(draw_list, p_min, sz, col) ImGui.RenderArrowPointingAt(draw_list, p_min + ImVec2(sz * 0.50, sz * 0.85), ImVec2(sz * 0.30, sz * 0.40), 3 --[[ImGuiDir.Down]], col) end --- Upstream CollapseButton (docking branch): replaces the port's simpler version +-- [Port] Upstream CollapseButton (docking branch): replaces the port's simpler version -- The Collapse button also functions as a Dock Menu button. function ImGui.CollapseButton(id, pos, dock_node) local g = ImGui.GetCurrentContext() @@ -4781,7 +4780,6 @@ function ImGui.CollapseButton(id, pos, dock_node) if is_clipped then return pressed end -- Render - --local is_dock_menu = (window.DockNodeAsHost and not window.Collapsed) local bg_col = ImGui.GetColorU32((held and hovered) and 24 --[[ImGuiCol.ButtonActive]] or (hovered and 23 --[[ImGuiCol.ButtonHovered]] or 22 --[[ImGuiCol.Button]])) local text_col = ImGui.GetColorU32(0 --[[ImGuiCol.Text]]) if hovered or held then @@ -4879,7 +4877,7 @@ local TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5, 1.0) -- Multiplied by g.Style.M local IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111 -- Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter. local string = string -ImFormatString = string.format -- TODO: an simplified version that operates on byte tables directly? +ImFormatString = string.format --- @module "imstd_minstdio" ImStd.sscanf = IM_INCLUDE"imstd_minstdio.lua" @@ -4891,47 +4889,34 @@ local bit32 = bit32 -- [SECTION] MISC HELPERS/UTILITIES (File functions) ------------------------------------------------------------------------------- ---- This closes the _file. +--- [Port] This closes the _file. --- @param _file any # File object function IM_FILE_CLOSE(_file) end ---- This returns the size of _file in bytes. +--- [Port] This returns the size of _file in bytes. --- @param _file any # File object --- @return int function IM_FILE_SIZE(_file) return -1 end ---- This writes _str into _file. +--- [Port] This writes _str into _file. --- @param _file any # File object --- @param _str string function IM_FILE_WRITE(_file, _str) end ---- This reads the specified _count of chars and returns them as a binary string. +--- [Port] This reads the specified _count of chars and returns them as a binary string. --- @param _file any # File object --- @param _count int --- @return string function IM_FILE_READ(_file, _count) return "" end ---- This opens the file at _filename in _mode and returns the File object. +--- [Port] This opens the file at _filename in _mode and returns the File object. --- @param _filename string --- @param _mode string # e.g. "rb" --- @return any function ImStd.ImFileOpen(_filename, _mode) end ---- [GMod] Platform specific -if gmod then - IM_FILE_CLOSE = FindMetaTable("File").Close --- @type function - IM_FILE_SIZE = FindMetaTable("File").Size --- @type function - IM_FILE_WRITE = FindMetaTable("File").Write --- @type function - IM_FILE_READ = FindMetaTable("File").Read --- @type function -end - -- Default file functions if not IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS then - --- [GMod] Another Platform specific - if gmod then - function ImStd.ImFileOpen(filename, mode) return file.Open(filename, mode, "GAME") end - end - function ImStd.ImFileClose(f) IM_FILE_CLOSE(f) end function ImStd.ImFileGetSize(f) return IM_FILE_SIZE(f) end @@ -4939,7 +4924,7 @@ if not IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS then --- @param data table # 1-based table to store result data --- @param count int # Amount of bytes to read from `f` function ImStd.ImFileRead(f, data, count) - local CHUNK_SIZE = 8000 -- We don't read byte by byte + local CHUNK_SIZE = 8000 -- [Port] We don't read byte by byte local offset = 0 while offset < count do @@ -5055,7 +5040,7 @@ local ImGuiResizeGripDef = { -- Data for resizing from borders -- InnerDir: Normal toward inside, SegmentN1/SegmentN2: End positions, normalized (0,0: upper left), OuterAngle: Angle toward outside ---- [1] Left, [2] Right, [3] Up, [4] Down +--- [Port] [1] Left, [2] Right, [3] Up, [4] Down local ImGuiResizeBorderDef = { {InnerDir = ImVec2( 1, 0), SegmentN1 = ImVec2( 0, 1), SegmentN2 = ImVec2( 0, 0), OuterAngle = IM_PI * 1.00}, -- Left {InnerDir = ImVec2(-1, 0), SegmentN1 = ImVec2( 1, 0), SegmentN2 = ImVec2( 1, 1), OuterAngle = IM_PI * 0.00}, -- Right @@ -5120,13 +5105,12 @@ end -- Zero-terminated string hash, with support for ### to reset back to seed value. -- e.g. "label###id" outputs the same hash as "id" (and "label" is generally displayed by the UI functions) --- Use FNV1a, as one ImGui FIXME suggested +-- [Port] Use FNV1a, as one ImGui FIXME suggested --- @param str string --- @param size int? --- @param seed int? --- @return int -- [Luau] memo for whole-string hashes: labels are re-hashed with the same seed every frame. --- ponytail: whole-memo reset at HASH_MEMO_MAX entries, LRU if ID churn makes it thrash local hash_memo, hash_memo_n, HASH_MEMO_MAX = {}, 0, 16384 local ImHashStrRaw @@ -5151,7 +5135,7 @@ end function ImHashStrRaw(str, size, seed) if str == "" or size == 0 then - return seed -- need to match cpp code edge case behavior while using FNV ourselves + return seed -- [Port] need to match cpp code edge case behavior while using FNV ourselves end local FNV_OFFSET_BASIS = 0x811C9DC5 @@ -5331,7 +5315,6 @@ function ImStd.ImTextFindValidUtf8CodepointEnd(text, in_text_start, in_text_end, local prev = ImStd.ImTextFindPreviousUtf8Codepoint(text, in_text_start, in_p) local prev_c_len, prev_c = ImStd.ImTextCharFromUtf8(text, prev, in_text_end) - -- Check if the previous character is valid and fits within the range if prev_c ~= 65533 --[[IM_UNICODE_CODEPOINT_INVALID]] and prev_c_len <= (in_p - prev) then return in_p end @@ -5515,7 +5498,7 @@ end -- Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible. --- @param buf char[] function ImStd.ImStrTrimBlanks(buf) - local p = 1 -- buf_begin + local p = 1 -- [Port] buf_begin while buf[p] == 32 or buf[p] == 9 do -- Leading blanks p = p + 1 end @@ -5854,7 +5837,7 @@ local GLocalizationEntriesEnUS = { } -- [Luau] Default platform handlers (upstream: next to the metrics section; defined here so Initialize() can see the local). --- Roblox has no shell: IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS path. Default clipboard/IME handlers are OS-specific: left nil +-- [Port] Roblox has no shell: IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS path. Default clipboard/IME handlers are OS-specific: left nil -- (the backends install their own clipboard handlers). local function Platform_OpenInShellFn_DefaultImpl(ctx, path) return false end @@ -6088,7 +6071,7 @@ end ------------------------------------------------------------------------------- -- [SECTION] SETTINGS --- (in-memory .ini; Roblox has no disk) +-- [Port] (in-memory .ini; Roblox has no disk) ------------------------------------------------------------------------------- -- - UpdateSettings() [Internal] -- - MarkIniSettingsDirty() [Internal] @@ -6119,7 +6102,7 @@ function ImGui.UpdateSettings() if g.SettingsDirtyTimer > 0.0 then g.SettingsDirtyTimer = g.SettingsDirtyTimer - g.IO.DeltaTime if g.SettingsDirtyTimer <= 0.0 then - -- No disk: always let the user know they can call SaveIniSettingsToMemory() + -- [Port] No disk: always let the user know they can call SaveIniSettingsToMemory() g.IO.WantSaveIniSettings = true -- Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves. g.SettingsDirtyTimer = 0.0 end @@ -6197,7 +6180,7 @@ function ImGui.LoadIniSettingsFromDisk(ini_filename) end -- Zero-tolerance, no error reporting, cheap .ini parsing --- Set ini_size==0 (or nil) to use the whole string (Lua strings know their length). +-- [Port] Set ini_size==0 (or nil) to use the whole string (Lua strings know their length). function ImGui.LoadIniSettingsFromMemory(ini_data, ini_size) local g = GImGui assert(g.Initialized) @@ -6249,7 +6232,7 @@ end function ImGui.SaveIniSettingsToDisk(ini_filename) local g = GImGui g.SettingsDirtyTimer = 0.0 - -- Roblox: no disk. Call SaveIniSettingsToMemory() and persist the string yourself (e.g. DataStore). + -- [Port] Roblox: no disk. Call SaveIniSettingsToMemory() and persist the string yourself (e.g. DataStore). end -- Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer @@ -6270,7 +6253,7 @@ function ImGui.CreateNewWindowSettings(name) -- Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier. if not g.IO.ConfigDebugIniSettings then - -- ImHashSkipUncontributingPrefix: skip everything up to the last "###" + -- [Port] ImHashSkipUncontributingPrefix: skip everything up to the last "###" local p = name:match("^.*()###") if p then name = name:sub(p) end end @@ -6455,7 +6438,7 @@ end local function LogTextV_Internal(g, fmt, ...) local s = (select("#", ...) > 0) and string.format(fmt, ...) or fmt if g.LogFile then - print(s) -- TTY (the only "file" available on Roblox) + print(s) -- [Port] TTY (the only "file" available on Roblox) else g.LogBuffer:append(s) end @@ -6471,7 +6454,7 @@ ImGui.LogTextV = ImGui.LogText -- Internal version that takes a position to decide on newline placement and pad items according to their depth. -- We split text into individual lines to add current tree level padding -- FIXME: This code is a little complicated perhaps, considering simplifying the whole system. ---- `text` is a Lua string, `text_begin/text_end` optional 1-based byte range (text_end exclusive). +--- [Port] `text` is a Lua string, `text_begin/text_end` optional 1-based byte range (text_end exclusive). function ImGui.LogRenderedText(ref_pos, text, text_end, text_begin) local g = GImGui local window = g.CurrentWindow @@ -6551,7 +6534,7 @@ end -- Start logging/capturing text output to given file function ImGui.LogToFile(auto_open_depth, filename) - -- Roblox: no file access. Falls back to TTY (output window). + -- [Port] Roblox: no file access. Falls back to TTY (output window). ImGui.LogToTTY(auto_open_depth) end @@ -7176,7 +7159,7 @@ function ImGui.GetWindowContentRegionMax() return window.ContentRegionRect.Max - window.Pos end --- Overloads: IsRectVisible(size) / IsRectVisible(rect_min, rect_max) +-- [Port] Overloads: IsRectVisible(size) / IsRectVisible(rect_min, rect_max) function ImGui.IsRectVisible(a, b) local window = GImGui.CurrentWindow if b == nil then @@ -7697,14 +7680,14 @@ function ImGui.BringWindowToDisplayBehind(window, behind_window) local g = GImGui window = window.RootWindow behind_window = behind_window.RootWindow - local pos_wnd = ImGui.FindWindowDisplayIndex(window) + 1 -- 1-based + local pos_wnd = ImGui.FindWindowDisplayIndex(window) + 1 -- [Port] 1-based local pos_beh = ImGui.FindWindowDisplayIndex(behind_window) + 1 local data = g.Windows.Data if pos_wnd < pos_beh then - for i = pos_wnd, pos_beh - 2 do data[i] = data[i + 1] end -- memmove + for i = pos_wnd, pos_beh - 2 do data[i] = data[i + 1] end -- [Port] memmove data[pos_beh - 1] = window else - for i = pos_wnd, pos_beh + 1, -1 do data[i] = data[i - 1] end -- memmove + for i = pos_wnd, pos_beh + 1, -1 do data[i] = data[i - 1] end -- [Port] memmove data[pos_beh] = window end end @@ -7969,7 +7952,7 @@ function MT.ImGuiWindow:GetIDFromRectangle(r_abs) return ImHashData({ math.floor(r_rel.Min.x), math.floor(r_rel.Min.y), math.floor(r_rel.Max.x), math.floor(r_rel.Max.y) }, 4, seed) end --- Overloads: GetID(str_id) / GetID(str_id_begin, str_id_end) / GetID(int_id) +-- [Port] Overloads: GetID(str_id) / GetID(str_id_begin, str_id_end) / GetID(int_id) --- @param str_or_int string|int --- @param str_end? int # exclusive end (1-based byte position) --- @return ImGuiID @@ -7984,7 +7967,7 @@ end -- Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call -- (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level. -- for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more) --- Overloads: GetIDWithSeed(str, str_end, seed) / GetIDWithSeed(n, seed) +-- [Port] Overloads: GetIDWithSeed(str, str_end, seed) / GetIDWithSeed(n, seed) function ImGui.GetIDWithSeed(a, b, c) local id if type(a) == "number" then @@ -9352,7 +9335,7 @@ local function IsKeyChordPotentiallyCharInput(key_chord) if key == 0 --[[ImGuiKey.None]] then return false end - return g.KeysMayBeCharInput:TestBit(key + 1) -- TestBit requires 1-based index + return g.KeysMayBeCharInput:TestBit(key + 1) -- [Port] TestBit requires 1-based index end -- Request a desired route for an input chord (key + mods). @@ -9807,7 +9790,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) local key = e.Key.Key assert(key ~= 0 --[[ImGuiKey.None]]) - -- TODO: Also gets 0-based index here, consider making key_data storage 1-based + -- [Port] TODO: Also gets 0-based index here, consider making key_data storage 1-based local key_data, key_data_index = ImGui.GetKeyData(g, key) if trickle_fast_inputs and key_data.Down ~= e.Key.Down and (key_changed_mask:TestBit(key_data_index + 1) or mouse_button_changed ~= 0) then @@ -10292,7 +10275,7 @@ end -- Handle resize for: Resize Grips, Borders, Gamepad -- Return true when using auto-fit (double-click on resize grip) --- Returns (ret_auto_fit_mask, border_hovered, border_held) +-- [Port] Returns (ret_auto_fit_mask, border_hovered, border_held) --- @param window ImGuiWindow --- @param resize_grip_count int --- @param resize_grip_col table @@ -11150,7 +11133,7 @@ ImGui.RenderWindowOuterBorders = RenderWindowOuterBorders -- When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead. -- Render title text, collapse button, close button --- Returns the updated 'open' value (nil when there is no close button) +-- [Port] Returns the updated 'open' value (nil when there is no close button) --- @param window ImGuiWindow --- @param title_bar_rect ImRect --- @param name string @@ -11307,7 +11290,7 @@ function ImGui.UpdateWindowSkipRefresh(window) c.ScrollX, c.ScrollY, c.DisplayX, c.DisplayY = window.Scroll.x, window.Scroll.y, ds.x, ds.y return end - -- skip: widgets early-out on SkipItems and Begin() returns visible=false; End() restores it + -- [Port] skip: widgets early-out on SkipItems and Begin() returns visible=false; End() restores it window.CacheSkipItemsBackup = window.SkipItems window.SkipItems = true end @@ -11417,7 +11400,7 @@ end --- @param pos ImVec2 --- @param cond? ImGuiCond function ImGui.SetWindowPos(window, pos, cond) - -- Overloads: SetWindowPos(pos, cond) / SetWindowPos(name, pos, cond) / SetWindowPos(window, pos, cond) + -- [Port] Overloads: SetWindowPos(pos, cond) / SetWindowPos(name, pos, cond) / SetWindowPos(window, pos, cond) if type(window) == "string" then window = ImGui.FindWindowByName(window) if window == nil then return end @@ -11555,7 +11538,7 @@ function ImGui.GetWindowSize() return ImGui.GetCurrentWindowRead().Size end --- Overloads: SetWindowFocus() / SetWindowFocus(name). Passing nil name removes focus. +-- [Port] Overloads: SetWindowFocus() / SetWindowFocus(name). Passing nil name removes focus. --- @param name? string function ImGui.SetWindowFocus(...) if select("#", ...) == 0 then @@ -11700,7 +11683,6 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) -- Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument. local ImGuiChildFlags_SupportedMask_ = bit32.bor(1 --[[ImGuiChildFlags.Borders]], 2 --[[ImGuiChildFlags.AlwaysUseWindowPadding]], 4 --[[ImGuiChildFlags.ResizeX]], 8 --[[ImGuiChildFlags.ResizeY]], 16 --[[ImGuiChildFlags.AutoResizeX]], 32 --[[ImGuiChildFlags.AutoResizeY]], 64 --[[ImGuiChildFlags.AlwaysAutoResize]], 128 --[[ImGuiChildFlags.FrameStyle]], 256 --[[ImGuiChildFlags.NavFlattened]]) - -- IM_UNUSED(ImGuiChildFlags_SupportedMask_) assert(bit32.band(child_flags, bit32.bnot(ImGuiChildFlags_SupportedMask_)) == 0, "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?") assert(bit32.band(window_flags, 64 --[[ImGuiWindowFlags.AlwaysAutoResize]]) == 0, "Cannot specify ImGuiWindowFlags.AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags.AlwaysAutoResize!") if bit32.band(child_flags, 64 --[[ImGuiChildFlags.AlwaysAutoResize]]) ~= 0 then @@ -11814,7 +11796,7 @@ end -- Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'. -- ImGuiChildFlags.Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details! --- `true` is accepted as ImGuiChildFlags.Borders for legacy code. +-- [Port] `true` is accepted as ImGuiChildFlags.Borders for legacy code. --- @param str_id_or_id string|ImGuiID --- @param size_arg? ImVec2 --- @param child_flags? ImGuiChildFlags|bool @@ -11963,7 +11945,7 @@ function ImGui.SetNextWindowClass(window_class) local g = GImGui g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, 8192 --[[ImGuiNextWindowDataFlags.HasWindowClass]]) local wc = ImGuiWindowClass() - for k, v in pairs(window_class) do wc[k] = v end -- C++ copies the struct + for k, v in pairs(window_class) do wc[k] = v end -- [Port] C++ copies the struct g.NextWindowData.WindowClass = wc end @@ -11990,7 +11972,7 @@ function ImGui.SetNextWindowCached(key) end function ImGui.GetWindowDpiScale() - return 1.0 -- Roblox: single viewport, no DPI scaling + return 1.0 -- [Port] Roblox: single viewport, no DPI scaling end function ImGui.GetWindowViewport() @@ -12090,7 +12072,7 @@ function ImGui.IsPopupOpen(id, popup_flags) local g = GImGui if popup_flags == nil then popup_flags = 0 end if type(id) == "string" then - -- str_id overload: with AnyPopupId the id must be 0, otherwise it is hashed with the current window's ID stack + -- [Port] str_id overload: with AnyPopupId the id must be 0, otherwise it is hashed with the current window's ID stack id = (bit32.band(popup_flags, 1024 --[[ImGuiPopupFlags.AnyPopupId]]) ~= 0) and 0 or g.CurrentWindow:GetID(id) end @@ -12220,7 +12202,6 @@ function ImGui.TranslateWindow(window, delta) ImVec2_Copy(window.DC.IdealMaxPos, window.DC.IdealMaxPos + delta) end ---- ImGui::FindWindowByID function ImGui.FindWindowByID(id) local g = GImGui @@ -13225,7 +13206,7 @@ end if bit32.band(flags, 8388608 --[[ImGuiWindowFlags.DockNodeHost]]) == 0 and not window.SkipRefresh then ImGui.PushClipRect(window.InnerClipRect.Min, window.InnerClipRect.Max, true) - -- [Roblox backend] content clip + scroll origin: lets the backend move scrolled content instead of redrawing it + -- [Port] [Roblox backend] content clip + scroll origin: lets the backend move scrolled content instead of redrawing it local dl, cr = window.DrawList, window.DrawList._CmdHeader.ClipRect dl._ContentClipX0, dl._ContentClipY0, dl._ContentClipX1, dl._ContentClipY1 = cr.x, cr.y, cr.z, cr.w dl._ScrollOriginX, dl._ScrollOriginY = window.Pos.x - window.Scroll.x, window.Pos.y - window.Scroll.y @@ -13399,8 +13380,8 @@ function ImGui.End() g.CurrentWindowStack:pop_back() - -- LUA: No "Ternary Operator", since lua (... and (1) or (2)) will eval (1) and (2) no matter what - -- so something like `SetCurrentWindow((g.CurrentWindowStack.Size == 0) and nil or g.CurrentWindowStack:back().Window)` will error + -- [Port] No "Ternary Operator", since lua (... and (1) or (2)) will eval (1) and (2) no matter what + -- [Port] so something like `SetCurrentWindow((g.CurrentWindowStack.Size == 0) and nil or g.CurrentWindowStack:back().Window)` will error if (g.CurrentWindowStack.Size == 0) then SetCurrentWindow(nil) else @@ -13556,7 +13537,7 @@ local function FindHoveredWindowEx(pos, find_first_and_in_any_viewport) if window.HitTestHoleSize.x ~= 0 then local hx, hy = window.Pos.x + window.HitTestHoleOffset.x, window.Pos.y + window.HitTestHoleOffset.y if pos.x >= hx and pos.y >= hy and pos.x < hx + window.HitTestHoleSize.x and pos.y < hy + window.HitTestHoleSize.y then - break -- continue + break -- [Port] continue end end @@ -13900,7 +13881,7 @@ local function LockWheelingWindow(window, wheel_amount) if (g.WheelingWindow == window) then return end - -- IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL") + -- [Port] IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL") g.WheelingWindow = window ImVec2_Copy(g.WheelingWindowRefMousePos, g.IO.MousePos) if window == nil then @@ -14002,7 +13983,6 @@ function ImGui.UpdateMouseWheel() if window == window.RootWindow then local offset = window.Size * (1.0 - scale) * (g.IO.MousePos - window.Pos) / window.Size ImGui.SetWindowPos(window, window.Pos + offset, 0) - -- MarkIniSettingsDirty(window) end return end @@ -14194,7 +14174,7 @@ end local function GetViewportBgFgDrawList(viewport, drawlist_no, drawlist_name) -- Create the draw list on demand, because they are not frequently used for all viewports local g = GImGui - assert(drawlist_no <= 2) -- IM_COUNTOF(viewport->BgFgDrawLists) + assert(drawlist_no <= 2) -- [Port] IM_COUNTOF(viewport->BgFgDrawLists) local draw_list = viewport.BgFgDrawLists[drawlist_no] if draw_list == nil then draw_list = ImDrawList(g.DrawListSharedData) @@ -14353,7 +14333,6 @@ function ImGui.NewFrame() g.MenusIdSubmittedThisFrame:resize(0) -- Calculate frame-rate for the user, as a purely luxurious feature - -- FIXME: are lines below correct and necessary g.FramerateSecPerFrameAccum = g.FramerateSecPerFrameAccum + (g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]) g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % 60 @@ -14687,7 +14666,7 @@ function ImGui.EndFrame() if viewport == nil then viewport = ImGui.GetMainViewport() end - -- IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f) for Viewport 0x%08X", ime_data.WantVisible, ime_data.InputPos.x, ime_data.InputPos.y, viewport.ID) + -- [Port] IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f) for Viewport 0x%08X", ime_data.WantVisible, ime_data.InputPos.x, ime_data.InputPos.y, viewport.ID) g.PlatformIO.Platform_SetImeDataFn(g, viewport, ime_data) end g.WantTextInputNextFrame = ime_data.WantTextInput @@ -14908,7 +14887,6 @@ function ImGui.Shutdown() IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == nil, "Forgot to shutdown Platform backend?") IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == nil, "Forgot to shutdown Renderer backend?") for _, viewport in g.Viewports:iter() do - -- IM_UNUSED(viewport) IM_ASSERT_USER_ERROR(viewport.RendererUserData == nil and viewport.PlatformUserData == nil and viewport.PlatformHandle == nil, "Backend or app forgot to call DestroyPlatformWindows()?") end @@ -15181,7 +15159,7 @@ function ImGui.ColorConvertHSVtoRGB(h, s, v) return p, q, v elseif i == 4 then return t, p, v - else -- i == 5 or default + else -- [Port] i == 5 or default return v, p, q end end @@ -15335,7 +15313,7 @@ local GStyleVarsInfo = { ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextPadding"), -- ImGuiStyleVar.SeparatorTextPadding ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DockingSeparatorSize"), -- ImGuiStyleVar.DockingSeparatorSize } -assert(#GStyleVarsInfo == ImGuiStyleVar.COUNT) -- IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar_COUNT) +assert(#GStyleVarsInfo == ImGuiStyleVar.COUNT) -- [Port] IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar_COUNT) --- @param idx ImGuiStyleVar --- @return ImGuiStyleVarInfo @@ -15358,7 +15336,7 @@ function ImGui.PushStyleVar(idx, val) g.StyleVarStack:push_back(ImGuiStyleMod(idx, var)) if type(val) == "number" then g.Style[var_info.Key] = val - else -- copy into the style's own ImVec2: storing the caller's vector would alias it into the style forever + else -- [Port] copy into the style's own ImVec2: storing the caller's vector would alias it into the style forever var.x = val.x; var.y = val.y end end @@ -15830,7 +15808,7 @@ function ImGui.SetScrollHereY(center_y_ratio) window.ScrollTargetEdgeSnapDist.y = ImMax(0.0, window.WindowPadding.y - spacing_y) end --- Overloads: SetScrollX(scroll_x) / SetScrollX(window, scroll_x) +-- [Port] Overloads: SetScrollX(scroll_x) / SetScrollX(window, scroll_x) --- @param window ImGuiWindow|float --- @param scroll_x float? function ImGui.SetScrollX(window, scroll_x) @@ -16083,7 +16061,7 @@ function ImGui.OpenPopupEx(id, popup_flags) ImVec2_Copy(popup_ref.OpenMousePos, popup_ref.OpenPopupPos) end - -- IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id) + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id) if g.OpenPopupStack.Size < current_stack_size + 1 then g.OpenPopupStack:push_back(popup_ref) return true @@ -16173,7 +16151,7 @@ function ImGui.ClosePopupsOverWindow(ref_window, restore_focus_to_window_under_p end end if popup_count_to_keep < g.OpenPopupStack.Size then -- This test is not required but it allows to set a convenient breakpoint on the statement below - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window and ref_window.Name or "") + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window and ref_window.Name or "") ImGui.ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup) end end @@ -16182,17 +16160,16 @@ end --- @param restore_focus_to_window_under_popup bool function ImGui.ClosePopupToLevel(remaining, restore_focus_to_window_under_popup) local g = GImGui - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup) + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup) assert(remaining >= 0 and remaining < g.OpenPopupStack.Size) - -- if bit32.band(g.DebugLogFlags, ImGuiDebugLogFlags.EventPopup) ~= 0 then - -- for n = remaining + 1, g.OpenPopupStack.Size do - -- local popup = g.OpenPopupStack.Data[n] - -- IMGUI_DEBUG_LOG_POPUP("[popup] - Closing PopupID 0x%08X Window \"%s\"", popup.PopupId, popup.Window and popup.Window.Name or nil) - -- end - -- end + -- [Port] if bit32.band(g.DebugLogFlags, ImGuiDebugLogFlags.EventPopup) ~= 0 then + -- [Port] for n = remaining + 1, g.OpenPopupStack.Size do + -- [Port] local popup = g.OpenPopupStack.Data[n] + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] - Closing PopupID 0x%08X Window \"%s\"", popup.PopupId, popup.Window and popup.Window.Name or nil) + -- [Port] end + -- [Port] end -- Trim open popup stack - -- FIXME: is it safer to full copy here? local prev_popup = g.OpenPopupStack.Data[remaining + 1] g.OpenPopupStack:resize(remaining) @@ -16241,7 +16218,7 @@ function ImGui.CloseCurrentPopup() popup_idx = popup_idx - 1 end - -- IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size, popup_idx) + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size, popup_idx) ImGui.ClosePopupToLevel(popup_idx - 1, true) -- A common pattern is to close a popup when selecting a menu item/selectable that will open another window. @@ -16743,7 +16720,7 @@ end function ImGui.SetNavWindow(window) local g = GImGui if g.NavWindow ~= window then - -- IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")", window and window.Name or "") + -- [Port] IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")", window and window.Name or "") g.NavWindow = window g.NavLastValidSelectionUserData = (-1) --[[ImGuiSelectionUserData_Invalid]] end @@ -16808,7 +16785,7 @@ function ImGui.NavRestoreLayer(layer) local prev_nav_window = g.NavWindow g.NavWindow = ImGui.NavRestoreLastChildNavWindow(g.NavWindow) -- FIXME-NAV: Should clear ongoing nav requests? g.NavLastValidSelectionUserData = (-1) --[[ImGuiSelectionUserData_Invalid]] - -- if (prev_nav_window) IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name) + -- [Port] if (prev_nav_window) IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name) end local window = g.NavWindow if window.NavLastIds[layer] ~= 0 then @@ -16852,7 +16829,7 @@ function ImGui.NavInitWindow(window, force_reinit) if window == window.RootWindow or bit32.band(window.Flags, 67108864 --[[ImGuiWindowFlags.Popup]]) ~= 0 or window.NavLastIds[0] == 0 or force_reinit then init_for_nav = true end - -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d", init_for_nav, window->Name, g.NavLayer) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d", init_for_nav, window->Name, g.NavLayer) if init_for_nav then ImGui.SetNavID(0, g.NavLayer, window.NavRootFocusScopeId, ImRect()) g.NavInitRequest = true @@ -17405,7 +17382,7 @@ function ImGui.NavUpdateCreateMoveRequest() -- (preserve most state, which were already set by the NavMoveRequestForward() function) assert(g.NavMoveDir ~= (-1) --[[ImGuiDir.None]] and g.NavMoveClipDir ~= (-1) --[[ImGuiDir.None]]) assert(bit32.band(g.NavMoveFlags, 128 --[[ImGuiNavMoveFlags.Forwarded]]) ~= 0) - -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir) else -- Initiate directional inputs request g.NavMoveDir = (-1) --[[ImGuiDir.None]] @@ -17437,7 +17414,7 @@ function ImGui.NavUpdateCreateMoveRequest() -- Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match) if g.NavMoveSubmitted and g.NavId == 0 then - -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "", g.NavLayer) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "", g.NavLayer) g.NavInitRequest = true; g.NavInitRequestFromMove = true g.NavInitResult.ID = 0 if g.IO.ConfigNavCursorVisibleAuto then -- NO check for _NoNavInputs here as we assume MoveRequests cannot be created. @@ -17459,7 +17436,7 @@ function ImGui.NavUpdateCreateMoveRequest() inner_rect_rel:Translate(ImVec2(next_scroll.x - window.Scroll.x, next_scroll.y - window.Scroll.y)) if (clamp_x or clamp_y) and not inner_rect_rel:Contains(window.NavRectRel[g.NavLayer]) then - -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n") + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n") local pad_x = ImMin(inner_rect_rel:GetWidth(), window.FontRefSize * 0.5) local pad_y = ImMin(inner_rect_rel:GetHeight(), window.FontRefSize * 0.5) -- Terrible approximation for the intent of starting navigation from first fully visible item inner_rect_rel.Min.x = clamp_x and (inner_rect_rel.Min.x + pad_x) or -3.4028234663853e+38 --[[FLT_MAX]] @@ -18103,7 +18080,7 @@ function ImGui.NavInitRequestApplyResult() -- Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) -- FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently. - -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) ImGui.SetNavID(result.ID, g.NavLayer, result.FocusScopeId, result.RectRel) g.NavIdIsAlive = true -- Mark as alive from previous frame as we got a result if result.SelectionUserData ~= (-1) --[[ImGuiSelectionUserData_Invalid]] then @@ -18145,7 +18122,7 @@ function ImGui.NavMoveRequestApplyResult() ImGui.SetNavCursorVisibleAfterMove() end ImGui.NavClearPreferredPosForAxis(axis) -- On a failed move, clear preferred pos for this axis. - -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n") + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n") return end @@ -18177,7 +18154,7 @@ function ImGui.NavMoveRequestApplyResult() end if g.NavWindow ~= result.Window then - -- IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name) + -- [Port] IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name) g.NavWindow = result.Window g.NavLastValidSelectionUserData = (-1) --[[ImGuiSelectionUserData_Invalid]] end @@ -18204,7 +18181,7 @@ function ImGui.NavMoveRequestApplyResult() end -- Apply new NavID/Focus - -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) local root_for_nav = g.NavWindow.RootWindowForNav local preferred_scoring_pos_rel = ImVec2() ImVec2_Copy(preferred_scoring_pos_rel, root_for_nav.NavPreferredScoringPosRel[g.NavLayer]) @@ -18428,7 +18405,7 @@ function ImGui.SetCurrentViewport(current_window, viewport) g.CurrentDpiScale = viewport and viewport.DpiScale or 1.0 g.CurrentViewport = viewport assert(g.CurrentDpiScale > 0.0 and g.CurrentDpiScale < 99.0) -- Typical correct values would be between 1.0f and 4.0f - -- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X", current_window and current_window.Name or "NULL", viewport and viewport.ID or 0) + -- [Port] IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X", current_window and current_window.Name or "NULL", viewport and viewport.ID or 0) if g.IO.ConfigDpiScaleFonts then g.Style.FontScaleDpi = g.CurrentDpiScale @@ -18732,7 +18709,7 @@ function ImGui.UpdateViewportsNewFrame() -- Erase unused viewports if n > 1 and viewport.LastFrameActive < g.FrameCount - 2 then ImGui.DestroyViewport(viewport) - -- n stays the same because we removed an element + -- [Port] n stays the same because we removed an element else local platform_funcs_available = viewport.PlatformWindowCreated @@ -18775,7 +18752,7 @@ function ImGui.UpdateViewportsNewFrame() viewport:UpdateWorkRect() -- Garbage collect transient buffers of recently BG/FG drawlists - for dl_n = 1, 2 do -- IM_COUNTOF(viewport->BgFgDrawLists) + for dl_n = 1, 2 do -- [Port] IM_COUNTOF(viewport->BgFgDrawLists) if viewport.BgFgDrawListsLastTimeActive[dl_n] < memory_compact_start_time and viewport.BgFgDrawLists[dl_n] ~= nil then IM_DELETE(viewport.BgFgDrawLists, dl_n) end @@ -19047,7 +19024,6 @@ function ImGui.DestroyViewport(viewport) assert(not g.PlatformIO.Viewports:contains(viewport)) assert(g.Viewports.Data[viewport.Idx] == viewport) g.Viewports:erase(viewport.Idx) - -- IM_DELETE(viewport) end -- FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten. @@ -19186,7 +19162,6 @@ function ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) -- Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM if window.Viewport.PlatformRequestMove then ImVec2_Copy(window.Pos, window.Viewport.Pos) - -- ImGui.MarkIniSettingsDirty(window) elseif window.Viewport.Pos.x ~= window.Pos.x or window.Viewport.Pos.y ~= window.Pos.y then viewport_rect_changed = true ImVec2_Copy(window.Viewport.Pos, window.Pos) @@ -19195,7 +19170,6 @@ function ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) if window.Viewport.PlatformRequestResize then ImVec2_Copy(window.Size, window.Viewport.Size) ImVec2_Copy(window.SizeFull, window.Viewport.Size) - -- ImGui.MarkIniSettingsDirty(window) elseif window.Viewport.Size.x ~= window.Size.x or window.Viewport.Size.y ~= window.Size.y then viewport_rect_changed = true ImVec2_Copy(window.Viewport.Size, window.Size) @@ -19352,7 +19326,7 @@ function ImGui.UpdatePlatformWindows() local title_end = ImGui.FindRenderedTextEnd(title) local title_hash = ImHashStr(title, title_end - title_begin) if viewport.LastNameHash ~= title_hash then - -- This still creates new strings + -- [Port] This still creates new strings g.PlatformIO.Platform_SetWindowTitle(viewport, string.sub(title, title_begin, title_end - 1)) viewport.LastNameHash = title_hash end @@ -19406,7 +19380,6 @@ function ImGui.RenderPlatformWindowsDefault(platform_render_arg, renderer_render -- Skip the main viewport (index 1 in Lua), which is always fully handled by the application! local platform_io = ImGui.GetPlatformIO() - -- First pass: render all windows for i = 2, platform_io.Viewports.Size do local viewport = platform_io.Viewports.Data[i] if bit32.band(viewport.Flags, 4096 --[[ImGuiViewportFlags.IsMinimized]]) == 0 then @@ -19419,7 +19392,6 @@ function ImGui.RenderPlatformWindowsDefault(platform_render_arg, renderer_render end end - -- Second pass: swap buffers for all windows for i = 2, platform_io.Viewports.Size do local viewport = platform_io.Viewports.Data[i] if bit32.band(viewport.Flags, 4096 --[[ImGuiViewportFlags.IsMinimized]]) == 0 then @@ -20112,7 +20084,7 @@ function MT.ImGuiTextFilter:Clear() self.InputBuf[1] = 0; self:Build() end function MT.ImGuiTextFilter:IsActive() return self._Items.Size ~= 0 end -- Parse filter and split into a format optimal for PassFilter() --- Items are { Text = string (lowercased), CountInclude = int } +-- [Port] Items are { Text = string (lowercased), CountInclude = int } function MT.ImGuiTextFilter:Build() local items = self._Items items:resize(0) @@ -20121,9 +20093,9 @@ function MT.ImGuiTextFilter:Build() local n = 0 while self.InputBuf[n + 1] ~= nil and self.InputBuf[n + 1] ~= 0 do n = n + 1 end local buf = ImGui._ByteArrayToString(self.InputBuf, 1, n + 1) - local buf_e = n + 1 -- exclusive, 1-based + local buf_e = n + 1 -- [Port] exclusive, 1-based local word_b = 1 - local seq_start_idx = -1 -- 1-based index into items, -1 = none + local seq_start_idx = -1 -- [Port] 1-based index into items, -1 = none while word_b < buf_e do -- Trim blanks while word_b < buf_e and ImCharIsBlankA(string.byte(buf, word_b)) do @@ -20217,7 +20189,7 @@ local function GetSkipItemForListClipping() end --- `offset` is a 0-based count of leading ranges to leave alone +-- [Port] `offset` is a 0-based count of leading ranges to leave alone local function ImGuiListClipper_SortAndFuseRanges(ranges, offset) if offset == nil then offset = 0 end if ranges.Size - offset <= 1 then return end @@ -20400,7 +20372,7 @@ local function ImGuiListClipper_StepInternal(clipper) -- Step 1: Let the clipper infer height from first range if clipper.ItemsHeight <= 0.0 then assert(data.StepNo == 1) - -- (no float precision mitigation needed: Luau numbers are doubles) + -- [Port] (no float precision mitigation needed: Luau numbers are doubles) clipper.ItemsHeight = (window.DC.CursorPos.y - clipper.StartPosY) / (clipper.DisplayEnd - clipper.DisplayStart) if clipper.ItemsHeight == 0.0 and clipper.ItemsCount == 2147483647 --[[INT_MAX]] then -- Accept that no item have been submitted if in indeterminate mode. return false @@ -20740,7 +20712,7 @@ function ImGui.ErrorRecoveryTryToRecoverWindowState(state_in) -- IM_ASSERT(g.FocusScopeStack.Size == state_in.SizeOfFocusScopeStack) end --- Lines are stored in g.DebugLogBuf (one chunk per call) +-- [Port] Lines are stored in g.DebugLogBuf (one chunk per call) function ImGui.DebugLog(fmt, ...) ImGui.DebugLogV(fmt, ...) end @@ -20756,7 +20728,7 @@ function ImGui.DebugLogV(fmt, ...) end local str = prefix .. ((select("#", ...) > 0) and string.format(fmt, ...) or fmt) g.DebugLogBuf:append(str) - -- Line index (upstream: g.DebugLogIndex). Lines are complete strings without '\n'. + -- [Port] Line index (upstream: g.DebugLogIndex). Lines are complete strings without '\n'. local lines = g.DebugLogLines for part, nl in string.gmatch(str, "([^\n]*)(\n?)") do lines[#lines] = lines[#lines] .. part @@ -20894,7 +20866,7 @@ do --[[ [SECTION] METRICS/DEBUGGER WINDOW, DEBUG LOG, ID STACK TOOL, FONT DEBUG -- [SECTION] Font atlas / font debugging ------------------------------------------------------------------------------- --- byte buffers for InputText (same as the demo's DemoBuf/DemoBufStr; kept here so the library doesn't need the demo) +-- [Port] byte buffers for InputText (same as the demo's DemoBuf/DemoBufStr; kept here so the library doesn't need the demo) local function DemoBuf(str, size) local t = {} for i = 1, #str do t[i] = string.byte(str, i) end @@ -20948,7 +20920,7 @@ function ImGui.DebugRenderKeyboardPreview(draw_list) local start_pos = ImVec2(board_min.x + 5.0 - key_step.x, board_min.y) local K = ImGuiKey - local keys_to_display = { -- { Row, Col, Label, Key } + local keys_to_display = { -- [Port] { Row, Col, Label, Key } { 0, 0, "", K.Tab }, { 0, 1, "Q", K.Q }, { 0, 2, "W", K.W }, { 0, 3, "E", K.E }, { 0, 4, "R", K.R }, { 1, 0, "", K.CapsLock }, { 1, 1, "A", K.A }, { 1, 2, "S", K.S }, { 1, 3, "D", K.D }, { 1, 4, "F", K.F }, { 2, 0, "", K.LeftShift }, { 2, 1, "Z", K.Z }, { 2, 2, "X", K.X }, { 2, 3, "C", K.C }, { 2, 4, "V", K.V }, @@ -21070,7 +21042,7 @@ function ImGui.DebugNodeFontGlyphsForSrcMask(font, baked, src_mask) local glyph_col = ImGui.GetColorU32(0 --[[ImGuiCol.Text]]) local cell_size = baked.Size * 1 local cell_spacing = ImGui.GetStyle().ItemSpacing.y - -- [port] only scans loaded codepoints (IndexLookup range) instead of the whole 0..0xFFFF range + -- [Port] only scans loaded codepoints (IndexLookup range) instead of the whole 0..0xFFFF range local max_c = baked.IndexLookup.Size - 1 local base = 0 while base <= max_c do @@ -21128,7 +21100,7 @@ local function CalcFontGlyphSrcOverlapMask(atlas, font, codepoint) local src = font.Sources.Data[src_n + 1] local loader = src.FontLoader or atlas.FontLoader if not (loader.FontSrcContainsGlyph ~= nil and loader.FontSrcContainsGlyph(atlas, src, codepoint)) then - break -- continue + break -- [Port] continue end mask = bit32.bor(mask, bit32.lshift(1, src_n)) count = count + 1 @@ -21223,7 +21195,7 @@ function ImGui.DebugNodeFont(font) if ImGui.TreeNode("Glyphs", "Baked at { %.2fpx, d.%.2f }: %d glyphs%s", baked.Size, baked.RasterizerDensity, baked.Glyphs.Size, (baked.LastUsedFrame < (builder.FrameCount or 0) - 1) and " *Unused*" or "") then if ImGui.SmallButton("Load all") then - for c = 0, 0x7F do baked:FindGlyph(c) end -- [port] ASCII only: loading the whole BMP in Luau stalls for seconds + for c = 0, 0x7F do baked:FindGlyph(c) end -- [Port] ASCII only: loading the whole BMP in Luau stalls for seconds end local surface_sqrt = math.floor(math.sqrt(baked.MetricsTotalSurface)) ImGui.Text("Ascent: %f, Descent: %f, Ascent-Descent: %f", baked.Ascent, baked.Descent, baked.Ascent - baked.Descent) @@ -21413,7 +21385,7 @@ function ImGui.ShowDebugLogWindow(p_open) g.DebugLogFlags = bit32.band(g.DebugLogFlags, bit32.bnot(L.EventClipper)) local lines = g.DebugLogLines local count = #lines - if lines[count] == "" then count = count - 1 end -- trailing partial line + if lines[count] == "" then count = count - 1 end -- [Port] trailing partial line local clipper = ImGuiListClipper() clipper:Begin(count) while clipper:Step() do @@ -21440,9 +21412,9 @@ function ImGui.DebugTextUnformattedWithLocateItem(line_begin, line_end) while p <= line_end - 10 do repeat -- [Luau] 1-based (C: p <= line_end - 10 with 0-based offsets) local b0, b1 = string.byte(line_begin, p, p + 1) local hex = string.match(line_begin, "^%x+", p + 2) - if b0 ~= 48 or (b1 ~= 120 and b1 ~= 88) or hex == nil or string.find(string.sub(line_begin, p + 10, p + 10), "^%x") then -- '0', 'x', 'X' + if b0 ~= 48 or (b1 ~= 120 and b1 ~= 88) or hex == nil or string.find(string.sub(line_begin, p + 10, p + 10), "^%x") then -- [Port] '0', 'x', 'X' p = p + 1 - break -- continue + break -- [Port] continue end local id = tonumber(hex, 16) -- [Luau] sscanf("%X") local p0 = ImGui.CalcTextSizeEx(line_begin, 1, p) @@ -21451,7 +21423,7 @@ function ImGui.DebugTextUnformattedWithLocateItem(line_begin, line_end) if ImGui.IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true) then ImGui.DebugLocateItemOnHover(id) end - p = p + 11 -- p += 10, then the loop's p++ + p = p + 11 -- [Port] p += 10, then the loop's p++ until true end end @@ -21631,7 +21603,7 @@ function ImGui.UpdateDebugToolItemPathQuery() end -- [DEBUG] ID Stack tool: hooks called by GetID() family functions --- `data_id` is the string/number that was hashed. +-- [Port] `data_id` is the string/number that was hashed. function ImGui.DebugHookIdInfo(id, data_type, data_id) local g = ImGui.GetCurrentContext() local query = PathQuery(g) @@ -21823,7 +21795,7 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) local pcmd = draw_list.CmdBuffer.Data[cmd_n] if pcmd.UserCallback then ImGui.BulletText("Callback %s, user_data %s", tostring(pcmd.UserCallback), tostring(pcmd.UserCallbackData)) - break -- continue + break -- [Port] continue end local texid_desc = FormatTextureRefForDebugDisplay(pcmd.TexRef) @@ -21835,7 +21807,7 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) ImGui.DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg.ShowDrawCmdMesh, cfg.ShowDrawCmdBoundingBoxes) end if not pcmd_node_open then - break -- continue + break -- [Port] continue end -- Calculate approximate coverage area (touched pixel count) @@ -22409,7 +22381,7 @@ function ImGui.ShowMetricsWindow(p_open) for i = 1, g.PlatformIO.Monitors.Size do ImGui.DebugNodePlatformMonitor(g.PlatformIO.Monitors.Data[i], "Monitor", i - 1) if ImGui.IsItemHovered() then - cfg.HighlightMonitorIdx = i - 1 -- 0-based, like Monitors:index_from_ptr() + cfg.HighlightMonitorIdx = i - 1 -- [Port] 0-based, like Monitors:index_from_ptr() end end if g.FallbackMonitor then ImGui.DebugNodePlatformMonitor(g.FallbackMonitor, "Fallback", 0) end @@ -22644,7 +22616,7 @@ function ImGui.ShowMetricsWindow(p_open) if ImGui.IsMousePosValid() then ImGui.Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y) else ImGui.Text("Mouse pos: ") end ImGui.Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y) ImGui.Text("Mouse down:") - local count = 5 --[[ImGuiMouseButton.COUNT]] -- IM_COUNTOF(io.MouseDown) + local count = 5 --[[ImGuiMouseButton.COUNT]] -- [Port] IM_COUNTOF(io.MouseDown) for i = 0, count - 1 do if ImGui.IsMouseDown(i) then ImGui.SameLine(); ImGui.Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]) end end ImGui.Text("Mouse clicked:") for i = 0, count - 1 do if ImGui.IsMouseClicked(i) then ImGui.SameLine(); ImGui.Text("b%d (%d)", i, io.MouseClickedCount[i]) end end @@ -22805,7 +22777,7 @@ function ImGui.DebugBreakButton(label, description_of_location) end end --[[ [SECTION] METRICS/DEBUGGER WINDOW, DEBUG LOG, ID STACK TOOL, FONT DEBUG ]] -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value end __FILES['imgui_demo.lua'] = function() @@ -24002,7 +23974,7 @@ S.DemoWindowWidgetsColorAndPickers = { color = ImVec4(114.0 / 255.0, 144.0 / 255.0, 154.0 / 255.0, 200.0 / 255.0), base_flags = ImGuiColorEditFlags.None, saved_palette_init = true, - saved_palette = {}, -- 32 x ImVec4, 1-based + saved_palette = {}, -- [Port] 32 x ImVec4, 1-based backup_color = ImVec4(), no_border = false, ref_color = false, @@ -24212,7 +24184,7 @@ end S.DemoWindowWidgetsComboBoxes = { flags = 0, item_selected_idx = 0, -- Here we store our selection data as an index. - filter = nil, -- ImGuiTextFilter, created lazily + filter = nil, -- [Port] ImGuiTextFilter, created lazily item_current_2 = 0, item_current_3 = -1, -- If the selection isn't within 0..count, Combo won't display a preview item_current_4 = 0, @@ -24330,7 +24302,7 @@ S.DemoWindowWidgetsDataTypes = { s16_v = 32767, u16_v = 65535, s32_v = -1, - u32_v = 4294967295, -- (ImU32)-1 + u32_v = 4294967295, -- [Port] (ImU32)-1 s64_v = -1, u64_v = 18446744073709551615, -- (ImU64)-1 [Port] Lua numbers are doubles: 64-bit values are exact only within +-2^53 f32_v = 0.123, @@ -24368,15 +24340,15 @@ function DemoWindowWidgetsDataTypes() local u8_zero, u8_one, u8_fifty, u8_min, u8_max = 0, 1, 50, 0, 255 local s16_zero, s16_one, s16_fifty, s16_min, s16_max = 0, 1, 50, -32768, 32767 local u16_zero, u16_one, u16_fifty, u16_min, u16_max = 0, 1, 50, 0, 65535 - local s32_zero, s32_one, s32_fifty, s32_min, s32_max, s32_hi_a, s32_hi_b = 0, 1, 50, -1073741824, 1073741823, 1073741823 - 100, 1073741823 -- INT_MIN/2, INT_MAX/2 - local u32_zero, u32_one, u32_fifty, u32_min, u32_max, u32_hi_a, u32_hi_b = 0, 1, 50, 0, 2147483647, 2147483647 - 100, 2147483647 -- UINT_MAX/2 + local s32_zero, s32_one, s32_fifty, s32_min, s32_max, s32_hi_a, s32_hi_b = 0, 1, 50, -1073741824, 1073741823, 1073741823 - 100, 1073741823 -- [Port] INT_MIN/2, INT_MAX/2 + local u32_zero, u32_one, u32_fifty, u32_min, u32_max, u32_hi_a, u32_hi_b = 0, 1, 50, 0, 2147483647, 2147483647 - 100, 2147483647 -- [Port] UINT_MAX/2 local s64_zero, s64_one, s64_fifty, s64_min, s64_max, s64_hi_a, s64_hi_b = 0, 1, 50, LLONG_MIN / 2, LLONG_MAX / 2, LLONG_MAX / 2 - 100, LLONG_MAX / 2 local u64_zero, u64_one, u64_fifty, u64_min, u64_max, u64_hi_a, u64_hi_b = 0, 1, 50, 0, ULLONG_MAX / 2, ULLONG_MAX / 2 - 100, ULLONG_MAX / 2 local f32_zero, f32_one, f32_lo_a, f32_hi_a = 0.0, 1.0, -10000000000.0, 10000000000.0 local f64_zero, f64_one, f64_lo_a, f64_hi_a = 0.0, 1.0, -1000000000000000.0, 1000000000000000.0 -- State - -- (see S.DemoWindowWidgetsDataTypes) + -- [Port] (see S.DemoWindowWidgetsDataTypes) local drag_speed = 0.2 IMGUI_DEMO_MARKER("Widgets/Data Types/Drags") @@ -24595,7 +24567,6 @@ function DemoWindowWidgetsDragAndDrop() local drop_target_flags = bit32.bor(1024 --[[ImGuiDragDropFlags.AcceptBeforeDelivery]], 4096 --[[ImGuiDragDropFlags.AcceptNoPreviewTooltip]]) local payload = ImGui.AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, drop_target_flags) if payload then - -- IM_UNUSED(payload) ImGui.SetMouseCursor(10 --[[ImGuiMouseCursor.NotAllowed]]) ImGui.SetTooltip("Cannot drop here!") end @@ -25011,7 +24982,7 @@ end S.DemoWindowWidgetsPlotting = { animate = true, arr = { 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2 }, - values = {}, -- 90 zeros, filled below + values = {}, -- [Port] 90 zeros, filled below values_offset = 0, refresh_time = 0.0, phase = 0.0, @@ -25935,7 +25906,7 @@ S.DemoWindowWidgetsSelectionAndMultiSelect = { show_in_table = false, show_color_button = true, flags = bit32.bor(ImGuiMultiSelectFlags.ClearOnEscape, ImGuiMultiSelectFlags.BoxSelect1d), - widget_type = 0, -- WidgetType_Selectable + widget_type = 0, -- [Port] WidgetType_Selectable items = ImVector(), items_next_id = 0, selection = ExampleSelectionWithDeletion(), @@ -26327,7 +26298,7 @@ function DemoWindowWidgetsSelectionAndMultiSelect(demo_data) if ImGui.TreeNode("Multi-Select (advanced)") then IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (advanced)") -- Options - local WidgetType_Selectable, WidgetType_TreeNode = 0, 1 -- enum WidgetType + local WidgetType_Selectable, WidgetType_TreeNode = 0, 1 -- [Port] enum WidgetType local st = s.advanced if ImGui.TreeNode("Options") then @@ -26924,22 +26895,22 @@ S.DemoWindowWidgetsTextInput = { "\tlock cmpxchg8b eax\n", 1024 * 16), flags = ImGuiInputTextFlags.AllowTabInput, }, - -- "Filtered Text Input" + -- [Port] "Filtered Text Input" filtered = { buf1 = ImGui.NewTextBuffer("", 32), buf2 = ImGui.NewTextBuffer("", 32), buf3 = ImGui.NewTextBuffer("", 32), buf4 = ImGui.NewTextBuffer("", 32), buf5 = ImGui.NewTextBuffer("", 32), buf6 = ImGui.NewTextBuffer("", 32), buf7 = ImGui.NewTextBuffer("", 32), }, - -- "Password Input" + -- [Port] "Password Input" password = { password = ImGui.NewTextBuffer("password123", 64) }, - -- "Completion, History, Edit Callbacks" + -- [Port] "Completion, History, Edit Callbacks" callbacks = { buf1 = ImGui.NewTextBuffer("", 64), buf2 = ImGui.NewTextBuffer("", 64), buf3 = ImGui.NewTextBuffer("", 64), edit_count = 0, }, -- "Resize Callback" resize = { flags = ImGuiInputTextFlags.None, my_str = ImVector() }, - -- "Eliding, Alignment" + -- [Port] "Eliding, Alignment" eliding = { buf1 = ImGui.NewTextBuffer("/path/to/some/folder/with/long/filename.cpp", 128), flags = ImGuiInputTextFlags.ElideLeft }, -- "Miscellaneous" misc = { buf1 = ImGui.NewTextBuffer("", 16), flags = ImGuiInputTextFlags.EscapeClearsAll }, @@ -27229,7 +27200,7 @@ end ------------------------------------------------------------------------------- S.DemoWindowWidgetsTreeNodes = { - base_flags = bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DefaultOpen), -- "Hierarchy Lines" + base_flags = bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DefaultOpen), -- [Port] "Hierarchy Lines" selection_mask = 0x00, base_flags_2 = bit32.bor(ImGuiTreeNodeFlags.OpenOnArrow, ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.SpanAvailWidth), -- "Advanced" align_label_with_current_x_position = false, @@ -27562,7 +27533,7 @@ S.DemoWindowLayout = { -- Widgets Width f = 0.0, show_indented_items = true, - -- Basic Horizontal Layout + -- [Port] Basic Horizontal Layout c1 = false, c2 = false, c3 = false, c4 = false, f0 = 1.0, f1 = 2.0, f2 = 3.0, item = -1, @@ -27587,7 +27558,7 @@ S.DemoWindowLayout = { -- Text Clipping size = ImVec2(100.0, 100.0), offset = ImVec2(30.0, 30.0), - -- Overlap Mode + -- [Port] Overlap Mode enable_allow_overlap = true, } @@ -28426,14 +28397,14 @@ end ------------------------------------------------------------------------------- S.DemoWindowPopups = { - selected_fish = -1, -- static int selected_fish = -1; - toggles = { true, false, false, false, false }, -- static bool toggles[] = { true, false, false, false, false }; - selected = -1, -- static int selected = -1; - value = 0.5, -- static float value = 0.5f; - name = ImGui.NewTextBuffer("Label1", 32), -- static char name[32] = "Label1"; - dont_ask_me_next_time = false, -- static bool dont_ask_me_next_time = false; - item = 1, -- static int item = 1; - color = { 0.4, 0.7, 0.0, 0.5 }, -- static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; + selected_fish = -1, -- [Port] static int selected_fish = -1; + toggles = { true, false, false, false, false }, -- [Port] static bool toggles[] = { true, false, false, false, false }; + selected = -1, -- [Port] static int selected = -1; + value = 0.5, -- [Port] static float value = 0.5f; + name = ImGui.NewTextBuffer("Label1", 32), -- [Port] static char name[32] = "Label1"; + dont_ask_me_next_time = false, -- [Port] static bool dont_ask_me_next_time = false; + item = 1, -- [Port] static int item = 1; + color = { 0.4, 0.7, 0.0, 0.5 }, -- [Port] static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; } function DemoWindowPopups() local s = S.DemoWindowPopups @@ -28730,7 +28701,7 @@ end -- This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID. -- But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex) -- If you don't use sorting, you will generally never care about giving column an ID! --- enum MyItemColumnID +-- [Port] enum MyItemColumnID MyItemColumnID_ID = 0 MyItemColumnID_Name = 1 MyItemColumnID_Action = 2 @@ -28812,7 +28783,7 @@ S.EditTableSizingFlags = { policies = nil } -- [Port] p_flags -> takes flags, returns the new flags. function EditTableSizingFlags(p_flags) local s = S.EditTableSizingFlags - -- struct EnumDesc { ImGuiTableFlags Value; const char* Name; const char* Tooltip; }; + -- [Port] struct EnumDesc { ImGuiTableFlags Value; const char* Name; const char* Tooltip; }; if s.policies == nil then s.policies = { @@ -28903,7 +28874,7 @@ end -- [SECTION] DemoWindowTables() ------------------------------------------------------------------------------- -S.DemoWindowTables = { -- statics of DemoWindowTables(), one sub-table per TreeNode +S.DemoWindowTables = { -- [Port] statics of DemoWindowTables(), one sub-table per TreeNode disable_indent = false, BordersBackground = { flags = bit32.bor(ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg), @@ -28928,14 +28899,14 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su flags2 = bit32.bor(ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg), cell_padding = ImVec2(0.0, 0.0), show_widget_frame_bg = true, - text_bufs = {}, -- 1-based, cell + 1 + text_bufs = {}, -- [Port] 1-based, cell + 1 init = true, }, SizingPolicies = { flags1 = bit32.bor(ImGuiTableFlags.BordersV, ImGuiTableFlags.BordersOuterH, ImGuiTableFlags.RowBg, ImGuiTableFlags.ContextMenuInBody), sizing_policy_flags = { ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.SizingFixedSame, ImGuiTableFlags.SizingStretchProp, ImGuiTableFlags.SizingStretchSame }, flags = bit32.bor(ImGuiTableFlags.ScrollY, ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg, ImGuiTableFlags.Resizable), - contents_type = 0, -- CT_ShowWidth + contents_type = 0, -- [Port] CT_ShowWidth column_count = 3, text_buf = ImGui.NewTextBuffer("", 32), }, @@ -28970,7 +28941,7 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su table_flags = bit32.bor(ImGuiTableFlags.BordersV, ImGuiTableFlags.BordersOuterH, ImGuiTableFlags.Resizable, ImGuiTableFlags.RowBg, ImGuiTableFlags.NoBordersInBody), tree_node_flags_base = bit32.bor(ImGuiTreeNodeFlags.SpanAllColumns, ImGuiTreeNodeFlags.DefaultOpen, ImGuiTreeNodeFlags.DrawLinesFull), MyTreeNode = nil, -- [Port] local struct, created once on first use - nodes = { -- 1-based; ChildIdx stays 0-based like upstream + nodes = { -- [Port] 1-based; ChildIdx stays 0-based like upstream { Name = "Root with Long Name", Type = "Folder", Size = -1, ChildIdx = 1, ChildCount = 3 }, -- 0 { Name = "Music", Type = "Folder", Size = -1, ChildIdx = 4, ChildCount = 2 }, -- 1 { Name = "Textures", Type = "Folder", Size = -1, ChildIdx = 6, ChildCount = 3 }, -- 2 @@ -28991,7 +28962,7 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su AngledHeaders = { table_flags = bit32.bor(ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY, ImGuiTableFlags.BordersOuter, ImGuiTableFlags.BordersInnerH, ImGuiTableFlags.Hideable, ImGuiTableFlags.Resizable, ImGuiTableFlags.Reorderable, ImGuiTableFlags.HighlightHoveredColumn), column_flags = bit32.bor(ImGuiTableColumnFlags.AngledHeader, ImGuiTableColumnFlags.WidthFixed), - bools = {}, -- 1-based, filled with false on first use + bools = {}, -- [Port] 1-based, filled with false on first use frozen_cols = 1, frozen_rows = 2, }, @@ -29020,11 +28991,11 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY, ImGuiTableFlags.SizingFixedFit), columns_base_flags = ImGuiTableColumnFlags.None, - contents_type = 5, -- CT_SelectableSpanRow + contents_type = 5, -- [Port] CT_SelectableSpanRow freeze_cols = 1, freeze_rows = 1, - items_count = 0, -- IM_COUNTOF(template_items_names) * 2, set below - outer_size_value = nil, -- ImVec2(0.0f, TEXT_BASE_HEIGHT * 12), set lazily (needs font) + items_count = 0, -- [Port] IM_COUNTOF(template_items_names) * 2, set below + outer_size_value = nil, -- [Port] ImVec2(0.0f, TEXT_BASE_HEIGHT * 12), set lazily (needs font) row_min_height = 0.0, -- Auto inner_width_with_scroll = 0.0, -- Auto-extend outer_size_enabled = true, @@ -29144,7 +29115,7 @@ function DemoWindowTables() if ImGui.TreeNode("Borders, background") then IMGUI_DEMO_MARKER("Tables/Borders, background") -- Expose a few Borders related flags interactively - local CT_Text, CT_FillButton = 0, 1 -- enum ContentsType + local CT_Text, CT_FillButton = 0, 1 -- [Port] enum ContentsType local s = s.BordersBackground PushStyleCompact() @@ -29507,7 +29478,7 @@ function DemoWindowTables() "This section allows you to interact and see the effect of various sizing policies " .. "depending on whether Scroll is enabled and the contents of your columns.") - local CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText = 0, 1, 2, 3, 4, 5 -- enum ContentsType + local CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText = 0, 1, 2, 3, 4, 5 -- [Port] enum ContentsType PushStyleCompact() ImGui.PushID("Advanced") @@ -30050,7 +30021,7 @@ function DemoWindowTables() ImGui.TableHeadersRow() -- Simple storage to output a dummy file-system. - -- struct MyTreeNode { Name, Type, Size, ChildIdx, ChildCount } (see s.nodes) + -- [Port] struct MyTreeNode { Name, Type, Size, ChildIdx, ChildCount } (see s.nodes) local MyTreeNode = s.MyTreeNode if MyTreeNode == nil then -- [Port] local struct with a static method, created once and kept in statics MyTreeNode = {} @@ -30486,7 +30457,7 @@ function DemoWindowTables() IMGUI_DEMO_MARKER("Tables/Advanced") local s = s.Advanced - local CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow = 0, 1, 2, 3, 4, 5 -- enum ContentsType + local CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow = 0, 1, 2, 3, 4, 5 -- [Port] enum ContentsType local contents_type_names = { "Text", "Button", "SmallButton", "FillButton", "Selectable", "Selectable (span row)" } if s.outer_size_value == nil then s.outer_size_value = ImVec2(0.0, TEXT_BASE_HEIGHT * 12) end -- static float row_min_height = 0.0f -- Auto @@ -31006,7 +30977,7 @@ function DemoWindowInputs() end ImGui.Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y) ImGui.Text("Mouse down:") - for i = 0, 5 --[[ImGuiMouseButton.COUNT]] - 1 do if ImGui.IsMouseDown(i) then ImGui.SameLine(); ImGui.Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]) end end -- IM_COUNTOF(io.MouseDown), 0-based + for i = 0, 5 --[[ImGuiMouseButton.COUNT]] - 1 do if ImGui.IsMouseDown(i) then ImGui.SameLine(); ImGui.Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]) end end -- [Port] IM_COUNTOF(io.MouseDown), 0-based ImGui.Text("Mouse wheel: %.1f", io.MouseWheel) ImGui.Text("Mouse clicked count:") for i = 0, 5 --[[ImGuiMouseButton.COUNT]] - 1 do if io.MouseClickedCount[i] > 0 then ImGui.SameLine(); ImGui.Text("b%d: %d", i, io.MouseClickedCount[i]) end end @@ -31480,12 +31451,12 @@ function GetTreeLinesFlagsName(flags) end S.ShowStyleEditor = { - ref_saved_style = nil, -- static ImGuiStyle ref_saved_style; (created lazily) + ref_saved_style = nil, -- [Port] static ImGuiStyle ref_saved_style; (created lazily) init = true, output_dest = 0, output_only_modified = true, alpha_flags = 0, - filter = nil, -- static ImGuiTextFilter filter; (created lazily) + filter = nil, -- [Port] static ImGuiTextFilter filter; (created lazily) } -- We omit the ImGui:: prefix in this function, as we don't expect user to be copy and pasting this code. -- [Port] Lua has no `using namespace`: calls keep the ImGui. prefix @@ -32014,17 +31985,17 @@ ExampleAppConsoleMT = {} ExampleAppConsoleMT.__index = ExampleAppConsoleMT function ExampleAppConsole() local self = setmetatable({}, ExampleAppConsoleMT) - self.InputBuf = nil -- char InputBuf[256] - self.Items = ImVector() -- ImVector - self.Commands = ImVector() -- ImVector - self.History = ImVector() -- ImVector + self.InputBuf = nil -- [Port] char InputBuf[256] + self.Items = ImVector() -- [Port] ImVector + self.Commands = ImVector() -- [Port] ImVector + self.History = ImVector() -- [Port] ImVector self.HistoryPos = 0 -- -1: new line, 0..History.Size-1 browsing history. self.Filter = ImGuiTextFilter() self.AutoScroll = false self.ScrollToBottom = false self:ClearLog() - self.InputBuf = ImGui.NewTextBuffer("", 256) -- memset(InputBuf, 0, sizeof(InputBuf)) + self.InputBuf = ImGui.NewTextBuffer("", 256) -- [Port] memset(InputBuf, 0, sizeof(InputBuf)) self.HistoryPos = -1 -- "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches. @@ -32265,7 +32236,7 @@ function ExampleAppConsoleMT:TextEditCallback(data) local word_end = data.CursorPos local word_start = word_end while word_start > 0 do - local c = data.Buf[word_start] -- word_start[-1] + local c = data.Buf[word_start] -- [Port] word_start[-1] if c == 32 or c == 9 or c == 44 or c == 59 then -- ' ', '\t', ',', ';' break end @@ -32353,7 +32324,7 @@ function ExampleAppConsoleMT:TextEditCallback(data) end S.ShowExampleAppConsole = { - console = nil, -- ExampleAppConsole, created on first use + console = nil, -- [Port] ExampleAppConsole, created on first use } function ShowExampleAppConsole(p_open) local s = S.ShowExampleAppConsole @@ -32366,7 +32337,7 @@ end ------------------------------------------------------------------------------- S.ShowExampleAppImageViewer = { - image_viewer = nil, -- ExampleImageViewerData, created on first use + image_viewer = nil, -- [Port] ExampleImageViewerData, created on first use } function ShowExampleAppImageViewer(p_open) local s = S.ShowExampleAppImageViewer @@ -32526,7 +32497,7 @@ end -- Demonstrate creating a simple log window with basic filtering. S.ShowExampleAppLog = { - log = nil, -- ExampleAppLog, created on first use + log = nil, -- [Port] ExampleAppLog, created on first use counter = 0, } function ShowExampleAppLog(p_open) @@ -32847,7 +32818,7 @@ end -- Demonstrate creating a simple property editor. S.ShowExampleAppPropertyEditor = { - property_editor = nil, -- ExampleAppPropertyEditor, created on first use + property_editor = nil, -- [Port] ExampleAppPropertyEditor, created on first use demo_data = nil, -- [Port] fallback when called without demo_data } function ShowExampleAppPropertyEditor(p_open, demo_data) @@ -33239,7 +33210,7 @@ S.ShowExampleAppCustomRendering = { opt_enable_grid = true, opt_enable_context_menu = true, adding_line = false, - -- BG/FG draw lists + -- [Port] BG/FG draw lists draw_bg = true, draw_fg = true, } @@ -33960,9 +33931,9 @@ end S.ShowExampleAppDocuments = { app = ExampleAppDocuments(), - opt_target = nil, -- set below to Target_Tab + opt_target = nil, -- [Port] set below to Target_Tab opt_reorderable = true, - opt_fitting_flags = nil, -- set below to ImGuiTabBarFlags.FittingPolicyDefault_ + opt_fitting_flags = nil, -- [Port] set below to ImGuiTabBarFlags.FittingPolicyDefault_ } function ShowExampleAppDocuments(p_open) local s = S.ShowExampleAppDocuments @@ -34698,14 +34669,14 @@ FONT_ATLAS_DEFAULT_TEX_DATA_H = 27 local IM_DRAWLIST_TEX_LINES_WIDTH_MAX = 32 -- The maximum line width to bake anti-aliased textures for. local writef64, writeu32, readf64, readu32 = buffer.writef64, buffer.writeu32, buffer.readf64, buffer.readu32 --- Write vertex i (1-based) of a VtxBuffer.Buf +-- [Port] Write vertex i (1-based) of a VtxBuffer.Buf local function WV(b, i, x, y, u, v, col) local o = (i - 1) * 36 writef64(b, o, x); writef64(b, o + 8, y); writef64(b, o + 16, u); writef64(b, o + 24, v); writeu32(b, o + 32, col) end -local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -- ((ImU16)-1) -local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE -- ((ImU16)-2) +local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -- [Port] ((ImU16)-1) +local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE -- [Port] ((ImU16)-2) --- @param str string --- @return table @@ -35043,7 +35014,7 @@ function ImGui.ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, end end --- Rotate and translate vertices [vert_start_idx, vert_end_idx) (1-based, like _VtxCurrentIdx) +-- [Port] Rotate and translate vertices [vert_start_idx, vert_end_idx) (1-based, like _VtxCurrentIdx) function ImGui.ShadeVertsTransformPos(draw_list, vert_start_idx, vert_end_idx, pivot_in, cos_a, sin_a, pivot_out) local data = draw_list.VtxBuffer.Buf local pix, piy, pox, poy = pivot_in.x, pivot_in.y, pivot_out.x, pivot_out.y @@ -36032,7 +36003,7 @@ local function ImGui_ImplStbTrueType_FontSrcData() } end --- Need this in Lua since I don't want to include 'stbrp' just for context constructor +-- [Port] Need this in Lua since I don't want to include 'stbrp' just for context constructor -- in ImFontAtlasBuilder def code. The cpp code has 'stbrp_context_opaque' which I don't/can't have here --- @param atlas ImFontAtlas local function ImGui_ImplStbTrueType_LoaderInit(atlas) @@ -36040,7 +36011,7 @@ local function ImGui_ImplStbTrueType_LoaderInit(atlas) end local function ImGui_ImplStbTrueType_FontSrcInit(atlas, src) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) --- @type ImGui_ImplStbTrueType_FontSrcData? local bd_font_data = ImGui_ImplStbTrueType_FontSrcData() @@ -36075,12 +36046,12 @@ local function ImGui_ImplStbTrueType_FontSrcInit(atlas, src) end local function ImGui_ImplStbTrueType_FontSrcDestroy(atlas, src) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) src.FontLoaderData = nil end local function ImGui_ImplStbTrueType_FontSrcContainsGlyph(atlas, src, codepoint) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) local bd_font_data = src.FontLoaderData assert(bd_font_data ~= nil) @@ -36089,7 +36060,7 @@ local function ImGui_ImplStbTrueType_FontSrcContainsGlyph(atlas, src, codepoint) end local function ImGui_ImplStbTrueType_FontBakedInit(atlas, src, baked) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) local bd_font_data = src.FontLoaderData if (src.MergeMode == false) then @@ -36268,14 +36239,14 @@ function ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, ba local loader = src.FontLoader and src.FontLoader or atlas.FontLoader loader_data_size = loader_data_size + loader.FontBakedSrcLoaderDataSize end - -- baked.FontLoaderDatas = (loader_data_size > 0) and IM_ALLOC(loader_data_size) or nil + -- [Port] baked.FontLoaderDatas = (loader_data_size > 0) and IM_ALLOC(loader_data_size) or nil -- local loader_data_p = baked->FontLoaderDatas for _, src in font.Sources:iter() do local loader = src.FontLoader and src.FontLoader or atlas.FontLoader if (loader.FontBakedInit) then loader.FontBakedInit(atlas, src, baked--[[, loader_data_p--]]) end - -- loader_data_p += loader->FontBakedSrcLoaderDataSize + -- [Port] loader_data_p += loader->FontBakedSrcLoaderDataSize end ImFontAtlasBuildSetupFontBakedBlanks(atlas, baked) @@ -36339,7 +36310,7 @@ function ImFontAtlasBakedDiscard(atlas, font, baked) end end - -- char* loader_data_p = (char*)baked->FontLoaderDatas + -- [Port] char* loader_data_p = (char*)baked->FontLoaderDatas for _, src in font.Sources:iter() do local loader = src.FontLoader and src.FontLoader or atlas.FontLoader if loader.FontBakedDestroy then @@ -36436,13 +36407,13 @@ end --- @param atlas ImFontAtlas --- @param src ImFontConfig function ImFontAtlasFontDestroySourceData(atlas, src) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) - -- if src.FontDataOwnedByAtlas then + -- [Port] if src.FontDataOwnedByAtlas then -- IM_FREE(src.FontData) -- end src.FontData = nil - -- if src.GlyphExcludeRanges then + -- [Port] if src.GlyphExcludeRanges then -- IM_FREE(src.GlyphExcludeRanges) -- end src.GlyphExcludeRanges = nil @@ -36454,7 +36425,7 @@ end --- @param font ImFont --- @param src ImFontConfig function ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) assert(font.Sources:contains(src)) -- Find Fallback character. Actual glyph loaded in GetFontBaked(). @@ -36609,7 +36580,7 @@ local function ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas) end local function ImFontAtlasBuildUpdatePointers(atlas) - -- for _, font in atlas.Fonts:iter() do + -- [Port] for _, font in atlas.Fonts:iter() do -- font.Sources:resize(0) -- end -- for _, src in atlas.Sources:iter() do @@ -36787,7 +36758,7 @@ function ImFontAtlasPackInit(atlas) end --- @param atlas ImFontAtlas --- #define IM_DRAWLIST_CORNER_POINTS_MAX (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4 + 3) // Max number of points in corner profiles +-- [Port] #define IM_DRAWLIST_CORNER_POINTS_MAX (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4 + 3) // Max number of points in corner profiles -- [Luau] ImVec2 line_normals[] / float line_distances[] / ImVec2 points[] are flat 1-based scratch arrays (x, y, distance). local corner_points_x, corner_points_y = {}, {} local corner_normals_x, corner_normals_y, corner_distances = {}, {}, {} @@ -36833,7 +36804,7 @@ local function InitCornerGeometry(cx, cy, rounding, circle_segment_max_error, li local inv_d = ImRsqrtPrecise(d2) line_normals_x[i] = diff_y * inv_d -- Normal points outwards line_normals_y[i] = -diff_x * inv_d - line_distances[i] = -(points_x[i] * line_normals_x[i] + points_y[i] * line_normals_y[i]) -- -ImDot() + line_distances[i] = -(points_x[i] * line_normals_x[i] + points_y[i] * line_normals_y[i]) -- [Port] -ImDot() end return num_points - 1 @@ -36856,12 +36827,12 @@ local function SampleCornerFillOrStroke(x, y, thickness, line_normals_x, line_no local aa_width = 1.0 if thickness == 0.0 then -- Fill - return math.floor(ImClamp(1.0 - (d + aa_width * 0.5) / aa_width, 0.0, 1.0) * 255.0) -- (ImU8) + return math.floor(ImClamp(1.0 - (d + aa_width * 0.5) / aa_width, 0.0, 1.0) * 255.0) -- [Port] (ImU8) else -- Stroke local outer = 1.0 - (d + aa_width * 0.5) / aa_width local inner = (d + thickness + aa_width * 0.5) / aa_width - return math.floor(ImClamp(ImMin(inner, outer), 0.0, 1.0) * 255.0) -- (ImU8) + return math.floor(ImClamp(ImMin(inner, outer), 0.0, 1.0) * 255.0) -- [Port] (ImU8) end end @@ -37025,7 +36996,7 @@ function ImFontAtlasBuildUpdateTexDataLines(atlas) -- Calculate super sampled line textures for smaller line widths to make transition between sizes smoother. -- Calculate ramp used for all the textures. - local ramp = {} -- ImU8[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT], 0-based + local ramp = {} -- [Port] ImU8[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT], 0-based for n = 0, 4 --[[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT]] - 1 do ramp[n] = math.floor((n / 4 --[[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT]]) * 255.0) end @@ -37286,7 +37257,7 @@ function ImFontAtlasBuildMain(atlas) end -- [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs - -- ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); + -- [Port] ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); -- if atlas.RendererHasTextures == false then -- ~ImGuiBackendFlags.RendererHasTextures -- ImFontAtlasBuildLegacyPreloadAllGlyphRanges(atlas) -- end @@ -37492,7 +37463,7 @@ end --- @param c ImWchar --- @return ImFontGlyph? function MT.ImFontBaked:FindGlyphNoFallback(c) - if c < self.IndexLookup.Size then -- IM_LIKELY + if c < self.IndexLookup.Size then -- [Port] IM_LIKELY local i = self.IndexLookup.Data[c + 1] if i == IM_FONTGLYPH_INDEX_NOT_FOUND then return nil @@ -37525,7 +37496,7 @@ function MT.ImFont:IsGlyphRangeUnused(c_begin, c_last) local page_begin = math.floor(c_begin / 8192) local page_last = math.floor(c_last / 8192) for page_n = page_begin, page_last do - if bit32.rshift(page_n, 3) < (65535 --[[IM_UNICODE_CODEPOINT_MAX]] + 1) / 8192 / 8 then -- sizeof(Used8kPagesMap) + if bit32.rshift(page_n, 3) < (65535 --[[IM_UNICODE_CODEPOINT_MAX]] + 1) / 8192 / 8 then -- [Port] sizeof(Used8kPagesMap) if bit32.band(self.Used8kPagesMap[bit32.rshift(page_n, 3) + 1] or 0, bit32.lshift(1, bit32.band(page_n, 7))) ~= 0 then return false end @@ -37634,7 +37605,7 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) local codepoint = glyph.Codepoint ImFontBaked_BuildGrowIndex(baked, codepoint + 1) baked.IndexAdvanceX.Data[codepoint + 1] = glyph.AdvanceX - baked.IndexLookup.Data[codepoint + 1] = glyph_idx -- (ImU16) + baked.IndexLookup.Data[codepoint + 1] = glyph_idx -- [Port] (ImU16) local page_n = math.floor(codepoint / 8192) baked.OwnerFont.Used8kPagesMap[bit32.rshift(page_n, 3) + 1] = bit32.bor(baked.OwnerFont.Used8kPagesMap[bit32.rshift(page_n, 3) + 1], bit32.lshift(1, bit32.band(page_n, 7))) @@ -37648,7 +37619,7 @@ end --- @param codepoint ImWchar --- @param advance_x float function ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, advance_x) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) if (src ~= nil) then -- Clamp & recenter if needed local ref_size = baked.OwnerFont.Sources[1].SizePixels @@ -37715,7 +37686,7 @@ end --- @return ImWchar --- @nodiscard local function ImFontAtlas_FontHookRemapCodepoint(atlas, font, c) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) if next(font.RemapPairs) ~= nil then -- [Luau] font->RemapPairs.Data.Size != 0 (RemapPairs is a hash table) local ret = font.RemapPairs[c] return (ret ~= nil) and ret or c @@ -37786,7 +37757,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) end end - -- loader_user_data_p = loader_user_data_p + loader.FontBakedSrcLoaderDataSize + -- [Port] loader_user_data_p = loader_user_data_p + loader.FontBakedSrcLoaderDataSize src_n = src_n + 1 end @@ -37897,7 +37868,7 @@ end --- @param c unsigned_int function ImTextClassifierSetCharClass(bits, codepoint_min, codepoint_end, char_class, c) assert(c >= codepoint_min and c < codepoint_end) - -- IM_UNUSED(codepoint_end) + -- [Port] IM_UNUSED(codepoint_end) c = c - codepoint_min local shift = bit32.lshift(bit32.band(c, 15), 1) bits[bit32.rshift(c, 4) + 1] = bit32.bor(bit32.band(bits[bit32.rshift(c, 4) + 1], bit32.bnot(bit32.lshift(0x03, shift))), bit32.lshift(char_class, shift)) @@ -37959,7 +37930,6 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt end -- [Luau] memo per baked font and string: CalcTextSize() and RenderText() of wrapped text ask for the same wrap points -- (same text/pos/width) every frame. The result only depends on these inputs and the (immutable once loaded) glyph advances. - -- ponytail: whole-memo reset at WRAP_MEMO_MAX strings, LRU if dynamic text churns it local memo = baked._WrapMemo if memo == nil or baked._WrapMemoN >= WRAP_MEMO_MAX then memo = {}; baked._WrapMemo = memo; baked._WrapMemoN = 0 @@ -38139,7 +38109,7 @@ local TEXT_SIZE_CACHE_MAX = 4096 function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags) local text_is_str = type(text) == "string" -- [Luau] cache for the common case (whole string, single pass, no wrap/limit): per baked font, text -> unscaled width, line count. - -- Advances of a baked font never change once loaded, so entries stay valid. ponytail: whole-cache reset at TEXT_SIZE_CACHE_MAX entries, LRU if dynamic text churns it + -- Advances of a baked font never change once loaded, so entries stay valid. local cache_key = nil local wrap_cache = nil local text_len1 = text_is_str and #text + 1 or -1 @@ -38570,7 +38540,7 @@ function MT.ImFontAtlas:AddFontFromFileTTF(filename, size_pixels, font_cfg_templ local data, data_size = ImStd.ImFileLoadToMemory(filename, "rb") if not data then if (font_cfg_template == nil or (bit32.band(font_cfg_template.Flags, 2 --[[ImFontFlags.NoLoadError]]) == 0)) then - -- IMGUI_DEBUG_LOG("While loading '%s'\n", filename) + -- [Port] IMGUI_DEBUG_LOG("While loading '%s'\n", filename) IM_ASSERT_USER_ERROR(0, "Could not load font file!") end @@ -38773,7 +38743,7 @@ local function ImAlphaMultiply(col, alpha_mul) return bit32.bor(bit32.band(col, bit32.bnot(4278190080 --[[IM_COL32_A_MASK]])), bit32.lshift(a, 24 --[[IM_COL32_A_SHIFT]])) end --- #define _GetStrokePos(_FLAGS, _DEFAULT_STROKE_POS) +-- [Port] #define _GetStrokePos(_FLAGS, _DEFAULT_STROKE_POS) local function _GetStrokePos(flags, default_stroke_pos) local stroke_pos = bit32.band(flags, 917504 --[[ImDrawFlags.StrokeMask_]]) if stroke_pos ~= 0 then return stroke_pos end @@ -38908,7 +38878,7 @@ function MT.ImDrawListSharedData:SetCircleTessellationMaxError(max_error) assert(max_error > 0) self.CircleTessellationMaxError = max_error - for i = 1, 64 do -- IM_COUNTOF(CircleSegmentCounts) + for i = 1, 64 do -- [Port] IM_COUNTOF(CircleSegmentCounts) local radius = (i - 1) self.CircleSegmentCounts[i] = (i > 1) and IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, self.CircleTessellationMaxError) or 48 --[[IM_DRAWLIST_ARCFAST_SAMPLE_MAX]] end @@ -38930,7 +38900,7 @@ end -- Initialize before use in a new frame. We always have a command ready in the buffer. -- In the majority of cases, you would want to call PushClipRect() and PushTexture() after this. function MT.ImDrawList:_ResetForNewFrame() - self._ContentClipX0 = nil -- set again by Begin() (Roblox backend scroll reuse) + self._ContentClipX0 = nil -- [Port] set again by Begin() (Roblox backend scroll reuse) if self._Splitter._Count > 1 then self._Splitter:Merge(self) end @@ -38951,7 +38921,7 @@ function MT.ImDrawList:_ResetForNewFrame() self._ClipRectStack:resize(0) self._TextureStack:resize(0) self._CallbacksDataBuf:resize(0) - self._DrawFlagsStack.Size = 0 -- _DrawFlagsStack.clear() (ImSmallStack_) + self._DrawFlagsStack.Size = 0 -- [Port] _DrawFlagsStack.clear() (ImSmallStack_) self._Path:resize(0) self.CmdBuffer:push_back(ImDrawCmd()) @@ -38972,7 +38942,7 @@ function MT.ImDrawList:_ClearFreeMemory() self._ClipRectStack:clear() self._TextureStack:clear() self._CallbacksDataBuf:clear() - self._DrawFlagsStack.Size = 0 -- _DrawFlagsStack.clear() (ImSmallStack_) + self._DrawFlagsStack.Size = 0 -- [Port] _DrawFlagsStack.clear() (ImSmallStack_) self._Path:clear() self._Splitter:ClearFreeMemory() end @@ -39054,7 +39024,7 @@ function MT.ImDrawList:AddCallback(callback, userdata, userdata_size) -- [Lua] No raw bytes: the "copy" is a shallow copy of a table userdata (other values are immutable and stored as is), -- so later changes to the caller's table don't affect this command. userdata_size is only recorded. assert(userdata ~= nil) - assert(userdata_size < 2147483648) -- (1u << 31) + assert(userdata_size < 2147483648) -- [Port] (1u << 31) curr_cmd.UserCallbackData = nil -- Will be resolved during Render() curr_cmd.UserCallbackDataSize = userdata_size curr_cmd.UserCallbackDataOffset = self._CallbacksDataBuf.Size -- 0-based @@ -39203,7 +39173,7 @@ end ------------------------------------------------------------------------------- -- FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap.. ------------------------------------------------------------------------------- --- Lua: channels swap ImVector objects with the draw list (C++ memcpy of the vector headers). +-- [Port] channels swap ImVector objects with the draw list (C++ memcpy of the vector headers). -- Channel 0 holds nothing while it is the current channel (its buffers live in the draw list). -- Copy ClipRect, TexRef, VtxOffset (TexRef is assigned by reference, never mutated) @@ -39248,7 +39218,7 @@ function MT.ImDrawListSplitter:Split(draw_list, channels_count) -- Channels[] hold storage that we'll swap with draw_list._CmdBuffer/_IdxBuffer -- The content of Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. -- When we switch to the next channel, we'll copy draw_list._CmdBuffer/_IdxBuffer into Channels[0] and then Channels[1] into draw_list.CmdBuffer/_IdxBuffer - -- Channel 0 is the draw list itself (memset to 0 in C++) + -- [Port] Channel 0 is the draw list itself (memset to 0 in C++) local channels = self._Channels.Data channels[1] = { _CmdBuffer = nil, _IdxBuffer = nil } for i = 2, channels_count do @@ -39320,7 +39290,7 @@ function MT.ImDrawListSplitter:Merge(draw_list) local src_cmds = ch._CmdBuffer.Data for n = 1, ch._CmdBuffer.Size do dst_cmds[cmd_write] = src_cmds[n] - src_cmds[n] = nil -- ownership moved to the draw list + src_cmds[n] = nil -- [Port] ownership moved to the draw list cmd_write = cmd_write + 1 end end @@ -39420,7 +39390,7 @@ end function MT.ImDrawList:PushDrawFlag(flags, enabled) assert(bit32.band(flags, bit32.bnot(8286704 --[[ImDrawFlags.AllowInPushScope_]])) == 0) assert(bit32.band(flags, 917504 --[[ImDrawFlags.StrokeMask_]]) == 0 or bit32.band(flags, 917504 --[[ImDrawFlags.StrokeMask_]]) == 917504 --[[ImDrawFlags.StrokeLegacy]]) - IM_ASSERT_USER_ERROR_RET(self._DrawFlagsStack.Size < 3, "PushDrawFlag() has a depth limit. Contact us.") -- _DrawFlagsStack.capacity() == 3 + IM_ASSERT_USER_ERROR_RET(self._DrawFlagsStack.Size < 3, "PushDrawFlag() has a depth limit. Contact us.") -- [Port] _DrawFlagsStack.capacity() == 3 self._DrawFlagsStack:push_back(self.Flags) if enabled then self.Flags = bit32.bor(self.Flags, flags) @@ -39626,7 +39596,7 @@ local function _SelectLineTexture(self, screen_thickness, flags) end -- Scale the fringe so that the texture matches the line thickness. - local tex_uvs = self._Data.TexUvLines[texture_idx] -- 0-based table + local tex_uvs = self._Data.TexUvLines[texture_idx] -- [Port] 0-based table return tex_uvs.x, tex_uvs.z, tex_uvs.y, tex_uvs.z, self._FringeScale * screen_thickness * tex_uvs.w -- tex_uvs.w = 1 / thickness else -- For no anti-alias we use fully opaque texture, and no fringe expansion. @@ -39680,7 +39650,7 @@ function MT.ImDrawList:_AddPolyline(points, points_count, col, thickness, flags, local dy = p1.y - p0.y local d2 = dx * dx + dy * dy local inv_len = 0.0 - if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- ImRsqrtPrecise() + if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- [Port] ImRsqrtPrecise() normals_x[i] = -dy * inv_len normals_y[i] = dx * inv_len sqr_lengths[i] = d2 @@ -39692,7 +39662,7 @@ function MT.ImDrawList:_AddPolyline(points, points_count, col, thickness, flags, local dy = p1.y - p0.y local d2 = dx * dx + dy * dy local inv_len = 0.0 - if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- ImRsqrtPrecise() + if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- [Port] ImRsqrtPrecise() normals_x[points_count] = -dy * inv_len normals_y[points_count] = dx * inv_len sqr_lengths[points_count] = d2 @@ -39755,8 +39725,8 @@ function MT.ImDrawList:_AddPolyline(points, points_count, col, thickness, flags, local vb = self.VtxBuffer.Buf local ib = self.IdxBuffer.Data - local vw = self._VtxWritePtr -- 1-based write position in VtxBuffer - local iw = self._IdxWritePtr -- 1-based write position in IdxBuffer + local vw = self._VtxWritePtr -- [Port] 1-based write position in VtxBuffer + local iw = self._IdxWritePtr -- [Port] 1-based write position in IdxBuffer local vtx_idx = self._VtxCurrentIdx local first_vtx_offset = vw local first_vtx_idx = vtx_idx -- [Luau] VtxBuffer position of index 'n' is first_vtx_offset + (n - first_vtx_idx) @@ -40051,7 +40021,7 @@ function MT.ImDrawList:AddConvexPolyFilled(points, points_count, col, flags) local dy = p1.y - p0.y local d2 = dx * dx + dy * dy if d2 > 0.0 then - local inv_len = 1.0 / math.sqrt(d2) -- ImRsqrtPrecise() + local inv_len = 1.0 / math.sqrt(d2) -- [Port] ImRsqrtPrecise() dx = dx * inv_len dy = dy * inv_len end @@ -40240,7 +40210,7 @@ local function PathRectXY(self, ax, ay, bx, by, rounding, flags) if not rounding then rounding = 0.0 end if not flags then flags = 0 end - local has_rounding = rounding >= 0.25 * self._FringeScale -- IM_HAS_ROUNDING(rounding) + local has_rounding = rounding >= 0.25 * self._FringeScale -- [Port] IM_HAS_ROUNDING(rounding) if has_rounding then if bit32.band(flags, 496 --[[ImDrawFlags.RoundMask_]]) == 0 then flags = bit32.bor(flags, 240 --[[ImDrawFlags.RoundAll]]) @@ -40295,7 +40265,7 @@ local function _AddLineXY(self, p1x, p1y, p2x, p2y, col, thickness, flags) local dir_y = p2y - p1y local d2 = dir_x * dir_x + dir_y * dir_y local inv_len = 0.0 - if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- ImRsqrtPrecise() + if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- [Port] ImRsqrtPrecise() dir_x = dir_x * inv_len dir_y = dir_y * inv_len local norm_x = -dir_y @@ -40460,7 +40430,7 @@ function MT.ImDrawList:AddLineH(min_x, max_x, y, col, thickness, flags) top_y = top_y - thickness end - local is_truncated = min_x % 1 == 0 and max_x % 1 == 0 and top_y % 1 == 0 and thickness % 1 == 0 -- IM_IS_TRUNCATED4() + local is_truncated = min_x % 1 == 0 and max_x % 1 == 0 and top_y % 1 == 0 and thickness % 1 == 0 -- [Port] IM_IS_TRUNCATED4() if self._FringeScaleIsInteger and is_truncated and bit32.band(flags, 2048 --[[ImDrawFlags.CapSquare]]) == 0 then if thickness < self._FringeScale then if thickness < (1.0 / 255.0) * self._FringeScale then @@ -40516,7 +40486,7 @@ function MT.ImDrawList:AddLineV(x, min_y, max_y, col, thickness, flags) left_x = left_x - thickness end - local is_truncated = left_x % 1 == 0 and min_y % 1 == 0 and max_y % 1 == 0 and thickness % 1 == 0 -- IM_IS_TRUNCATED4() + local is_truncated = left_x % 1 == 0 and min_y % 1 == 0 and max_y % 1 == 0 and thickness % 1 == 0 -- [Port] IM_IS_TRUNCATED4() if self._FringeScaleIsInteger and is_truncated and bit32.band(flags, 2048 --[[ImDrawFlags.CapSquare]]) == 0 then if thickness < self._FringeScale then if thickness < (1.0 / 255.0) * self._FringeScale then @@ -40560,7 +40530,7 @@ end -- [Luau] _AddRectBaked() taking p_min/p_max as scalars local function _AddRectBakedXY(self, p_min_x, p_min_y, p_max_x, p_max_y, col, r, t, tex_uvs, flags) - local uv_l, uv_t, uv_r, uv_b = tex_uvs.x, tex_uvs.y, tex_uvs.z, tex_uvs.w -- uv_tl = (l,t), uv_tr = (r,t), uv_br = (r,b), uv_bl = (l,b) + local uv_l, uv_t, uv_r, uv_b = tex_uvs.x, tex_uvs.y, tex_uvs.z, tex_uvs.w -- [Port] uv_tl = (l,t), uv_tr = (r,t), uv_br = (r,b), uv_bl = (l,b) local idx_allocated = 8 * 2 * 3 local vtx_allocated = 8 * 4 @@ -40656,7 +40626,7 @@ function MT.ImDrawList:_AddRectBaked(p_min, p_max, col, r, t, tex_uvs, flags) _AddRectBakedXY(self, p_min.x, p_min.y, p_max.x, p_max.y, col, r, t, tex_uvs, flags) end -local corner_offset_x = { 1, -1, -1, 1 } -- static const ImVec2 corner_offset[4] = { {1,1}, {-1,1}, {-1,-1}, {1,-1} }; +local corner_offset_x = { 1, -1, -1, 1 } -- [Port] static const ImVec2 corner_offset[4] = { {1,1}, {-1,1}, {-1,-1}, {1,-1} }; local corner_offset_y = { 1, 1, -1, -1 } local corner_flags = { ImDrawFlags.RoundTopLeft, ImDrawFlags.RoundTopRight, ImDrawFlags.RoundBottomRight, ImDrawFlags.RoundBottomLeft } local corner_pos_x, corner_pos_y = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } -- [Luau] scratch @@ -40828,7 +40798,7 @@ function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags) end local fringe_scale = self._FringeScale - local has_rounding = rounding >= 0.25 * fringe_scale -- IM_HAS_ROUNDING(rounding) + local has_rounding = rounding >= 0.25 * fringe_scale -- [Port] IM_HAS_ROUNDING(rounding) -- Calculate the outer boundary of the rectangle based on the stroke position. local offset = 0.0 -- Inside @@ -40863,7 +40833,7 @@ function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags) outer_rounding = ImMin(outer_rounding, ImAbs(height) * (((bit32.band(flags, 80 --[[ImDrawFlags.RoundLeft]]) == 80 --[[ImDrawFlags.RoundLeft]]) or (bit32.band(flags, 160 --[[ImDrawFlags.RoundRight]]) == 160 --[[ImDrawFlags.RoundRight]])) and 0.5 or 1.0) - 1.0) end - local is_truncated = outer_min_x % 1 == 0 and outer_min_y % 1 == 0 and outer_max_x % 1 == 0 and outer_max_y % 1 == 0 and outer_rounding % 1 == 0 and thickness % 1 == 0 -- IM_IS_TRUNCATED4() x2 + local is_truncated = outer_min_x % 1 == 0 and outer_min_y % 1 == 0 and outer_max_x % 1 == 0 and outer_max_y % 1 == 0 and outer_rounding % 1 == 0 and thickness % 1 == 0 -- [Port] IM_IS_TRUNCATED4() x2 if self._FringeScaleIsInteger and is_truncated then local s_rounding = ImTrunc64(outer_rounding * self._InvFringeScale) local s_thickness = ImTrunc64(thickness * self._InvFringeScale) @@ -40959,7 +40929,7 @@ end local function _AddRectFilledBakedXY(self, p_min_x, p_min_y, p_max_x, p_max_y, col, r, tex_uvs, flags) -- 9-slice with corner mirroring - local uv_l, uv_t, uv_r, uv_b = tex_uvs.x, tex_uvs.y, tex_uvs.z, tex_uvs.w -- uv_tl = (l,t), uv_tr = (r,t), uv_br = (r,b), uv_bl = (l,b) + local uv_l, uv_t, uv_r, uv_b = tex_uvs.x, tex_uvs.y, tex_uvs.z, tex_uvs.w -- [Port] uv_tl = (l,t), uv_tr = (r,t), uv_br = (r,b), uv_bl = (l,b) PrimReserve(self, 9 * 2 * 3, 4 * 4) @@ -41067,8 +41037,8 @@ function MT.ImDrawList:AddRectFilled(p_min, p_max, col, rounding, flags) end -- When rounding non-integer and under threshold, has_rounding may be false but still affect is_truncated. Likely not worth catering for. - local has_rounding = bit32.band(flags, 496 --[[ImDrawFlags.RoundMask_]]) ~= 256 --[[ImDrawFlags.RoundNone]] and rounding >= 0.25 * fringe_scale -- IM_HAS_ROUNDING(rounding) - local is_truncated = ax % 1 == 0 and ay % 1 == 0 and bx % 1 == 0 and by % 1 == 0 and rounding % 1 == 0 -- IM_IS_TRUNCATED4() && IM_IS_TRUNCATED() + local has_rounding = bit32.band(flags, 496 --[[ImDrawFlags.RoundMask_]]) ~= 256 --[[ImDrawFlags.RoundNone]] and rounding >= 0.25 * fringe_scale -- [Port] IM_HAS_ROUNDING(rounding) + local is_truncated = ax % 1 == 0 and ay % 1 == 0 and bx % 1 == 0 and by % 1 == 0 and rounding % 1 == 0 -- [Port] IM_IS_TRUNCATED4() && IM_IS_TRUNCATED() if self._FringeScaleIsInteger and is_truncated then -- Fast path for the non-AA non-rounded rect. @@ -41510,7 +41480,7 @@ local AddText_clip_rect = ImVec4() function MT.ImDrawList:AddText(font, font_size, pos, col, text, text_begin, text_end, wrap_width, cpu_fine_clip_rect) - -- Overload: AddText(pos, col, text, text_end?) + -- [Port] Overload: AddText(pos, col, text, text_end?) if type(font) == "table" and type(font[1]) == "number" then font, font_size, pos, col, text, text_begin, text_end, wrap_width, cpu_fine_clip_rect = nil, 0.0, font, font_size, pos, 1, col, 0.0, nil if text_end == nil then text_end = #text + 1 end @@ -41643,7 +41613,7 @@ function MT.ImDrawList:_CalcCircleAutoSegmentCount(radius) -- Automatic segment count local radius_idx = ImFloor(radius + 0.999) + 1 -- ceil to never reduce accuracy - if radius_idx >= 1 and radius_idx <= 64 then -- IM_COUNTOF(_Data->CircleSegmentCounts) + if radius_idx >= 1 and radius_idx <= 64 then -- [Port] IM_COUNTOF(_Data->CircleSegmentCounts) return self._Data.CircleSegmentCounts[radius_idx] -- Use cached value else return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, self._Data.CircleTessellationMaxError) @@ -41683,7 +41653,7 @@ function MT.ImDrawList:PopClipRect() local stack = self._ClipRectStack assert(stack.Size > 0) stack.Size = stack.Size - 1 -- [Luau] inline pop_back() - if (stack.Size == 0) then -- LUA: No "Ternary Operator" + if (stack.Size == 0) then -- [Port] No "Ternary Operator" ImVec4_Copy(self._CmdHeader.ClipRect, self._Data.ClipRectFullscreen) else ImVec4_Copy(self._CmdHeader.ClipRect, stack.Data[stack.Size]) @@ -41702,7 +41672,7 @@ function MT.ImDrawList:GetClipRectMax() local cr = self._ClipRectStack:back(); r -- [Luau] scalar center (cx, cy); assigned to the forward-declared local, _PathArcToFastEx() wraps it function _PathArcToFastExXY(self, cx, cy, radius, a_min_sample, a_max_sample, a_step) - if not (radius >= 0.25 * self._FringeScale) then -- !IM_HAS_ROUNDING(radius) + if not (radius >= 0.25 * self._FringeScale) then -- [Port] !IM_HAS_ROUNDING(radius) PathLineToXY(self, cx, cy) return end @@ -41808,7 +41778,7 @@ end -- 0: East, 3: South, 6: West, 9: North, 12: East function MT.ImDrawList:PathArcToFast(center, radius, a_min_of_12, a_max_of_12) - if not (radius >= 0.25 * self._FringeScale) then -- !IM_HAS_ROUNDING(radius) + if not (radius >= 0.25 * self._FringeScale) then -- [Port] !IM_HAS_ROUNDING(radius) self._Path:push_back(center) return end @@ -41822,7 +41792,7 @@ end --- @param a_max float --- @param num_segments int function MT.ImDrawList:_PathArcToN(center, radius, a_min, a_max, num_segments) - if not (radius >= 0.25 * self._FringeScale) then -- !IM_HAS_ROUNDING(radius) + if not (radius >= 0.25 * self._FringeScale) then -- [Port] !IM_HAS_ROUNDING(radius) self._Path:push_back(center) return end @@ -41850,7 +41820,7 @@ end function MT.ImDrawList:PathArcTo(center, radius, a_min, a_max, num_segments) if num_segments == nil then num_segments = 0 end - if not (radius >= 0.25 * self._FringeScale) then -- !IM_HAS_ROUNDING(radius) + if not (radius >= 0.25 * self._FringeScale) then -- [Port] !IM_HAS_ROUNDING(radius) self._Path:push_back(center) return end @@ -41929,8 +41899,6 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b y = IM_TRUNC(y) end - -- if not text_end then - -- end local line_height = size local baked = self:GetFontBaked(size) @@ -42050,7 +42018,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b if gi ~= nil and gi ~= IM_FONTGLYPH_INDEX_NOT_FOUND and gi ~= IM_FONTGLYPH_INDEX_UNUSED then glyph = glyphs[gi] else - glyph = baked:FindGlyph(c) -- may load the glyph and grow the tables + glyph = baked:FindGlyph(c) -- [Port] may load the glyph and grow the tables lookup, lookup_n, glyphs = baked.IndexLookup.Data, baked.IndexLookup.Size, baked.Glyphs.Data end @@ -42125,7 +42093,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b draw_list:PrimUnreserve(idx_count_max, vtx_count_max) draw_list:AddDrawCmd() - return self:RenderText(draw_list, size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, flags) -- was `goto begin` + return self:RenderText(draw_list, size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, flags) -- [Port] was `goto begin` end -- Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action. @@ -42158,7 +42126,7 @@ end --- @param color ImU32 --- @param dir ImGuiDir --- @param scale? float -local arrow_a, arrow_b, arrow_c = ImVec2(), ImVec2(), ImVec2() -- scratch: the path is consumed by AddTriangleFilled before returning +local arrow_a, arrow_b, arrow_c = ImVec2(), ImVec2(), ImVec2() -- [Port] scratch: the path is consumed by AddTriangleFilled before returning function ImGui.RenderArrow(draw_list, pos, color, dir, scale) if scale == nil then scale = 1.0 end @@ -42434,7 +42402,7 @@ function ImGui.RenderRectFilledWithHole(draw_list, outer, inner, col, rounding) end ------------------------------------------------------------------------------- --- Extra path functions (elliptical arc, bezier curves) and concave fill +-- [Port] Extra path functions (elliptical arc, bezier curves) and concave fill ------------------------------------------------------------------------------- function MT.ImDrawList:PathEllipticalArcTo(center, radius, rot, a_min, a_max, num_segments) @@ -42547,7 +42515,7 @@ local function ImTriangulatorNode_Unlink(tri, n) tri.Prev[tri.Next[n]] = tri.Pre local function ImTriangulator_IsReflex(a, b, c) return ((b.x - a.x) * (c.y - b.y)) - ((c.x - b.x) * (b.y - a.y)) < 0.0 end local function ImTriangulatorNodeSpan() - return { Data = {}, Size = 0 } -- Data: node handles, 1-based + return { Data = {}, Size = 0 } -- [Port] Data: node handles, 1-based end MT.ImTriangulatorNodeSpan = {} MT.ImTriangulatorNodeSpan.__index = MT.ImTriangulatorNodeSpan @@ -42559,7 +42527,7 @@ function MT.ImTriangulatorNodeSpan:find_erase_unsorted(idx) for i = self.Size, 1 local function ImTriangulator() return setmetatable({ _TrianglesLeft = 0, - _Nodes = 0, -- node handle (head of the circular list) + _Nodes = 0, -- [Port] node handle (head of the circular list) _Ears = setmetatable(ImTriangulatorNodeSpan(), MT.ImTriangulatorNodeSpan), _Reflexes = setmetatable(ImTriangulatorNodeSpan(), MT.ImTriangulatorNodeSpan), Type = {}, Index = {}, Pos = {}, Next = {}, Prev = {}, -- [Luau] ImTriangulatorNode fields, one array each @@ -42990,7 +42958,7 @@ function stb_decompress(output, i, length) end end -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value end __FILES['imgui_h.lua'] = function() @@ -43010,7 +42978,7 @@ __FILES['imgui_h.lua'] = function() -- Index of this file: -- [SECTION] Forward declarations and basic types --- [SECTION] METATABLE MANAGEMENT +-- [Port] [SECTION] METATABLE MANAGEMENT -- [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> -- [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) -- [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) @@ -43029,7 +42997,7 @@ __FILES['imgui_h.lua'] = function() local type = type -- [Luau] builtin (FASTCALL); ImGui._GetTypeFunc() kept for compatibility local rawget = rawget; local rawset = rawset --- [LuaBitOp](https://bitop.luajit.org/semantics.html) +-- [Port] [LuaBitOp](https://bitop.luajit.org/semantics.html) local bitAnd = bit32.band; local bitOr = bit32.bor local bitLShift = bit32.lshift @@ -43134,10 +43102,10 @@ IM_FREE = ImGui.MemFree IM_DELETE = function(owner, field) if owner[field] ~= nil then owner[field] = nil; ImGui.MemFree(owner, field); end end ------------------------------------------------------------------------------- --- [SECTION] METATABLE MANAGEMENT +-- [Port] [SECTION] METATABLE MANAGEMENT ------------------------------------------------------------------------------- ---- File-scope metatable storage +--- [Port] File-scope metatable storage local MT = {} function ImGui.GetMetatables() return MT end @@ -43149,7 +43117,7 @@ function IM_ASSERT(_EXPR, _MSG) assert((_EXPR), _MSG) end IM_ASSERT_PARANOID = IM_ASSERT -- A primary data type ---- Note that `S64` and `U64` are not supported +--- [Port] Note that `S64` and `U64` are not supported --- @enum ImGuiDataType ImGuiDataType = { @@ -43330,7 +43298,7 @@ function ImVec2_SubVA(v, sub_x, sub_y) return v.x - sub_x, v.y - sub_y end function ImVec2_MulVX(a, scalar) return a.x * scalar, a.y * scalar end ---- An inlined version of `ImVec2_Copy` currently for use in certain ImVector `push_back` +--- [Port] An inlined version of `ImVec2_Copy` currently for use in certain ImVector `push_back` local function ImVec2_TCopy(t, k, v) local dest = t[k]; dest.x = v.x; dest.y = v.y; end -- ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type] @@ -43379,7 +43347,7 @@ function ImVec4_Copy(dest, src) dest.x = src.x; dest.y = src.y; dest.z = src.z; ------------------------------------------------------------------------------- -- ImVector<> ---- A compact ImVector clone +--- [Port] A compact ImVector clone --- @class ImVector --- @field Data T[] # 1-based table --- @field Size int # >= 0 @@ -43387,22 +43355,22 @@ function ImVec4_Copy(dest, src) dest.x = src.x; dest.y = src.y; dest.z = src.z; --- @field _CopyFunc function local IM_VECTOR = {} --- Support 1-based number key indexing while keep method accessing speed +-- [Port] Support 1-based number key indexing while keep method accessing speed --- @param t ImVector --- @param k string|int --- @return any IM_VECTOR.__index = function(t, k) - local m = IM_VECTOR[k] -- methods first (hot path) + local m = IM_VECTOR[k] -- [Port] methods first (hot path) if m ~= nil then return m end - if k == "Data" then return nil end -- Data has already been discarded - return t.Data[IM_ASSERT(k >= 1 and k <= t.Size) or k] -- if the mt access turns out nil, the k must be int index into Data + if k == "Data" then return nil end -- [Port] Data has already been discarded + return t.Data[IM_ASSERT(k >= 1 and k <= t.Size) or k] -- [Port] if the mt access turns out nil, the k must be int index into Data end --- @param t ImVector --- @param k int --- @param v any IM_VECTOR.__newindex = function(t, k, v) - if k == "Data" then rawset(t, "Data", v); return; end -- set new Data. old Data is already discarded + if k == "Data" then rawset(t, "Data", v); return; end -- [Port] set new Data. old Data is already discarded assert(k >= 1 and k <= t.Size) t.Data[k] = v end @@ -43465,10 +43433,10 @@ end function IM_VECTOR:swap(other) self.Size, other.Size = other.Size, self.Size; self.Capacity, other.Capacity = other.Capacity, self.Capacity; self.Data, other.Data = other.Data, self.Data end function IM_VECTOR:contains(v) for i = 1, self.Size do if self.Data[i] == v then return true end end return false end --- NOTE: This currently does not use type-aware copy! +-- [Port] NOTE: This currently does not use type-aware copy! function IM_VECTOR:insert(pos, value) assert(pos >= 1 and pos <= self.Size + 1); if self.Size == self.Capacity then self:reserve(_grow_capacity(self, self.Size + 1)) end; for i = self.Size, pos, -1 do self.Data[i + 1] = self.Data[i] end self.Data[pos] = value self.Size = self.Size + 1 return value end --- NOTE: This currently does not copy type related info! +-- [Port] NOTE: This currently does not copy type related info! --- @nodiscard function IM_VECTOR:copy() local v = ImVector(); v:resize(self.Size) @@ -43477,7 +43445,7 @@ function IM_VECTOR:copy() return v end --- Not keeping value-key records inside `ImVector`, instead just find it +-- [Port] Not keeping value-key records inside `ImVector`, instead just find it --- @return int # 0-based index function IM_VECTOR:index_from_ptr(p) local data = self.Data; for i = 1, self.Size do if p == data[i] then return i - 1 end end @@ -43595,7 +43563,7 @@ function ImDrawChannel() return { _CmdBuffer = ImVector(), _IdxBuffer = ImVector --- @return ImDrawListSplitter --- @nodiscard -MT.ImDrawListSplitter = {} -- methods in imgui_draw.lua +MT.ImDrawListSplitter = {} -- [Port] methods in imgui_draw.lua MT.ImDrawListSplitter.__index = MT.ImDrawListSplitter function ImDrawListSplitter() return setmetatable({ _Current = 0, _Count = 0, _Channels = ImVector() }, MT.ImDrawListSplitter) end @@ -44341,7 +44309,7 @@ function ImGuiIO() -- - Suggested use, e.g. io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map to SHIFT modifier ConfigDebugDrawListDefaultsToStrokeLegacy = false, -- false -- Default all ImDrawList to ImDrawList_StrokeLegacy mode, mimicking pre-1.93.0 rendering. - IniFilename = "imgui.ini", -- Roblox: no disk access, only used as a flag (nil disables .ini handling) + IniFilename = "imgui.ini", -- [Port] no disk access, only used as a flag (nil disables .ini handling) IniSavingRate = 5.0, -- = 5.0f -- Minimum time between saving positions/sizes to .ini file, in seconds. LogFilename = "imgui_log.txt", -- = "imgui_log.txt"-- Path to .log file (default parameter to ImGui.LogToFile when no file is specified). WantSaveIniSettings = false, -- When manual .ini load/save is active (io.IniFilename == nil), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! @@ -45108,7 +45076,7 @@ ImGuiKey = { RightCtrl = 531, RightShift = 532, RightAlt = 533, RightSuper = 534, Menu = 535, - -- 0 ~ 9 (upstream ImGuiKey_0..ImGuiKey_9: K0..K9 in this port, ImGuiKey["0"]..ImGuiKey["9"] are aliases) + -- [Port] 0 ~ 9 (upstream ImGuiKey_0..ImGuiKey_9: K0..K9 in this port, ImGuiKey["0"]..ImGuiKey["9"] are aliases) K0 = 536, K1 = 537, K2 = 538, K3 = 539, K4 = 540, K5 = 541, K6 = 542, K7 = 543, K8 = 544, K9 = 545, ["0"] = 536, ["1"] = 537, ["2"] = 538, ["3"] = 539, ["4"] = 540, ["5"] = 541, ["6"] = 542, ["7"] = 543, ["8"] = 544, ["9"] = 545, @@ -45530,7 +45498,7 @@ ImGuiInputTextFlags = { --- @class ImGuiInputTextCallbackData --- @return ImGuiInputTextCallbackData --- Buf is a 1-based zero-terminated byte table; positions (CursorPos, pos...) are 0-based byte offsets like upstream. +-- [Port] Buf is a 1-based zero-terminated byte table; positions (CursorPos, pos...) are 0-based byte offsets like upstream. MT.ImGuiInputTextCallbackData = {} MT.ImGuiInputTextCallbackData.__index = MT.ImGuiInputTextCallbackData function ImGuiInputTextCallbackData() @@ -45540,7 +45508,7 @@ end function MT.ImGuiInputTextCallbackData:DeleteChars(pos, bytes_count) assert(pos + bytes_count <= self.BufTextLen) local buf = self.Buf - local n = self.BufTextLen - bytes_count - pos + 1 -- includes zero terminator + local n = self.BufTextLen - bytes_count - pos + 1 -- [Port] includes zero terminator for i = 1, n do buf[pos + i] = buf[pos + bytes_count + i] end if self.CursorPos >= pos + bytes_count then @@ -45561,10 +45529,10 @@ function MT.ImGuiInputTextCallbackData:InsertChars(pos, new_text) -- We support partial insertion local avail = self.BufSize - 1 - self.BufTextLen if not is_resizable and new_text_len > avail then - new_text_len = avail -- ponytail: truncates by bytes, not to the closest UTF-8 codepoint + new_text_len = avail end if new_text_len <= 0 then return end - -- ponytail: CallbackResize buffer growth not supported, text is truncated at BufSize instead + if self.BufTextLen + new_text_len + 1 > self.BufSize then new_text_len = self.BufSize - 1 - self.BufTextLen if new_text_len <= 0 then return end @@ -45798,7 +45766,7 @@ end -- Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() --- @class ImGuiPayload ---- Drag and drop payload. `Data` is any Lua value (C++ stores raw bytes); `DataSize` kept for API parity. +--- [Port] Drag and drop payload. `Data` is any Lua value (C++ stores raw bytes); `DataSize` kept for API parity. local IM_PAYLOAD = {} IM_PAYLOAD.__index = IM_PAYLOAD function IM_PAYLOAD:Clear() ImGuiPayload_Clear(self) end @@ -45976,18 +45944,18 @@ function ImGuiMultiSelectIO() return { Requests = ImVector(ImGuiSelectionRequest, ImGuiSelectionRequest_Copy), RangeSrcItem = -1, NavIdItem = -1, NavIdSelected = false, RangeSrcReset = false, ItemsCount = 0 } end --- ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage: see [SECTION] Widgets: Multi-Select helpers in imgui_widgets.lua +-- [Port] ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage: see [SECTION] Widgets: Multi-Select helpers in imgui_widgets.lua -- (constructors and methods are defined there, like upstream's out-of-line definitions in imgui_widgets.cpp). --- @class ImGuiSettingsHandler ---- Fns take (ctx, handler, ...) like upstream. ReadOpenFn(ctx, handler, name) returns entry; ReadLineFn(ctx, handler, entry, line); +--- [Port] Fns take (ctx, handler, ...) like upstream. ReadOpenFn(ctx, handler, name) returns entry; ReadLineFn(ctx, handler, entry, line); --- WriteAllFn(ctx, handler, buf: ImGuiTextBuffer) function ImGuiSettingsHandler() return { TypeName = nil, TypeHash = 0, ClearAllFn = nil, ReadInitFn = nil, ReadOpenFn = nil, ReadLineFn = nil, ApplyAllFn = nil, WriteAllFn = nil, CleanupFn = nil, UserData = nil } end -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value end __FILES['imgui_impl_love.lua'] = function() @@ -46563,7 +46531,7 @@ __FILES['imgui_internal.lua'] = function() -- [SECTION] ImFontLoader -- [SECTION] ImFontAtlas internal API -- --- PORT: the order of declarations in this file does not strictly follow upstream's imgui_internal.h. +-- [Port] the order of declarations in this file does not strictly follow upstream's imgui_internal.h. --- @meta @@ -46581,11 +46549,10 @@ local t_sort = table.sort --- @alias ImGuiTableColumnIdx ImS16 --- TODO: Implement actual ImString type +-- [Port] TODO: Implement actual ImString type --- @alias ImString char[]|string --- @alias ImStringBuffer char[] --- NOTE: temporary solution --- @param buf char[] --- @param buf_begin int --- @param buf_end int # exclusive @@ -46601,7 +46568,7 @@ end -- Helper: ImPool<> -- Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer, -- Indexes have the same lifetime as the associated object. ---- ImPool: pool of objects keyed by ID. Public indices are 0-based like upstream (Buf is stored 1-based). +--- [Port] ImPool: pool of objects keyed by ID. Public indices are 0-based like upstream (Buf is stored 1-based). --- `ctor` creates a new element. Removed slots are recycled via FreeIdx (-1 = none; free slots chain through `_NextFree`). local IM_POOL = {} IM_POOL.__index = IM_POOL @@ -46636,7 +46603,7 @@ function IM_POOL:Remove(key, p) self.AliveCount = self.AliveCount - 1 end function IM_POOL:Reserve(n) end --- NOTE: removed slots hold `false`; iterate with `for i = 0, pool:GetMapSize() - 1 do local t = pool:GetByIndex(i) if t then ... end end` +-- [Port] NOTE: removed slots hold `false`; iterate with `for i = 0, pool:GetMapSize() - 1 do local t = pool:GetByIndex(i) if t then ... end end` ------------------------------------------------------------------------------- -- [SECTION] Context pointer @@ -46646,7 +46613,7 @@ function IM_POOL:Reserve(n) end --- @type ImGuiContext? local GImGui -- Current implicit context pointer --- Sets local `GImGui` in this file(imgui_internal.lua). +-- [Port] Sets local `GImGui` in this file(imgui_internal.lua). -- This is currently only used in main code `ImGui.SetCurrentContext()` --- @param ctx ImGuiContext? function ImGui._SetCurrentContext_Internal(ctx) @@ -46788,7 +46755,7 @@ ImTrunc64 = _Trunc --- @param f float function ImCeilFast(f) local i - if f >= 0 then i = math.floor(f) else i = math.ceil(f) end -- same as `ImTrunc()` + if f >= 0 then i = math.floor(f) else i = math.ceil(f) end -- [Port] same as `ImTrunc()` if f > i then return i + 1 end return i end @@ -46848,7 +46815,7 @@ function ImStd.ImExponentialMovingAverage(avg, sample, n) return avg end --- Uses `string.match` internally +-- [Port] Uses `string.match` internally --- @param str string function ImAtof(str) return tonumber(string.match(str, "[+-]?%d*%.?%d+")) @@ -46866,7 +46833,6 @@ do local _memmove = function(dest, dest_start, src, src_start, count) if count <= 0 then return end - -- more compact instead of writing separate if-else and for loops local c = (dest == src and dest_start >= src_start) for i = (c and count - 1 or 0), (c and 0 or count - 1), (c and -1 or 1) do dest[dest_start + i] = src[src_start + i] @@ -46874,12 +46840,8 @@ local _memmove = function(dest, dest_start, src, src_start, count) end if table.move then - --- [GMod] Platform specific: the `table.move` polyfill in non-x86-64 currently uses `unpack` which will break if too many elements - -- Remove this check when the polyfill is fixed or removed - if not gmod or (gmod and BRANCH == "x86-64") then - _memmove = function(dest, dest_start, src, src_start, count) - table.move(src, src_start, src_start + count - 1, dest_start, dest) - end + _memmove = function(dest, dest_start, src, src_start, count) + table.move(src, src_start, src_start + count - 1, dest_start, dest) end end @@ -47026,9 +46988,9 @@ function ImStd.ImStrlen(str, begin) assert(false) end --- FIXME: should also accept count? --- FIXME: avoid dynamic type checking? --- string.find with patterns disabled +-- [Port] FIXME: should also accept count? +-- [Port] FIXME: avoid dynamic type checking? +-- [Port] string.find with patterns disabled --- @param str string|char[] --- @param s string|char --- @param start_pos? int @@ -47076,7 +47038,7 @@ IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT = ((IM_DRAWLIST_TEX_LINES_DETAILED_WI -- - The message will always be a string literal, in order to increase likelihood of being display by an assert handler. -- - See 'Demo->Configuration->Error Handling' and ImGuiIO definitions for details on error handling. -- - Read https://github.com/ocornut/imgui/wiki/Error-Handling for details on error handling. --- Upstream: `if (!(expr) && ErrorLog(msg)) IM_ASSERT(0)`. ErrorLog() returns io.ConfigErrorRecoveryEnableAssert. +-- [Port] Upstream: `if (!(expr) && ErrorLog(msg)) IM_ASSERT(0)`. ErrorLog() returns io.ConfigErrorRecoveryEnableAssert. function IM_ASSERT_USER_ERROR(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then if not ImGui.ErrorLog or ImGui.ErrorLog(_MSG) then error(_MSG, 2) end end end -- Recoverable User Error function IM_ASSERT_USER_ERROR_RET(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then error(_MSG, 2) end end @@ -47589,7 +47551,7 @@ end -- Helper: ImBitArray class (wrapper over ImBitArray functions) -- Store 1-bit per value. ---- NOTE: This struct is expensive to create +--- [Port] NOTE: This struct is expensive to create --- @class ImBitArray --- @field Data ImU32[] @@ -47813,7 +47775,7 @@ function ImFontAtlasBuilder() this.PreloadedAllGlyphsRanges = false -- Set when missing ImGuiBackendFlags.RendererHasTextures features forces atlas to preload everything. -- Cache of all ImFontBaked - this.BakedPool = ImVector() -- ImStableVector + this.BakedPool = ImVector() -- [Port] ImStableVector this.BakedMap = {} -- BakedId --> ImFontBaked this.BakedDiscardedCount = 0 @@ -47854,7 +47816,7 @@ end -- [SECTION] Style support ------------------------------------------------------------------------------- ---- `GetVarPtr()` is currently only used on `g.Style` in Dear ImGui, and we don't have pointers! +--- [Port] `GetVarPtr()` is currently only used on `g.Style` in Dear ImGui, and we don't have pointers! --- @class ImGuiStyleVarInfo --- @field Count ImU32 # 1+ --- @field DataType ImGuiDataType @@ -48369,7 +48331,7 @@ local function ImGuiInputTextState() SelectedAllMouseLock = false, -- after a double-click to select all, we ignore further mouse drags to update selection EditedBefore = false, -- edited since activated EditedThisFrame = false, -- edited this frame - ValidatedThisFrame = false, -- validated this frame (e.g. Enter pressed) + ValidatedThisFrame = false, WantReloadUserBuf = false, -- force a reload of user buf so it may be modified externally. may be automatic in future version. LastMoveDirectionLR = 0 --[[ImGuiDir.Left]], -- ImGuiDir_Left or ImGuiDir_Right. track last movement direction so when cursor cross over a word-wrapping boundaries we can display it on either line depending on last move.s ReloadSelectionStart = 0, @@ -48662,7 +48624,7 @@ end ------------------------------------------------------------------------------- -- We always assume that -1 is an invalid value (which works for indices and pointers) --- (ImGuiSelectionUserData_Invalid is defined above with the ImGuiSelectionUserData alias) +-- [Port] (ImGuiSelectionUserData_Invalid is defined above with the ImGuiSelectionUserData alias) -- Temporary storage for multi-select --- @class ImGuiMultiSelectTempData @@ -48803,7 +48765,7 @@ function ImGui.GetMultiSelectState(id) local g = GImGui; return g.MultiSelectSto ------------------------------------------------------------------------------- -- [SECTION] Tab bar, Tab item support --- PORT: public flags from imgui.h + private extensions +-- [Port] public flags from imgui.h + private extensions ------------------------------------------------------------------------------- -- Flags for ImGui.BeginTabBar() @@ -48852,7 +48814,7 @@ ImGuiTabItemFlags = { } ImGuiTabItemFlags.SectionMask_ = bitOr(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing) --- Storage for one active tab item. In this port the label is stored in `Name` (C++ uses NameOffset into TabBar.TabsNames) +-- [Port] Storage for one active tab item. In this port the label is stored in `Name` (C++ uses NameOffset into TabBar.TabsNames) --- @class ImGuiTabItem --- @return ImGuiTabItem function ImGuiTabItem() @@ -48871,7 +48833,7 @@ function ImGuiTabItem() } end --- Storage for a tab bar. Tabs: ImVector of ImGuiTabItem tables (references; "pointers" stay valid across reorders) +-- [Port] Storage for a tab bar. Tabs: ImVector of ImGuiTabItem tables (references; "pointers" stay valid across reorders) --- @class ImGuiTabBar --- @return ImGuiTabBar function ImGuiTabBar() @@ -48903,7 +48865,7 @@ function ImGuiShrinkWidthItem() return { Index = 0, Width = 0.0, InitialWidth = --- @param shared_font_atlas? ImFontAtlas --- @return ImGuiContext --- @nodiscard -function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this structure +function ImGuiContext(shared_font_atlas) local this = { Style = ImGuiStyle(), ColorStack = ImVector(), -- Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() @@ -49141,20 +49103,20 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct ComboPreviewData = ImGuiComboPreviewData(), CurrentTabBar = nil, - TabBars = ImPool(ImGuiTabBar), -- ImPool + TabBars = ImPool(ImGuiTabBar), -- [Port] ImPool -- Docking DockContext = ImGuiDockContext(), DockNodeWindowMenuHandler = nil, DebugHoveredDockNode = nil, -- Hovered dock node. - CurrentTabBarStack = ImVector(), -- ImVector - ShrinkWidthBuffer = ImVector(), -- ImGuiShrinkWidthItem + CurrentTabBarStack = ImVector(), -- [Port] ImVector + ShrinkWidthBuffer = ImVector(), -- [Port] ImGuiShrinkWidthItem -- Multi-Select state BoxSelectState = ImGuiBoxSelectState(), CurrentMultiSelect = nil, MultiSelectTempDataStacked = 0, -- Temporary multi-select data size (because we leave previous instances undestructed, we generally don't use MultiSelectTempData.Size) - MultiSelectTempData = ImVector(), -- ImVector, 1-based - MultiSelectStorage = ImPool(ImGuiMultiSelectState), -- ImPool + MultiSelectTempData = ImVector(), -- [Port] ImVector, 1-based + MultiSelectStorage = ImPool(ImGuiMultiSelectState), -- [Port] ImPool WindowResizeBorderExpectedRect = ImRect(), -- Expected border rect, switch to relative edit if moving WindowResizeRelativeMode = false, @@ -49276,7 +49238,7 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct DebugAllocInfo = ImGuiDebugAllocInfo(), --- Misc - FramerateSecPerFrame = {}, -- size = 60 + FramerateSecPerFrame = {}, -- [Port] size = 60 FramerateSecPerFrameIdx = 0, FramerateSecPerFrameCount = 0, FramerateSecPerFrameAccum = 0, @@ -49286,15 +49248,15 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct WantTextInputNextFrame = -1, -- Copied in EndFrame() from g.PlatformImeData.WantTextInput. Needs to be set for some backends (SDL3) to emit character inputs. TempBuffer = ImVector(), -- Temporary text buffer - -- Tables (imgui_tables.lua) + -- [Port] Tables (imgui_tables.lua) CurrentTable = nil, DebugBreakInTable = 0, -- Set to break in BeginTable() call. TablesTempDataStacked = 0, -- Temporary table data size (because we leave previous instances undestructed, we generally don't use TablesTempData.Size) TablesTempData = ImVector(), -- Temporary table data (buffers reused/shared across instances, support nesting) - Tables = ImPool(), -- ImPool, 0-based indices (imgui_tables.lua) - TablesLastTimeActive = ImVector(), -- [table_idx + 1] = float + Tables = ImPool(), -- [Port] ImPool, 0-based indices (imgui_tables.lua) + TablesLastTimeActive = ImVector(), -- [Port] [table_idx + 1] = float DrawChannelsTempMergeBuffer = ImVector(), - SettingsTables = ImVector(), -- ImChunkStream: plain vector, SettingsOffset = 1-based index + SettingsTables = ImVector(), -- [Port] ImChunkStream: plain vector, SettingsOffset = 1-based index } for i = 0, 59 do this.FramerateSecPerFrame[i] = 0 end @@ -49469,7 +49431,7 @@ local function ImGuiWindowTempData() TreeRecordsClippedNodesY2Mask = nil, -- Store whether we should keep recording Y2. Cleared when passing clip max. Equivalent TreeHasStackDataDepthMask value should always be set. ChildWindows = ImVector(), - CurrentTableIdx = -1, -- 0-based index into g.Tables, -1 if none + CurrentTableIdx = -1, -- [Port] 0-based index into g.Tables, -1 if none CurrentColumns = nil, -- ImGuiOldColumns (legacy Columns API) StateStorage = nil, -- Current persistent per-window storage (store e.g. tree node open/close state) @@ -49667,7 +49629,7 @@ function ImGuiWindow(ctx, name) LastTimeActive = -1.0, -- Last timestamp the window was Active (using float as we don't need high precision there) StateStorage = {}, - ColumnsStorage = ImVector(), -- ImVector + ColumnsStorage = ImVector(), -- [Port] ImVector WriteAccessed = false, -- Set to true when any widget access the current window @@ -49677,7 +49639,7 @@ function ImGuiWindow(ctx, name) HitTestHoleSize = ImVec2(), -- Define an optional rectangular hole where mouse will pass-through the window. NavLastChildNavWindow = nil, -- When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) - NavLastIds = {[0] = 0, [1] = 0}, -- FIXME: 1-based instead + NavLastIds = {[0] = 0, [1] = 0}, -- [Port] FIXME: 1-based instead NavRectRel = {[0] = ImRect(), [1] = ImRect()}, -- Reference rectangle, in window relative space NavPreferredScoringPosRel = {[0] = ImVec2(), [1] = ImVec2()}, -- Preferred X/Y position updated when moving on a given axis, reset to FLT_MAX. NavRootFocusScopeId = 0 -- Focus Scope ID at the time of Begin() @@ -50503,7 +50465,7 @@ function ImGui.GetCurrentTabBar() local g = GImGui; return g.CurrentTabBar end function ImGui.IsItemActiveAsInputText() local g = GImGui; return g.ActiveId ~= 0 and g.ActiveId == g.LastItemData.ID and g.InputTextState.ID == g.LastItemData.ID end -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value end __FILES['imgui_tables.lua'] = function() @@ -50685,22 +50647,22 @@ __FILES['imgui_tables.lua'] = function() -- - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false. ------------------------------------------------------------------------------- --- Port notes: --- - Column indices / display orders / draw channel indices are 0-based VALUES like upstream. --- Per-column arrays (table.Columns, table.DisplayOrderToIndex, table.RowCellData) are Lua tables with 0-based keys. --- table.ColumnsSize mirrors upstream `table->Columns.size()`. --- - ImBitArray masks are Lua tables { [n] = true }. --- - table.ColumnsNames is a Lua array of strings, column.NameOffset is a 0-based index into it (-1 = none). --- - g.SettingsTables is a plain vector of ImGuiTableSettings; table.SettingsOffset is a 1-based index into it (-1 = none). --- Each settings entry owns `Columns` (0-based Lua table of ImGuiTableColumnSettings). --- - ImGuiTableSortSpecs.Specs is a 1-based Lua array of ImGuiTableColumnSortSpecs. +-- [Port] Port notes: +-- [Port] - Column indices / display orders / draw channel indices are 0-based VALUES like upstream. +-- [Port] Per-column arrays (table.Columns, table.DisplayOrderToIndex, table.RowCellData) are Lua tables with 0-based keys. +-- [Port] table.ColumnsSize mirrors upstream `table->Columns.size()`. +-- [Port] - ImBitArray masks are Lua tables { [n] = true }. +-- [Port] - table.ColumnsNames is a Lua array of strings, column.NameOffset is a 0-based index into it (-1 = none). +-- [Port] - g.SettingsTables is a plain vector of ImGuiTableSettings; table.SettingsOffset is a 1-based index into it (-1 = none). +-- [Port] Each settings entry owns `Columns` (0-based Lua table of ImGuiTableColumnSettings). +-- [Port] - ImGuiTableSortSpecs.Specs is a 1-based Lua array of ImGuiTableColumnSortSpecs. --- @type ImGuiContext? local GImGui local MT = ImGui.GetMetatables() --- Sets local `GImGui` in this file(imgui_tables.lua). +-- [Port] Sets local `GImGui` in this file(imgui_tables.lua). -- This is currently only used in main code `ImGui.SetCurrentContext()` --- @param ctx ImGuiContext? function ImGui._SetCurrentContext_Tables(ctx) @@ -50998,7 +50960,7 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi -- Acquire storage for the table local table_ = g.Tables:GetOrAddByKey(id) - if table_.Columns == nil then -- pool created a plain table + if table_.Columns == nil then -- [Port] pool created a plain table for k, v in pairs(ImGuiTable()) do table_[k] = v end end @@ -52502,7 +52464,7 @@ function ImGui.TableReconcileColumns(table_) end -- Remaining entries are matched sequentially. - local dst_idx = 1 -- index in reconcile array (1-based) + local dst_idx = 1 -- [Port] index in reconcile array (1-based) if matches ~= reconcile_requests.Size then for src_n = 0, src_count - 1 do local src_column = src_columns[src_n] @@ -52594,7 +52556,7 @@ function ImGui.TableGetColumnCount() return table_ and table_.ColumnsCount or 0 end --- Overloads: TableGetColumnName(column_n?) / TableGetColumnName(table, column_n) +-- [Port] Overloads: TableGetColumnName(column_n?) / TableGetColumnName(table, column_n) function ImGui.TableGetColumnName(a, b) local table_, column_n if type(a) == "table" then @@ -53512,7 +53474,7 @@ end -- Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd. -- -- This function is particularly tricky to understand.. take a breath. --- (Lua: splitter channel n lives in splitter._Channels.Data[n + 1]; bit arrays are Lua sets) +-- [Port] (Lua: splitter channel n lives in splitter._Channels.Data[n + 1]; bit arrays are Lua sets) local TableMergeDrawChannels_MergeGroups = {} for n = 0, 3 do TableMergeDrawChannels_MergeGroups[n] = { ClipRect = ImRect(), ChannelsCount = 0, ChannelsMask = {} } @@ -53810,7 +53772,7 @@ end -- changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, -- else you may wastefully sort your data every frame! -- Lifetime: don't hold on this table over multiple frames or past any subsequent call to BeginTable()! --- PORT: Specs is a 1-based Lua array. +-- [Port] Specs is a 1-based Lua array. function ImGui.TableGetSortSpecs() local g = GImGui local table_ = g.CurrentTable @@ -53902,7 +53864,7 @@ function ImGui.TableSortSpecsSanitize(table_) -- Clear SortOrder from hidden column and verify that there's no gap or duplicate. local sort_order_count = 0 - local sort_order_set = {} -- C++: ImU64 sort_order_mask + local sort_order_set = {} -- [Port] C++: ImU64 sort_order_mask local sort_order_dup = false for column_n = 0, table_.ColumnsCount - 1 do local column = table_.Columns[column_n] @@ -53917,7 +53879,7 @@ function ImGui.TableSortSpecsSanitize(table_) end end - -- need_fix_linearize: (1 << count) != (mask + 1) <=> the set of sort orders isn't exactly {0..count-1} + -- [Port] need_fix_linearize: (1 << count) != (mask + 1) <=> the set of sort orders isn't exactly {0..count-1} local need_fix_linearize = sort_order_dup for n = 0, sort_order_count - 1 do if not sort_order_set[n] then need_fix_linearize = true end @@ -55101,7 +55063,7 @@ function ImGui.TableRemove(table_) end -- Free up/compact internal Table buffers for when it gets unused --- Overloads: (ImGuiTable) / (ImGuiTableTempData) +-- [Port] Overloads: (ImGuiTable) / (ImGuiTableTempData) function ImGui.TableGcCompactTransientBuffers(t) if not t then return end if t.TableIndex ~= nil then -- ImGuiTableTempData @@ -55179,7 +55141,7 @@ end -- - EndColumns() -- - Columns() ------------------------------------------------------------------------------- --- (Lua: columns.Columns is an ImVector, column n lives in .Data[n + 1]) +-- [Port] (Lua: columns.Columns is an ImVector, column n lives in .Data[n + 1]) function ImGui.GetColumnIndex() local window = ImGui.GetCurrentWindowRead() @@ -55595,7 +55557,7 @@ function ImGui.Columns(columns_count, id, borders) end end -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value end __FILES['imgui_widgets.lua'] = function() @@ -55628,7 +55590,7 @@ __FILES['imgui_widgets.lua'] = function() --- @type ImGuiContext? local GImGui --- Sets local `GImGui` in this file(imgui_widgets.lua). +-- [Port] Sets local `GImGui` in this file(imgui_widgets.lua). -- This is currently only used in main code `ImGui.SetCurrentContext()` --- @param ctx ImGuiContext? function ImGui._SetCurrentContext_Widgets(ctx) @@ -55970,7 +55932,7 @@ function ImGui.BulletText(fmt, ...) ImGui.RenderText(ImVec2(bb.Min.x + (g.FontSize + style.FramePadding.x * 2), bb.Min.y + 0.0), text, 1, text_end, false) end --- va_list variants: identical to the varargs versions in Lua +-- [Port] va_list variants: identical to the varargs versions in Lua ImGui.TextColoredV = ImGui.TextColored ImGui.TextDisabledV = ImGui.TextDisabled ImGui.TextWrappedV = ImGui.TextWrapped @@ -55985,8 +55947,8 @@ ImGui.BulletTextV = ImGui.BulletText -- - Value() ------------------------------------------------------------------------------- --- Value(prefix, b) / Value(prefix, int) / Value(prefix, float, float_format) --- Lua can't tell int from float: integers without float_format print as %d, otherwise %.3f +-- [Port] Value(prefix, b) / Value(prefix, int) / Value(prefix, float, float_format) +-- [Port] Lua can't tell int from float: integers without float_format print as %d, otherwise %.3f function ImGui.Value(prefix, v, float_format) if type(v) == "boolean" then ImGui.Text("%s: %s", prefix, v and "true" or "false") @@ -56086,7 +56048,7 @@ end -- with same ID and different MouseButton (see #8030). You can fix it by: -- (1) switching to use a single ButtonBehavior() with multiple _MouseButton flags. -- or (2) surrounding those calls with PushItemFlag(ImGuiItemFlags.AllowDuplicateId, true); ... PopItemFlag() --- Returns (pressed, hovered, held). +-- [Port] Returns (pressed, hovered, held). --- @param bb ImRect --- @param id ImGuiID --- @param flags? ImGuiButtonFlags @@ -56364,7 +56326,7 @@ function ImGui.ButtonEx(label, size_arg, flags) local label_size = ImGui.CalcTextSize(label, label_end, false) -- [Luau] scalar pos, no temporary ImVec2 - local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y -- Don't modify the cursor! + local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y local frame_padding = style.FramePadding if bit32.band(flags, 32768 --[[ImGuiButtonFlags.AlignTextBaseLine]]) ~= 0 and frame_padding.y < window.DC.CurrLineTextBaseOffset then -- Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos_y = pos_y + window.DC.CurrLineTextBaseOffset - frame_padding.y @@ -56672,7 +56634,7 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ -- As a special thing, we allow scrollbar near the edge of a screen/viewport to be reachable with mouse at the extreme edge (#9276) local bb_hit = ImRect() ImRect_Copy(bb_hit, bb_frame) - ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb_hit, g.Style.WindowBorderSize, 1 --[[ImGuiAxis.X]] + 2 --[[ImGuiAxis.Y]] - axis) -- swap axis here + ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb_hit, g.Style.WindowBorderSize, 1 --[[ImGuiAxis.X]] + 2 --[[ImGuiAxis.Y]] - axis) -- [Port] swap axis here -- Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). ImGui.ItemAdd(bb_frame, id, nil, 2 --[[ImGuiItemFlags.NoNav]]) @@ -57082,7 +57044,7 @@ function ImGui.RadioButtonEx(label, active) return pressed end --- `rawequal` is used here to check if v == v_button +-- [Port] `rawequal` is used here to check if v == v_button --- @param label string --- @param v any --- @param v_button any @@ -57812,7 +57774,7 @@ function ImGui.EndComboPreview() preview_data.WithinPreview = false end --- Getter for the old Combo() API: Lua array of strings (1-based), `idx` is 0-based +-- [Port] Getter for the old Combo() API: Lua array of strings (1-based), `idx` is 0-based local function Items_ArrayGetter(data, idx) return data[idx + 1] end @@ -57842,7 +57804,7 @@ local function Items_SingleStringCount(data) return items_count end --- Normalizes the 3 upstream overloads to (getter, user_data, items_count, height) +-- [Port] Normalizes the 3 upstream overloads to (getter, user_data, items_count, height) -- - (items: string[], items_count?, height?) -- - (items_separated_by_zeros: string, height?) -- - (getter: fun(user_data, idx): string?, user_data, items_count, height?) @@ -57969,9 +57931,9 @@ function ImGui.DataTypeGetInfo(data_type) end -- [Luau] string.format() has no length modifiers (%lld, %I64d...) and formats negative numbers as 64-bit for %u/%x/%X/%o: --- strip modifiers and re-apply C's integer promotion/two's complement for signed types. +-- [Port] strip modifiers and re-apply C's integer promotion/two's complement for signed types. local DataTypeFormatStringCached do -local fmt_info_memo = {} -- format -> { stripped format, is unsigned conversion } +local fmt_info_memo = {} -- [Port] format -> { stripped format, is unsigned conversion } local function GetFormatInfo(format) local info = fmt_info_memo[format] if info == nil then @@ -57983,7 +57945,7 @@ local function GetFormatInfo(format) return info end ---- Lua-string version of DataTypeFormatString() (memoized), used for display. +--- [Port] Lua-string version of DataTypeFormatString() (memoized), used for display. --- @param data_type ImGuiDataType --- @param data number --- @param format string @@ -57997,14 +57959,14 @@ function DataTypeFormatStringCached(data_type, data, format) elseif data_type == 1 --[[ImGuiDataType.U8]] then data = (ImU8)(data) elseif data_type == 2 --[[ImGuiDataType.S16]] then data = (ImS16)(data) elseif data_type == 3 --[[ImGuiDataType.U16]] then data = (ImU16)(data) - elseif data_type == 4 --[[ImGuiDataType.S32]] then -- (signed values are already stored signed) + elseif data_type == 4 --[[ImGuiDataType.S32]] then -- [Port] (signed values are already stored signed) elseif data_type == 5 --[[ImGuiDataType.U32]] then data = (ImU32)(data) elseif data_type == 6 --[[ImGuiDataType.S64]] or data_type == 7 --[[ImGuiDataType.U64]] then - -- (string.format() already prints negative numbers as 64-bit two's complement for %u/%x/%X/%o) + -- [Port] (string.format() already prints negative numbers as 64-bit two's complement for %u/%x/%X/%o) if info[2] then - if data >= 18446744073709551616 then data = -1 end -- (ImU64)-1 rounds to 2^64 in a double: print ULLONG_MAX + if data >= 18446744073709551616 then data = -1 end -- [Port] (ImU64)-1 rounds to 2^64 in a double: print ULLONG_MAX elseif data >= 9223372036854775808 then - data = 9223372036854774784 -- largest double below 2^63 (LLONG_MAX isn't representable) + data = 9223372036854774784 -- [Port] largest double below 2^63 (LLONG_MAX isn't representable) end return FormatCached(info[1], data) else @@ -58023,7 +57985,7 @@ end --- @return int function ImGui.DataTypeFormatString(buf, buf_size, data_type, data, format) local str = DataTypeFormatStringCached(data_type, data, format) - local len = ImMin(#str, buf_size - 1) -- ImFormatString(): truncate and return the written length + local len = ImMin(#str, buf_size - 1) -- [Port] ImFormatString(): truncate and return the written length ImStd.ImStrncpy(buf, 1, { string.byte(str, 1, len) }, 1, len + 1) return len end @@ -58576,7 +58538,7 @@ function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min return data, value_changed end --- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For an Input widget, step and step_fast are optional. +-- [Port] Note: data is passed by value and the new value is returned: Returns (data, value_changed). For an Input widget, step and step_fast are optional. -- Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. --- @param label string --- @param data_type ImGuiDataType @@ -58603,7 +58565,7 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag local data_default = (bit32.band(g.NextItemData.HasFlags, 8 --[[ImGuiNextItemDataFlags.HasRefVal]]) ~= 0) and g.NextItemData.RefVal or g.DataTypeZeroValue - local buf, buf_size = {}, 64 -- char buf[64]; IM_COUNTOF(buf) + local buf, buf_size = {}, 64 -- [Port] char buf[64]; IM_COUNTOF(buf) if bit32.band(flags, 16384 --[[ImGuiInputTextFlags.DisplayEmptyRefVal]]) ~= 0 and ImGui.DataTypeCompare(data_type, data, data_default) == 0 then buf[1] = 0 else @@ -59080,7 +59042,7 @@ local function TempInputIsClampEnabled(flags, data_type, min, max) if bit32.band(flags, 512 --[[ImGuiSliderFlags.ClampOnInput]]) ~= 0 and (min ~= nil or max ~= nil) then local clamp_range_dir = 0 if min ~= nil and max ~= nil then - clamp_range_dir = ImGui.DataTypeCompare(data_type, min, max) -- -1 when min < max, == 0 when min == max + clamp_range_dir = ImGui.DataTypeCompare(data_type, min, max) end if min == nil or max == nil or clamp_range_dir < 0 then return true @@ -59101,7 +59063,7 @@ end --- @param format string --- @param flags ImGuiSliderFlags -- [Luau] memo of string.format(format, value) for drag/slider value text (same values are redrawn every frame). --- ponytail: whole-memo reset at 4096 entries, LRU if values churn + local fmt_memo, fmt_memo_n = {}, 0 local SliderScalar_total_bb, SliderScalar_grab_bb = ImRect(), ImRect() -- [Luau] scratch for SliderScalar()/DragScalar(), never escape local DRAG_TEXT_ALIGN = ImVec2(0.5, 0.5) @@ -59116,7 +59078,7 @@ function FormatCached(format, v) return r end --- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a Drag widget, min and max are optional. +-- [Port] Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a Drag widget, min and max are optional. -- Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, flags) @@ -59270,7 +59232,7 @@ function ImGui.DragInt(label, v, v_speed, v_min, v_max, format, flags) return ImGui.DragScalar(label, 4 --[[ImGuiDataType.S32]], v, v_speed, v_min, v_max, format, flags) end --- `v` is mutated in place (1-based), returns value_changed +-- [Port] `v` is mutated in place (1-based), returns value_changed function ImGui.DragScalarN(label, data_type, v, components, v_speed, v_min, v_max, format, flags) if v_speed == nil then v_speed = 1.0 end if flags == nil then flags = 0 end @@ -59549,7 +59511,7 @@ function ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, t, v_min, v_max -- - Not doing a *1.0 multiply at the end of a range as it tends to be lossy. While absolute aiming at a large s64/u64 -- range is going to be imprecise anyway, with this check we at least make the edge values matches expected limits. local v_new_off_f = (SIGNEDTYPE)((v_max - v_min)) * t - result = (TYPE)((SIGNEDTYPE)(v_min) + (SIGNEDTYPE)(v_new_off_f + 0)) -- LUA: + 0 instead of + ((v_min > v_max) and -0.5 or 0.5) + result = (TYPE)((SIGNEDTYPE)(v_min) + (SIGNEDTYPE)(v_new_off_f + 0)) -- [Port] + 0 instead of + ((v_min > v_max) and -0.5 or 0.5) end end @@ -59814,7 +59776,7 @@ function ImGui.SliderBehavior(bb, id, data_type, v, min, max, format, flags, out return v, false end --- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a slider, min and max are required. +-- [Port] Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a slider, min and max are required. -- Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. --- @generic T : number --- @param label string @@ -60857,7 +60819,7 @@ function ImGui.InputTextDeactivateHook(id) assert(state.TextA.Data ~= nil) -- IM_ASSERT(state.TextA[state.TextLen + 1] == 0) g.InputTextDeactivatedState.TextA:resize(state.TextLen + 1) - ImStd.memmove(g.InputTextDeactivatedState.TextA.Data, 1, state.TextA.Data, 1, state.TextLen) -- state.TextLen + 1 + ImStd.memmove(g.InputTextDeactivatedState.TextA.Data, 1, state.TextA.Data, 1, state.TextLen) -- [Port] state.TextLen + 1 end end @@ -60982,7 +60944,7 @@ local function InputTextLineIndexGetPosOffset(g, state, line_index, buf, buf_end end end - local line_no = (it == it_begin) and 0 or (it - 1) -- 0-based (index_from_ptr) + local line_no = (it == it_begin) and 0 or (it - 1) -- [Port] 0-based (index_from_ptr) local line_start = line_index:get_line_begin(1, line_no) local offset = ImVec2() offset.x = InputTextCalcTextSize(g, buf, line_start, cursor_ptr, buf_end, nil, 2 --[[ImDrawTextFlags.WrapKeepBlanks]]).x @@ -61204,7 +61166,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback -- Find initial scroll position for right alignment ImVec2_Copy(state.Scroll, ImVec2(0.0, 0.0)) if bit32.band(flags, 131072 --[[ImGuiInputTextFlags.ElideLeft]]) ~= 0 then - state.Scroll.x = state.Scroll.x + ImMax(0.0, ImGui.CalcTextSize(table.concat(buf)).x - frame_size.x + style.FramePadding.x * 2.0) -- FIXME: no table.concat here + state.Scroll.x = state.Scroll.x + ImMax(0.0, ImGui.CalcTextSize(table.concat(buf)).x - frame_size.x + style.FramePadding.x * 2.0) -- [Port] FIXME: no table.concat here end -- Recycle existing cursor/selection/undo stack but clamp position @@ -61836,7 +61798,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end -- Calculate visibility - local line_visible_n0, line_visible_n1 = 0, 1 -- 0-based like upstream + local line_visible_n0, line_visible_n1 = 0, 1 -- [Port] 0-based like upstream if is_multiline then line_visible_n0, line_visible_n1 = ImGui.CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize) end @@ -62336,7 +62298,7 @@ function ImGui.ColorEdit4(label, col, flags) end elseif bit32.band(flags, 4194304 --[[ImGuiColorEditFlags.DisplayHex]]) ~= 0 and bit32.band(flags, 32 --[[ImGuiColorEditFlags.NoInputs]]) == 0 then -- RGB Hexadecimal Input - -- TODO: resolve sprintf, sscanf requirement. currently this section creates a lot of temp tables and strings... + -- [Port] TODO: resolve sprintf, sscanf requirement. currently this section creates a lot of temp tables and strings... local buf, buf_size = nil, 64 if alpha then local str = ImFormatString("#%02X%02X%02X%02X", ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255), ImClamp(i[3], 0, 255), ImClamp(i[4], 0, 255)) @@ -62494,7 +62456,7 @@ function ImGui.ColorEdit3(label, col, flags) return ImGui.ColorEdit4(label, col, bit32.bor(flags, 2 --[[ImGuiColorEditFlags.NoAlpha]])) end --- `col` mutated in place, returns value_changed +-- [Port] `col` mutated in place, returns value_changed function ImGui.ColorPicker3(label, col, flags) if flags == nil then flags = 0 end local col4 = { col[1], col[2], col[3], 1.0 } @@ -62757,7 +62719,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) -- Convert back color to RGB if value_changed_h or value_changed_sv then if bit32.band(flags, 268435456 --[[ImGuiColorEditFlags.InputRGB]]) ~= 0 then - col[1], col[2], col[3] = ImGui.ColorConvertHSVtoRGB(H, S, V) -- Lua 1-based indexing + col[1], col[2], col[3] = ImGui.ColorConvertHSVtoRGB(H, S, V) -- [Port] Lua 1-based indexing g.ColorEditSavedHue = H g.ColorEditSavedSat = S g.ColorEditSavedID = g.ColorEditCurrentID @@ -62803,7 +62765,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) -- Try to cancel hue wrap (after ColorEdit4 call), if any if value_changed_fix_hue_wrap and bit32.band(flags, 268435456 --[[ImGuiColorEditFlags.InputRGB]]) ~= 0 then - local new_H, new_S, new_V = ImGui.ColorConvertRGBtoHSV(col[1], col[2], col[3]) -- Lua 1-based indexing + local new_H, new_S, new_V = ImGui.ColorConvertRGBtoHSV(col[1], col[2], col[3]) -- [Port] Lua 1-based indexing if new_H <= 0 and H > 0 then if new_V <= 0 and V ~= new_V then @@ -63259,7 +63221,7 @@ end -- - CollapsingHeader() ------------------------------------------------------------------------------- --- va_list variants: identical in Lua (varargs) +-- [Port] va_list variants: identical in Lua (varargs) ImGui.TextColoredV = function(...) return ImGui.TextColored(...) end ImGui.TextDisabledV = function(...) return ImGui.TextDisabled(...) end ImGui.TextWrappedV = function(...) return ImGui.TextWrapped(...) end @@ -63275,7 +63237,7 @@ function ImGui.SetNextItemRefVal(data_type, v) g.NextItemData.RefVal = v end --- Overloads: TreeNode(label) / TreeNode(str_id, fmt, ...) +-- [Port] Overloads: TreeNode(label) / TreeNode(str_id, fmt, ...) --- @param label string function ImGui.TreeNode(label, fmt, ...) @@ -63294,7 +63256,7 @@ function ImGui.TreeNodeV(str_id, fmt, ...) return ImGui.TreeNodeExV(str_id, 0, fmt, ...) end --- Overloads: TreeNodeEx(label, flags) / TreeNodeEx(str_id, flags, fmt, ...) +-- [Port] Overloads: TreeNodeEx(label, flags) / TreeNodeEx(str_id, flags, fmt, ...) --- @param label string --- @param flags? ImGuiTreeNodeFlags function ImGui.TreeNodeEx(label, flags, fmt, ...) @@ -63864,7 +63826,7 @@ end -- CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags.NoTreePushOnOpen flag). -- This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags.CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). --- Overloads: CollapsingHeader(label, flags?) -> is_open +-- [Port] Overloads: CollapsingHeader(label, flags?) -> is_open -- CollapsingHeader(label, p_visible: bool, flags?) -> is_open, p_visible -- p_visible == nil : regular collapsing header -- p_visible == true : show a small close button on the corner of the header, clicking the button will set p_visible = false (returned as 2nd value) @@ -64214,7 +64176,7 @@ function ImGui.GetTypingSelectRequest(flags) -- Handle backspace if bit32.band(flags, 1 --[[ImGuiTypingSelectFlags.AllowBackspace]]) ~= 0 and ImGui.IsKeyPressedEx(523 --[[ImGuiKey.Backspace]], 1 --[[ImGuiInputFlags.Repeat]]) then - local p = ImStd.ImTextFindPreviousUtf8Codepoint(data.SearchBuffer, 1, buffer_len + 1) -- 1-based byte position + local p = ImStd.ImTextFindPreviousUtf8Codepoint(data.SearchBuffer, 1, buffer_len + 1) -- [Port] 1-based byte position data.SearchBuffer = string.sub(data.SearchBuffer, 1, p - 1) buffer_len = p - 1 end @@ -64507,7 +64469,7 @@ function ImGui.BeginBoxSelect(scope_rect, window, box_select_id, ms_flags) end end - -- box_select_intersection = BoxSelectRectPrev + BoxSelectRectCurr + -- [Port] box_select_intersection = BoxSelectRectPrev + BoxSelectRectCurr local box_select_intersection_min_x, box_select_intersection_min_y = ImMin(prev.Min.x, curr.Min.x), ImMin(prev.Min.y, curr.Min.y) local box_select_intersection_max_x, box_select_intersection_max_y = ImMax(prev.Max.x, curr.Max.x), ImMax(prev.Max.y, curr.Max.y) if bit32.band(ms_flags, 128 --[[ImGuiMultiSelectFlags.BoxSelect2d]]) ~= 0 then @@ -65194,7 +65156,7 @@ function ImGui.MultiSelectAddSetRange(ms, selected, range_dir, first_item, last_ -- FIXME-OPT: Disabled on 2026/04/09 as this would break with any form of coarse clipping that we don't know about (e.g. TableNextColumn() return value). -- The low-hanging fruit would be to know that ImGuiSelectionUserData are sequential indices, in which case we can trivially compare PrevSubmittedItem + RangeDir == FirstItem. -- User can always perform this merge if required. - -- (#if 0 block not ported) + -- [Port] (#if 0 block not ported) local req = MultiSelectScratchRequest -- ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, (ImS8)range_dir, (range_dir > 0) ? first_item : last_item, (range_dir > 0) ? last_item : first_item } req.Type = 2 --[[ImGuiSelectionRequestType.SetRange]]; req.Selected = selected; req.RangeDirection = range_dir @@ -65306,7 +65268,7 @@ function MT.ImGuiSelectionBasicStorage:GetNextSelectedItem(opaque_it) table.sort(keys, PairComparerByValueInt) -- ~ImGuiStorage::BuildSortByValueInt() PairComparerStorage = nil else - table.sort(keys) -- ImGuiStorage is sorted by key + table.sort(keys) -- [Port] ImGuiStorage is sorted by key end it = 1 end @@ -65463,7 +65425,7 @@ function MT.ImGuiSelectionExternalStorage:ApplyRequests(ms_io) end end -end -- do (Typing-Select, Box-Select, Multi-Select) +end -- [Port] do (Typing-Select, Box-Select, Multi-Select) ------------------------------------------------------------------------------- -- [SECTION] Widgets: ListBox @@ -65532,7 +65494,7 @@ end -- This is merely a helper around BeginListBox(), EndListBox(). -- Considering using those directly to submit custom data or store selection differently. --- Overloads: (label, current_item, items[], items_count?, height_in_items?) or (label, current_item, getter, user_data, items_count, height_in_items?) +-- [Port] Overloads: (label, current_item, items[], items_count?, height_in_items?) or (label, current_item, getter, user_data, items_count, height_in_items?) --- @param current_item int # 0-based --- @return int current_item --- @return bool value_changed @@ -65637,7 +65599,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local v_min = 3.4028234663853e+38 --[[FLT_MAX]] local v_max = -3.4028234663853e+38 --[[FLT_MAX]] for i = 1, values_count do - local v = values_getter(data, i) -- NaN isn't checked here + local v = values_getter(data, i) -- [Port] NaN isn't checked here v_min = ImMin(v_min, v) v_max = ImMax(v_max, v) @@ -66456,7 +66418,7 @@ end do --[[ [SECTION] Widgets: BeginTabBar, EndTabBar, etc. (was imgui_tabs.lua) ]] --- Dear ImGui --- Tab bars & tab items: 1:1 port of imgui_widgets.cpp [SECTION] Widgets: BeginTabBar/BeginTabItem (docking branch) +-- [Port] Tab bars & tab items: 1:1 port of imgui_widgets.cpp [SECTION] Widgets: BeginTabBar/BeginTabItem (docking branch) -- -- Port notes: -- - tab_bar.Tabs is an ImVector of ImGuiTabItem tables (references). C++ pointer arithmetic on the array is replaced by @@ -66509,7 +66471,7 @@ local function GetTabBarRefFromTabBar(tab_bar) return ImGuiPtrOrIndex(tab_bar) end --- Stable sorts (C++ ImQsort is not stable, but the comparers are total orders in practice) +-- [Port] Stable sorts (C++ ImQsort is not stable, but the comparers are total orders in practice) local function SortTabsBySection(tab_bar) table.sort(tab_bar.Tabs.Data, TabItemComparerBySection) end @@ -66541,7 +66503,7 @@ end -- Shrink excess width from a set of item, by removing width from the larger items first. -- Set items Width to -1.0f to disable shrinking this item. --- items: 1-based array of ImGuiShrinkWidthItem, `first` = 1-based index of first item, `count` items +-- [Port] items: 1-based array of ImGuiShrinkWidthItem, `first` = 1-based index of first item, `count` items function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) if count <= 0 then return end if count == 1 then @@ -66764,7 +66726,7 @@ function ImGui.TabBarLayout(tab_bar) local tabs = tab_bar.Tabs local tab_dst_n = 0 local need_sort_by_section = false - local sections = { ImGuiTabBarSection(), ImGuiTabBarSection(), ImGuiTabBarSection() } -- Layout sections: Leading, Central, Trailing (1-based: [1]=Leading,[2]=Central,[3]=Trailing) + local sections = { ImGuiTabBarSection(), ImGuiTabBarSection(), ImGuiTabBarSection() } -- [Port] Layout sections: Leading, Central, Trailing (1-based: [1]=Leading,[2]=Central,[3]=Trailing) for tab_src_n = 0, tabs.Size - 1 do local tab = tabs.Data[tab_src_n + 1] if tab.LastFrameVisible < tab_bar.PrevFrameVisible or tab.WantClose then @@ -66834,7 +66796,7 @@ function ImGui.TabBarLayout(tab_bar) -- Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central -- (whereas our tabs are stored as: leading, central, trailing) - -- (shrink_buffer_indexes holds 0-based offsets) + -- [Port] (shrink_buffer_indexes holds 0-based offsets) local shrink_buffer_indexes = { 0, sections[1].TabCount + sections[3].TabCount, sections[1].TabCount } local swb = g.ShrinkWidthBuffer swb:resize(tabs.Size) @@ -67243,7 +67205,7 @@ function ImGui.TabBarProcessReorder(tab_bar) if bit32.band(tab2.Flags, 32 --[[ImGuiTabItemFlags.NoReorder]]) ~= 0 then return false end if bit32.band(tab1.Flags, 192 --[[ImGuiTabItemFlags.SectionMask_]]) ~= bit32.band(tab2.Flags, 192 --[[ImGuiTabItemFlags.SectionMask_]]) then return false end - -- Move tab1 to tab2's position, shifting the tabs in between + -- [Port] Move tab1 to tab2's position, shifting the tabs in between table.remove(tab_bar.Tabs.Data, tab1_order + 1) table.insert(tab_bar.Tabs.Data, tab2_order + 1, tab1) @@ -67834,10 +67796,10 @@ end __FILES['imstb_rectpack.lua'] = function() --- Dear ImGui --- This is a Lua port of original `imstb_rectpack.h` +-- [Port] This is a Lua port of original `imstb_rectpack.h` --- ALL TABLES IN THIS FILE ARE 1-BASED! --- Avoids table creation when possible +-- [Port] ALL TABLES IN THIS FILE ARE 1-BASED! +-- [Port] Avoids table creation when possible -- [DEAR IMGUI] -- This is a slightly modified version of stb_rect_pack.h 1.01. @@ -68107,7 +68069,7 @@ function stbrp_init_target(context, width, height, nodes, num_nodes) end -- find minimum y position if it starts at x1 --- Returns (min_y, waste_area) +-- [Port] Returns (min_y, waste_area) --- @param c stbrp_context --- @param first stbrp_node --- @param x0 int @@ -68498,7 +68460,7 @@ end __FILES['imstb_textedit.lua'] = function() --- Dear ImGui --- This is a Lua port of original `imstb_textedit.h` +-- [Port] This is a Lua port of original `imstb_textedit.h` -- [DEAR IMGUI] -- This is a slightly modified version of stb_textedit.h 1.14. @@ -68537,7 +68499,7 @@ __FILES['imstb_textedit.lua'] = function() -- -- Uses the C runtime function 'memmove', which you can override -- by defining IMSTB_TEXTEDIT_memmove before the implementation. --- (In this port: ImStb.TEXTEDIT_memmove.) +-- [Port] (In this port: ImStb.TEXTEDIT_memmove.) -- -- -- VERSION HISTORY @@ -68715,7 +68677,7 @@ __FILES['imstb_textedit.lua'] = function() -- efficient, but it's not horrible on modern computers. But you wouldn't -- want to edit million-line files with it. --- ALL TABLES IN THIS FILE ARE 1-BASED! +-- [Port] ALL TABLES IN THIS FILE ARE 1-BASED! -- Character Indexing: -- idx=n, the n'th char (1-based) -- Cursor Indexing: @@ -68954,7 +68916,7 @@ end local stb_text_locate_coord do --- only create once, reuse later +-- [Port] only create once, reuse later local r = StbTexteditRow() --- traverse the layout to locate the nearest character to a display position @@ -69463,7 +69425,7 @@ function stb_textedit_key(str, state, key) if not is_page and state.single_line then -- on windows, up&down in single-line behave like left&right key = bit32.bor(2097153 --[[STB_TEXTEDIT_K_RIGHT]], bit32.band(key, 4194304 --[[STB_TEXTEDIT_K_SHIFT]])) - return stb_textedit_key(str, state, key) -- was `goto retry` + return stb_textedit_key(str, state, key) -- [Port] was `goto retry` end if sel then @@ -69536,7 +69498,7 @@ function stb_textedit_key(str, state, key) if not is_page and state.single_line then -- on windows, up&down become left&right key = bit32.bor(2097152 --[[STB_TEXTEDIT_K_LEFT]], bit32.band(key, 4194304 --[[STB_TEXTEDIT_K_SHIFT]])) - return stb_textedit_key(str, state, key) -- was `goto retry` + return stb_textedit_key(str, state, key) -- [Port] was `goto retry` end if sel then @@ -70040,7 +70002,7 @@ end __FILES['imstb_truetype.lua'] = function() --- Dear ImGui --- This is a Lua port of original `imstb_truetype.h` +-- [Port] This is a Lua port of original `imstb_truetype.h` -- [DEAR IMGUI] -- This is a slightly modified version of stb_truetype.h 1.26. @@ -70117,7 +70079,7 @@ __FILES['imstb_truetype.lua'] = function() -- accurately measures pixel coverage for anti-aliasing, except in the case -- where multiple shapes overlap, in which case it overestimates the AA pixel -- coverage. Thus, anti-aliasing of intersecting shapes may look wrong. --- (This port only implements the new rasterizer.) +-- [Port] (This port only implements the new rasterizer.) -- -- ADDITIONAL DOCUMENTATION -- @@ -70235,7 +70197,7 @@ local STBTT_MS_EID = { -- encodingID for STBTT_PLATFORM_ID_MICROSOFT UNICODE_FULL = 10 } --- original enum doesn't have a name, so we name it +-- [Port] original enum doesn't have a name, so we name it --- @enum STBTT_VTX local STBTT_VTX = { MOVE = 1, @@ -70834,7 +70796,7 @@ local function stbtt_InitFont_internal(info, data, fontstart) info.fdselect = stbtt__new_buf(nil, 0) -- @TODO this should use size from table (not 512MB) - info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- PORT: 64MB here instead of 512MB + info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- [Port] 64MB here instead of 512MB local b = info.cff -- read the header @@ -71125,7 +71087,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) if numberOfContours > 0 then local endPtsOfContours = g + 10 local ins = ttUSHORT(data, endPtsOfContours + numberOfContours * 2) - local points = (endPtsOfContours + numberOfContours * 2 + 2 + ins) + 1 -- 1-based idx + local points = (endPtsOfContours + numberOfContours * 2 + 2 + ins) + 1 -- [Port] 1-based idx local n = 1 + ttUSHORT(data, endPtsOfContours + numberOfContours * 2 - 2) local m = n + 2 * numberOfContours -- a loose bound on how many vertices we might need @@ -71345,7 +71307,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) end -- Append vertices. - if num_vertices == 0 then -- LUA: No malloc + if num_vertices == 0 then -- [Port] No malloc vertices = comp_verts else for i = 1, comp_num_vertices do @@ -71495,7 +71457,7 @@ local function stbtt__run_charstring(info, glyph_index, c) local has_subrs = 0 local clear_stack - local s = {} -- size = 48, 0-based + local s = {} -- [Port] size = 48, 0-based local subr_stack = {} for i = 1, 10 do subr_stack[i] = stbtt__buf() end @@ -72226,8 +72188,8 @@ end local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y) local active = nil - local scanline = {} -- size = result.w, 0-based - local scanline2 = {} -- size = result.w + 1, 0-based + local scanline = {} -- [Port] size = result.w, 0-based + local scanline2 = {} -- [Port] size = result.w + 1, 0-based STBTT__NOTUSED(vsubsample) @@ -72312,7 +72274,7 @@ end --- @param a stbtt__edge --- @param b stbtt__edge local STBTT__COMPARE = function(a, b) - if a.y0 == nil then return false end -- sentinels on the back + if a.y0 == nil then return false end -- [Port] sentinels on the back if b.y0 == nil then return true end return a.y0 < b.y0 end @@ -72521,7 +72483,7 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) local num_contours = n if n == 0 then return nil end - local contour_lengths = {} -- size = n + local contour_lengths = {} -- [Port] size = n -- make two passes through the points so we don't need to realloc for pass = 0, 1 do @@ -72828,15 +72790,15 @@ end __FILES['imstd_minstdio.lua'] = function() --- Dear ImGui --- This is a minimal Lua impl of C-like sscanf, sprintf sub-set +-- [Port] This is a minimal Lua impl of C-like sscanf, sprintf sub-set --- Supports: +-- [Port] Supports: -- - %x, %X, %nx, %nX (where n is a number) -- - %d, %nd, %u, %nu (where n is a number) -- - length modifiers h, hh, l, ll, I64 on integers: ll/I64 = 64-bit range (doubles: exact only within +-2^53) -- - %f, %lf (very limited) -- --- Returns items_matched instead of EOF on error +-- [Port] Returns items_matched instead of EOF on error local _byte = string.byte @@ -72869,7 +72831,7 @@ local function hex_digit_to_int(c) if c >= CHAR_A and c <= CHAR_F then return c - CHAR_A + 10 end end --- we force this behavior by default +-- [Port] we force this behavior by default local function clamp_if_overflow(spec, val, is_64) if spec == CHAR_d or spec == CHAR_x or spec == CHAR_X then local max = is_64 and 9223372036854775807 or 2147483647 --[[INT_MAX]] @@ -72890,7 +72852,7 @@ end --- @param result table # table to store parsed values local function sscanf(buffer, buffer_begin, format, result) local p = buffer_begin - local f = 1 -- format_begin + local f = 1 -- [Port] format_begin local format_len = #format local assigned = 0 local items_matched = 0 @@ -72917,10 +72879,10 @@ local function sscanf(buffer, buffer_begin, format, result) break end - -- encountered % in fmt + -- [Port] encountered % in fmt f = f + 1 - -- %% + -- [Port] %% if _byte(format, f, f) == CHAR_PERCENT then if buffer[p] == CHAR_PERCENT then p = p + 1 @@ -72932,7 +72894,7 @@ local function sscanf(buffer, buffer_begin, format, result) break end - -- handle optional width + -- [Port] handle optional width local width = 0 while isdigit(_byte(format, f, f)) do width = width * 10 + _byte(format, f, f) - CHAR_0 @@ -72942,7 +72904,7 @@ local function sscanf(buffer, buffer_begin, format, result) width = math.huge end - -- length modifiers + -- [Port] length modifiers local n_l = 0 while _byte(format, f, f) == CHAR_l or _byte(format, f, f) == CHAR_h do if _byte(format, f, f) == CHAR_l then n_l = n_l + 1 end @@ -72962,7 +72924,7 @@ local function sscanf(buffer, buffer_begin, format, result) elseif spec == CHAR_d or spec == CHAR_u then base = 10 elseif spec == CHAR_f or spec == CHAR_F then - is_float = true -- TODO: distinguish %lf from %f? + is_float = true -- [Port] TODO: distinguish %lf from %f? else return items_matched end @@ -72982,7 +72944,7 @@ local function sscanf(buffer, buffer_begin, format, result) p = p + 1 end - -- inf, nan are not handled + -- [Port] inf, nan are not handled local p_start = p local int_part = 0 @@ -73010,7 +72972,7 @@ local function sscanf(buffer, buffer_begin, format, result) val = sign * (int_part + frac_part / frac_div) else local sign = 1 - -- optional sign + -- [Port] optional sign if base == 10 then if buffer[p] == CHAR_PLUS then p = p + 1 @@ -73029,7 +72991,6 @@ local function sscanf(buffer, buffer_begin, format, result) end if p == p_start then - -- failed to match return items_matched end @@ -73046,7 +73007,7 @@ local function sscanf(buffer, buffer_begin, format, result) end end if spec == CHAR_u and val < 0 then - val = val + (is_64 and 18446744073709551616 or 4294967296) -- unsigned wrap-around like strtoul() + val = val + (is_64 and 18446744073709551616 or 4294967296) -- [Port] unsigned wrap-around like strtoul() end end diff --git a/default.project.json b/default.project.json index 35dd797..c700c03 100644 --- a/default.project.json +++ b/default.project.json @@ -3,11 +3,15 @@ "tree": { "$className": "DataModel", "ReplicatedStorage": { - "ImGui": { "$path": "build/ImGuiTyped.luau", "Impl": { "$path": "build/ImGui.luau" } } + "ImGui": { + "$path": "build/ImGuiTyped.luau", + "Impl": { "$path": "build/ImGui.luau" }, + "Worker": { "$path": "build/ImGuiWorker.client.luau" } + } }, "StarterPlayer": { "StarterPlayerScripts": { - "ImGuiMain": { "$path": "examples/example_roblox/main.client.luau" } + "ImGuiMain": { "$path": "examples/example_roblox_parallel/main.client.luau" } } } } diff --git a/docs/PORTING.md b/docs/PORTING.md index 37f2380..ef4cc01 100644 --- a/docs/PORTING.md +++ b/docs/PORTING.md @@ -8,11 +8,16 @@ there, but keep this port's existing data structures and conventions. Read the s file shares one global namespace. Globals defined by one file are visible to the others at call time. - Layout mirrors upstream: library at the repo root (`imgui.lua` incl. docking, drag & drop and the debug tools, `imgui_widgets.lua` incl. tab bars, `imgui_draw.lua`, `imgui_tables.lua`, `imgui_internal.lua`, `imgui_h.lua`, - `imstb_*.lua`), demo in `imgui_demo.lua` only, backend in `backends/`, fonts in `fonts/`, the example LocalScript in + `imstb_*.lua`), demo in `imgui_demo.lua` only, backends in `backends//` (`bundle.py` bundles every `*.lua` of the + target's folder: `roblox/` = `imgui_impl_roblox.lua` + its modules, `love/`), fonts in `fonts/`, the example LocalScript in `examples/example_roblox/`. The library must never call into `imgui_demo.lua` (`tools/bundle.py --no-demo`, `tools/test/undefined.py --no-demo`, `NO_DEMO=1 run.py --main tools/test/scripts/t_nodemo.luau`). - Each `.lua` file is a function body in the bundle. New files must be loaded with `IM_INCLUDE"file.lua"` from an existing file. Merged-in sections are wrapped in `do ... end` so their locals stay private. +- Roblox backend modules (`backends/roblox/*.lua`) start with `local X = IM_INCLUDE("roblox/x.lua")` lines and end with + `return M`; `bundle.py` inlines them into the `imgui_impl_roblox.lua` function (one `do ... end` each, in dependency + order, `X` a local of that function). Use one name per module everywhere; no circular includes (late-bind a field on + a shared table instead, e.g. `EditableImages.FreeTile`). - No `goto`, no `::labels::`, no `setfenv/getfenv`, no LuaJIT `bit`/`ffi`. Use `bit32`. For `continue` use `repeat ... until true` with `break`, and an explicit flag when the loop itself must break out of the wrapper. - Luau has a limit of 200 locals per function and 255 upvalues; split huge functions (like demo sections) into @@ -21,7 +26,7 @@ there, but keep this port's existing data structures and conventions. Read the s ## Portability (LÖVE build) - Library code must stay valid **Lua 5.1/LuaJIT syntax** apart from `@native` lines (stripped for LÖVE): no `+=`, `//`, `continue`, type annotations, `if`-expressions or string interpolation. Luau library calls are fine only if - the COMPAT section of `backends/imgui_impl_love.lua` shims them (`bit32`, `buffer`, `table.clear/find/move/unpack`, `utf8`). + the COMPAT section of `backends/love/imgui_impl_love.lua` shims them (`bit32`, `buffer`, `table.clear/find/move/unpack`, `utf8`). - Check with `tools/test/love/run.sh` (LuaJIT draw checksums must equal the Luau ones). ## Conventions (follow what the port already does) diff --git a/examples/example_roblox/main.client.luau b/examples/example_roblox/main.client.luau index d427cd6..50fe537 100755 --- a/examples/example_roblox/main.client.luau +++ b/examples/example_roblox/main.client.luau @@ -83,6 +83,7 @@ local function StyleColorsCatppuccinMocha(Style) { "ScrollbarGrabActive", Overlay0 }, { "CheckMark", Mauve }, + { "CheckboxSelectedBg", Surface0 }, { "SliderGrab", Mauve, 0.8 }, { "SliderGrabActive", Mauve }, diff --git a/examples/example_roblox_parallel/main.client.luau b/examples/example_roblox_parallel/main.client.luau new file mode 100644 index 0000000..2b68ea1 --- /dev/null +++ b/examples/example_roblox_parallel/main.client.luau @@ -0,0 +1,234 @@ + +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local RunService = game:GetService("RunService") + +local ImGuiModule = ReplicatedStorage:WaitForChild("ImGui") +local G = require(ImGuiModule) +local ImGui, ImGui_ImplRoblox = G.ImGui, G.ImGui_ImplRoblox + +ImGui.CreateContext() +local IO = ImGui.GetIO() +IO.ConfigFlags = bit32.bor(IO.ConfigFlags, G.ImGuiConfigFlags.NavEnableKeyboard, G.ImGuiConfigFlags.DockingEnable) + +-- catppuccin mocha mauve https://catppuccin.com/palette +local function StyleColorsCatppuccinMocha(Style) + local function Hex(Value, Alpha) + return G.ImVec4( + bit32.extract(Value, 16, 8) / 255, + bit32.extract(Value, 8, 8) / 255, + bit32.extract(Value, 0, 8) / 255, + Alpha or 1.0 + ) + end + + local Crust, Mantle, Base = 0x11111b, 0x181825, 0x1e1e2e + local Surface0, Surface1, Surface2 = 0x313244, 0x45475a, 0x585b70 + local Overlay0, Overlay2, Text = 0x6c7086, 0x9399b2, 0xcdd6f4 + local Mauve, Lavender = 0xcba6f7, 0xb4befe + + local Entries = { + { "Text", Text }, + { "TextDisabled", Overlay0 }, + + { "WindowBg", Base }, + { "ChildBg", Base, 0.0 }, + { "PopupBg", Mantle, 0.98 }, + { "Border", Surface1 }, + { "BorderShadow", Crust, 0.0 }, + + { "FrameBg", Surface0 }, + { "FrameBgHovered", Surface1 }, + { "FrameBgActive", Surface2 }, + + { "TitleBg", Mantle }, + { "TitleBgActive", Crust }, + { "TitleBgCollapsed", Mantle, 0.75 }, + { "MenuBarBg", Mantle }, + + { "ScrollbarBg", Mantle }, + { "ScrollbarGrab", Surface1 }, + { "ScrollbarGrabHovered", Surface2 }, + { "ScrollbarGrabActive", Overlay0 }, + + { "CheckMark", Mauve }, + { "CheckboxSelectedBg", Surface0 }, + { "SliderGrab", Mauve, 0.8 }, + { "SliderGrabActive", Mauve }, + + { "Button", Surface0 }, + { "ButtonHovered", Surface1 }, + { "ButtonActive", Mauve, 0.6 }, + + { "Header", Surface0 }, + { "HeaderHovered", Surface1 }, + { "HeaderActive", Mauve, 0.5 }, + + { "Separator", Surface1 }, + { "SeparatorHovered", Mauve, 0.7 }, + { "SeparatorActive", Mauve }, + + { "ResizeGrip", Mauve, 0.2 }, + { "ResizeGripHovered", Mauve, 0.6 }, + { "ResizeGripActive", Mauve, 0.9 }, + + { "InputTextCursor", Text }, + + { "Tab", Surface0 }, + { "TabHovered", Surface2 }, + { "TabSelected", Surface1 }, + { "TabSelectedOverline", Mauve }, + { "TabDimmed", Mantle }, + { "TabDimmedSelected", Surface0 }, + { "TabDimmedSelectedOverline", Overlay0 }, + + { "DockingPreview", Mauve, 0.7 }, + { "DockingEmptyBg", Crust }, + + { "PlotLines", Overlay2 }, + { "PlotLinesHovered", Mauve }, + { "PlotHistogram", Mauve, 0.8 }, + { "PlotHistogramHovered", Lavender }, + + { "TableHeaderBg", Surface0 }, + { "TableBorderStrong", Surface1 }, + { "TableBorderLight", Surface0 }, + { "TableRowBg", Base, 0.0 }, + { "TableRowBgAlt", Surface0, 0.3 }, + + { "TextLink", Mauve }, + { "TextSelectedBg", Mauve, 0.35 }, + { "TreeLines", Surface2 }, + { "DragDropTarget", Mauve, 0.9 }, + + { "NavCursor", Lavender }, + { "NavWindowingHighlight", Lavender, 0.7 }, + { "NavWindowingDimBg", Crust, 0.5 }, + { "ModalWindowDimBg", Crust, 0.6 }, + } + + for _, Entry in ipairs(Entries) do + local Name, Color, Alpha = Entry[1], Entry[2], Entry[3] + Style.Colors[G.ImGuiCol[Name]] = Hex(Color, Alpha) + end +end + +StyleColorsCatppuccinMocha(ImGui.GetStyle()) +IO.Fonts:AddFontDefault() +for _, Name in { "Cousine-Regular", "DroidSans", "Karla-Regular", "ProggyTiny", "Roboto-Medium" } do + IO.Fonts:AddFontFromFileTTF("fonts/" .. Name .. ".ttf", 13.0) +end + +ImGui_ImplRoblox.Init() +local RenderRate = 60 -- UI redraws per second (0 = every frame) +ImGui_ImplRoblox.SetRenderRate(RenderRate) +ImGui_ImplRoblox.EnableParallel({ Actors = 4 }) + +-- Game FPS and ImGui render FPS, sampled every 0.5 s +local GameFps, RenderFps, Frames, Renders, Since = 0, 0, 0, nil, os.clock() +RunService.RenderStepped:Connect(function() + Frames += 1 + local Now = os.clock() + local Dt = Now - Since + if Dt >= 0.5 then + GameFps = Frames / Dt + local R = ImGui_ImplRoblox.GetStats().Renders + RenderFps = (R and Renders) and (R - Renders) / Dt or 0 + Frames, Renders, Since = 0, R, Now + end +end) + +local function Help(Desc) + ImGui.SameLine() + ImGui.TextDisabled("(?)") + if ImGui.BeginItemTooltip() then + ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0) + ImGui.TextUnformatted(Desc) + ImGui.PopTextWrapPos() + ImGui.EndTooltip() + end +end + +local Enabled, Timing = true, false +local function ShowParallelWindow() + local C, S = ImGui_ImplRoblox.GetParallelConfig(), ImGui_ImplRoblox.GetParallelStats() + ImGui.Begin("Parallel") + + local Fr = IO.Framerate + ImGui.Text("Game %.1f FPS (%.2f ms)", GameFps, GameFps > 0 and 1000 / GameFps or 0) + Help("Frames Roblox actually renders per second (counted from RenderStepped).") + ImGui.Text("ImGui Logic %.1f FPS (%.2f ms)", Fr, Fr > 0 and 1000 / Fr or 0) + Help("How often ImGui logic runs NewFrame..Render (io.Framerate, 60-frame average). Runs every game frame so input stays responsive.") + ImGui.Text("ImGui Render %.1f FPS", RenderFps) + Help("How often the backend actually redraws the UI (capped by Render rate). Frames in between reuse the last drawn UI.") + local Rate, RateChanged = ImGui.SliderInt("Render rate", RenderRate, 0, 240, RenderRate == 0 and "every frame" or "%d Hz") + Help("Max UI redraws per second (SetRenderRate). 0 = redraw every game frame.") + if RateChanged then + RenderRate = Rate + ImGui_ImplRoblox.SetRenderRate(Rate) + end + + ImGui.Separator() + local Changed + Changed, Enabled = ImGui.Checkbox("Enabled", Enabled) + Help("Rasterize dirty tiles on Actors (parallel Luau). Off = everything is rasterized on the main thread.") + if Changed then + if Enabled then + ImGui_ImplRoblox.EnableParallel() + else + ImGui_ImplRoblox.DisableParallel() + end + end + local Actors = C.Actors + Actors, Changed = ImGui.SliderInt("Actors", Actors, 1, 16) + Help("Number of worker Actors. Changing it finishes the pending frame and replaces the Actors. More than your CPU core count won't help.") + if Changed then + C.Actors = Actors + if Enabled then + ImGui_ImplRoblox.EnableParallel() + end + end + C.MinTiles = ImGui.SliderInt("MinTiles", C.MinTiles, 0, 64) + Help("A frame with fewer dirty tiles than this is rasterized on the main thread (dispatch overhead isn't worth it).") + C.MinPixels = ImGui.SliderInt("MinPixels", C.MinPixels, 0, 262144) + Help("A frame with fewer dirty pixels than this is rasterized on the main thread.") + C.MaxBytesPerPixel = ImGui.SliderFloat("MaxBytesPerPixel", C.MaxBytesPerPixel, 0, 16) + Help("If the packed data sent to Actors exceeds this many bytes per dirty pixel (e.g. lots of small text), the frame stays on the main thread, since copying would cost more than it saves. 0 = no limit.") + + local B = ImGui_ImplRoblox.GetStats() + ImGui.Separator() + ImGui.Text("Flushes parallel %d serial %d", S.ParallelFlushes, S.SerialFlushes) + Help("Frames whose dirty tiles went to Actors vs. were rasterized on the main thread (below thresholds, or ImGui ran too late in the frame).") + ImGui.Text("Fallbacks %d Late %d", S.Fallbacks, S.Late) + Help("Fallbacks: Actor batches not finished in time, rasterized on the main thread so the frame is never partial. Late: results that arrived after that and were discarded. Both should stay at 0.") + ImGui.Text("Tiles %d EditableImage %.1f MB", B.Tiles, B.EditableImageBytes / 1048576) + Help("Live 128x128 raster tiles and EditableImage memory used by the backend (hard-capped).") + Changed, Timing = ImGui.Checkbox("Stage timing", Timing) + Help("Per-stage main-thread time of the last rendered frame. With parallel on, Raster is only the packing for Actors.") + if Changed then + ImGui_ImplRoblox.SetStageTiming(Timing) + end + if Timing and B.Frame then + for _, K in { "Compare", "Collect", "Hash", "Raster", "Upload", "Other", "Total" } do + ImGui.Text("%-8s %.3f ms", K, (B.Frame[K] or 0) * 1000) + end + end + + ImGui.End() +end + +-- PreSimulation, not RenderStepped: the parallel Finish runs in PostSimulation +RunService.PreSimulation:Connect(function() + ImGui_ImplRoblox.NewFrame() + ImGui.NewFrame() + ImGui.DockSpaceOverViewport(0, nil, G.ImGuiDockNodeFlags.PassthruCentralNode) + ImGui.ShowDemoWindow() + ShowParallelWindow() + ImGui.Render() + ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData()) +end) + +script.Destroying:Connect(function() + ImGui_ImplRoblox.DisableParallel() + ImGui_ImplRoblox.Shutdown() + ImGui.DestroyContext() +end) diff --git a/imgui.lua b/imgui.lua index f0ffc1e..418a59e 100644 --- a/imgui.lua +++ b/imgui.lua @@ -239,7 +239,7 @@ -- - See https://github.com/ocornut/imgui/wiki/Getting-Started, and README.md of this repository. -- - Run and study the examples and demo in imgui_demo.lua to get acquainted with the library. -- - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder --- (backends/imgui_impl_roblox.lua for Roblox, backends/imgui_impl_love.lua for LÖVE). +-- (backends/roblox/imgui_impl_roblox.lua for Roblox, backends/love/imgui_impl_love.lua for LÖVE). -- - Build a single file with tools/bundle.py: build/ImGui.luau (Roblox ModuleScript) or build/imgui_love.lua (LÖVE), -- then require() / load it. All exported names (ImGui, ImVec2, ImVec4, IM_COL32, every ImGui*Flags enum...) are fields of the returned table. -- - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. @@ -342,9 +342,9 @@ -- ------------------------------------ -- -- A backend implements the usual Dear ImGui contract: Init, NewFrame, RenderDrawData, inputs -> io:AddXXXEvent(), --- texture updates via ImTextureData. Adding another Lua host means a new backends/imgui_impl_.lua. +-- texture updates via ImTextureData. Adding another Lua host means a new backends//imgui_impl_.lua. -- -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for basic instructions. --- -> the backends in backends/imgui_impl_roblox.lua and backends/imgui_impl_love.lua are complete implementations. +-- -> the backends in backends/roblox/imgui_impl_roblox.lua and backends/love/imgui_impl_love.lua are complete implementations. -- -- Basic application/backend skeleton: -- @@ -418,13 +418,12 @@ -- (Core Code) --- Flags: --- IMGUI_DISABLE_OBSOLETE_FUNCTIONS = true -- This flag is not implemented +-- [Port] IMGUI_DISABLE_OBSOLETE_FUNCTIONS = true -- This flag is not implemented --- NOTE: you must implement ImStd.ImFileOpen if you are not in GMod IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS = true -- Don't implement ImStd.ImFileOpen/ImStd.ImFileClose/ImStd.ImFileRead/ImFileWrite so you can implement them yourself IMGUI_DISABLE_DEBUG_TOOLS = false -- Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty -IMGUI_DISABLE_TIME_FUNCTIONS = false -- Disable setting platform_io.Platform_SessionDate from os.date() in Initialize() +IMGUI_DISABLE_TIME_FUNCTIONS = false -- [Port] Disable setting platform_io.Platform_SessionDate from os.date() in Initialize() -- Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be ~= nil. -- - ImGui.CreateContext() will automatically set this pointer if it is nil. @@ -443,9 +442,9 @@ end ImGui = {} -ImStd = {} -- Contains functions that originally don't belong to cpp namespaces +ImStd = {} -- [Port] Contains functions that originally don't belong to cpp namespaces --- IM_INCLUDE(name) is provided by the bundle (see tools/bundle.py): runs the bundled file once, returns its result. +-- [Port] IM_INCLUDE(name) is provided by the bundle (see tools/bundle.py): runs the bundled file once, returns its result. function ImGui._GetTypeFunc() return type end @@ -474,7 +473,7 @@ function ImGui.MemAlloc(constructor, size) end -- IM_FREE() == ImGui.MemFree() --- This does not set `owner[field]` to nil! +-- [Port] This does not set `owner[field]` to nil! --- @param owner table --- @param field string|int function ImGui.MemFree(owner, field) @@ -536,8 +535,8 @@ IM_INCLUDE"imgui_tables.lua" do --[[ [SECTION] imgui_dragdrop (was imgui_dragdrop.lua) ]] --- Dear ImGui --- Drag and drop: 1:1 port of imgui.cpp [SECTION] DRAG AND DROP (docking branch) --- Payload `Data` is any Lua value (no copy is made). `data_size` is optional and only kept for API parity. +-- [Port] Drag and drop: 1:1 port of imgui.cpp [SECTION] DRAG AND DROP (docking branch) +-- [Port] Payload `Data` is any Lua value (no copy is made). `data_size` is optional and only kept for API parity. ------------------------------------------------------------------------------- -- [SECTION] DRAG AND DROP @@ -868,15 +867,15 @@ function ImGui.EndDragDropTarget() if g.DragDropPayload.Delivery then ImGui.ClearDragDrop() end end --- Payload methods (C++ ImGuiPayload members): payload:IsDataType(t) etc. also work through these globals +-- [Port] Payload methods (C++ ImGuiPayload members): payload:IsDataType(t) etc. also work through these globals function ImGui.PayloadIsDataType(payload, t) return ImGuiPayload_IsDataType(payload, t) end end --[[ [SECTION] imgui_dragdrop (was imgui_dragdrop.lua) ]] do --[[ [SECTION] imgui_docking (was imgui_docking.lua) ]] --- Dear ImGui --- Docking: 1:1 port of imgui.cpp [SECTION] DOCKING (docking branch, 1.93 WIP) +-- [Port] Docking: 1:1 port of imgui.cpp [SECTION] DOCKING (docking branch, 1.93 WIP) -- --- Port notes: +-- [Port] Port notes: -- - Main viewport only (no multi-viewports on Roblox): viewport creation/merging code paths are kept where cheap, but -- windows always live in the main viewport. -- - ImGuiDockContext.Nodes (ImGuiStorage in C++) is a Lua table ID -> node. Iterations that upstream does over the @@ -1145,7 +1144,7 @@ end local function IsRectInverted(r) return r.Min.x > r.Max.x or r.Min.y > r.Max.y end ---- Sorted snapshot of node IDs (upstream iterates ImGuiStorage which is sorted by key) +--- [Port] Sorted snapshot of node IDs (upstream iterates ImGuiStorage which is sorted by key) local function DockContextNodesSorted(ctx) local ids = {} for id in pairs(ctx.DockContext.Nodes) do ids[#ids + 1] = id end @@ -1680,7 +1679,7 @@ local function FixLargeWindowsWhenUndocking(size, ref_viewport) end function ImGui.DockContextProcessUndockWindow(ctx, window, clear_persistent_docking_ref) - if clear_persistent_docking_ref == nil then clear_persistent_docking_ref = true end -- C++ default argument + if clear_persistent_docking_ref == nil then clear_persistent_docking_ref = true end -- [Port] C++ default argument if window.DockNode then ImGui.DockNodeRemoveWindow(window.DockNode, window, clear_persistent_docking_ref and 0 or window.DockId) else @@ -1926,7 +1925,7 @@ function ImGui.DockNodeMoveWindows(dst_node, src_node) end -- Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar(). - -- Snapshot: DockNodeAddWindow() won't touch src_node.Windows since window.DockNode is cleared first + -- [Port] Snapshot: DockNodeAddWindow() won't touch src_node.Windows since window.DockNode is cleared first local windows = {} for i = 1, src_node.Windows.Size do windows[i] = src_node.Windows.Data[i] end for _, window in ipairs(windows) do @@ -2625,7 +2624,7 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) end -- If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value - local tabs_unsorted_start = tab_bar.Tabs.Size -- 0-based + local tabs_unsorted_start = tab_bar.Tabs.Size -- [Port] 0-based local tab_n = tab_bar.Tabs.Size - 1 while tab_n >= 0 and bit32.band(tab_bar.Tabs.Data[tab_n + 1].Flags, ImGuiTabItemFlags.Unsorted) ~= 0 do -- FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting? @@ -2872,12 +2871,12 @@ function ImGui.DockNodeCalcTabBarLayout(node) return out_title_rect, r, window_menu_button_pos, out_close_button_pos end ---- Modifies pos_old/size_old/pos_new/size_new in place (ImVec2 tables) +--- [Port] Modifies pos_old/size_old/pos_new/size_new in place (ImVec2 tables) function ImGui.DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, dir, size_new_desired) local g = ImGui.GetCurrentContext() local dock_spacing = g.Style.ItemInnerSpacing.x local axis = (dir == ImGuiDir.Left or dir == ImGuiDir.Right) and ImGuiAxis.X or ImGuiAxis.Y - local a, o = axis, 3 - axis -- the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index + local a, o = axis, 3 - axis -- [Port] the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index pos_new[o] = pos_old[o] size_new[o] = size_old[o] @@ -3362,7 +3361,7 @@ function ImGui.DockNodeTreeUpdateSplitter(node) -- Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally) local axis = node.SplitAxis IM_ASSERT(axis ~= ImGuiAxis.None) - local a, o = axis, 3 - axis -- the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index + local a, o = axis, 3 - axis -- [Port] the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index local bb = ImRect(ImVec2(child_0.Pos.x, child_0.Pos.y), ImVec2(child_1.Pos.x, child_1.Pos.y)) bb.Min[a] = bb.Min[a] + child_0.Size[a] bb.Max[o] = bb.Max[o] + child_1.Size[o] @@ -4516,7 +4515,7 @@ DockSettingsHandler_WriteAll = function(ctx, handler, buf) end ------------------------------------------------------------------------------- --- Docking: helpers (imgui_internal.h inlines) + widgets used by docking +-- [Port] Docking: helpers (imgui_internal.h inlines) + widgets used by docking ------------------------------------------------------------------------------- function ImGui.DockNodeGetRootNode(node) @@ -4587,7 +4586,7 @@ function ImGui.RenderArrowDockMenu(draw_list, p_min, sz, col) ImGui.RenderArrowPointingAt(draw_list, p_min + ImVec2(sz * 0.50, sz * 0.85), ImVec2(sz * 0.30, sz * 0.40), ImGuiDir.Down, col) end --- Upstream CollapseButton (docking branch): replaces the port's simpler version +-- [Port] Upstream CollapseButton (docking branch): replaces the port's simpler version -- The Collapse button also functions as a Dock Menu button. function ImGui.CollapseButton(id, pos, dock_node) local g = ImGui.GetCurrentContext() @@ -4599,7 +4598,6 @@ function ImGui.CollapseButton(id, pos, dock_node) if is_clipped then return pressed end -- Render - --local is_dock_menu = (window.DockNodeAsHost and not window.Collapsed) local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.ButtonActive or (hovered and ImGuiCol.ButtonHovered or ImGuiCol.Button)) local text_col = ImGui.GetColorU32(ImGuiCol.Text) if hovered or held then @@ -4697,7 +4695,7 @@ local TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5, 1.0) -- Multiplied by g.Style.M local IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111 -- Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter. local string = string -ImFormatString = string.format -- TODO: an simplified version that operates on byte tables directly? +ImFormatString = string.format --- @module "imstd_minstdio" ImStd.sscanf = IM_INCLUDE"imstd_minstdio.lua" @@ -4709,47 +4707,34 @@ local bit32 = bit32 -- [SECTION] MISC HELPERS/UTILITIES (File functions) ------------------------------------------------------------------------------- ---- This closes the _file. +--- [Port] This closes the _file. --- @param _file any # File object function IM_FILE_CLOSE(_file) end ---- This returns the size of _file in bytes. +--- [Port] This returns the size of _file in bytes. --- @param _file any # File object --- @return int function IM_FILE_SIZE(_file) return -1 end ---- This writes _str into _file. +--- [Port] This writes _str into _file. --- @param _file any # File object --- @param _str string function IM_FILE_WRITE(_file, _str) end ---- This reads the specified _count of chars and returns them as a binary string. +--- [Port] This reads the specified _count of chars and returns them as a binary string. --- @param _file any # File object --- @param _count int --- @return string function IM_FILE_READ(_file, _count) return "" end ---- This opens the file at _filename in _mode and returns the File object. +--- [Port] This opens the file at _filename in _mode and returns the File object. --- @param _filename string --- @param _mode string # e.g. "rb" --- @return any function ImStd.ImFileOpen(_filename, _mode) end ---- [GMod] Platform specific -if gmod then - IM_FILE_CLOSE = FindMetaTable("File").Close --- @type function - IM_FILE_SIZE = FindMetaTable("File").Size --- @type function - IM_FILE_WRITE = FindMetaTable("File").Write --- @type function - IM_FILE_READ = FindMetaTable("File").Read --- @type function -end - -- Default file functions if not IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS then - --- [GMod] Another Platform specific - if gmod then - function ImStd.ImFileOpen(filename, mode) return file.Open(filename, mode, "GAME") end - end - function ImStd.ImFileClose(f) IM_FILE_CLOSE(f) end function ImStd.ImFileGetSize(f) return IM_FILE_SIZE(f) end @@ -4757,7 +4742,7 @@ if not IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS then --- @param data table # 1-based table to store result data --- @param count int # Amount of bytes to read from `f` function ImStd.ImFileRead(f, data, count) - local CHUNK_SIZE = 8000 -- We don't read byte by byte + local CHUNK_SIZE = 8000 -- [Port] We don't read byte by byte local offset = 0 while offset < count do @@ -4873,7 +4858,7 @@ local ImGuiResizeGripDef = { -- Data for resizing from borders -- InnerDir: Normal toward inside, SegmentN1/SegmentN2: End positions, normalized (0,0: upper left), OuterAngle: Angle toward outside ---- [1] Left, [2] Right, [3] Up, [4] Down +--- [Port] [1] Left, [2] Right, [3] Up, [4] Down local ImGuiResizeBorderDef = { {InnerDir = ImVec2( 1, 0), SegmentN1 = ImVec2( 0, 1), SegmentN2 = ImVec2( 0, 0), OuterAngle = IM_PI * 1.00}, -- Left {InnerDir = ImVec2(-1, 0), SegmentN1 = ImVec2( 1, 0), SegmentN2 = ImVec2( 1, 1), OuterAngle = IM_PI * 0.00}, -- Right @@ -4938,13 +4923,12 @@ end -- Zero-terminated string hash, with support for ### to reset back to seed value. -- e.g. "label###id" outputs the same hash as "id" (and "label" is generally displayed by the UI functions) --- Use FNV1a, as one ImGui FIXME suggested +-- [Port] Use FNV1a, as one ImGui FIXME suggested --- @param str string --- @param size int? --- @param seed int? --- @return int -- [Luau] memo for whole-string hashes: labels are re-hashed with the same seed every frame. --- ponytail: whole-memo reset at HASH_MEMO_MAX entries, LRU if ID churn makes it thrash local hash_memo, hash_memo_n, HASH_MEMO_MAX = {}, 0, 16384 local ImHashStrRaw @@ -4969,7 +4953,7 @@ end function ImHashStrRaw(str, size, seed) if str == "" or size == 0 then - return seed -- need to match cpp code edge case behavior while using FNV ourselves + return seed -- [Port] need to match cpp code edge case behavior while using FNV ourselves end local FNV_OFFSET_BASIS = 0x811C9DC5 @@ -5149,7 +5133,6 @@ function ImStd.ImTextFindValidUtf8CodepointEnd(text, in_text_start, in_text_end, local prev = ImStd.ImTextFindPreviousUtf8Codepoint(text, in_text_start, in_p) local prev_c_len, prev_c = ImStd.ImTextCharFromUtf8(text, prev, in_text_end) - -- Check if the previous character is valid and fits within the range if prev_c ~= IM_UNICODE_CODEPOINT_INVALID and prev_c_len <= (in_p - prev) then return in_p end @@ -5333,7 +5316,7 @@ end -- Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible. --- @param buf char[] function ImStd.ImStrTrimBlanks(buf) - local p = 1 -- buf_begin + local p = 1 -- [Port] buf_begin while buf[p] == 32 or buf[p] == 9 do -- Leading blanks p = p + 1 end @@ -5672,7 +5655,7 @@ local GLocalizationEntriesEnUS = { } -- [Luau] Default platform handlers (upstream: next to the metrics section; defined here so Initialize() can see the local). --- Roblox has no shell: IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS path. Default clipboard/IME handlers are OS-specific: left nil +-- [Port] Roblox has no shell: IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS path. Default clipboard/IME handlers are OS-specific: left nil -- (the backends install their own clipboard handlers). local function Platform_OpenInShellFn_DefaultImpl(ctx, path) return false end @@ -5906,7 +5889,7 @@ end ------------------------------------------------------------------------------- -- [SECTION] SETTINGS --- (in-memory .ini; Roblox has no disk) +-- [Port] (in-memory .ini; Roblox has no disk) ------------------------------------------------------------------------------- -- - UpdateSettings() [Internal] -- - MarkIniSettingsDirty() [Internal] @@ -5937,7 +5920,7 @@ function ImGui.UpdateSettings() if g.SettingsDirtyTimer > 0.0 then g.SettingsDirtyTimer = g.SettingsDirtyTimer - g.IO.DeltaTime if g.SettingsDirtyTimer <= 0.0 then - -- No disk: always let the user know they can call SaveIniSettingsToMemory() + -- [Port] No disk: always let the user know they can call SaveIniSettingsToMemory() g.IO.WantSaveIniSettings = true -- Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves. g.SettingsDirtyTimer = 0.0 end @@ -6015,7 +5998,7 @@ function ImGui.LoadIniSettingsFromDisk(ini_filename) end -- Zero-tolerance, no error reporting, cheap .ini parsing --- Set ini_size==0 (or nil) to use the whole string (Lua strings know their length). +-- [Port] Set ini_size==0 (or nil) to use the whole string (Lua strings know their length). function ImGui.LoadIniSettingsFromMemory(ini_data, ini_size) local g = GImGui IM_ASSERT(g.Initialized) @@ -6067,7 +6050,7 @@ end function ImGui.SaveIniSettingsToDisk(ini_filename) local g = GImGui g.SettingsDirtyTimer = 0.0 - -- Roblox: no disk. Call SaveIniSettingsToMemory() and persist the string yourself (e.g. DataStore). + -- [Port] Roblox: no disk. Call SaveIniSettingsToMemory() and persist the string yourself (e.g. DataStore). end -- Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer @@ -6088,7 +6071,7 @@ function ImGui.CreateNewWindowSettings(name) -- Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier. if not g.IO.ConfigDebugIniSettings then - -- ImHashSkipUncontributingPrefix: skip everything up to the last "###" + -- [Port] ImHashSkipUncontributingPrefix: skip everything up to the last "###" local p = name:match("^.*()###") if p then name = name:sub(p) end end @@ -6273,7 +6256,7 @@ end local function LogTextV_Internal(g, fmt, ...) local s = (select("#", ...) > 0) and string.format(fmt, ...) or fmt if g.LogFile then - print(s) -- TTY (the only "file" available on Roblox) + print(s) -- [Port] TTY (the only "file" available on Roblox) else g.LogBuffer:append(s) end @@ -6289,7 +6272,7 @@ ImGui.LogTextV = ImGui.LogText -- Internal version that takes a position to decide on newline placement and pad items according to their depth. -- We split text into individual lines to add current tree level padding -- FIXME: This code is a little complicated perhaps, considering simplifying the whole system. ---- `text` is a Lua string, `text_begin/text_end` optional 1-based byte range (text_end exclusive). +--- [Port] `text` is a Lua string, `text_begin/text_end` optional 1-based byte range (text_end exclusive). function ImGui.LogRenderedText(ref_pos, text, text_end, text_begin) local g = GImGui local window = g.CurrentWindow @@ -6369,7 +6352,7 @@ end -- Start logging/capturing text output to given file function ImGui.LogToFile(auto_open_depth, filename) - -- Roblox: no file access. Falls back to TTY (output window). + -- [Port] Roblox: no file access. Falls back to TTY (output window). ImGui.LogToTTY(auto_open_depth) end @@ -6994,7 +6977,7 @@ function ImGui.GetWindowContentRegionMax() return window.ContentRegionRect.Max - window.Pos end --- Overloads: IsRectVisible(size) / IsRectVisible(rect_min, rect_max) +-- [Port] Overloads: IsRectVisible(size) / IsRectVisible(rect_min, rect_max) function ImGui.IsRectVisible(a, b) local window = GImGui.CurrentWindow if b == nil then @@ -7515,14 +7498,14 @@ function ImGui.BringWindowToDisplayBehind(window, behind_window) local g = GImGui window = window.RootWindow behind_window = behind_window.RootWindow - local pos_wnd = ImGui.FindWindowDisplayIndex(window) + 1 -- 1-based + local pos_wnd = ImGui.FindWindowDisplayIndex(window) + 1 -- [Port] 1-based local pos_beh = ImGui.FindWindowDisplayIndex(behind_window) + 1 local data = g.Windows.Data if pos_wnd < pos_beh then - for i = pos_wnd, pos_beh - 2 do data[i] = data[i + 1] end -- memmove + for i = pos_wnd, pos_beh - 2 do data[i] = data[i + 1] end -- [Port] memmove data[pos_beh - 1] = window else - for i = pos_wnd, pos_beh + 1, -1 do data[i] = data[i - 1] end -- memmove + for i = pos_wnd, pos_beh + 1, -1 do data[i] = data[i - 1] end -- [Port] memmove data[pos_beh] = window end end @@ -7787,7 +7770,7 @@ function MT.ImGuiWindow:GetIDFromRectangle(r_abs) return ImHashData({ math.floor(r_rel.Min.x), math.floor(r_rel.Min.y), math.floor(r_rel.Max.x), math.floor(r_rel.Max.y) }, 4, seed) end --- Overloads: GetID(str_id) / GetID(str_id_begin, str_id_end) / GetID(int_id) +-- [Port] Overloads: GetID(str_id) / GetID(str_id_begin, str_id_end) / GetID(int_id) --- @param str_or_int string|int --- @param str_end? int # exclusive end (1-based byte position) --- @return ImGuiID @@ -7802,7 +7785,7 @@ end -- Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call -- (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level. -- for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more) --- Overloads: GetIDWithSeed(str, str_end, seed) / GetIDWithSeed(n, seed) +-- [Port] Overloads: GetIDWithSeed(str, str_end, seed) / GetIDWithSeed(n, seed) function ImGui.GetIDWithSeed(a, b, c) local id if type(a) == "number" then @@ -9170,7 +9153,7 @@ local function IsKeyChordPotentiallyCharInput(key_chord) if key == ImGuiKey.None then return false end - return g.KeysMayBeCharInput:TestBit(key + 1) -- TestBit requires 1-based index + return g.KeysMayBeCharInput:TestBit(key + 1) -- [Port] TestBit requires 1-based index end -- Request a desired route for an input chord (key + mods). @@ -9625,7 +9608,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) local key = e.Key.Key IM_ASSERT(key ~= ImGuiKey.None) - -- TODO: Also gets 0-based index here, consider making key_data storage 1-based + -- [Port] TODO: Also gets 0-based index here, consider making key_data storage 1-based local key_data, key_data_index = ImGui.GetKeyData(g, key) if trickle_fast_inputs and key_data.Down ~= e.Key.Down and (key_changed_mask:TestBit(key_data_index + 1) or mouse_button_changed ~= 0) then @@ -10110,7 +10093,7 @@ end -- Handle resize for: Resize Grips, Borders, Gamepad -- Return true when using auto-fit (double-click on resize grip) --- Returns (ret_auto_fit_mask, border_hovered, border_held) +-- [Port] Returns (ret_auto_fit_mask, border_hovered, border_held) --- @param window ImGuiWindow --- @param resize_grip_count int --- @param resize_grip_col table @@ -10968,7 +10951,7 @@ ImGui.RenderWindowOuterBorders = RenderWindowOuterBorders -- When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead. -- Render title text, collapse button, close button --- Returns the updated 'open' value (nil when there is no close button) +-- [Port] Returns the updated 'open' value (nil when there is no close button) --- @param window ImGuiWindow --- @param title_bar_rect ImRect --- @param name string @@ -11125,7 +11108,7 @@ function ImGui.UpdateWindowSkipRefresh(window) c.ScrollX, c.ScrollY, c.DisplayX, c.DisplayY = window.Scroll.x, window.Scroll.y, ds.x, ds.y return end - -- skip: widgets early-out on SkipItems and Begin() returns visible=false; End() restores it + -- [Port] skip: widgets early-out on SkipItems and Begin() returns visible=false; End() restores it window.CacheSkipItemsBackup = window.SkipItems window.SkipItems = true end @@ -11235,7 +11218,7 @@ end --- @param pos ImVec2 --- @param cond? ImGuiCond function ImGui.SetWindowPos(window, pos, cond) - -- Overloads: SetWindowPos(pos, cond) / SetWindowPos(name, pos, cond) / SetWindowPos(window, pos, cond) + -- [Port] Overloads: SetWindowPos(pos, cond) / SetWindowPos(name, pos, cond) / SetWindowPos(window, pos, cond) if type(window) == "string" then window = ImGui.FindWindowByName(window) if window == nil then return end @@ -11373,7 +11356,7 @@ function ImGui.GetWindowSize() return ImGui.GetCurrentWindowRead().Size end --- Overloads: SetWindowFocus() / SetWindowFocus(name). Passing nil name removes focus. +-- [Port] Overloads: SetWindowFocus() / SetWindowFocus(name). Passing nil name removes focus. --- @param name? string function ImGui.SetWindowFocus(...) if select("#", ...) == 0 then @@ -11518,7 +11501,6 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) -- Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument. local ImGuiChildFlags_SupportedMask_ = bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY, ImGuiChildFlags.AutoResizeX, ImGuiChildFlags.AutoResizeY, ImGuiChildFlags.AlwaysAutoResize, ImGuiChildFlags.FrameStyle, ImGuiChildFlags.NavFlattened) - -- IM_UNUSED(ImGuiChildFlags_SupportedMask_) IM_ASSERT(bit32.band(child_flags, bit32.bnot(ImGuiChildFlags_SupportedMask_)) == 0, "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?") IM_ASSERT(bit32.band(window_flags, ImGuiWindowFlags.AlwaysAutoResize) == 0, "Cannot specify ImGuiWindowFlags.AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags.AlwaysAutoResize!") if bit32.band(child_flags, ImGuiChildFlags.AlwaysAutoResize) ~= 0 then @@ -11632,7 +11614,7 @@ end -- Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'. -- ImGuiChildFlags.Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details! --- `true` is accepted as ImGuiChildFlags.Borders for legacy code. +-- [Port] `true` is accepted as ImGuiChildFlags.Borders for legacy code. --- @param str_id_or_id string|ImGuiID --- @param size_arg? ImVec2 --- @param child_flags? ImGuiChildFlags|bool @@ -11781,7 +11763,7 @@ function ImGui.SetNextWindowClass(window_class) local g = GImGui g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasWindowClass) local wc = ImGuiWindowClass() - for k, v in pairs(window_class) do wc[k] = v end -- C++ copies the struct + for k, v in pairs(window_class) do wc[k] = v end -- [Port] C++ copies the struct g.NextWindowData.WindowClass = wc end @@ -11808,7 +11790,7 @@ function ImGui.SetNextWindowCached(key) end function ImGui.GetWindowDpiScale() - return 1.0 -- Roblox: single viewport, no DPI scaling + return 1.0 -- [Port] Roblox: single viewport, no DPI scaling end function ImGui.GetWindowViewport() @@ -11908,7 +11890,7 @@ function ImGui.IsPopupOpen(id, popup_flags) local g = GImGui if popup_flags == nil then popup_flags = 0 end if type(id) == "string" then - -- str_id overload: with AnyPopupId the id must be 0, otherwise it is hashed with the current window's ID stack + -- [Port] str_id overload: with AnyPopupId the id must be 0, otherwise it is hashed with the current window's ID stack id = (bit32.band(popup_flags, ImGuiPopupFlags.AnyPopupId) ~= 0) and 0 or g.CurrentWindow:GetID(id) end @@ -12038,7 +12020,6 @@ function ImGui.TranslateWindow(window, delta) ImVec2_Copy(window.DC.IdealMaxPos, window.DC.IdealMaxPos + delta) end ---- ImGui::FindWindowByID function ImGui.FindWindowByID(id) local g = GImGui @@ -13043,7 +13024,7 @@ end if bit32.band(flags, ImGuiWindowFlags.DockNodeHost) == 0 and not window.SkipRefresh then ImGui.PushClipRect(window.InnerClipRect.Min, window.InnerClipRect.Max, true) - -- [Roblox backend] content clip + scroll origin: lets the backend move scrolled content instead of redrawing it + -- [Port] [Roblox backend] content clip + scroll origin: lets the backend move scrolled content instead of redrawing it local dl, cr = window.DrawList, window.DrawList._CmdHeader.ClipRect dl._ContentClipX0, dl._ContentClipY0, dl._ContentClipX1, dl._ContentClipY1 = cr.x, cr.y, cr.z, cr.w dl._ScrollOriginX, dl._ScrollOriginY = window.Pos.x - window.Scroll.x, window.Pos.y - window.Scroll.y @@ -13217,8 +13198,8 @@ function ImGui.End() g.CurrentWindowStack:pop_back() - -- LUA: No "Ternary Operator", since lua (... and (1) or (2)) will eval (1) and (2) no matter what - -- so something like `SetCurrentWindow((g.CurrentWindowStack.Size == 0) and nil or g.CurrentWindowStack:back().Window)` will error + -- [Port] No "Ternary Operator", since lua (... and (1) or (2)) will eval (1) and (2) no matter what + -- [Port] so something like `SetCurrentWindow((g.CurrentWindowStack.Size == 0) and nil or g.CurrentWindowStack:back().Window)` will error if (g.CurrentWindowStack.Size == 0) then SetCurrentWindow(nil) else @@ -13374,7 +13355,7 @@ local function FindHoveredWindowEx(pos, find_first_and_in_any_viewport) if window.HitTestHoleSize.x ~= 0 then local hx, hy = window.Pos.x + window.HitTestHoleOffset.x, window.Pos.y + window.HitTestHoleOffset.y if pos.x >= hx and pos.y >= hy and pos.x < hx + window.HitTestHoleSize.x and pos.y < hy + window.HitTestHoleSize.y then - break -- continue + break -- [Port] continue end end @@ -13718,7 +13699,7 @@ local function LockWheelingWindow(window, wheel_amount) if (g.WheelingWindow == window) then return end - -- IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL") + -- [Port] IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL") g.WheelingWindow = window ImVec2_Copy(g.WheelingWindowRefMousePos, g.IO.MousePos) if window == nil then @@ -13820,7 +13801,6 @@ function ImGui.UpdateMouseWheel() if window == window.RootWindow then local offset = window.Size * (1.0 - scale) * (g.IO.MousePos - window.Pos) / window.Size ImGui.SetWindowPos(window, window.Pos + offset, 0) - -- MarkIniSettingsDirty(window) end return end @@ -14012,7 +13992,7 @@ end local function GetViewportBgFgDrawList(viewport, drawlist_no, drawlist_name) -- Create the draw list on demand, because they are not frequently used for all viewports local g = GImGui - IM_ASSERT(drawlist_no <= 2) -- IM_COUNTOF(viewport->BgFgDrawLists) + IM_ASSERT(drawlist_no <= 2) -- [Port] IM_COUNTOF(viewport->BgFgDrawLists) local draw_list = viewport.BgFgDrawLists[drawlist_no] if draw_list == nil then draw_list = ImDrawList(g.DrawListSharedData) @@ -14171,7 +14151,6 @@ function ImGui.NewFrame() g.MenusIdSubmittedThisFrame:resize(0) -- Calculate frame-rate for the user, as a purely luxurious feature - -- FIXME: are lines below correct and necessary g.FramerateSecPerFrameAccum = g.FramerateSecPerFrameAccum + (g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]) g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % 60 @@ -14505,7 +14484,7 @@ function ImGui.EndFrame() if viewport == nil then viewport = ImGui.GetMainViewport() end - -- IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f) for Viewport 0x%08X", ime_data.WantVisible, ime_data.InputPos.x, ime_data.InputPos.y, viewport.ID) + -- [Port] IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f) for Viewport 0x%08X", ime_data.WantVisible, ime_data.InputPos.x, ime_data.InputPos.y, viewport.ID) g.PlatformIO.Platform_SetImeDataFn(g, viewport, ime_data) end g.WantTextInputNextFrame = ime_data.WantTextInput @@ -14726,7 +14705,6 @@ function ImGui.Shutdown() IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == nil, "Forgot to shutdown Platform backend?") IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == nil, "Forgot to shutdown Renderer backend?") for _, viewport in g.Viewports:iter() do - -- IM_UNUSED(viewport) IM_ASSERT_USER_ERROR(viewport.RendererUserData == nil and viewport.PlatformUserData == nil and viewport.PlatformHandle == nil, "Backend or app forgot to call DestroyPlatformWindows()?") end @@ -14999,7 +14977,7 @@ function ImGui.ColorConvertHSVtoRGB(h, s, v) return p, q, v elseif i == 4 then return t, p, v - else -- i == 5 or default + else -- [Port] i == 5 or default return v, p, q end end @@ -15153,7 +15131,7 @@ local GStyleVarsInfo = { ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextPadding"), -- ImGuiStyleVar.SeparatorTextPadding ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DockingSeparatorSize"), -- ImGuiStyleVar.DockingSeparatorSize } -IM_ASSERT(#GStyleVarsInfo == ImGuiStyleVar.COUNT) -- IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar_COUNT) +IM_ASSERT(#GStyleVarsInfo == ImGuiStyleVar.COUNT) -- [Port] IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar_COUNT) --- @param idx ImGuiStyleVar --- @return ImGuiStyleVarInfo @@ -15176,7 +15154,7 @@ function ImGui.PushStyleVar(idx, val) g.StyleVarStack:push_back(ImGuiStyleMod(idx, var)) if type(val) == "number" then g.Style[var_info.Key] = val - else -- copy into the style's own ImVec2: storing the caller's vector would alias it into the style forever + else -- [Port] copy into the style's own ImVec2: storing the caller's vector would alias it into the style forever var.x = val.x; var.y = val.y end end @@ -15648,7 +15626,7 @@ function ImGui.SetScrollHereY(center_y_ratio) window.ScrollTargetEdgeSnapDist.y = ImMax(0.0, window.WindowPadding.y - spacing_y) end --- Overloads: SetScrollX(scroll_x) / SetScrollX(window, scroll_x) +-- [Port] Overloads: SetScrollX(scroll_x) / SetScrollX(window, scroll_x) --- @param window ImGuiWindow|float --- @param scroll_x float? function ImGui.SetScrollX(window, scroll_x) @@ -15901,7 +15879,7 @@ function ImGui.OpenPopupEx(id, popup_flags) ImVec2_Copy(popup_ref.OpenMousePos, popup_ref.OpenPopupPos) end - -- IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id) + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id) if g.OpenPopupStack.Size < current_stack_size + 1 then g.OpenPopupStack:push_back(popup_ref) return true @@ -15991,7 +15969,7 @@ function ImGui.ClosePopupsOverWindow(ref_window, restore_focus_to_window_under_p end end if popup_count_to_keep < g.OpenPopupStack.Size then -- This test is not required but it allows to set a convenient breakpoint on the statement below - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window and ref_window.Name or "") + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window and ref_window.Name or "") ImGui.ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup) end end @@ -16000,17 +15978,16 @@ end --- @param restore_focus_to_window_under_popup bool function ImGui.ClosePopupToLevel(remaining, restore_focus_to_window_under_popup) local g = GImGui - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup) + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup) IM_ASSERT(remaining >= 0 and remaining < g.OpenPopupStack.Size) - -- if bit32.band(g.DebugLogFlags, ImGuiDebugLogFlags.EventPopup) ~= 0 then - -- for n = remaining + 1, g.OpenPopupStack.Size do - -- local popup = g.OpenPopupStack.Data[n] - -- IMGUI_DEBUG_LOG_POPUP("[popup] - Closing PopupID 0x%08X Window \"%s\"", popup.PopupId, popup.Window and popup.Window.Name or nil) - -- end - -- end + -- [Port] if bit32.band(g.DebugLogFlags, ImGuiDebugLogFlags.EventPopup) ~= 0 then + -- [Port] for n = remaining + 1, g.OpenPopupStack.Size do + -- [Port] local popup = g.OpenPopupStack.Data[n] + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] - Closing PopupID 0x%08X Window \"%s\"", popup.PopupId, popup.Window and popup.Window.Name or nil) + -- [Port] end + -- [Port] end -- Trim open popup stack - -- FIXME: is it safer to full copy here? local prev_popup = g.OpenPopupStack.Data[remaining + 1] g.OpenPopupStack:resize(remaining) @@ -16059,7 +16036,7 @@ function ImGui.CloseCurrentPopup() popup_idx = popup_idx - 1 end - -- IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size, popup_idx) + -- [Port] IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size, popup_idx) ImGui.ClosePopupToLevel(popup_idx - 1, true) -- A common pattern is to close a popup when selecting a menu item/selectable that will open another window. @@ -16561,7 +16538,7 @@ end function ImGui.SetNavWindow(window) local g = GImGui if g.NavWindow ~= window then - -- IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")", window and window.Name or "") + -- [Port] IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")", window and window.Name or "") g.NavWindow = window g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid end @@ -16626,7 +16603,7 @@ function ImGui.NavRestoreLayer(layer) local prev_nav_window = g.NavWindow g.NavWindow = ImGui.NavRestoreLastChildNavWindow(g.NavWindow) -- FIXME-NAV: Should clear ongoing nav requests? g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid - -- if (prev_nav_window) IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name) + -- [Port] if (prev_nav_window) IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name) end local window = g.NavWindow if window.NavLastIds[layer] ~= 0 then @@ -16670,7 +16647,7 @@ function ImGui.NavInitWindow(window, force_reinit) if window == window.RootWindow or bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 or window.NavLastIds[0] == 0 or force_reinit then init_for_nav = true end - -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d", init_for_nav, window->Name, g.NavLayer) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d", init_for_nav, window->Name, g.NavLayer) if init_for_nav then ImGui.SetNavID(0, g.NavLayer, window.NavRootFocusScopeId, ImRect()) g.NavInitRequest = true @@ -17223,7 +17200,7 @@ function ImGui.NavUpdateCreateMoveRequest() -- (preserve most state, which were already set by the NavMoveRequestForward() function) IM_ASSERT(g.NavMoveDir ~= ImGuiDir.None and g.NavMoveClipDir ~= ImGuiDir.None) IM_ASSERT(bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Forwarded) ~= 0) - -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir) else -- Initiate directional inputs request g.NavMoveDir = ImGuiDir.None @@ -17255,7 +17232,7 @@ function ImGui.NavUpdateCreateMoveRequest() -- Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match) if g.NavMoveSubmitted and g.NavId == 0 then - -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "", g.NavLayer) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "", g.NavLayer) g.NavInitRequest = true; g.NavInitRequestFromMove = true g.NavInitResult.ID = 0 if g.IO.ConfigNavCursorVisibleAuto then -- NO check for _NoNavInputs here as we assume MoveRequests cannot be created. @@ -17277,7 +17254,7 @@ function ImGui.NavUpdateCreateMoveRequest() inner_rect_rel:Translate(ImVec2(next_scroll.x - window.Scroll.x, next_scroll.y - window.Scroll.y)) if (clamp_x or clamp_y) and not inner_rect_rel:Contains(window.NavRectRel[g.NavLayer]) then - -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n") + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n") local pad_x = ImMin(inner_rect_rel:GetWidth(), window.FontRefSize * 0.5) local pad_y = ImMin(inner_rect_rel:GetHeight(), window.FontRefSize * 0.5) -- Terrible approximation for the intent of starting navigation from first fully visible item inner_rect_rel.Min.x = clamp_x and (inner_rect_rel.Min.x + pad_x) or -FLT_MAX @@ -17921,7 +17898,7 @@ function ImGui.NavInitRequestApplyResult() -- Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) -- FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently. - -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) ImGui.SetNavID(result.ID, g.NavLayer, result.FocusScopeId, result.RectRel) g.NavIdIsAlive = true -- Mark as alive from previous frame as we got a result if result.SelectionUserData ~= ImGuiSelectionUserData_Invalid then @@ -17963,7 +17940,7 @@ function ImGui.NavMoveRequestApplyResult() ImGui.SetNavCursorVisibleAfterMove() end ImGui.NavClearPreferredPosForAxis(axis) -- On a failed move, clear preferred pos for this axis. - -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n") + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n") return end @@ -17995,7 +17972,7 @@ function ImGui.NavMoveRequestApplyResult() end if g.NavWindow ~= result.Window then - -- IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name) + -- [Port] IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name) g.NavWindow = result.Window g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid end @@ -18022,7 +17999,7 @@ function ImGui.NavMoveRequestApplyResult() end -- Apply new NavID/Focus - -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) + -- [Port] IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) local root_for_nav = g.NavWindow.RootWindowForNav local preferred_scoring_pos_rel = ImVec2() ImVec2_Copy(preferred_scoring_pos_rel, root_for_nav.NavPreferredScoringPosRel[g.NavLayer]) @@ -18246,7 +18223,7 @@ function ImGui.SetCurrentViewport(current_window, viewport) g.CurrentDpiScale = viewport and viewport.DpiScale or 1.0 g.CurrentViewport = viewport IM_ASSERT(g.CurrentDpiScale > 0.0 and g.CurrentDpiScale < 99.0) -- Typical correct values would be between 1.0f and 4.0f - -- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X", current_window and current_window.Name or "NULL", viewport and viewport.ID or 0) + -- [Port] IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X", current_window and current_window.Name or "NULL", viewport and viewport.ID or 0) if g.IO.ConfigDpiScaleFonts then g.Style.FontScaleDpi = g.CurrentDpiScale @@ -18550,7 +18527,7 @@ function ImGui.UpdateViewportsNewFrame() -- Erase unused viewports if n > 1 and viewport.LastFrameActive < g.FrameCount - 2 then ImGui.DestroyViewport(viewport) - -- n stays the same because we removed an element + -- [Port] n stays the same because we removed an element else local platform_funcs_available = viewport.PlatformWindowCreated @@ -18593,7 +18570,7 @@ function ImGui.UpdateViewportsNewFrame() viewport:UpdateWorkRect() -- Garbage collect transient buffers of recently BG/FG drawlists - for dl_n = 1, 2 do -- IM_COUNTOF(viewport->BgFgDrawLists) + for dl_n = 1, 2 do -- [Port] IM_COUNTOF(viewport->BgFgDrawLists) if viewport.BgFgDrawListsLastTimeActive[dl_n] < memory_compact_start_time and viewport.BgFgDrawLists[dl_n] ~= nil then IM_DELETE(viewport.BgFgDrawLists, dl_n) end @@ -18865,7 +18842,6 @@ function ImGui.DestroyViewport(viewport) IM_ASSERT(not g.PlatformIO.Viewports:contains(viewport)) IM_ASSERT(g.Viewports.Data[viewport.Idx] == viewport) g.Viewports:erase(viewport.Idx) - -- IM_DELETE(viewport) end -- FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten. @@ -19004,7 +18980,6 @@ function ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) -- Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM if window.Viewport.PlatformRequestMove then ImVec2_Copy(window.Pos, window.Viewport.Pos) - -- ImGui.MarkIniSettingsDirty(window) elseif window.Viewport.Pos.x ~= window.Pos.x or window.Viewport.Pos.y ~= window.Pos.y then viewport_rect_changed = true ImVec2_Copy(window.Viewport.Pos, window.Pos) @@ -19013,7 +18988,6 @@ function ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) if window.Viewport.PlatformRequestResize then ImVec2_Copy(window.Size, window.Viewport.Size) ImVec2_Copy(window.SizeFull, window.Viewport.Size) - -- ImGui.MarkIniSettingsDirty(window) elseif window.Viewport.Size.x ~= window.Size.x or window.Viewport.Size.y ~= window.Size.y then viewport_rect_changed = true ImVec2_Copy(window.Viewport.Size, window.Size) @@ -19170,7 +19144,7 @@ function ImGui.UpdatePlatformWindows() local title_end = ImGui.FindRenderedTextEnd(title) local title_hash = ImHashStr(title, title_end - title_begin) if viewport.LastNameHash ~= title_hash then - -- This still creates new strings + -- [Port] This still creates new strings g.PlatformIO.Platform_SetWindowTitle(viewport, string.sub(title, title_begin, title_end - 1)) viewport.LastNameHash = title_hash end @@ -19224,7 +19198,6 @@ function ImGui.RenderPlatformWindowsDefault(platform_render_arg, renderer_render -- Skip the main viewport (index 1 in Lua), which is always fully handled by the application! local platform_io = ImGui.GetPlatformIO() - -- First pass: render all windows for i = 2, platform_io.Viewports.Size do local viewport = platform_io.Viewports.Data[i] if bit32.band(viewport.Flags, ImGuiViewportFlags.IsMinimized) == 0 then @@ -19237,7 +19210,6 @@ function ImGui.RenderPlatformWindowsDefault(platform_render_arg, renderer_render end end - -- Second pass: swap buffers for all windows for i = 2, platform_io.Viewports.Size do local viewport = platform_io.Viewports.Data[i] if bit32.band(viewport.Flags, ImGuiViewportFlags.IsMinimized) == 0 then @@ -19930,7 +19902,7 @@ function MT.ImGuiTextFilter:Clear() self.InputBuf[1] = 0; self:Build() end function MT.ImGuiTextFilter:IsActive() return self._Items.Size ~= 0 end -- Parse filter and split into a format optimal for PassFilter() --- Items are { Text = string (lowercased), CountInclude = int } +-- [Port] Items are { Text = string (lowercased), CountInclude = int } function MT.ImGuiTextFilter:Build() local items = self._Items items:resize(0) @@ -19939,9 +19911,9 @@ function MT.ImGuiTextFilter:Build() local n = 0 while self.InputBuf[n + 1] ~= nil and self.InputBuf[n + 1] ~= 0 do n = n + 1 end local buf = ImGui._ByteArrayToString(self.InputBuf, 1, n + 1) - local buf_e = n + 1 -- exclusive, 1-based + local buf_e = n + 1 -- [Port] exclusive, 1-based local word_b = 1 - local seq_start_idx = -1 -- 1-based index into items, -1 = none + local seq_start_idx = -1 -- [Port] 1-based index into items, -1 = none while word_b < buf_e do -- Trim blanks while word_b < buf_e and ImCharIsBlankA(string.byte(buf, word_b)) do @@ -20035,7 +20007,7 @@ local function GetSkipItemForListClipping() end --- `offset` is a 0-based count of leading ranges to leave alone +-- [Port] `offset` is a 0-based count of leading ranges to leave alone local function ImGuiListClipper_SortAndFuseRanges(ranges, offset) if offset == nil then offset = 0 end if ranges.Size - offset <= 1 then return end @@ -20218,7 +20190,7 @@ local function ImGuiListClipper_StepInternal(clipper) -- Step 1: Let the clipper infer height from first range if clipper.ItemsHeight <= 0.0 then IM_ASSERT(data.StepNo == 1) - -- (no float precision mitigation needed: Luau numbers are doubles) + -- [Port] (no float precision mitigation needed: Luau numbers are doubles) clipper.ItemsHeight = (window.DC.CursorPos.y - clipper.StartPosY) / (clipper.DisplayEnd - clipper.DisplayStart) if clipper.ItemsHeight == 0.0 and clipper.ItemsCount == INT_MAX then -- Accept that no item have been submitted if in indeterminate mode. return false @@ -20558,7 +20530,7 @@ function ImGui.ErrorRecoveryTryToRecoverWindowState(state_in) -- IM_ASSERT(g.FocusScopeStack.Size == state_in.SizeOfFocusScopeStack) end --- Lines are stored in g.DebugLogBuf (one chunk per call) +-- [Port] Lines are stored in g.DebugLogBuf (one chunk per call) function ImGui.DebugLog(fmt, ...) ImGui.DebugLogV(fmt, ...) end @@ -20574,7 +20546,7 @@ function ImGui.DebugLogV(fmt, ...) end local str = prefix .. ((select("#", ...) > 0) and string.format(fmt, ...) or fmt) g.DebugLogBuf:append(str) - -- Line index (upstream: g.DebugLogIndex). Lines are complete strings without '\n'. + -- [Port] Line index (upstream: g.DebugLogIndex). Lines are complete strings without '\n'. local lines = g.DebugLogLines for part, nl in string.gmatch(str, "([^\n]*)(\n?)") do lines[#lines] = lines[#lines] .. part @@ -20712,7 +20684,7 @@ do --[[ [SECTION] METRICS/DEBUGGER WINDOW, DEBUG LOG, ID STACK TOOL, FONT DEBUG -- [SECTION] Font atlas / font debugging ------------------------------------------------------------------------------- --- byte buffers for InputText (same as the demo's DemoBuf/DemoBufStr; kept here so the library doesn't need the demo) +-- [Port] byte buffers for InputText (same as the demo's DemoBuf/DemoBufStr; kept here so the library doesn't need the demo) local function DemoBuf(str, size) local t = {} for i = 1, #str do t[i] = string.byte(str, i) end @@ -20766,7 +20738,7 @@ function ImGui.DebugRenderKeyboardPreview(draw_list) local start_pos = ImVec2(board_min.x + 5.0 - key_step.x, board_min.y) local K = ImGuiKey - local keys_to_display = { -- { Row, Col, Label, Key } + local keys_to_display = { -- [Port] { Row, Col, Label, Key } { 0, 0, "", K.Tab }, { 0, 1, "Q", K.Q }, { 0, 2, "W", K.W }, { 0, 3, "E", K.E }, { 0, 4, "R", K.R }, { 1, 0, "", K.CapsLock }, { 1, 1, "A", K.A }, { 1, 2, "S", K.S }, { 1, 3, "D", K.D }, { 1, 4, "F", K.F }, { 2, 0, "", K.LeftShift }, { 2, 1, "Z", K.Z }, { 2, 2, "X", K.X }, { 2, 3, "C", K.C }, { 2, 4, "V", K.V }, @@ -20888,7 +20860,7 @@ function ImGui.DebugNodeFontGlyphsForSrcMask(font, baked, src_mask) local glyph_col = ImGui.GetColorU32(ImGuiCol.Text) local cell_size = baked.Size * 1 local cell_spacing = ImGui.GetStyle().ItemSpacing.y - -- [port] only scans loaded codepoints (IndexLookup range) instead of the whole 0..0xFFFF range + -- [Port] only scans loaded codepoints (IndexLookup range) instead of the whole 0..0xFFFF range local max_c = baked.IndexLookup.Size - 1 local base = 0 while base <= max_c do @@ -20946,7 +20918,7 @@ local function CalcFontGlyphSrcOverlapMask(atlas, font, codepoint) local src = font.Sources.Data[src_n + 1] local loader = src.FontLoader or atlas.FontLoader if not (loader.FontSrcContainsGlyph ~= nil and loader.FontSrcContainsGlyph(atlas, src, codepoint)) then - break -- continue + break -- [Port] continue end mask = bit32.bor(mask, bit32.lshift(1, src_n)) count = count + 1 @@ -21041,7 +21013,7 @@ function ImGui.DebugNodeFont(font) if ImGui.TreeNode("Glyphs", "Baked at { %.2fpx, d.%.2f }: %d glyphs%s", baked.Size, baked.RasterizerDensity, baked.Glyphs.Size, (baked.LastUsedFrame < (builder.FrameCount or 0) - 1) and " *Unused*" or "") then if ImGui.SmallButton("Load all") then - for c = 0, 0x7F do baked:FindGlyph(c) end -- [port] ASCII only: loading the whole BMP in Luau stalls for seconds + for c = 0, 0x7F do baked:FindGlyph(c) end -- [Port] ASCII only: loading the whole BMP in Luau stalls for seconds end local surface_sqrt = math.floor(math.sqrt(baked.MetricsTotalSurface)) ImGui.Text("Ascent: %f, Descent: %f, Ascent-Descent: %f", baked.Ascent, baked.Descent, baked.Ascent - baked.Descent) @@ -21231,7 +21203,7 @@ function ImGui.ShowDebugLogWindow(p_open) g.DebugLogFlags = bit32.band(g.DebugLogFlags, bit32.bnot(L.EventClipper)) local lines = g.DebugLogLines local count = #lines - if lines[count] == "" then count = count - 1 end -- trailing partial line + if lines[count] == "" then count = count - 1 end -- [Port] trailing partial line local clipper = ImGuiListClipper() clipper:Begin(count) while clipper:Step() do @@ -21258,9 +21230,9 @@ function ImGui.DebugTextUnformattedWithLocateItem(line_begin, line_end) while p <= line_end - 10 do repeat -- [Luau] 1-based (C: p <= line_end - 10 with 0-based offsets) local b0, b1 = string.byte(line_begin, p, p + 1) local hex = string.match(line_begin, "^%x+", p + 2) - if b0 ~= 48 or (b1 ~= 120 and b1 ~= 88) or hex == nil or string.find(string.sub(line_begin, p + 10, p + 10), "^%x") then -- '0', 'x', 'X' + if b0 ~= 48 or (b1 ~= 120 and b1 ~= 88) or hex == nil or string.find(string.sub(line_begin, p + 10, p + 10), "^%x") then -- [Port] '0', 'x', 'X' p = p + 1 - break -- continue + break -- [Port] continue end local id = tonumber(hex, 16) -- [Luau] sscanf("%X") local p0 = ImGui.CalcTextSizeEx(line_begin, 1, p) @@ -21269,7 +21241,7 @@ function ImGui.DebugTextUnformattedWithLocateItem(line_begin, line_end) if ImGui.IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true) then ImGui.DebugLocateItemOnHover(id) end - p = p + 11 -- p += 10, then the loop's p++ + p = p + 11 -- [Port] p += 10, then the loop's p++ until true end end @@ -21449,7 +21421,7 @@ function ImGui.UpdateDebugToolItemPathQuery() end -- [DEBUG] ID Stack tool: hooks called by GetID() family functions --- `data_id` is the string/number that was hashed. +-- [Port] `data_id` is the string/number that was hashed. function ImGui.DebugHookIdInfo(id, data_type, data_id) local g = ImGui.GetCurrentContext() local query = PathQuery(g) @@ -21641,7 +21613,7 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) local pcmd = draw_list.CmdBuffer.Data[cmd_n] if pcmd.UserCallback then ImGui.BulletText("Callback %s, user_data %s", tostring(pcmd.UserCallback), tostring(pcmd.UserCallbackData)) - break -- continue + break -- [Port] continue end local texid_desc = FormatTextureRefForDebugDisplay(pcmd.TexRef) @@ -21653,7 +21625,7 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) ImGui.DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg.ShowDrawCmdMesh, cfg.ShowDrawCmdBoundingBoxes) end if not pcmd_node_open then - break -- continue + break -- [Port] continue end -- Calculate approximate coverage area (touched pixel count) @@ -22227,7 +22199,7 @@ function ImGui.ShowMetricsWindow(p_open) for i = 1, g.PlatformIO.Monitors.Size do ImGui.DebugNodePlatformMonitor(g.PlatformIO.Monitors.Data[i], "Monitor", i - 1) if ImGui.IsItemHovered() then - cfg.HighlightMonitorIdx = i - 1 -- 0-based, like Monitors:index_from_ptr() + cfg.HighlightMonitorIdx = i - 1 -- [Port] 0-based, like Monitors:index_from_ptr() end end if g.FallbackMonitor then ImGui.DebugNodePlatformMonitor(g.FallbackMonitor, "Fallback", 0) end @@ -22462,7 +22434,7 @@ function ImGui.ShowMetricsWindow(p_open) if ImGui.IsMousePosValid() then ImGui.Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y) else ImGui.Text("Mouse pos: ") end ImGui.Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y) ImGui.Text("Mouse down:") - local count = ImGuiMouseButton.COUNT -- IM_COUNTOF(io.MouseDown) + local count = ImGuiMouseButton.COUNT -- [Port] IM_COUNTOF(io.MouseDown) for i = 0, count - 1 do if ImGui.IsMouseDown(i) then ImGui.SameLine(); ImGui.Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]) end end ImGui.Text("Mouse clicked:") for i = 0, count - 1 do if ImGui.IsMouseClicked(i) then ImGui.SameLine(); ImGui.Text("b%d (%d)", i, io.MouseClickedCount[i]) end end @@ -22623,4 +22595,4 @@ function ImGui.DebugBreakButton(label, description_of_location) end end --[[ [SECTION] METRICS/DEBUGGER WINDOW, DEBUG LOG, ID STACK TOOL, FONT DEBUG ]] -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value diff --git a/imgui_demo.lua b/imgui_demo.lua index d37ffee..70f35a7 100644 --- a/imgui_demo.lua +++ b/imgui_demo.lua @@ -1191,7 +1191,7 @@ S.DemoWindowWidgetsColorAndPickers = { color = ImVec4(114.0 / 255.0, 144.0 / 255.0, 154.0 / 255.0, 200.0 / 255.0), base_flags = ImGuiColorEditFlags.None, saved_palette_init = true, - saved_palette = {}, -- 32 x ImVec4, 1-based + saved_palette = {}, -- [Port] 32 x ImVec4, 1-based backup_color = ImVec4(), no_border = false, ref_color = false, @@ -1401,7 +1401,7 @@ end S.DemoWindowWidgetsComboBoxes = { flags = 0, item_selected_idx = 0, -- Here we store our selection data as an index. - filter = nil, -- ImGuiTextFilter, created lazily + filter = nil, -- [Port] ImGuiTextFilter, created lazily item_current_2 = 0, item_current_3 = -1, -- If the selection isn't within 0..count, Combo won't display a preview item_current_4 = 0, @@ -1519,7 +1519,7 @@ S.DemoWindowWidgetsDataTypes = { s16_v = 32767, u16_v = 65535, s32_v = -1, - u32_v = 4294967295, -- (ImU32)-1 + u32_v = 4294967295, -- [Port] (ImU32)-1 s64_v = -1, u64_v = 18446744073709551615, -- (ImU64)-1 [Port] Lua numbers are doubles: 64-bit values are exact only within +-2^53 f32_v = 0.123, @@ -1557,15 +1557,15 @@ function DemoWindowWidgetsDataTypes() local u8_zero, u8_one, u8_fifty, u8_min, u8_max = 0, 1, 50, 0, 255 local s16_zero, s16_one, s16_fifty, s16_min, s16_max = 0, 1, 50, -32768, 32767 local u16_zero, u16_one, u16_fifty, u16_min, u16_max = 0, 1, 50, 0, 65535 - local s32_zero, s32_one, s32_fifty, s32_min, s32_max, s32_hi_a, s32_hi_b = 0, 1, 50, -1073741824, 1073741823, 1073741823 - 100, 1073741823 -- INT_MIN/2, INT_MAX/2 - local u32_zero, u32_one, u32_fifty, u32_min, u32_max, u32_hi_a, u32_hi_b = 0, 1, 50, 0, 2147483647, 2147483647 - 100, 2147483647 -- UINT_MAX/2 + local s32_zero, s32_one, s32_fifty, s32_min, s32_max, s32_hi_a, s32_hi_b = 0, 1, 50, -1073741824, 1073741823, 1073741823 - 100, 1073741823 -- [Port] INT_MIN/2, INT_MAX/2 + local u32_zero, u32_one, u32_fifty, u32_min, u32_max, u32_hi_a, u32_hi_b = 0, 1, 50, 0, 2147483647, 2147483647 - 100, 2147483647 -- [Port] UINT_MAX/2 local s64_zero, s64_one, s64_fifty, s64_min, s64_max, s64_hi_a, s64_hi_b = 0, 1, 50, LLONG_MIN / 2, LLONG_MAX / 2, LLONG_MAX / 2 - 100, LLONG_MAX / 2 local u64_zero, u64_one, u64_fifty, u64_min, u64_max, u64_hi_a, u64_hi_b = 0, 1, 50, 0, ULLONG_MAX / 2, ULLONG_MAX / 2 - 100, ULLONG_MAX / 2 local f32_zero, f32_one, f32_lo_a, f32_hi_a = 0.0, 1.0, -10000000000.0, 10000000000.0 local f64_zero, f64_one, f64_lo_a, f64_hi_a = 0.0, 1.0, -1000000000000000.0, 1000000000000000.0 -- State - -- (see S.DemoWindowWidgetsDataTypes) + -- [Port] (see S.DemoWindowWidgetsDataTypes) local drag_speed = 0.2 IMGUI_DEMO_MARKER("Widgets/Data Types/Drags") @@ -1784,7 +1784,6 @@ function DemoWindowWidgetsDragAndDrop() local drop_target_flags = bit32.bor(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoPreviewTooltip) local payload = ImGui.AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, drop_target_flags) if payload then - -- IM_UNUSED(payload) ImGui.SetMouseCursor(ImGuiMouseCursor.NotAllowed) ImGui.SetTooltip("Cannot drop here!") end @@ -2200,7 +2199,7 @@ end S.DemoWindowWidgetsPlotting = { animate = true, arr = { 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2 }, - values = {}, -- 90 zeros, filled below + values = {}, -- [Port] 90 zeros, filled below values_offset = 0, refresh_time = 0.0, phase = 0.0, @@ -3124,7 +3123,7 @@ S.DemoWindowWidgetsSelectionAndMultiSelect = { show_in_table = false, show_color_button = true, flags = bit32.bor(ImGuiMultiSelectFlags.ClearOnEscape, ImGuiMultiSelectFlags.BoxSelect1d), - widget_type = 0, -- WidgetType_Selectable + widget_type = 0, -- [Port] WidgetType_Selectable items = ImVector(), items_next_id = 0, selection = ExampleSelectionWithDeletion(), @@ -3516,7 +3515,7 @@ function DemoWindowWidgetsSelectionAndMultiSelect(demo_data) if ImGui.TreeNode("Multi-Select (advanced)") then IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (advanced)") -- Options - local WidgetType_Selectable, WidgetType_TreeNode = 0, 1 -- enum WidgetType + local WidgetType_Selectable, WidgetType_TreeNode = 0, 1 -- [Port] enum WidgetType local st = s.advanced if ImGui.TreeNode("Options") then @@ -4113,22 +4112,22 @@ S.DemoWindowWidgetsTextInput = { "\tlock cmpxchg8b eax\n", 1024 * 16), flags = ImGuiInputTextFlags.AllowTabInput, }, - -- "Filtered Text Input" + -- [Port] "Filtered Text Input" filtered = { buf1 = ImGui.NewTextBuffer("", 32), buf2 = ImGui.NewTextBuffer("", 32), buf3 = ImGui.NewTextBuffer("", 32), buf4 = ImGui.NewTextBuffer("", 32), buf5 = ImGui.NewTextBuffer("", 32), buf6 = ImGui.NewTextBuffer("", 32), buf7 = ImGui.NewTextBuffer("", 32), }, - -- "Password Input" + -- [Port] "Password Input" password = { password = ImGui.NewTextBuffer("password123", 64) }, - -- "Completion, History, Edit Callbacks" + -- [Port] "Completion, History, Edit Callbacks" callbacks = { buf1 = ImGui.NewTextBuffer("", 64), buf2 = ImGui.NewTextBuffer("", 64), buf3 = ImGui.NewTextBuffer("", 64), edit_count = 0, }, -- "Resize Callback" resize = { flags = ImGuiInputTextFlags.None, my_str = ImVector() }, - -- "Eliding, Alignment" + -- [Port] "Eliding, Alignment" eliding = { buf1 = ImGui.NewTextBuffer("/path/to/some/folder/with/long/filename.cpp", 128), flags = ImGuiInputTextFlags.ElideLeft }, -- "Miscellaneous" misc = { buf1 = ImGui.NewTextBuffer("", 16), flags = ImGuiInputTextFlags.EscapeClearsAll }, @@ -4418,7 +4417,7 @@ end ------------------------------------------------------------------------------- S.DemoWindowWidgetsTreeNodes = { - base_flags = bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DefaultOpen), -- "Hierarchy Lines" + base_flags = bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DefaultOpen), -- [Port] "Hierarchy Lines" selection_mask = 0x00, base_flags_2 = bit32.bor(ImGuiTreeNodeFlags.OpenOnArrow, ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.SpanAvailWidth), -- "Advanced" align_label_with_current_x_position = false, @@ -4751,7 +4750,7 @@ S.DemoWindowLayout = { -- Widgets Width f = 0.0, show_indented_items = true, - -- Basic Horizontal Layout + -- [Port] Basic Horizontal Layout c1 = false, c2 = false, c3 = false, c4 = false, f0 = 1.0, f1 = 2.0, f2 = 3.0, item = -1, @@ -4776,7 +4775,7 @@ S.DemoWindowLayout = { -- Text Clipping size = ImVec2(100.0, 100.0), offset = ImVec2(30.0, 30.0), - -- Overlap Mode + -- [Port] Overlap Mode enable_allow_overlap = true, } @@ -5615,14 +5614,14 @@ end ------------------------------------------------------------------------------- S.DemoWindowPopups = { - selected_fish = -1, -- static int selected_fish = -1; - toggles = { true, false, false, false, false }, -- static bool toggles[] = { true, false, false, false, false }; - selected = -1, -- static int selected = -1; - value = 0.5, -- static float value = 0.5f; - name = ImGui.NewTextBuffer("Label1", 32), -- static char name[32] = "Label1"; - dont_ask_me_next_time = false, -- static bool dont_ask_me_next_time = false; - item = 1, -- static int item = 1; - color = { 0.4, 0.7, 0.0, 0.5 }, -- static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; + selected_fish = -1, -- [Port] static int selected_fish = -1; + toggles = { true, false, false, false, false }, -- [Port] static bool toggles[] = { true, false, false, false, false }; + selected = -1, -- [Port] static int selected = -1; + value = 0.5, -- [Port] static float value = 0.5f; + name = ImGui.NewTextBuffer("Label1", 32), -- [Port] static char name[32] = "Label1"; + dont_ask_me_next_time = false, -- [Port] static bool dont_ask_me_next_time = false; + item = 1, -- [Port] static int item = 1; + color = { 0.4, 0.7, 0.0, 0.5 }, -- [Port] static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; } function DemoWindowPopups() local s = S.DemoWindowPopups @@ -5919,7 +5918,7 @@ end -- This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID. -- But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex) -- If you don't use sorting, you will generally never care about giving column an ID! --- enum MyItemColumnID +-- [Port] enum MyItemColumnID MyItemColumnID_ID = 0 MyItemColumnID_Name = 1 MyItemColumnID_Action = 2 @@ -6001,7 +6000,7 @@ S.EditTableSizingFlags = { policies = nil } -- [Port] p_flags -> takes flags, returns the new flags. function EditTableSizingFlags(p_flags) local s = S.EditTableSizingFlags - -- struct EnumDesc { ImGuiTableFlags Value; const char* Name; const char* Tooltip; }; + -- [Port] struct EnumDesc { ImGuiTableFlags Value; const char* Name; const char* Tooltip; }; if s.policies == nil then s.policies = { @@ -6092,7 +6091,7 @@ end -- [SECTION] DemoWindowTables() ------------------------------------------------------------------------------- -S.DemoWindowTables = { -- statics of DemoWindowTables(), one sub-table per TreeNode +S.DemoWindowTables = { -- [Port] statics of DemoWindowTables(), one sub-table per TreeNode disable_indent = false, BordersBackground = { flags = bit32.bor(ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg), @@ -6117,14 +6116,14 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su flags2 = bit32.bor(ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg), cell_padding = ImVec2(0.0, 0.0), show_widget_frame_bg = true, - text_bufs = {}, -- 1-based, cell + 1 + text_bufs = {}, -- [Port] 1-based, cell + 1 init = true, }, SizingPolicies = { flags1 = bit32.bor(ImGuiTableFlags.BordersV, ImGuiTableFlags.BordersOuterH, ImGuiTableFlags.RowBg, ImGuiTableFlags.ContextMenuInBody), sizing_policy_flags = { ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.SizingFixedSame, ImGuiTableFlags.SizingStretchProp, ImGuiTableFlags.SizingStretchSame }, flags = bit32.bor(ImGuiTableFlags.ScrollY, ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg, ImGuiTableFlags.Resizable), - contents_type = 0, -- CT_ShowWidth + contents_type = 0, -- [Port] CT_ShowWidth column_count = 3, text_buf = ImGui.NewTextBuffer("", 32), }, @@ -6159,7 +6158,7 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su table_flags = bit32.bor(ImGuiTableFlags.BordersV, ImGuiTableFlags.BordersOuterH, ImGuiTableFlags.Resizable, ImGuiTableFlags.RowBg, ImGuiTableFlags.NoBordersInBody), tree_node_flags_base = bit32.bor(ImGuiTreeNodeFlags.SpanAllColumns, ImGuiTreeNodeFlags.DefaultOpen, ImGuiTreeNodeFlags.DrawLinesFull), MyTreeNode = nil, -- [Port] local struct, created once on first use - nodes = { -- 1-based; ChildIdx stays 0-based like upstream + nodes = { -- [Port] 1-based; ChildIdx stays 0-based like upstream { Name = "Root with Long Name", Type = "Folder", Size = -1, ChildIdx = 1, ChildCount = 3 }, -- 0 { Name = "Music", Type = "Folder", Size = -1, ChildIdx = 4, ChildCount = 2 }, -- 1 { Name = "Textures", Type = "Folder", Size = -1, ChildIdx = 6, ChildCount = 3 }, -- 2 @@ -6180,7 +6179,7 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su AngledHeaders = { table_flags = bit32.bor(ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY, ImGuiTableFlags.BordersOuter, ImGuiTableFlags.BordersInnerH, ImGuiTableFlags.Hideable, ImGuiTableFlags.Resizable, ImGuiTableFlags.Reorderable, ImGuiTableFlags.HighlightHoveredColumn), column_flags = bit32.bor(ImGuiTableColumnFlags.AngledHeader, ImGuiTableColumnFlags.WidthFixed), - bools = {}, -- 1-based, filled with false on first use + bools = {}, -- [Port] 1-based, filled with false on first use frozen_cols = 1, frozen_rows = 2, }, @@ -6209,11 +6208,11 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY, ImGuiTableFlags.SizingFixedFit), columns_base_flags = ImGuiTableColumnFlags.None, - contents_type = 5, -- CT_SelectableSpanRow + contents_type = 5, -- [Port] CT_SelectableSpanRow freeze_cols = 1, freeze_rows = 1, - items_count = 0, -- IM_COUNTOF(template_items_names) * 2, set below - outer_size_value = nil, -- ImVec2(0.0f, TEXT_BASE_HEIGHT * 12), set lazily (needs font) + items_count = 0, -- [Port] IM_COUNTOF(template_items_names) * 2, set below + outer_size_value = nil, -- [Port] ImVec2(0.0f, TEXT_BASE_HEIGHT * 12), set lazily (needs font) row_min_height = 0.0, -- Auto inner_width_with_scroll = 0.0, -- Auto-extend outer_size_enabled = true, @@ -6333,7 +6332,7 @@ function DemoWindowTables() if ImGui.TreeNode("Borders, background") then IMGUI_DEMO_MARKER("Tables/Borders, background") -- Expose a few Borders related flags interactively - local CT_Text, CT_FillButton = 0, 1 -- enum ContentsType + local CT_Text, CT_FillButton = 0, 1 -- [Port] enum ContentsType local s = s.BordersBackground PushStyleCompact() @@ -6696,7 +6695,7 @@ function DemoWindowTables() "This section allows you to interact and see the effect of various sizing policies " .. "depending on whether Scroll is enabled and the contents of your columns.") - local CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText = 0, 1, 2, 3, 4, 5 -- enum ContentsType + local CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText = 0, 1, 2, 3, 4, 5 -- [Port] enum ContentsType PushStyleCompact() ImGui.PushID("Advanced") @@ -7239,7 +7238,7 @@ function DemoWindowTables() ImGui.TableHeadersRow() -- Simple storage to output a dummy file-system. - -- struct MyTreeNode { Name, Type, Size, ChildIdx, ChildCount } (see s.nodes) + -- [Port] struct MyTreeNode { Name, Type, Size, ChildIdx, ChildCount } (see s.nodes) local MyTreeNode = s.MyTreeNode if MyTreeNode == nil then -- [Port] local struct with a static method, created once and kept in statics MyTreeNode = {} @@ -7675,7 +7674,7 @@ function DemoWindowTables() IMGUI_DEMO_MARKER("Tables/Advanced") local s = s.Advanced - local CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow = 0, 1, 2, 3, 4, 5 -- enum ContentsType + local CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow = 0, 1, 2, 3, 4, 5 -- [Port] enum ContentsType local contents_type_names = { "Text", "Button", "SmallButton", "FillButton", "Selectable", "Selectable (span row)" } if s.outer_size_value == nil then s.outer_size_value = ImVec2(0.0, TEXT_BASE_HEIGHT * 12) end -- static float row_min_height = 0.0f -- Auto @@ -8195,7 +8194,7 @@ function DemoWindowInputs() end ImGui.Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y) ImGui.Text("Mouse down:") - for i = 0, ImGuiMouseButton.COUNT - 1 do if ImGui.IsMouseDown(i) then ImGui.SameLine(); ImGui.Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]) end end -- IM_COUNTOF(io.MouseDown), 0-based + for i = 0, ImGuiMouseButton.COUNT - 1 do if ImGui.IsMouseDown(i) then ImGui.SameLine(); ImGui.Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]) end end -- [Port] IM_COUNTOF(io.MouseDown), 0-based ImGui.Text("Mouse wheel: %.1f", io.MouseWheel) ImGui.Text("Mouse clicked count:") for i = 0, ImGuiMouseButton.COUNT - 1 do if io.MouseClickedCount[i] > 0 then ImGui.SameLine(); ImGui.Text("b%d: %d", i, io.MouseClickedCount[i]) end end @@ -8669,12 +8668,12 @@ function GetTreeLinesFlagsName(flags) end S.ShowStyleEditor = { - ref_saved_style = nil, -- static ImGuiStyle ref_saved_style; (created lazily) + ref_saved_style = nil, -- [Port] static ImGuiStyle ref_saved_style; (created lazily) init = true, output_dest = 0, output_only_modified = true, alpha_flags = 0, - filter = nil, -- static ImGuiTextFilter filter; (created lazily) + filter = nil, -- [Port] static ImGuiTextFilter filter; (created lazily) } -- We omit the ImGui:: prefix in this function, as we don't expect user to be copy and pasting this code. -- [Port] Lua has no `using namespace`: calls keep the ImGui. prefix @@ -9203,17 +9202,17 @@ ExampleAppConsoleMT = {} ExampleAppConsoleMT.__index = ExampleAppConsoleMT function ExampleAppConsole() local self = setmetatable({}, ExampleAppConsoleMT) - self.InputBuf = nil -- char InputBuf[256] - self.Items = ImVector() -- ImVector - self.Commands = ImVector() -- ImVector - self.History = ImVector() -- ImVector + self.InputBuf = nil -- [Port] char InputBuf[256] + self.Items = ImVector() -- [Port] ImVector + self.Commands = ImVector() -- [Port] ImVector + self.History = ImVector() -- [Port] ImVector self.HistoryPos = 0 -- -1: new line, 0..History.Size-1 browsing history. self.Filter = ImGuiTextFilter() self.AutoScroll = false self.ScrollToBottom = false self:ClearLog() - self.InputBuf = ImGui.NewTextBuffer("", 256) -- memset(InputBuf, 0, sizeof(InputBuf)) + self.InputBuf = ImGui.NewTextBuffer("", 256) -- [Port] memset(InputBuf, 0, sizeof(InputBuf)) self.HistoryPos = -1 -- "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches. @@ -9454,7 +9453,7 @@ function ExampleAppConsoleMT:TextEditCallback(data) local word_end = data.CursorPos local word_start = word_end while word_start > 0 do - local c = data.Buf[word_start] -- word_start[-1] + local c = data.Buf[word_start] -- [Port] word_start[-1] if c == 32 or c == 9 or c == 44 or c == 59 then -- ' ', '\t', ',', ';' break end @@ -9542,7 +9541,7 @@ function ExampleAppConsoleMT:TextEditCallback(data) end S.ShowExampleAppConsole = { - console = nil, -- ExampleAppConsole, created on first use + console = nil, -- [Port] ExampleAppConsole, created on first use } function ShowExampleAppConsole(p_open) local s = S.ShowExampleAppConsole @@ -9555,7 +9554,7 @@ end ------------------------------------------------------------------------------- S.ShowExampleAppImageViewer = { - image_viewer = nil, -- ExampleImageViewerData, created on first use + image_viewer = nil, -- [Port] ExampleImageViewerData, created on first use } function ShowExampleAppImageViewer(p_open) local s = S.ShowExampleAppImageViewer @@ -9715,7 +9714,7 @@ end -- Demonstrate creating a simple log window with basic filtering. S.ShowExampleAppLog = { - log = nil, -- ExampleAppLog, created on first use + log = nil, -- [Port] ExampleAppLog, created on first use counter = 0, } function ShowExampleAppLog(p_open) @@ -10036,7 +10035,7 @@ end -- Demonstrate creating a simple property editor. S.ShowExampleAppPropertyEditor = { - property_editor = nil, -- ExampleAppPropertyEditor, created on first use + property_editor = nil, -- [Port] ExampleAppPropertyEditor, created on first use demo_data = nil, -- [Port] fallback when called without demo_data } function ShowExampleAppPropertyEditor(p_open, demo_data) @@ -10428,7 +10427,7 @@ S.ShowExampleAppCustomRendering = { opt_enable_grid = true, opt_enable_context_menu = true, adding_line = false, - -- BG/FG draw lists + -- [Port] BG/FG draw lists draw_bg = true, draw_fg = true, } @@ -11149,9 +11148,9 @@ end S.ShowExampleAppDocuments = { app = ExampleAppDocuments(), - opt_target = nil, -- set below to Target_Tab + opt_target = nil, -- [Port] set below to Target_Tab opt_reorderable = true, - opt_fitting_flags = nil, -- set below to ImGuiTabBarFlags.FittingPolicyDefault_ + opt_fitting_flags = nil, -- [Port] set below to ImGuiTabBarFlags.FittingPolicyDefault_ } function ShowExampleAppDocuments(p_open) local s = S.ShowExampleAppDocuments diff --git a/imgui_draw.lua b/imgui_draw.lua index 65c9dca..dd1fa3a 100644 --- a/imgui_draw.lua +++ b/imgui_draw.lua @@ -29,14 +29,14 @@ FONT_ATLAS_DEFAULT_TEX_DATA_H = 27 local IM_DRAWLIST_TEX_LINES_WIDTH_MAX = 32 -- The maximum line width to bake anti-aliased textures for. local writef64, writeu32, readf64, readu32 = buffer.writef64, buffer.writeu32, buffer.readf64, buffer.readu32 --- Write vertex i (1-based) of a VtxBuffer.Buf +-- [Port] Write vertex i (1-based) of a VtxBuffer.Buf local function WV(b, i, x, y, u, v, col) local o = (i - 1) * 36 writef64(b, o, x); writef64(b, o + 8, y); writef64(b, o + 16, u); writef64(b, o + 24, v); writeu32(b, o + 32, col) end -local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -- ((ImU16)-1) -local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE -- ((ImU16)-2) +local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -- [Port] ((ImU16)-1) +local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE -- [Port] ((ImU16)-2) --- @param str string --- @return table @@ -374,7 +374,7 @@ function ImGui.ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, end end --- Rotate and translate vertices [vert_start_idx, vert_end_idx) (1-based, like _VtxCurrentIdx) +-- [Port] Rotate and translate vertices [vert_start_idx, vert_end_idx) (1-based, like _VtxCurrentIdx) function ImGui.ShadeVertsTransformPos(draw_list, vert_start_idx, vert_end_idx, pivot_in, cos_a, sin_a, pivot_out) local data = draw_list.VtxBuffer.Buf local pix, piy, pox, poy = pivot_in.x, pivot_in.y, pivot_out.x, pivot_out.y @@ -1363,7 +1363,7 @@ local function ImGui_ImplStbTrueType_FontSrcData() } end --- Need this in Lua since I don't want to include 'stbrp' just for context constructor +-- [Port] Need this in Lua since I don't want to include 'stbrp' just for context constructor -- in ImFontAtlasBuilder def code. The cpp code has 'stbrp_context_opaque' which I don't/can't have here --- @param atlas ImFontAtlas local function ImGui_ImplStbTrueType_LoaderInit(atlas) @@ -1371,7 +1371,7 @@ local function ImGui_ImplStbTrueType_LoaderInit(atlas) end local function ImGui_ImplStbTrueType_FontSrcInit(atlas, src) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) --- @type ImGui_ImplStbTrueType_FontSrcData? local bd_font_data = ImGui_ImplStbTrueType_FontSrcData() @@ -1406,12 +1406,12 @@ local function ImGui_ImplStbTrueType_FontSrcInit(atlas, src) end local function ImGui_ImplStbTrueType_FontSrcDestroy(atlas, src) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) src.FontLoaderData = nil end local function ImGui_ImplStbTrueType_FontSrcContainsGlyph(atlas, src, codepoint) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) local bd_font_data = src.FontLoaderData IM_ASSERT(bd_font_data ~= nil) @@ -1420,7 +1420,7 @@ local function ImGui_ImplStbTrueType_FontSrcContainsGlyph(atlas, src, codepoint) end local function ImGui_ImplStbTrueType_FontBakedInit(atlas, src, baked) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) local bd_font_data = src.FontLoaderData if (src.MergeMode == false) then @@ -1599,14 +1599,14 @@ function ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, ba local loader = src.FontLoader and src.FontLoader or atlas.FontLoader loader_data_size = loader_data_size + loader.FontBakedSrcLoaderDataSize end - -- baked.FontLoaderDatas = (loader_data_size > 0) and IM_ALLOC(loader_data_size) or nil + -- [Port] baked.FontLoaderDatas = (loader_data_size > 0) and IM_ALLOC(loader_data_size) or nil -- local loader_data_p = baked->FontLoaderDatas for _, src in font.Sources:iter() do local loader = src.FontLoader and src.FontLoader or atlas.FontLoader if (loader.FontBakedInit) then loader.FontBakedInit(atlas, src, baked--[[, loader_data_p--]]) end - -- loader_data_p += loader->FontBakedSrcLoaderDataSize + -- [Port] loader_data_p += loader->FontBakedSrcLoaderDataSize end ImFontAtlasBuildSetupFontBakedBlanks(atlas, baked) @@ -1670,7 +1670,7 @@ function ImFontAtlasBakedDiscard(atlas, font, baked) end end - -- char* loader_data_p = (char*)baked->FontLoaderDatas + -- [Port] char* loader_data_p = (char*)baked->FontLoaderDatas for _, src in font.Sources:iter() do local loader = src.FontLoader and src.FontLoader or atlas.FontLoader if loader.FontBakedDestroy then @@ -1767,13 +1767,13 @@ end --- @param atlas ImFontAtlas --- @param src ImFontConfig function ImFontAtlasFontDestroySourceData(atlas, src) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) - -- if src.FontDataOwnedByAtlas then + -- [Port] if src.FontDataOwnedByAtlas then -- IM_FREE(src.FontData) -- end src.FontData = nil - -- if src.GlyphExcludeRanges then + -- [Port] if src.GlyphExcludeRanges then -- IM_FREE(src.GlyphExcludeRanges) -- end src.GlyphExcludeRanges = nil @@ -1785,7 +1785,7 @@ end --- @param font ImFont --- @param src ImFontConfig function ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) IM_ASSERT(font.Sources:contains(src)) -- Find Fallback character. Actual glyph loaded in GetFontBaked(). @@ -1940,7 +1940,7 @@ local function ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas) end local function ImFontAtlasBuildUpdatePointers(atlas) - -- for _, font in atlas.Fonts:iter() do + -- [Port] for _, font in atlas.Fonts:iter() do -- font.Sources:resize(0) -- end -- for _, src in atlas.Sources:iter() do @@ -2118,7 +2118,7 @@ function ImFontAtlasPackInit(atlas) end --- @param atlas ImFontAtlas --- #define IM_DRAWLIST_CORNER_POINTS_MAX (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4 + 3) // Max number of points in corner profiles +-- [Port] #define IM_DRAWLIST_CORNER_POINTS_MAX (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4 + 3) // Max number of points in corner profiles -- [Luau] ImVec2 line_normals[] / float line_distances[] / ImVec2 points[] are flat 1-based scratch arrays (x, y, distance). local corner_points_x, corner_points_y = {}, {} local corner_normals_x, corner_normals_y, corner_distances = {}, {}, {} @@ -2164,7 +2164,7 @@ local function InitCornerGeometry(cx, cy, rounding, circle_segment_max_error, li local inv_d = ImRsqrtPrecise(d2) line_normals_x[i] = diff_y * inv_d -- Normal points outwards line_normals_y[i] = -diff_x * inv_d - line_distances[i] = -(points_x[i] * line_normals_x[i] + points_y[i] * line_normals_y[i]) -- -ImDot() + line_distances[i] = -(points_x[i] * line_normals_x[i] + points_y[i] * line_normals_y[i]) -- [Port] -ImDot() end return num_points - 1 @@ -2187,12 +2187,12 @@ local function SampleCornerFillOrStroke(x, y, thickness, line_normals_x, line_no local aa_width = 1.0 if thickness == 0.0 then -- Fill - return math.floor(ImClamp(1.0 - (d + aa_width * 0.5) / aa_width, 0.0, 1.0) * 255.0) -- (ImU8) + return math.floor(ImClamp(1.0 - (d + aa_width * 0.5) / aa_width, 0.0, 1.0) * 255.0) -- [Port] (ImU8) else -- Stroke local outer = 1.0 - (d + aa_width * 0.5) / aa_width local inner = (d + thickness + aa_width * 0.5) / aa_width - return math.floor(ImClamp(ImMin(inner, outer), 0.0, 1.0) * 255.0) -- (ImU8) + return math.floor(ImClamp(ImMin(inner, outer), 0.0, 1.0) * 255.0) -- [Port] (ImU8) end end @@ -2356,7 +2356,7 @@ function ImFontAtlasBuildUpdateTexDataLines(atlas) -- Calculate super sampled line textures for smaller line widths to make transition between sizes smoother. -- Calculate ramp used for all the textures. - local ramp = {} -- ImU8[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT], 0-based + local ramp = {} -- [Port] ImU8[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT], 0-based for n = 0, IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT - 1 do ramp[n] = math.floor((n / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) * 255.0) end @@ -2617,7 +2617,7 @@ function ImFontAtlasBuildMain(atlas) end -- [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs - -- ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); + -- [Port] ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); -- if atlas.RendererHasTextures == false then -- ~ImGuiBackendFlags.RendererHasTextures -- ImFontAtlasBuildLegacyPreloadAllGlyphRanges(atlas) -- end @@ -2823,7 +2823,7 @@ end --- @param c ImWchar --- @return ImFontGlyph? function MT.ImFontBaked:FindGlyphNoFallback(c) - if c < self.IndexLookup.Size then -- IM_LIKELY + if c < self.IndexLookup.Size then -- [Port] IM_LIKELY local i = self.IndexLookup.Data[c + 1] if i == IM_FONTGLYPH_INDEX_NOT_FOUND then return nil @@ -2856,7 +2856,7 @@ function MT.ImFont:IsGlyphRangeUnused(c_begin, c_last) local page_begin = math.floor(c_begin / 8192) local page_last = math.floor(c_last / 8192) for page_n = page_begin, page_last do - if bit32.rshift(page_n, 3) < (IM_UNICODE_CODEPOINT_MAX + 1) / 8192 / 8 then -- sizeof(Used8kPagesMap) + if bit32.rshift(page_n, 3) < (IM_UNICODE_CODEPOINT_MAX + 1) / 8192 / 8 then -- [Port] sizeof(Used8kPagesMap) if bit32.band(self.Used8kPagesMap[bit32.rshift(page_n, 3) + 1] or 0, bit32.lshift(1, bit32.band(page_n, 7))) ~= 0 then return false end @@ -2965,7 +2965,7 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) local codepoint = glyph.Codepoint ImFontBaked_BuildGrowIndex(baked, codepoint + 1) baked.IndexAdvanceX.Data[codepoint + 1] = glyph.AdvanceX - baked.IndexLookup.Data[codepoint + 1] = glyph_idx -- (ImU16) + baked.IndexLookup.Data[codepoint + 1] = glyph_idx -- [Port] (ImU16) local page_n = math.floor(codepoint / 8192) baked.OwnerFont.Used8kPagesMap[bit32.rshift(page_n, 3) + 1] = bit32.bor(baked.OwnerFont.Used8kPagesMap[bit32.rshift(page_n, 3) + 1], bit32.lshift(1, bit32.band(page_n, 7))) @@ -2979,7 +2979,7 @@ end --- @param codepoint ImWchar --- @param advance_x float function ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, advance_x) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) if (src ~= nil) then -- Clamp & recenter if needed local ref_size = baked.OwnerFont.Sources[1].SizePixels @@ -3046,7 +3046,7 @@ end --- @return ImWchar --- @nodiscard local function ImFontAtlas_FontHookRemapCodepoint(atlas, font, c) - -- IM_UNUSED(atlas) + -- [Port] IM_UNUSED(atlas) if next(font.RemapPairs) ~= nil then -- [Luau] font->RemapPairs.Data.Size != 0 (RemapPairs is a hash table) local ret = font.RemapPairs[c] return (ret ~= nil) and ret or c @@ -3117,7 +3117,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) end end - -- loader_user_data_p = loader_user_data_p + loader.FontBakedSrcLoaderDataSize + -- [Port] loader_user_data_p = loader_user_data_p + loader.FontBakedSrcLoaderDataSize src_n = src_n + 1 end @@ -3228,7 +3228,7 @@ end --- @param c unsigned_int function ImTextClassifierSetCharClass(bits, codepoint_min, codepoint_end, char_class, c) IM_ASSERT(c >= codepoint_min and c < codepoint_end) - -- IM_UNUSED(codepoint_end) + -- [Port] IM_UNUSED(codepoint_end) c = c - codepoint_min local shift = bit32.lshift(bit32.band(c, 15), 1) bits[bit32.rshift(c, 4) + 1] = bit32.bor(bit32.band(bits[bit32.rshift(c, 4) + 1], bit32.bnot(bit32.lshift(0x03, shift))), bit32.lshift(char_class, shift)) @@ -3290,7 +3290,6 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt end -- [Luau] memo per baked font and string: CalcTextSize() and RenderText() of wrapped text ask for the same wrap points -- (same text/pos/width) every frame. The result only depends on these inputs and the (immutable once loaded) glyph advances. - -- ponytail: whole-memo reset at WRAP_MEMO_MAX strings, LRU if dynamic text churns it local memo = baked._WrapMemo if memo == nil or baked._WrapMemoN >= WRAP_MEMO_MAX then memo = {}; baked._WrapMemo = memo; baked._WrapMemoN = 0 @@ -3470,7 +3469,7 @@ local TEXT_SIZE_CACHE_MAX = 4096 function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags) local text_is_str = type(text) == "string" -- [Luau] cache for the common case (whole string, single pass, no wrap/limit): per baked font, text -> unscaled width, line count. - -- Advances of a baked font never change once loaded, so entries stay valid. ponytail: whole-cache reset at TEXT_SIZE_CACHE_MAX entries, LRU if dynamic text churns it + -- Advances of a baked font never change once loaded, so entries stay valid. local cache_key = nil local wrap_cache = nil local text_len1 = text_is_str and #text + 1 or -1 @@ -3901,7 +3900,7 @@ function MT.ImFontAtlas:AddFontFromFileTTF(filename, size_pixels, font_cfg_templ local data, data_size = ImStd.ImFileLoadToMemory(filename, "rb") if not data then if (font_cfg_template == nil or (bit32.band(font_cfg_template.Flags, ImFontFlags.NoLoadError) == 0)) then - -- IMGUI_DEBUG_LOG("While loading '%s'\n", filename) + -- [Port] IMGUI_DEBUG_LOG("While loading '%s'\n", filename) IM_ASSERT_USER_ERROR(0, "Could not load font file!") end @@ -4104,7 +4103,7 @@ local function ImAlphaMultiply(col, alpha_mul) return bit32.bor(bit32.band(col, bit32.bnot(IM_COL32_A_MASK)), bit32.lshift(a, IM_COL32_A_SHIFT)) end --- #define _GetStrokePos(_FLAGS, _DEFAULT_STROKE_POS) +-- [Port] #define _GetStrokePos(_FLAGS, _DEFAULT_STROKE_POS) local function _GetStrokePos(flags, default_stroke_pos) local stroke_pos = bit32.band(flags, ImDrawFlags.StrokeMask_) if stroke_pos ~= 0 then return stroke_pos end @@ -4239,7 +4238,7 @@ function MT.ImDrawListSharedData:SetCircleTessellationMaxError(max_error) IM_ASSERT(max_error > 0) self.CircleTessellationMaxError = max_error - for i = 1, 64 do -- IM_COUNTOF(CircleSegmentCounts) + for i = 1, 64 do -- [Port] IM_COUNTOF(CircleSegmentCounts) local radius = (i - 1) self.CircleSegmentCounts[i] = (i > 1) and IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, self.CircleTessellationMaxError) or IM_DRAWLIST_ARCFAST_SAMPLE_MAX end @@ -4261,7 +4260,7 @@ end -- Initialize before use in a new frame. We always have a command ready in the buffer. -- In the majority of cases, you would want to call PushClipRect() and PushTexture() after this. function MT.ImDrawList:_ResetForNewFrame() - self._ContentClipX0 = nil -- set again by Begin() (Roblox backend scroll reuse) + self._ContentClipX0 = nil -- [Port] set again by Begin() (Roblox backend scroll reuse) if self._Splitter._Count > 1 then self._Splitter:Merge(self) end @@ -4282,7 +4281,7 @@ function MT.ImDrawList:_ResetForNewFrame() self._ClipRectStack:resize(0) self._TextureStack:resize(0) self._CallbacksDataBuf:resize(0) - self._DrawFlagsStack.Size = 0 -- _DrawFlagsStack.clear() (ImSmallStack_) + self._DrawFlagsStack.Size = 0 -- [Port] _DrawFlagsStack.clear() (ImSmallStack_) self._Path:resize(0) self.CmdBuffer:push_back(ImDrawCmd()) @@ -4303,7 +4302,7 @@ function MT.ImDrawList:_ClearFreeMemory() self._ClipRectStack:clear() self._TextureStack:clear() self._CallbacksDataBuf:clear() - self._DrawFlagsStack.Size = 0 -- _DrawFlagsStack.clear() (ImSmallStack_) + self._DrawFlagsStack.Size = 0 -- [Port] _DrawFlagsStack.clear() (ImSmallStack_) self._Path:clear() self._Splitter:ClearFreeMemory() end @@ -4385,7 +4384,7 @@ function MT.ImDrawList:AddCallback(callback, userdata, userdata_size) -- [Lua] No raw bytes: the "copy" is a shallow copy of a table userdata (other values are immutable and stored as is), -- so later changes to the caller's table don't affect this command. userdata_size is only recorded. IM_ASSERT(userdata ~= nil) - IM_ASSERT(userdata_size < 2147483648) -- (1u << 31) + IM_ASSERT(userdata_size < 2147483648) -- [Port] (1u << 31) curr_cmd.UserCallbackData = nil -- Will be resolved during Render() curr_cmd.UserCallbackDataSize = userdata_size curr_cmd.UserCallbackDataOffset = self._CallbacksDataBuf.Size -- 0-based @@ -4534,7 +4533,7 @@ end ------------------------------------------------------------------------------- -- FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap.. ------------------------------------------------------------------------------- --- Lua: channels swap ImVector objects with the draw list (C++ memcpy of the vector headers). +-- [Port] channels swap ImVector objects with the draw list (C++ memcpy of the vector headers). -- Channel 0 holds nothing while it is the current channel (its buffers live in the draw list). -- Copy ClipRect, TexRef, VtxOffset (TexRef is assigned by reference, never mutated) @@ -4579,7 +4578,7 @@ function MT.ImDrawListSplitter:Split(draw_list, channels_count) -- Channels[] hold storage that we'll swap with draw_list._CmdBuffer/_IdxBuffer -- The content of Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. -- When we switch to the next channel, we'll copy draw_list._CmdBuffer/_IdxBuffer into Channels[0] and then Channels[1] into draw_list.CmdBuffer/_IdxBuffer - -- Channel 0 is the draw list itself (memset to 0 in C++) + -- [Port] Channel 0 is the draw list itself (memset to 0 in C++) local channels = self._Channels.Data channels[1] = { _CmdBuffer = nil, _IdxBuffer = nil } for i = 2, channels_count do @@ -4651,7 +4650,7 @@ function MT.ImDrawListSplitter:Merge(draw_list) local src_cmds = ch._CmdBuffer.Data for n = 1, ch._CmdBuffer.Size do dst_cmds[cmd_write] = src_cmds[n] - src_cmds[n] = nil -- ownership moved to the draw list + src_cmds[n] = nil -- [Port] ownership moved to the draw list cmd_write = cmd_write + 1 end end @@ -4751,7 +4750,7 @@ end function MT.ImDrawList:PushDrawFlag(flags, enabled) IM_ASSERT(bit32.band(flags, bit32.bnot(ImDrawFlags.AllowInPushScope_)) == 0) IM_ASSERT(bit32.band(flags, ImDrawFlags.StrokeMask_) == 0 or bit32.band(flags, ImDrawFlags.StrokeMask_) == ImDrawFlags.StrokeLegacy) - IM_ASSERT_USER_ERROR_RET(self._DrawFlagsStack.Size < 3, "PushDrawFlag() has a depth limit. Contact us.") -- _DrawFlagsStack.capacity() == 3 + IM_ASSERT_USER_ERROR_RET(self._DrawFlagsStack.Size < 3, "PushDrawFlag() has a depth limit. Contact us.") -- [Port] _DrawFlagsStack.capacity() == 3 self._DrawFlagsStack:push_back(self.Flags) if enabled then self.Flags = bit32.bor(self.Flags, flags) @@ -4957,7 +4956,7 @@ local function _SelectLineTexture(self, screen_thickness, flags) end -- Scale the fringe so that the texture matches the line thickness. - local tex_uvs = self._Data.TexUvLines[texture_idx] -- 0-based table + local tex_uvs = self._Data.TexUvLines[texture_idx] -- [Port] 0-based table return tex_uvs.x, tex_uvs.z, tex_uvs.y, tex_uvs.z, self._FringeScale * screen_thickness * tex_uvs.w -- tex_uvs.w = 1 / thickness else -- For no anti-alias we use fully opaque texture, and no fringe expansion. @@ -5011,7 +5010,7 @@ function MT.ImDrawList:_AddPolyline(points, points_count, col, thickness, flags, local dy = p1.y - p0.y local d2 = dx * dx + dy * dy local inv_len = 0.0 - if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- ImRsqrtPrecise() + if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- [Port] ImRsqrtPrecise() normals_x[i] = -dy * inv_len normals_y[i] = dx * inv_len sqr_lengths[i] = d2 @@ -5023,7 +5022,7 @@ function MT.ImDrawList:_AddPolyline(points, points_count, col, thickness, flags, local dy = p1.y - p0.y local d2 = dx * dx + dy * dy local inv_len = 0.0 - if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- ImRsqrtPrecise() + if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- [Port] ImRsqrtPrecise() normals_x[points_count] = -dy * inv_len normals_y[points_count] = dx * inv_len sqr_lengths[points_count] = d2 @@ -5086,8 +5085,8 @@ function MT.ImDrawList:_AddPolyline(points, points_count, col, thickness, flags, local vb = self.VtxBuffer.Buf local ib = self.IdxBuffer.Data - local vw = self._VtxWritePtr -- 1-based write position in VtxBuffer - local iw = self._IdxWritePtr -- 1-based write position in IdxBuffer + local vw = self._VtxWritePtr -- [Port] 1-based write position in VtxBuffer + local iw = self._IdxWritePtr -- [Port] 1-based write position in IdxBuffer local vtx_idx = self._VtxCurrentIdx local first_vtx_offset = vw local first_vtx_idx = vtx_idx -- [Luau] VtxBuffer position of index 'n' is first_vtx_offset + (n - first_vtx_idx) @@ -5382,7 +5381,7 @@ function MT.ImDrawList:AddConvexPolyFilled(points, points_count, col, flags) local dy = p1.y - p0.y local d2 = dx * dx + dy * dy if d2 > 0.0 then - local inv_len = 1.0 / math.sqrt(d2) -- ImRsqrtPrecise() + local inv_len = 1.0 / math.sqrt(d2) -- [Port] ImRsqrtPrecise() dx = dx * inv_len dy = dy * inv_len end @@ -5571,7 +5570,7 @@ local function PathRectXY(self, ax, ay, bx, by, rounding, flags) if not rounding then rounding = 0.0 end if not flags then flags = 0 end - local has_rounding = rounding >= 0.25 * self._FringeScale -- IM_HAS_ROUNDING(rounding) + local has_rounding = rounding >= 0.25 * self._FringeScale -- [Port] IM_HAS_ROUNDING(rounding) if has_rounding then if bit32.band(flags, ImDrawFlags.RoundMask_) == 0 then flags = bit32.bor(flags, ImDrawFlags.RoundAll) @@ -5626,7 +5625,7 @@ local function _AddLineXY(self, p1x, p1y, p2x, p2y, col, thickness, flags) local dir_y = p2y - p1y local d2 = dir_x * dir_x + dir_y * dir_y local inv_len = 0.0 - if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- ImRsqrtPrecise() + if d2 > 0.0 then inv_len = 1.0 / math.sqrt(d2) end -- [Port] ImRsqrtPrecise() dir_x = dir_x * inv_len dir_y = dir_y * inv_len local norm_x = -dir_y @@ -5791,7 +5790,7 @@ function MT.ImDrawList:AddLineH(min_x, max_x, y, col, thickness, flags) top_y = top_y - thickness end - local is_truncated = min_x % 1 == 0 and max_x % 1 == 0 and top_y % 1 == 0 and thickness % 1 == 0 -- IM_IS_TRUNCATED4() + local is_truncated = min_x % 1 == 0 and max_x % 1 == 0 and top_y % 1 == 0 and thickness % 1 == 0 -- [Port] IM_IS_TRUNCATED4() if self._FringeScaleIsInteger and is_truncated and bit32.band(flags, ImDrawFlags.CapSquare) == 0 then if thickness < self._FringeScale then if thickness < (1.0 / 255.0) * self._FringeScale then @@ -5847,7 +5846,7 @@ function MT.ImDrawList:AddLineV(x, min_y, max_y, col, thickness, flags) left_x = left_x - thickness end - local is_truncated = left_x % 1 == 0 and min_y % 1 == 0 and max_y % 1 == 0 and thickness % 1 == 0 -- IM_IS_TRUNCATED4() + local is_truncated = left_x % 1 == 0 and min_y % 1 == 0 and max_y % 1 == 0 and thickness % 1 == 0 -- [Port] IM_IS_TRUNCATED4() if self._FringeScaleIsInteger and is_truncated and bit32.band(flags, ImDrawFlags.CapSquare) == 0 then if thickness < self._FringeScale then if thickness < (1.0 / 255.0) * self._FringeScale then @@ -5891,7 +5890,7 @@ end -- [Luau] _AddRectBaked() taking p_min/p_max as scalars @native local function _AddRectBakedXY(self, p_min_x, p_min_y, p_max_x, p_max_y, col, r, t, tex_uvs, flags) - local uv_l, uv_t, uv_r, uv_b = tex_uvs.x, tex_uvs.y, tex_uvs.z, tex_uvs.w -- uv_tl = (l,t), uv_tr = (r,t), uv_br = (r,b), uv_bl = (l,b) + local uv_l, uv_t, uv_r, uv_b = tex_uvs.x, tex_uvs.y, tex_uvs.z, tex_uvs.w -- [Port] uv_tl = (l,t), uv_tr = (r,t), uv_br = (r,b), uv_bl = (l,b) local idx_allocated = 8 * 2 * 3 local vtx_allocated = 8 * 4 @@ -5987,7 +5986,7 @@ function MT.ImDrawList:_AddRectBaked(p_min, p_max, col, r, t, tex_uvs, flags) _AddRectBakedXY(self, p_min.x, p_min.y, p_max.x, p_max.y, col, r, t, tex_uvs, flags) end -local corner_offset_x = { 1, -1, -1, 1 } -- static const ImVec2 corner_offset[4] = { {1,1}, {-1,1}, {-1,-1}, {1,-1} }; +local corner_offset_x = { 1, -1, -1, 1 } -- [Port] static const ImVec2 corner_offset[4] = { {1,1}, {-1,1}, {-1,-1}, {1,-1} }; local corner_offset_y = { 1, 1, -1, -1 } local corner_flags = { ImDrawFlags.RoundTopLeft, ImDrawFlags.RoundTopRight, ImDrawFlags.RoundBottomRight, ImDrawFlags.RoundBottomLeft } local corner_pos_x, corner_pos_y = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } -- [Luau] scratch @@ -6159,7 +6158,7 @@ function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags) end local fringe_scale = self._FringeScale - local has_rounding = rounding >= 0.25 * fringe_scale -- IM_HAS_ROUNDING(rounding) + local has_rounding = rounding >= 0.25 * fringe_scale -- [Port] IM_HAS_ROUNDING(rounding) -- Calculate the outer boundary of the rectangle based on the stroke position. local offset = 0.0 -- Inside @@ -6194,7 +6193,7 @@ function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags) outer_rounding = ImMin(outer_rounding, ImAbs(height) * (((bit32.band(flags, ImDrawFlags.RoundLeft) == ImDrawFlags.RoundLeft) or (bit32.band(flags, ImDrawFlags.RoundRight) == ImDrawFlags.RoundRight)) and 0.5 or 1.0) - 1.0) end - local is_truncated = outer_min_x % 1 == 0 and outer_min_y % 1 == 0 and outer_max_x % 1 == 0 and outer_max_y % 1 == 0 and outer_rounding % 1 == 0 and thickness % 1 == 0 -- IM_IS_TRUNCATED4() x2 + local is_truncated = outer_min_x % 1 == 0 and outer_min_y % 1 == 0 and outer_max_x % 1 == 0 and outer_max_y % 1 == 0 and outer_rounding % 1 == 0 and thickness % 1 == 0 -- [Port] IM_IS_TRUNCATED4() x2 if self._FringeScaleIsInteger and is_truncated then local s_rounding = ImTrunc64(outer_rounding * self._InvFringeScale) local s_thickness = ImTrunc64(thickness * self._InvFringeScale) @@ -6290,7 +6289,7 @@ end @native local function _AddRectFilledBakedXY(self, p_min_x, p_min_y, p_max_x, p_max_y, col, r, tex_uvs, flags) -- 9-slice with corner mirroring - local uv_l, uv_t, uv_r, uv_b = tex_uvs.x, tex_uvs.y, tex_uvs.z, tex_uvs.w -- uv_tl = (l,t), uv_tr = (r,t), uv_br = (r,b), uv_bl = (l,b) + local uv_l, uv_t, uv_r, uv_b = tex_uvs.x, tex_uvs.y, tex_uvs.z, tex_uvs.w -- [Port] uv_tl = (l,t), uv_tr = (r,t), uv_br = (r,b), uv_bl = (l,b) PrimReserve(self, 9 * 2 * 3, 4 * 4) @@ -6398,8 +6397,8 @@ function MT.ImDrawList:AddRectFilled(p_min, p_max, col, rounding, flags) end -- When rounding non-integer and under threshold, has_rounding may be false but still affect is_truncated. Likely not worth catering for. - local has_rounding = bit32.band(flags, ImDrawFlags.RoundMask_) ~= ImDrawFlags.RoundNone and rounding >= 0.25 * fringe_scale -- IM_HAS_ROUNDING(rounding) - local is_truncated = ax % 1 == 0 and ay % 1 == 0 and bx % 1 == 0 and by % 1 == 0 and rounding % 1 == 0 -- IM_IS_TRUNCATED4() && IM_IS_TRUNCATED() + local has_rounding = bit32.band(flags, ImDrawFlags.RoundMask_) ~= ImDrawFlags.RoundNone and rounding >= 0.25 * fringe_scale -- [Port] IM_HAS_ROUNDING(rounding) + local is_truncated = ax % 1 == 0 and ay % 1 == 0 and bx % 1 == 0 and by % 1 == 0 and rounding % 1 == 0 -- [Port] IM_IS_TRUNCATED4() && IM_IS_TRUNCATED() if self._FringeScaleIsInteger and is_truncated then -- Fast path for the non-AA non-rounded rect. @@ -6841,7 +6840,7 @@ local AddText_clip_rect = ImVec4() @native function MT.ImDrawList:AddText(font, font_size, pos, col, text, text_begin, text_end, wrap_width, cpu_fine_clip_rect) - -- Overload: AddText(pos, col, text, text_end?) + -- [Port] Overload: AddText(pos, col, text, text_end?) if type(font) == "table" and type(font[1]) == "number" then font, font_size, pos, col, text, text_begin, text_end, wrap_width, cpu_fine_clip_rect = nil, 0.0, font, font_size, pos, 1, col, 0.0, nil if text_end == nil then text_end = #text + 1 end @@ -6974,7 +6973,7 @@ function MT.ImDrawList:_CalcCircleAutoSegmentCount(radius) -- Automatic segment count local radius_idx = ImFloor(radius + 0.999) + 1 -- ceil to never reduce accuracy - if radius_idx >= 1 and radius_idx <= 64 then -- IM_COUNTOF(_Data->CircleSegmentCounts) + if radius_idx >= 1 and radius_idx <= 64 then -- [Port] IM_COUNTOF(_Data->CircleSegmentCounts) return self._Data.CircleSegmentCounts[radius_idx] -- Use cached value else return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, self._Data.CircleTessellationMaxError) @@ -7014,7 +7013,7 @@ function MT.ImDrawList:PopClipRect() local stack = self._ClipRectStack IM_ASSERT(stack.Size > 0) stack.Size = stack.Size - 1 -- [Luau] inline pop_back() - if (stack.Size == 0) then -- LUA: No "Ternary Operator" + if (stack.Size == 0) then -- [Port] No "Ternary Operator" ImVec4_Copy(self._CmdHeader.ClipRect, self._Data.ClipRectFullscreen) else ImVec4_Copy(self._CmdHeader.ClipRect, stack.Data[stack.Size]) @@ -7033,7 +7032,7 @@ function MT.ImDrawList:GetClipRectMax() local cr = self._ClipRectStack:back(); r -- [Luau] scalar center (cx, cy); assigned to the forward-declared local, _PathArcToFastEx() wraps it @native function _PathArcToFastExXY(self, cx, cy, radius, a_min_sample, a_max_sample, a_step) - if not (radius >= 0.25 * self._FringeScale) then -- !IM_HAS_ROUNDING(radius) + if not (radius >= 0.25 * self._FringeScale) then -- [Port] !IM_HAS_ROUNDING(radius) PathLineToXY(self, cx, cy) return end @@ -7139,7 +7138,7 @@ end -- 0: East, 3: South, 6: West, 9: North, 12: East @native function MT.ImDrawList:PathArcToFast(center, radius, a_min_of_12, a_max_of_12) - if not (radius >= 0.25 * self._FringeScale) then -- !IM_HAS_ROUNDING(radius) + if not (radius >= 0.25 * self._FringeScale) then -- [Port] !IM_HAS_ROUNDING(radius) self._Path:push_back(center) return end @@ -7153,7 +7152,7 @@ end --- @param a_max float --- @param num_segments int function MT.ImDrawList:_PathArcToN(center, radius, a_min, a_max, num_segments) - if not (radius >= 0.25 * self._FringeScale) then -- !IM_HAS_ROUNDING(radius) + if not (radius >= 0.25 * self._FringeScale) then -- [Port] !IM_HAS_ROUNDING(radius) self._Path:push_back(center) return end @@ -7181,7 +7180,7 @@ end function MT.ImDrawList:PathArcTo(center, radius, a_min, a_max, num_segments) if num_segments == nil then num_segments = 0 end - if not (radius >= 0.25 * self._FringeScale) then -- !IM_HAS_ROUNDING(radius) + if not (radius >= 0.25 * self._FringeScale) then -- [Port] !IM_HAS_ROUNDING(radius) self._Path:push_back(center) return end @@ -7260,8 +7259,6 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b y = IM_TRUNC(y) end - -- if not text_end then - -- end local line_height = size local baked = self:GetFontBaked(size) @@ -7381,7 +7378,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b if gi ~= nil and gi ~= IM_FONTGLYPH_INDEX_NOT_FOUND and gi ~= IM_FONTGLYPH_INDEX_UNUSED then glyph = glyphs[gi] else - glyph = baked:FindGlyph(c) -- may load the glyph and grow the tables + glyph = baked:FindGlyph(c) -- [Port] may load the glyph and grow the tables lookup, lookup_n, glyphs = baked.IndexLookup.Data, baked.IndexLookup.Size, baked.Glyphs.Data end @@ -7456,7 +7453,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b draw_list:PrimUnreserve(idx_count_max, vtx_count_max) draw_list:AddDrawCmd() - return self:RenderText(draw_list, size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, flags) -- was `goto begin` + return self:RenderText(draw_list, size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, flags) -- [Port] was `goto begin` end -- Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action. @@ -7489,7 +7486,7 @@ end --- @param color ImU32 --- @param dir ImGuiDir --- @param scale? float -local arrow_a, arrow_b, arrow_c = ImVec2(), ImVec2(), ImVec2() -- scratch: the path is consumed by AddTriangleFilled before returning +local arrow_a, arrow_b, arrow_c = ImVec2(), ImVec2(), ImVec2() -- [Port] scratch: the path is consumed by AddTriangleFilled before returning function ImGui.RenderArrow(draw_list, pos, color, dir, scale) if scale == nil then scale = 1.0 end @@ -7765,7 +7762,7 @@ function ImGui.RenderRectFilledWithHole(draw_list, outer, inner, col, rounding) end ------------------------------------------------------------------------------- --- Extra path functions (elliptical arc, bezier curves) and concave fill +-- [Port] Extra path functions (elliptical arc, bezier curves) and concave fill ------------------------------------------------------------------------------- function MT.ImDrawList:PathEllipticalArcTo(center, radius, rot, a_min, a_max, num_segments) @@ -7878,7 +7875,7 @@ local function ImTriangulatorNode_Unlink(tri, n) tri.Prev[tri.Next[n]] = tri.Pre local function ImTriangulator_IsReflex(a, b, c) return ((b.x - a.x) * (c.y - b.y)) - ((c.x - b.x) * (b.y - a.y)) < 0.0 end local function ImTriangulatorNodeSpan() - return { Data = {}, Size = 0 } -- Data: node handles, 1-based + return { Data = {}, Size = 0 } -- [Port] Data: node handles, 1-based end MT.ImTriangulatorNodeSpan = {} MT.ImTriangulatorNodeSpan.__index = MT.ImTriangulatorNodeSpan @@ -7890,7 +7887,7 @@ function MT.ImTriangulatorNodeSpan:find_erase_unsorted(idx) for i = self.Size, 1 local function ImTriangulator() return setmetatable({ _TrianglesLeft = 0, - _Nodes = 0, -- node handle (head of the circular list) + _Nodes = 0, -- [Port] node handle (head of the circular list) _Ears = setmetatable(ImTriangulatorNodeSpan(), MT.ImTriangulatorNodeSpan), _Reflexes = setmetatable(ImTriangulatorNodeSpan(), MT.ImTriangulatorNodeSpan), Type = {}, Index = {}, Pos = {}, Next = {}, Prev = {}, -- [Luau] ImTriangulatorNode fields, one array each @@ -8321,4 +8318,4 @@ function stb_decompress(output, i, length) end end -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value diff --git a/imgui_h.lua b/imgui_h.lua index 33f3e6c..dbd9409 100644 --- a/imgui_h.lua +++ b/imgui_h.lua @@ -14,7 +14,7 @@ -- Index of this file: -- [SECTION] Forward declarations and basic types --- [SECTION] METATABLE MANAGEMENT +-- [Port] [SECTION] METATABLE MANAGEMENT -- [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> -- [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) -- [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) @@ -33,7 +33,7 @@ local type = type -- [Luau] builtin (FASTCALL); ImGui._GetTypeFunc() kept for compatibility local rawget = rawget; local rawset = rawset --- [LuaBitOp](https://bitop.luajit.org/semantics.html) +-- [Port] [LuaBitOp](https://bitop.luajit.org/semantics.html) local bitAnd = bit32.band; local bitOr = bit32.bor local bitLShift = bit32.lshift @@ -138,10 +138,10 @@ IM_FREE = ImGui.MemFree IM_DELETE = function(owner, field) if owner[field] ~= nil then owner[field] = nil; ImGui.MemFree(owner, field); end end ------------------------------------------------------------------------------- --- [SECTION] METATABLE MANAGEMENT +-- [Port] [SECTION] METATABLE MANAGEMENT ------------------------------------------------------------------------------- ---- File-scope metatable storage +--- [Port] File-scope metatable storage local MT = {} function ImGui.GetMetatables() return MT end @@ -153,7 +153,7 @@ function IM_ASSERT(_EXPR, _MSG) assert((_EXPR), _MSG) end IM_ASSERT_PARANOID = IM_ASSERT -- A primary data type ---- Note that `S64` and `U64` are not supported +--- [Port] Note that `S64` and `U64` are not supported --- @enum ImGuiDataType ImGuiDataType = { @@ -334,7 +334,7 @@ function ImVec2_SubVA(v, sub_x, sub_y) return v.x - sub_x, v.y - sub_y end function ImVec2_MulVX(a, scalar) return a.x * scalar, a.y * scalar end ---- An inlined version of `ImVec2_Copy` currently for use in certain ImVector `push_back` +--- [Port] An inlined version of `ImVec2_Copy` currently for use in certain ImVector `push_back` local function ImVec2_TCopy(t, k, v) local dest = t[k]; dest.x = v.x; dest.y = v.y; end -- ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type] @@ -383,7 +383,7 @@ function ImVec4_Copy(dest, src) dest.x = src.x; dest.y = src.y; dest.z = src.z; ------------------------------------------------------------------------------- -- ImVector<> ---- A compact ImVector clone +--- [Port] A compact ImVector clone --- @class ImVector --- @field Data T[] # 1-based table --- @field Size int # >= 0 @@ -391,22 +391,22 @@ function ImVec4_Copy(dest, src) dest.x = src.x; dest.y = src.y; dest.z = src.z; --- @field _CopyFunc function local IM_VECTOR = {} --- Support 1-based number key indexing while keep method accessing speed +-- [Port] Support 1-based number key indexing while keep method accessing speed --- @param t ImVector --- @param k string|int --- @return any IM_VECTOR.__index = function(t, k) - local m = IM_VECTOR[k] -- methods first (hot path) + local m = IM_VECTOR[k] -- [Port] methods first (hot path) if m ~= nil then return m end - if k == "Data" then return nil end -- Data has already been discarded - return t.Data[IM_ASSERT(k >= 1 and k <= t.Size) or k] -- if the mt access turns out nil, the k must be int index into Data + if k == "Data" then return nil end -- [Port] Data has already been discarded + return t.Data[IM_ASSERT(k >= 1 and k <= t.Size) or k] -- [Port] if the mt access turns out nil, the k must be int index into Data end --- @param t ImVector --- @param k int --- @param v any IM_VECTOR.__newindex = function(t, k, v) - if k == "Data" then rawset(t, "Data", v); return; end -- set new Data. old Data is already discarded + if k == "Data" then rawset(t, "Data", v); return; end -- [Port] set new Data. old Data is already discarded IM_ASSERT(k >= 1 and k <= t.Size) t.Data[k] = v end @@ -469,10 +469,10 @@ end function IM_VECTOR:swap(other) self.Size, other.Size = other.Size, self.Size; self.Capacity, other.Capacity = other.Capacity, self.Capacity; self.Data, other.Data = other.Data, self.Data end function IM_VECTOR:contains(v) for i = 1, self.Size do if self.Data[i] == v then return true end end return false end --- NOTE: This currently does not use type-aware copy! +-- [Port] NOTE: This currently does not use type-aware copy! function IM_VECTOR:insert(pos, value) IM_ASSERT(pos >= 1 and pos <= self.Size + 1); if self.Size == self.Capacity then self:reserve(_grow_capacity(self, self.Size + 1)) end; for i = self.Size, pos, -1 do self.Data[i + 1] = self.Data[i] end self.Data[pos] = value self.Size = self.Size + 1 return value end --- NOTE: This currently does not copy type related info! +-- [Port] NOTE: This currently does not copy type related info! --- @nodiscard function IM_VECTOR:copy() local v = ImVector(); v:resize(self.Size) @@ -481,7 +481,7 @@ function IM_VECTOR:copy() return v end --- Not keeping value-key records inside `ImVector`, instead just find it +-- [Port] Not keeping value-key records inside `ImVector`, instead just find it --- @return int # 0-based index function IM_VECTOR:index_from_ptr(p) local data = self.Data; for i = 1, self.Size do if p == data[i] then return i - 1 end end @@ -599,7 +599,7 @@ function ImDrawChannel() return { _CmdBuffer = ImVector(), _IdxBuffer = ImVector --- @return ImDrawListSplitter --- @nodiscard -MT.ImDrawListSplitter = {} -- methods in imgui_draw.lua +MT.ImDrawListSplitter = {} -- [Port] methods in imgui_draw.lua MT.ImDrawListSplitter.__index = MT.ImDrawListSplitter function ImDrawListSplitter() return setmetatable({ _Current = 0, _Count = 0, _Channels = ImVector() }, MT.ImDrawListSplitter) end @@ -1345,7 +1345,7 @@ function ImGuiIO() -- - Suggested use, e.g. io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map to SHIFT modifier ConfigDebugDrawListDefaultsToStrokeLegacy = false, -- false -- Default all ImDrawList to ImDrawList_StrokeLegacy mode, mimicking pre-1.93.0 rendering. - IniFilename = "imgui.ini", -- Roblox: no disk access, only used as a flag (nil disables .ini handling) + IniFilename = "imgui.ini", -- [Port] no disk access, only used as a flag (nil disables .ini handling) IniSavingRate = 5.0, -- = 5.0f -- Minimum time between saving positions/sizes to .ini file, in seconds. LogFilename = "imgui_log.txt", -- = "imgui_log.txt"-- Path to .log file (default parameter to ImGui.LogToFile when no file is specified). WantSaveIniSettings = false, -- When manual .ini load/save is active (io.IniFilename == nil), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! @@ -2112,7 +2112,7 @@ ImGuiKey = { RightCtrl = 531, RightShift = 532, RightAlt = 533, RightSuper = 534, Menu = 535, - -- 0 ~ 9 (upstream ImGuiKey_0..ImGuiKey_9: K0..K9 in this port, ImGuiKey["0"]..ImGuiKey["9"] are aliases) + -- [Port] 0 ~ 9 (upstream ImGuiKey_0..ImGuiKey_9: K0..K9 in this port, ImGuiKey["0"]..ImGuiKey["9"] are aliases) K0 = 536, K1 = 537, K2 = 538, K3 = 539, K4 = 540, K5 = 541, K6 = 542, K7 = 543, K8 = 544, K9 = 545, ["0"] = 536, ["1"] = 537, ["2"] = 538, ["3"] = 539, ["4"] = 540, ["5"] = 541, ["6"] = 542, ["7"] = 543, ["8"] = 544, ["9"] = 545, @@ -2534,7 +2534,7 @@ ImGuiInputTextFlags = { --- @class ImGuiInputTextCallbackData --- @return ImGuiInputTextCallbackData --- Buf is a 1-based zero-terminated byte table; positions (CursorPos, pos...) are 0-based byte offsets like upstream. +-- [Port] Buf is a 1-based zero-terminated byte table; positions (CursorPos, pos...) are 0-based byte offsets like upstream. MT.ImGuiInputTextCallbackData = {} MT.ImGuiInputTextCallbackData.__index = MT.ImGuiInputTextCallbackData function ImGuiInputTextCallbackData() @@ -2544,7 +2544,7 @@ end function MT.ImGuiInputTextCallbackData:DeleteChars(pos, bytes_count) IM_ASSERT(pos + bytes_count <= self.BufTextLen) local buf = self.Buf - local n = self.BufTextLen - bytes_count - pos + 1 -- includes zero terminator + local n = self.BufTextLen - bytes_count - pos + 1 -- [Port] includes zero terminator for i = 1, n do buf[pos + i] = buf[pos + bytes_count + i] end if self.CursorPos >= pos + bytes_count then @@ -2565,10 +2565,10 @@ function MT.ImGuiInputTextCallbackData:InsertChars(pos, new_text) -- We support partial insertion local avail = self.BufSize - 1 - self.BufTextLen if not is_resizable and new_text_len > avail then - new_text_len = avail -- ponytail: truncates by bytes, not to the closest UTF-8 codepoint + new_text_len = avail end if new_text_len <= 0 then return end - -- ponytail: CallbackResize buffer growth not supported, text is truncated at BufSize instead + if self.BufTextLen + new_text_len + 1 > self.BufSize then new_text_len = self.BufSize - 1 - self.BufTextLen if new_text_len <= 0 then return end @@ -2802,7 +2802,7 @@ end -- Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() --- @class ImGuiPayload ---- Drag and drop payload. `Data` is any Lua value (C++ stores raw bytes); `DataSize` kept for API parity. +--- [Port] Drag and drop payload. `Data` is any Lua value (C++ stores raw bytes); `DataSize` kept for API parity. local IM_PAYLOAD = {} IM_PAYLOAD.__index = IM_PAYLOAD function IM_PAYLOAD:Clear() ImGuiPayload_Clear(self) end @@ -2980,15 +2980,15 @@ function ImGuiMultiSelectIO() return { Requests = ImVector(ImGuiSelectionRequest, ImGuiSelectionRequest_Copy), RangeSrcItem = -1, NavIdItem = -1, NavIdSelected = false, RangeSrcReset = false, ItemsCount = 0 } end --- ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage: see [SECTION] Widgets: Multi-Select helpers in imgui_widgets.lua +-- [Port] ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage: see [SECTION] Widgets: Multi-Select helpers in imgui_widgets.lua -- (constructors and methods are defined there, like upstream's out-of-line definitions in imgui_widgets.cpp). --- @class ImGuiSettingsHandler ---- Fns take (ctx, handler, ...) like upstream. ReadOpenFn(ctx, handler, name) returns entry; ReadLineFn(ctx, handler, entry, line); +--- [Port] Fns take (ctx, handler, ...) like upstream. ReadOpenFn(ctx, handler, name) returns entry; ReadLineFn(ctx, handler, entry, line); --- WriteAllFn(ctx, handler, buf: ImGuiTextBuffer) function ImGuiSettingsHandler() return { TypeName = nil, TypeHash = 0, ClearAllFn = nil, ReadInitFn = nil, ReadOpenFn = nil, ReadLineFn = nil, ApplyAllFn = nil, WriteAllFn = nil, CleanupFn = nil, UserData = nil } end -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value diff --git a/imgui_internal.lua b/imgui_internal.lua index f1f7306..60c19ed 100644 --- a/imgui_internal.lua +++ b/imgui_internal.lua @@ -26,7 +26,7 @@ -- [SECTION] ImFontLoader -- [SECTION] ImFontAtlas internal API -- --- PORT: the order of declarations in this file does not strictly follow upstream's imgui_internal.h. +-- [Port] the order of declarations in this file does not strictly follow upstream's imgui_internal.h. --- @meta @@ -44,11 +44,10 @@ local t_sort = table.sort --- @alias ImGuiTableColumnIdx ImS16 --- TODO: Implement actual ImString type +-- [Port] TODO: Implement actual ImString type --- @alias ImString char[]|string --- @alias ImStringBuffer char[] --- NOTE: temporary solution --- @param buf char[] --- @param buf_begin int --- @param buf_end int # exclusive @@ -64,7 +63,7 @@ end -- Helper: ImPool<> -- Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer, -- Indexes have the same lifetime as the associated object. ---- ImPool: pool of objects keyed by ID. Public indices are 0-based like upstream (Buf is stored 1-based). +--- [Port] ImPool: pool of objects keyed by ID. Public indices are 0-based like upstream (Buf is stored 1-based). --- `ctor` creates a new element. Removed slots are recycled via FreeIdx (-1 = none; free slots chain through `_NextFree`). local IM_POOL = {} IM_POOL.__index = IM_POOL @@ -99,7 +98,7 @@ function IM_POOL:Remove(key, p) self.AliveCount = self.AliveCount - 1 end function IM_POOL:Reserve(n) end --- NOTE: removed slots hold `false`; iterate with `for i = 0, pool:GetMapSize() - 1 do local t = pool:GetByIndex(i) if t then ... end end` +-- [Port] NOTE: removed slots hold `false`; iterate with `for i = 0, pool:GetMapSize() - 1 do local t = pool:GetByIndex(i) if t then ... end end` ------------------------------------------------------------------------------- -- [SECTION] Context pointer @@ -109,7 +108,7 @@ function IM_POOL:Reserve(n) end --- @type ImGuiContext? local GImGui -- Current implicit context pointer --- Sets local `GImGui` in this file(imgui_internal.lua). +-- [Port] Sets local `GImGui` in this file(imgui_internal.lua). -- This is currently only used in main code `ImGui.SetCurrentContext()` --- @param ctx ImGuiContext? function ImGui._SetCurrentContext_Internal(ctx) @@ -251,7 +250,7 @@ ImTrunc64 = _Trunc --- @param f float function ImCeilFast(f) local i - if f >= 0 then i = math.floor(f) else i = math.ceil(f) end -- same as `ImTrunc()` + if f >= 0 then i = math.floor(f) else i = math.ceil(f) end -- [Port] same as `ImTrunc()` if f > i then return i + 1 end return i end @@ -311,7 +310,7 @@ function ImStd.ImExponentialMovingAverage(avg, sample, n) return avg end --- Uses `string.match` internally +-- [Port] Uses `string.match` internally --- @param str string function ImAtof(str) return tonumber(string.match(str, "[+-]?%d*%.?%d+")) @@ -329,7 +328,6 @@ do local _memmove = function(dest, dest_start, src, src_start, count) if count <= 0 then return end - -- more compact instead of writing separate if-else and for loops local c = (dest == src and dest_start >= src_start) for i = (c and count - 1 or 0), (c and 0 or count - 1), (c and -1 or 1) do dest[dest_start + i] = src[src_start + i] @@ -337,12 +335,8 @@ local _memmove = function(dest, dest_start, src, src_start, count) end if table.move then - --- [GMod] Platform specific: the `table.move` polyfill in non-x86-64 currently uses `unpack` which will break if too many elements - -- Remove this check when the polyfill is fixed or removed - if not gmod or (gmod and BRANCH == "x86-64") then - _memmove = function(dest, dest_start, src, src_start, count) - table.move(src, src_start, src_start + count - 1, dest_start, dest) - end + _memmove = function(dest, dest_start, src, src_start, count) + table.move(src, src_start, src_start + count - 1, dest_start, dest) end end @@ -489,9 +483,9 @@ function ImStd.ImStrlen(str, begin) IM_ASSERT(false) end --- FIXME: should also accept count? --- FIXME: avoid dynamic type checking? --- string.find with patterns disabled +-- [Port] FIXME: should also accept count? +-- [Port] FIXME: avoid dynamic type checking? +-- [Port] string.find with patterns disabled --- @param str string|char[] --- @param s string|char --- @param start_pos? int @@ -539,7 +533,7 @@ IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT = ((IM_DRAWLIST_TEX_LINES_DETAILED_WI -- - The message will always be a string literal, in order to increase likelihood of being display by an assert handler. -- - See 'Demo->Configuration->Error Handling' and ImGuiIO definitions for details on error handling. -- - Read https://github.com/ocornut/imgui/wiki/Error-Handling for details on error handling. --- Upstream: `if (!(expr) && ErrorLog(msg)) IM_ASSERT(0)`. ErrorLog() returns io.ConfigErrorRecoveryEnableAssert. +-- [Port] Upstream: `if (!(expr) && ErrorLog(msg)) IM_ASSERT(0)`. ErrorLog() returns io.ConfigErrorRecoveryEnableAssert. function IM_ASSERT_USER_ERROR(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then if not ImGui.ErrorLog or ImGui.ErrorLog(_MSG) then error(_MSG, 2) end end end -- Recoverable User Error function IM_ASSERT_USER_ERROR_RET(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then error(_MSG, 2) end end @@ -1052,7 +1046,7 @@ end -- Helper: ImBitArray class (wrapper over ImBitArray functions) -- Store 1-bit per value. ---- NOTE: This struct is expensive to create +--- [Port] NOTE: This struct is expensive to create --- @class ImBitArray --- @field Data ImU32[] @@ -1276,7 +1270,7 @@ function ImFontAtlasBuilder() this.PreloadedAllGlyphsRanges = false -- Set when missing ImGuiBackendFlags.RendererHasTextures features forces atlas to preload everything. -- Cache of all ImFontBaked - this.BakedPool = ImVector() -- ImStableVector + this.BakedPool = ImVector() -- [Port] ImStableVector this.BakedMap = {} -- BakedId --> ImFontBaked this.BakedDiscardedCount = 0 @@ -1317,7 +1311,7 @@ end -- [SECTION] Style support ------------------------------------------------------------------------------- ---- `GetVarPtr()` is currently only used on `g.Style` in Dear ImGui, and we don't have pointers! +--- [Port] `GetVarPtr()` is currently only used on `g.Style` in Dear ImGui, and we don't have pointers! --- @class ImGuiStyleVarInfo --- @field Count ImU32 # 1+ --- @field DataType ImGuiDataType @@ -1832,7 +1826,7 @@ local function ImGuiInputTextState() SelectedAllMouseLock = false, -- after a double-click to select all, we ignore further mouse drags to update selection EditedBefore = false, -- edited since activated EditedThisFrame = false, -- edited this frame - ValidatedThisFrame = false, -- validated this frame (e.g. Enter pressed) + ValidatedThisFrame = false, WantReloadUserBuf = false, -- force a reload of user buf so it may be modified externally. may be automatic in future version. LastMoveDirectionLR = ImGuiDir.Left, -- ImGuiDir_Left or ImGuiDir_Right. track last movement direction so when cursor cross over a word-wrapping boundaries we can display it on either line depending on last move.s ReloadSelectionStart = 0, @@ -2125,7 +2119,7 @@ end ------------------------------------------------------------------------------- -- We always assume that -1 is an invalid value (which works for indices and pointers) --- (ImGuiSelectionUserData_Invalid is defined above with the ImGuiSelectionUserData alias) +-- [Port] (ImGuiSelectionUserData_Invalid is defined above with the ImGuiSelectionUserData alias) -- Temporary storage for multi-select --- @class ImGuiMultiSelectTempData @@ -2266,7 +2260,7 @@ function ImGui.GetMultiSelectState(id) local g = GImGui; return g.MultiSelectSto ------------------------------------------------------------------------------- -- [SECTION] Tab bar, Tab item support --- PORT: public flags from imgui.h + private extensions +-- [Port] public flags from imgui.h + private extensions ------------------------------------------------------------------------------- -- Flags for ImGui.BeginTabBar() @@ -2315,7 +2309,7 @@ ImGuiTabItemFlags = { } ImGuiTabItemFlags.SectionMask_ = bitOr(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing) --- Storage for one active tab item. In this port the label is stored in `Name` (C++ uses NameOffset into TabBar.TabsNames) +-- [Port] Storage for one active tab item. In this port the label is stored in `Name` (C++ uses NameOffset into TabBar.TabsNames) --- @class ImGuiTabItem --- @return ImGuiTabItem function ImGuiTabItem() @@ -2334,7 +2328,7 @@ function ImGuiTabItem() } end --- Storage for a tab bar. Tabs: ImVector of ImGuiTabItem tables (references; "pointers" stay valid across reorders) +-- [Port] Storage for a tab bar. Tabs: ImVector of ImGuiTabItem tables (references; "pointers" stay valid across reorders) --- @class ImGuiTabBar --- @return ImGuiTabBar function ImGuiTabBar() @@ -2366,7 +2360,7 @@ function ImGuiShrinkWidthItem() return { Index = 0, Width = 0.0, InitialWidth = --- @param shared_font_atlas? ImFontAtlas --- @return ImGuiContext --- @nodiscard -function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this structure +function ImGuiContext(shared_font_atlas) local this = { Style = ImGuiStyle(), ColorStack = ImVector(), -- Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() @@ -2604,20 +2598,20 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct ComboPreviewData = ImGuiComboPreviewData(), CurrentTabBar = nil, - TabBars = ImPool(ImGuiTabBar), -- ImPool + TabBars = ImPool(ImGuiTabBar), -- [Port] ImPool -- Docking DockContext = ImGuiDockContext(), DockNodeWindowMenuHandler = nil, DebugHoveredDockNode = nil, -- Hovered dock node. - CurrentTabBarStack = ImVector(), -- ImVector - ShrinkWidthBuffer = ImVector(), -- ImGuiShrinkWidthItem + CurrentTabBarStack = ImVector(), -- [Port] ImVector + ShrinkWidthBuffer = ImVector(), -- [Port] ImGuiShrinkWidthItem -- Multi-Select state BoxSelectState = ImGuiBoxSelectState(), CurrentMultiSelect = nil, MultiSelectTempDataStacked = 0, -- Temporary multi-select data size (because we leave previous instances undestructed, we generally don't use MultiSelectTempData.Size) - MultiSelectTempData = ImVector(), -- ImVector, 1-based - MultiSelectStorage = ImPool(ImGuiMultiSelectState), -- ImPool + MultiSelectTempData = ImVector(), -- [Port] ImVector, 1-based + MultiSelectStorage = ImPool(ImGuiMultiSelectState), -- [Port] ImPool WindowResizeBorderExpectedRect = ImRect(), -- Expected border rect, switch to relative edit if moving WindowResizeRelativeMode = false, @@ -2739,7 +2733,7 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct DebugAllocInfo = ImGuiDebugAllocInfo(), --- Misc - FramerateSecPerFrame = {}, -- size = 60 + FramerateSecPerFrame = {}, -- [Port] size = 60 FramerateSecPerFrameIdx = 0, FramerateSecPerFrameCount = 0, FramerateSecPerFrameAccum = 0, @@ -2749,15 +2743,15 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct WantTextInputNextFrame = -1, -- Copied in EndFrame() from g.PlatformImeData.WantTextInput. Needs to be set for some backends (SDL3) to emit character inputs. TempBuffer = ImVector(), -- Temporary text buffer - -- Tables (imgui_tables.lua) + -- [Port] Tables (imgui_tables.lua) CurrentTable = nil, DebugBreakInTable = 0, -- Set to break in BeginTable() call. TablesTempDataStacked = 0, -- Temporary table data size (because we leave previous instances undestructed, we generally don't use TablesTempData.Size) TablesTempData = ImVector(), -- Temporary table data (buffers reused/shared across instances, support nesting) - Tables = ImPool(), -- ImPool, 0-based indices (imgui_tables.lua) - TablesLastTimeActive = ImVector(), -- [table_idx + 1] = float + Tables = ImPool(), -- [Port] ImPool, 0-based indices (imgui_tables.lua) + TablesLastTimeActive = ImVector(), -- [Port] [table_idx + 1] = float DrawChannelsTempMergeBuffer = ImVector(), - SettingsTables = ImVector(), -- ImChunkStream: plain vector, SettingsOffset = 1-based index + SettingsTables = ImVector(), -- [Port] ImChunkStream: plain vector, SettingsOffset = 1-based index } for i = 0, 59 do this.FramerateSecPerFrame[i] = 0 end @@ -2932,7 +2926,7 @@ local function ImGuiWindowTempData() TreeRecordsClippedNodesY2Mask = nil, -- Store whether we should keep recording Y2. Cleared when passing clip max. Equivalent TreeHasStackDataDepthMask value should always be set. ChildWindows = ImVector(), - CurrentTableIdx = -1, -- 0-based index into g.Tables, -1 if none + CurrentTableIdx = -1, -- [Port] 0-based index into g.Tables, -1 if none CurrentColumns = nil, -- ImGuiOldColumns (legacy Columns API) StateStorage = nil, -- Current persistent per-window storage (store e.g. tree node open/close state) @@ -3130,7 +3124,7 @@ function ImGuiWindow(ctx, name) LastTimeActive = -1.0, -- Last timestamp the window was Active (using float as we don't need high precision there) StateStorage = {}, - ColumnsStorage = ImVector(), -- ImVector + ColumnsStorage = ImVector(), -- [Port] ImVector WriteAccessed = false, -- Set to true when any widget access the current window @@ -3140,7 +3134,7 @@ function ImGuiWindow(ctx, name) HitTestHoleSize = ImVec2(), -- Define an optional rectangular hole where mouse will pass-through the window. NavLastChildNavWindow = nil, -- When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) - NavLastIds = {[0] = 0, [1] = 0}, -- FIXME: 1-based instead + NavLastIds = {[0] = 0, [1] = 0}, -- [Port] FIXME: 1-based instead NavRectRel = {[0] = ImRect(), [1] = ImRect()}, -- Reference rectangle, in window relative space NavPreferredScoringPosRel = {[0] = ImVec2(), [1] = ImVec2()}, -- Preferred X/Y position updated when moving on a given axis, reset to FLT_MAX. NavRootFocusScopeId = 0 -- Focus Scope ID at the time of Begin() @@ -3966,4 +3960,4 @@ function ImGui.GetCurrentTabBar() local g = GImGui; return g.CurrentTabBar end function ImGui.IsItemActiveAsInputText() local g = GImGui; return g.ActiveId ~= 0 and g.ActiveId == g.LastItemData.ID and g.InputTextState.ID == g.LastItemData.ID end -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value diff --git a/imgui_tables.lua b/imgui_tables.lua index 0d7822a..e6a9731 100644 --- a/imgui_tables.lua +++ b/imgui_tables.lua @@ -176,22 +176,22 @@ -- - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false. ------------------------------------------------------------------------------- --- Port notes: --- - Column indices / display orders / draw channel indices are 0-based VALUES like upstream. --- Per-column arrays (table.Columns, table.DisplayOrderToIndex, table.RowCellData) are Lua tables with 0-based keys. --- table.ColumnsSize mirrors upstream `table->Columns.size()`. --- - ImBitArray masks are Lua tables { [n] = true }. --- - table.ColumnsNames is a Lua array of strings, column.NameOffset is a 0-based index into it (-1 = none). --- - g.SettingsTables is a plain vector of ImGuiTableSettings; table.SettingsOffset is a 1-based index into it (-1 = none). --- Each settings entry owns `Columns` (0-based Lua table of ImGuiTableColumnSettings). --- - ImGuiTableSortSpecs.Specs is a 1-based Lua array of ImGuiTableColumnSortSpecs. +-- [Port] Port notes: +-- [Port] - Column indices / display orders / draw channel indices are 0-based VALUES like upstream. +-- [Port] Per-column arrays (table.Columns, table.DisplayOrderToIndex, table.RowCellData) are Lua tables with 0-based keys. +-- [Port] table.ColumnsSize mirrors upstream `table->Columns.size()`. +-- [Port] - ImBitArray masks are Lua tables { [n] = true }. +-- [Port] - table.ColumnsNames is a Lua array of strings, column.NameOffset is a 0-based index into it (-1 = none). +-- [Port] - g.SettingsTables is a plain vector of ImGuiTableSettings; table.SettingsOffset is a 1-based index into it (-1 = none). +-- [Port] Each settings entry owns `Columns` (0-based Lua table of ImGuiTableColumnSettings). +-- [Port] - ImGuiTableSortSpecs.Specs is a 1-based Lua array of ImGuiTableColumnSortSpecs. --- @type ImGuiContext? local GImGui local MT = ImGui.GetMetatables() --- Sets local `GImGui` in this file(imgui_tables.lua). +-- [Port] Sets local `GImGui` in this file(imgui_tables.lua). -- This is currently only used in main code `ImGui.SetCurrentContext()` --- @param ctx ImGuiContext? function ImGui._SetCurrentContext_Tables(ctx) @@ -489,7 +489,7 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi -- Acquire storage for the table local table_ = g.Tables:GetOrAddByKey(id) - if table_.Columns == nil then -- pool created a plain table + if table_.Columns == nil then -- [Port] pool created a plain table for k, v in pairs(ImGuiTable()) do table_[k] = v end end @@ -1993,7 +1993,7 @@ function ImGui.TableReconcileColumns(table_) end -- Remaining entries are matched sequentially. - local dst_idx = 1 -- index in reconcile array (1-based) + local dst_idx = 1 -- [Port] index in reconcile array (1-based) if matches ~= reconcile_requests.Size then for src_n = 0, src_count - 1 do local src_column = src_columns[src_n] @@ -2085,7 +2085,7 @@ function ImGui.TableGetColumnCount() return table_ and table_.ColumnsCount or 0 end --- Overloads: TableGetColumnName(column_n?) / TableGetColumnName(table, column_n) +-- [Port] Overloads: TableGetColumnName(column_n?) / TableGetColumnName(table, column_n) function ImGui.TableGetColumnName(a, b) local table_, column_n if type(a) == "table" then @@ -3003,7 +3003,7 @@ end -- Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd. -- -- This function is particularly tricky to understand.. take a breath. --- (Lua: splitter channel n lives in splitter._Channels.Data[n + 1]; bit arrays are Lua sets) +-- [Port] (Lua: splitter channel n lives in splitter._Channels.Data[n + 1]; bit arrays are Lua sets) local TableMergeDrawChannels_MergeGroups = {} for n = 0, 3 do TableMergeDrawChannels_MergeGroups[n] = { ClipRect = ImRect(), ChannelsCount = 0, ChannelsMask = {} } @@ -3301,7 +3301,7 @@ end -- changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, -- else you may wastefully sort your data every frame! -- Lifetime: don't hold on this table over multiple frames or past any subsequent call to BeginTable()! --- PORT: Specs is a 1-based Lua array. +-- [Port] Specs is a 1-based Lua array. function ImGui.TableGetSortSpecs() local g = GImGui local table_ = g.CurrentTable @@ -3393,7 +3393,7 @@ function ImGui.TableSortSpecsSanitize(table_) -- Clear SortOrder from hidden column and verify that there's no gap or duplicate. local sort_order_count = 0 - local sort_order_set = {} -- C++: ImU64 sort_order_mask + local sort_order_set = {} -- [Port] C++: ImU64 sort_order_mask local sort_order_dup = false for column_n = 0, table_.ColumnsCount - 1 do local column = table_.Columns[column_n] @@ -3408,7 +3408,7 @@ function ImGui.TableSortSpecsSanitize(table_) end end - -- need_fix_linearize: (1 << count) != (mask + 1) <=> the set of sort orders isn't exactly {0..count-1} + -- [Port] need_fix_linearize: (1 << count) != (mask + 1) <=> the set of sort orders isn't exactly {0..count-1} local need_fix_linearize = sort_order_dup for n = 0, sort_order_count - 1 do if not sort_order_set[n] then need_fix_linearize = true end @@ -4592,7 +4592,7 @@ function ImGui.TableRemove(table_) end -- Free up/compact internal Table buffers for when it gets unused --- Overloads: (ImGuiTable) / (ImGuiTableTempData) +-- [Port] Overloads: (ImGuiTable) / (ImGuiTableTempData) function ImGui.TableGcCompactTransientBuffers(t) if not t then return end if t.TableIndex ~= nil then -- ImGuiTableTempData @@ -4670,7 +4670,7 @@ end -- - EndColumns() -- - Columns() ------------------------------------------------------------------------------- --- (Lua: columns.Columns is an ImVector, column n lives in .Data[n + 1]) +-- [Port] (Lua: columns.Columns is an ImVector, column n lives in .Data[n + 1]) function ImGui.GetColumnIndex() local window = ImGui.GetCurrentWindowRead() @@ -5086,4 +5086,4 @@ function ImGui.Columns(columns_count, id, borders) end end -return true -- [Roblox] ModuleScripts must return exactly one value +return true -- [Port] [Roblox] ModuleScripts must return exactly one value diff --git a/imgui_widgets.lua b/imgui_widgets.lua index c7f4a45..c292890 100644 --- a/imgui_widgets.lua +++ b/imgui_widgets.lua @@ -27,7 +27,7 @@ --- @type ImGuiContext? local GImGui --- Sets local `GImGui` in this file(imgui_widgets.lua). +-- [Port] Sets local `GImGui` in this file(imgui_widgets.lua). -- This is currently only used in main code `ImGui.SetCurrentContext()` --- @param ctx ImGuiContext? function ImGui._SetCurrentContext_Widgets(ctx) @@ -369,7 +369,7 @@ function ImGui.BulletText(fmt, ...) ImGui.RenderText(ImVec2(bb.Min.x + (g.FontSize + style.FramePadding.x * 2), bb.Min.y + 0.0), text, 1, text_end, false) end --- va_list variants: identical to the varargs versions in Lua +-- [Port] va_list variants: identical to the varargs versions in Lua ImGui.TextColoredV = ImGui.TextColored ImGui.TextDisabledV = ImGui.TextDisabled ImGui.TextWrappedV = ImGui.TextWrapped @@ -384,8 +384,8 @@ ImGui.BulletTextV = ImGui.BulletText -- - Value() ------------------------------------------------------------------------------- --- Value(prefix, b) / Value(prefix, int) / Value(prefix, float, float_format) --- Lua can't tell int from float: integers without float_format print as %d, otherwise %.3f +-- [Port] Value(prefix, b) / Value(prefix, int) / Value(prefix, float, float_format) +-- [Port] Lua can't tell int from float: integers without float_format print as %d, otherwise %.3f function ImGui.Value(prefix, v, float_format) if type(v) == "boolean" then ImGui.Text("%s: %s", prefix, v and "true" or "false") @@ -485,7 +485,7 @@ end -- with same ID and different MouseButton (see #8030). You can fix it by: -- (1) switching to use a single ButtonBehavior() with multiple _MouseButton flags. -- or (2) surrounding those calls with PushItemFlag(ImGuiItemFlags.AllowDuplicateId, true); ... PopItemFlag() --- Returns (pressed, hovered, held). +-- [Port] Returns (pressed, hovered, held). --- @param bb ImRect --- @param id ImGuiID --- @param flags? ImGuiButtonFlags @@ -763,7 +763,7 @@ function ImGui.ButtonEx(label, size_arg, flags) local label_size = ImGui.CalcTextSize(label, label_end, false) -- [Luau] scalar pos, no temporary ImVec2 - local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y -- Don't modify the cursor! + local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y local frame_padding = style.FramePadding if bit32.band(flags, ImGuiButtonFlags.AlignTextBaseLine) ~= 0 and frame_padding.y < window.DC.CurrLineTextBaseOffset then -- Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos_y = pos_y + window.DC.CurrLineTextBaseOffset - frame_padding.y @@ -1071,7 +1071,7 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ -- As a special thing, we allow scrollbar near the edge of a screen/viewport to be reachable with mouse at the extreme edge (#9276) local bb_hit = ImRect() ImRect_Copy(bb_hit, bb_frame) - ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb_hit, g.Style.WindowBorderSize, ImGuiAxis.X + ImGuiAxis.Y - axis) -- swap axis here + ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb_hit, g.Style.WindowBorderSize, ImGuiAxis.X + ImGuiAxis.Y - axis) -- [Port] swap axis here -- Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). ImGui.ItemAdd(bb_frame, id, nil, ImGuiItemFlags.NoNav) @@ -1481,7 +1481,7 @@ function ImGui.RadioButtonEx(label, active) return pressed end --- `rawequal` is used here to check if v == v_button +-- [Port] `rawequal` is used here to check if v == v_button --- @param label string --- @param v any --- @param v_button any @@ -2211,7 +2211,7 @@ function ImGui.EndComboPreview() preview_data.WithinPreview = false end --- Getter for the old Combo() API: Lua array of strings (1-based), `idx` is 0-based +-- [Port] Getter for the old Combo() API: Lua array of strings (1-based), `idx` is 0-based local function Items_ArrayGetter(data, idx) return data[idx + 1] end @@ -2241,7 +2241,7 @@ local function Items_SingleStringCount(data) return items_count end --- Normalizes the 3 upstream overloads to (getter, user_data, items_count, height) +-- [Port] Normalizes the 3 upstream overloads to (getter, user_data, items_count, height) -- - (items: string[], items_count?, height?) -- - (items_separated_by_zeros: string, height?) -- - (getter: fun(user_data, idx): string?, user_data, items_count, height?) @@ -2368,9 +2368,9 @@ function ImGui.DataTypeGetInfo(data_type) end -- [Luau] string.format() has no length modifiers (%lld, %I64d...) and formats negative numbers as 64-bit for %u/%x/%X/%o: --- strip modifiers and re-apply C's integer promotion/two's complement for signed types. +-- [Port] strip modifiers and re-apply C's integer promotion/two's complement for signed types. local DataTypeFormatStringCached do -local fmt_info_memo = {} -- format -> { stripped format, is unsigned conversion } +local fmt_info_memo = {} -- [Port] format -> { stripped format, is unsigned conversion } local function GetFormatInfo(format) local info = fmt_info_memo[format] if info == nil then @@ -2382,7 +2382,7 @@ local function GetFormatInfo(format) return info end ---- Lua-string version of DataTypeFormatString() (memoized), used for display. +--- [Port] Lua-string version of DataTypeFormatString() (memoized), used for display. --- @param data_type ImGuiDataType --- @param data number --- @param format string @@ -2396,14 +2396,14 @@ function DataTypeFormatStringCached(data_type, data, format) elseif data_type == ImGuiDataType.U8 then data = (ImU8)(data) elseif data_type == ImGuiDataType.S16 then data = (ImS16)(data) elseif data_type == ImGuiDataType.U16 then data = (ImU16)(data) - elseif data_type == ImGuiDataType.S32 then -- (signed values are already stored signed) + elseif data_type == ImGuiDataType.S32 then -- [Port] (signed values are already stored signed) elseif data_type == ImGuiDataType.U32 then data = (ImU32)(data) elseif data_type == ImGuiDataType.S64 or data_type == ImGuiDataType.U64 then - -- (string.format() already prints negative numbers as 64-bit two's complement for %u/%x/%X/%o) + -- [Port] (string.format() already prints negative numbers as 64-bit two's complement for %u/%x/%X/%o) if info[2] then - if data >= 18446744073709551616 then data = -1 end -- (ImU64)-1 rounds to 2^64 in a double: print ULLONG_MAX + if data >= 18446744073709551616 then data = -1 end -- [Port] (ImU64)-1 rounds to 2^64 in a double: print ULLONG_MAX elseif data >= 9223372036854775808 then - data = 9223372036854774784 -- largest double below 2^63 (LLONG_MAX isn't representable) + data = 9223372036854774784 -- [Port] largest double below 2^63 (LLONG_MAX isn't representable) end return FormatCached(info[1], data) else @@ -2422,7 +2422,7 @@ end --- @return int function ImGui.DataTypeFormatString(buf, buf_size, data_type, data, format) local str = DataTypeFormatStringCached(data_type, data, format) - local len = ImMin(#str, buf_size - 1) -- ImFormatString(): truncate and return the written length + local len = ImMin(#str, buf_size - 1) -- [Port] ImFormatString(): truncate and return the written length ImStd.ImStrncpy(buf, 1, { string.byte(str, 1, len) }, 1, len + 1) return len end @@ -2975,7 +2975,7 @@ function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min return data, value_changed end --- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For an Input widget, step and step_fast are optional. +-- [Port] Note: data is passed by value and the new value is returned: Returns (data, value_changed). For an Input widget, step and step_fast are optional. -- Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. --- @param label string --- @param data_type ImGuiDataType @@ -3002,7 +3002,7 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag local data_default = (bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasRefVal) ~= 0) and g.NextItemData.RefVal or g.DataTypeZeroValue - local buf, buf_size = {}, 64 -- char buf[64]; IM_COUNTOF(buf) + local buf, buf_size = {}, 64 -- [Port] char buf[64]; IM_COUNTOF(buf) if bit32.band(flags, ImGuiInputTextFlags.DisplayEmptyRefVal) ~= 0 and ImGui.DataTypeCompare(data_type, data, data_default) == 0 then buf[1] = 0 else @@ -3479,7 +3479,7 @@ local function TempInputIsClampEnabled(flags, data_type, min, max) if bit32.band(flags, ImGuiSliderFlags.ClampOnInput) ~= 0 and (min ~= nil or max ~= nil) then local clamp_range_dir = 0 if min ~= nil and max ~= nil then - clamp_range_dir = ImGui.DataTypeCompare(data_type, min, max) -- -1 when min < max, == 0 when min == max + clamp_range_dir = ImGui.DataTypeCompare(data_type, min, max) end if min == nil or max == nil or clamp_range_dir < 0 then return true @@ -3500,7 +3500,7 @@ end --- @param format string --- @param flags ImGuiSliderFlags -- [Luau] memo of string.format(format, value) for drag/slider value text (same values are redrawn every frame). --- ponytail: whole-memo reset at 4096 entries, LRU if values churn + local fmt_memo, fmt_memo_n = {}, 0 local SliderScalar_total_bb, SliderScalar_grab_bb = ImRect(), ImRect() -- [Luau] scratch for SliderScalar()/DragScalar(), never escape local DRAG_TEXT_ALIGN = ImVec2(0.5, 0.5) @@ -3515,7 +3515,7 @@ function FormatCached(format, v) return r end --- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a Drag widget, min and max are optional. +-- [Port] Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a Drag widget, min and max are optional. -- Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. @native function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, flags) @@ -3669,7 +3669,7 @@ function ImGui.DragInt(label, v, v_speed, v_min, v_max, format, flags) return ImGui.DragScalar(label, ImGuiDataType.S32, v, v_speed, v_min, v_max, format, flags) end --- `v` is mutated in place (1-based), returns value_changed +-- [Port] `v` is mutated in place (1-based), returns value_changed function ImGui.DragScalarN(label, data_type, v, components, v_speed, v_min, v_max, format, flags) if v_speed == nil then v_speed = 1.0 end if flags == nil then flags = 0 end @@ -3948,7 +3948,7 @@ function ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, t, v_min, v_max -- - Not doing a *1.0 multiply at the end of a range as it tends to be lossy. While absolute aiming at a large s64/u64 -- range is going to be imprecise anyway, with this check we at least make the edge values matches expected limits. local v_new_off_f = (SIGNEDTYPE)((v_max - v_min)) * t - result = (TYPE)((SIGNEDTYPE)(v_min) + (SIGNEDTYPE)(v_new_off_f + 0)) -- LUA: + 0 instead of + ((v_min > v_max) and -0.5 or 0.5) + result = (TYPE)((SIGNEDTYPE)(v_min) + (SIGNEDTYPE)(v_new_off_f + 0)) -- [Port] + 0 instead of + ((v_min > v_max) and -0.5 or 0.5) end end @@ -4213,7 +4213,7 @@ function ImGui.SliderBehavior(bb, id, data_type, v, min, max, format, flags, out return v, false end --- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a slider, min and max are required. +-- [Port] Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a slider, min and max are required. -- Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. --- @generic T : number --- @param label string @@ -5256,7 +5256,7 @@ function ImGui.InputTextDeactivateHook(id) IM_ASSERT(state.TextA.Data ~= nil) -- IM_ASSERT(state.TextA[state.TextLen + 1] == 0) g.InputTextDeactivatedState.TextA:resize(state.TextLen + 1) - ImStd.memmove(g.InputTextDeactivatedState.TextA.Data, 1, state.TextA.Data, 1, state.TextLen) -- state.TextLen + 1 + ImStd.memmove(g.InputTextDeactivatedState.TextA.Data, 1, state.TextA.Data, 1, state.TextLen) -- [Port] state.TextLen + 1 end end @@ -5381,7 +5381,7 @@ local function InputTextLineIndexGetPosOffset(g, state, line_index, buf, buf_end end end - local line_no = (it == it_begin) and 0 or (it - 1) -- 0-based (index_from_ptr) + local line_no = (it == it_begin) and 0 or (it - 1) -- [Port] 0-based (index_from_ptr) local line_start = line_index:get_line_begin(1, line_no) local offset = ImVec2() offset.x = InputTextCalcTextSize(g, buf, line_start, cursor_ptr, buf_end, nil, ImDrawTextFlags.WrapKeepBlanks).x @@ -5603,7 +5603,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback -- Find initial scroll position for right alignment ImVec2_Copy(state.Scroll, ImVec2(0.0, 0.0)) if bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 then - state.Scroll.x = state.Scroll.x + ImMax(0.0, ImGui.CalcTextSize(table.concat(buf)).x - frame_size.x + style.FramePadding.x * 2.0) -- FIXME: no table.concat here + state.Scroll.x = state.Scroll.x + ImMax(0.0, ImGui.CalcTextSize(table.concat(buf)).x - frame_size.x + style.FramePadding.x * 2.0) -- [Port] FIXME: no table.concat here end -- Recycle existing cursor/selection/undo stack but clamp position @@ -6235,7 +6235,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end -- Calculate visibility - local line_visible_n0, line_visible_n1 = 0, 1 -- 0-based like upstream + local line_visible_n0, line_visible_n1 = 0, 1 -- [Port] 0-based like upstream if is_multiline then line_visible_n0, line_visible_n1 = ImGui.CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize) end @@ -6735,7 +6735,7 @@ function ImGui.ColorEdit4(label, col, flags) end elseif bit32.band(flags, ImGuiColorEditFlags.DisplayHex) ~= 0 and bit32.band(flags, ImGuiColorEditFlags.NoInputs) == 0 then -- RGB Hexadecimal Input - -- TODO: resolve sprintf, sscanf requirement. currently this section creates a lot of temp tables and strings... + -- [Port] TODO: resolve sprintf, sscanf requirement. currently this section creates a lot of temp tables and strings... local buf, buf_size = nil, 64 if alpha then local str = ImFormatString("#%02X%02X%02X%02X", ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255), ImClamp(i[3], 0, 255), ImClamp(i[4], 0, 255)) @@ -6893,7 +6893,7 @@ function ImGui.ColorEdit3(label, col, flags) return ImGui.ColorEdit4(label, col, bit32.bor(flags, ImGuiColorEditFlags.NoAlpha)) end --- `col` mutated in place, returns value_changed +-- [Port] `col` mutated in place, returns value_changed function ImGui.ColorPicker3(label, col, flags) if flags == nil then flags = 0 end local col4 = { col[1], col[2], col[3], 1.0 } @@ -7156,7 +7156,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) -- Convert back color to RGB if value_changed_h or value_changed_sv then if bit32.band(flags, ImGuiColorEditFlags.InputRGB) ~= 0 then - col[1], col[2], col[3] = ImGui.ColorConvertHSVtoRGB(H, S, V) -- Lua 1-based indexing + col[1], col[2], col[3] = ImGui.ColorConvertHSVtoRGB(H, S, V) -- [Port] Lua 1-based indexing g.ColorEditSavedHue = H g.ColorEditSavedSat = S g.ColorEditSavedID = g.ColorEditCurrentID @@ -7202,7 +7202,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) -- Try to cancel hue wrap (after ColorEdit4 call), if any if value_changed_fix_hue_wrap and bit32.band(flags, ImGuiColorEditFlags.InputRGB) ~= 0 then - local new_H, new_S, new_V = ImGui.ColorConvertRGBtoHSV(col[1], col[2], col[3]) -- Lua 1-based indexing + local new_H, new_S, new_V = ImGui.ColorConvertRGBtoHSV(col[1], col[2], col[3]) -- [Port] Lua 1-based indexing if new_H <= 0 and H > 0 then if new_V <= 0 and V ~= new_V then @@ -7658,7 +7658,7 @@ end -- - CollapsingHeader() ------------------------------------------------------------------------------- --- va_list variants: identical in Lua (varargs) +-- [Port] va_list variants: identical in Lua (varargs) ImGui.TextColoredV = function(...) return ImGui.TextColored(...) end ImGui.TextDisabledV = function(...) return ImGui.TextDisabled(...) end ImGui.TextWrappedV = function(...) return ImGui.TextWrapped(...) end @@ -7674,7 +7674,7 @@ function ImGui.SetNextItemRefVal(data_type, v) g.NextItemData.RefVal = v end --- Overloads: TreeNode(label) / TreeNode(str_id, fmt, ...) +-- [Port] Overloads: TreeNode(label) / TreeNode(str_id, fmt, ...) --- @param label string @native function ImGui.TreeNode(label, fmt, ...) @@ -7693,7 +7693,7 @@ function ImGui.TreeNodeV(str_id, fmt, ...) return ImGui.TreeNodeExV(str_id, 0, fmt, ...) end --- Overloads: TreeNodeEx(label, flags) / TreeNodeEx(str_id, flags, fmt, ...) +-- [Port] Overloads: TreeNodeEx(label, flags) / TreeNodeEx(str_id, flags, fmt, ...) --- @param label string --- @param flags? ImGuiTreeNodeFlags function ImGui.TreeNodeEx(label, flags, fmt, ...) @@ -8263,7 +8263,7 @@ end -- CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags.NoTreePushOnOpen flag). -- This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags.CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). --- Overloads: CollapsingHeader(label, flags?) -> is_open +-- [Port] Overloads: CollapsingHeader(label, flags?) -> is_open -- CollapsingHeader(label, p_visible: bool, flags?) -> is_open, p_visible -- p_visible == nil : regular collapsing header -- p_visible == true : show a small close button on the corner of the header, clicking the button will set p_visible = false (returned as 2nd value) @@ -8613,7 +8613,7 @@ function ImGui.GetTypingSelectRequest(flags) -- Handle backspace if bit32.band(flags, ImGuiTypingSelectFlags.AllowBackspace) ~= 0 and ImGui.IsKeyPressedEx(ImGuiKey.Backspace, ImGuiInputFlags.Repeat) then - local p = ImStd.ImTextFindPreviousUtf8Codepoint(data.SearchBuffer, 1, buffer_len + 1) -- 1-based byte position + local p = ImStd.ImTextFindPreviousUtf8Codepoint(data.SearchBuffer, 1, buffer_len + 1) -- [Port] 1-based byte position data.SearchBuffer = string.sub(data.SearchBuffer, 1, p - 1) buffer_len = p - 1 end @@ -8906,7 +8906,7 @@ function ImGui.BeginBoxSelect(scope_rect, window, box_select_id, ms_flags) end end - -- box_select_intersection = BoxSelectRectPrev + BoxSelectRectCurr + -- [Port] box_select_intersection = BoxSelectRectPrev + BoxSelectRectCurr local box_select_intersection_min_x, box_select_intersection_min_y = ImMin(prev.Min.x, curr.Min.x), ImMin(prev.Min.y, curr.Min.y) local box_select_intersection_max_x, box_select_intersection_max_y = ImMax(prev.Max.x, curr.Max.x), ImMax(prev.Max.y, curr.Max.y) if bit32.band(ms_flags, ImGuiMultiSelectFlags.BoxSelect2d) ~= 0 then @@ -9593,7 +9593,7 @@ function ImGui.MultiSelectAddSetRange(ms, selected, range_dir, first_item, last_ -- FIXME-OPT: Disabled on 2026/04/09 as this would break with any form of coarse clipping that we don't know about (e.g. TableNextColumn() return value). -- The low-hanging fruit would be to know that ImGuiSelectionUserData are sequential indices, in which case we can trivially compare PrevSubmittedItem + RangeDir == FirstItem. -- User can always perform this merge if required. - -- (#if 0 block not ported) + -- [Port] (#if 0 block not ported) local req = MultiSelectScratchRequest -- ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, (ImS8)range_dir, (range_dir > 0) ? first_item : last_item, (range_dir > 0) ? last_item : first_item } req.Type = ImGuiSelectionRequestType.SetRange; req.Selected = selected; req.RangeDirection = range_dir @@ -9705,7 +9705,7 @@ function MT.ImGuiSelectionBasicStorage:GetNextSelectedItem(opaque_it) table.sort(keys, PairComparerByValueInt) -- ~ImGuiStorage::BuildSortByValueInt() PairComparerStorage = nil else - table.sort(keys) -- ImGuiStorage is sorted by key + table.sort(keys) -- [Port] ImGuiStorage is sorted by key end it = 1 end @@ -9862,7 +9862,7 @@ function MT.ImGuiSelectionExternalStorage:ApplyRequests(ms_io) end end -end -- do (Typing-Select, Box-Select, Multi-Select) +end -- [Port] do (Typing-Select, Box-Select, Multi-Select) ------------------------------------------------------------------------------- -- [SECTION] Widgets: ListBox @@ -9931,7 +9931,7 @@ end -- This is merely a helper around BeginListBox(), EndListBox(). -- Considering using those directly to submit custom data or store selection differently. --- Overloads: (label, current_item, items[], items_count?, height_in_items?) or (label, current_item, getter, user_data, items_count, height_in_items?) +-- [Port] Overloads: (label, current_item, items[], items_count?, height_in_items?) or (label, current_item, getter, user_data, items_count, height_in_items?) --- @param current_item int # 0-based --- @return int current_item --- @return bool value_changed @@ -10036,7 +10036,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local v_min = FLT_MAX local v_max = -FLT_MAX for i = 1, values_count do - local v = values_getter(data, i) -- NaN isn't checked here + local v = values_getter(data, i) -- [Port] NaN isn't checked here v_min = ImMin(v_min, v) v_max = ImMax(v_max, v) @@ -10855,7 +10855,7 @@ end do --[[ [SECTION] Widgets: BeginTabBar, EndTabBar, etc. (was imgui_tabs.lua) ]] --- Dear ImGui --- Tab bars & tab items: 1:1 port of imgui_widgets.cpp [SECTION] Widgets: BeginTabBar/BeginTabItem (docking branch) +-- [Port] Tab bars & tab items: 1:1 port of imgui_widgets.cpp [SECTION] Widgets: BeginTabBar/BeginTabItem (docking branch) -- -- Port notes: -- - tab_bar.Tabs is an ImVector of ImGuiTabItem tables (references). C++ pointer arithmetic on the array is replaced by @@ -10908,7 +10908,7 @@ local function GetTabBarRefFromTabBar(tab_bar) return ImGuiPtrOrIndex(tab_bar) end --- Stable sorts (C++ ImQsort is not stable, but the comparers are total orders in practice) +-- [Port] Stable sorts (C++ ImQsort is not stable, but the comparers are total orders in practice) local function SortTabsBySection(tab_bar) table.sort(tab_bar.Tabs.Data, TabItemComparerBySection) end @@ -10940,7 +10940,7 @@ end -- Shrink excess width from a set of item, by removing width from the larger items first. -- Set items Width to -1.0f to disable shrinking this item. --- items: 1-based array of ImGuiShrinkWidthItem, `first` = 1-based index of first item, `count` items +-- [Port] items: 1-based array of ImGuiShrinkWidthItem, `first` = 1-based index of first item, `count` items function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) if count <= 0 then return end if count == 1 then @@ -11163,7 +11163,7 @@ function ImGui.TabBarLayout(tab_bar) local tabs = tab_bar.Tabs local tab_dst_n = 0 local need_sort_by_section = false - local sections = { ImGuiTabBarSection(), ImGuiTabBarSection(), ImGuiTabBarSection() } -- Layout sections: Leading, Central, Trailing (1-based: [1]=Leading,[2]=Central,[3]=Trailing) + local sections = { ImGuiTabBarSection(), ImGuiTabBarSection(), ImGuiTabBarSection() } -- [Port] Layout sections: Leading, Central, Trailing (1-based: [1]=Leading,[2]=Central,[3]=Trailing) for tab_src_n = 0, tabs.Size - 1 do local tab = tabs.Data[tab_src_n + 1] if tab.LastFrameVisible < tab_bar.PrevFrameVisible or tab.WantClose then @@ -11233,7 +11233,7 @@ function ImGui.TabBarLayout(tab_bar) -- Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central -- (whereas our tabs are stored as: leading, central, trailing) - -- (shrink_buffer_indexes holds 0-based offsets) + -- [Port] (shrink_buffer_indexes holds 0-based offsets) local shrink_buffer_indexes = { 0, sections[1].TabCount + sections[3].TabCount, sections[1].TabCount } local swb = g.ShrinkWidthBuffer swb:resize(tabs.Size) @@ -11642,7 +11642,7 @@ function ImGui.TabBarProcessReorder(tab_bar) if bit32.band(tab2.Flags, ImGuiTabItemFlags.NoReorder) ~= 0 then return false end if bit32.band(tab1.Flags, ImGuiTabItemFlags.SectionMask_) ~= bit32.band(tab2.Flags, ImGuiTabItemFlags.SectionMask_) then return false end - -- Move tab1 to tab2's position, shifting the tabs in between + -- [Port] Move tab1 to tab2's position, shifting the tabs in between table.remove(tab_bar.Tabs.Data, tab1_order + 1) table.insert(tab_bar.Tabs.Data, tab2_order + 1, tab1) diff --git a/imstb_rectpack.lua b/imstb_rectpack.lua index 6915eb8..2a6ff04 100644 --- a/imstb_rectpack.lua +++ b/imstb_rectpack.lua @@ -1,8 +1,8 @@ --- Dear ImGui --- This is a Lua port of original `imstb_rectpack.h` +-- [Port] This is a Lua port of original `imstb_rectpack.h` --- ALL TABLES IN THIS FILE ARE 1-BASED! --- Avoids table creation when possible +-- [Port] ALL TABLES IN THIS FILE ARE 1-BASED! +-- [Port] Avoids table creation when possible -- [DEAR IMGUI] -- This is a slightly modified version of stb_rect_pack.h 1.01. @@ -272,7 +272,7 @@ function stbrp_init_target(context, width, height, nodes, num_nodes) end -- find minimum y position if it starts at x1 --- Returns (min_y, waste_area) +-- [Port] Returns (min_y, waste_area) --- @param c stbrp_context --- @param first stbrp_node --- @param x0 int diff --git a/imstb_textedit.lua b/imstb_textedit.lua index 60d4299..016d6f7 100644 --- a/imstb_textedit.lua +++ b/imstb_textedit.lua @@ -1,5 +1,5 @@ --- Dear ImGui --- This is a Lua port of original `imstb_textedit.h` +-- [Port] This is a Lua port of original `imstb_textedit.h` -- [DEAR IMGUI] -- This is a slightly modified version of stb_textedit.h 1.14. @@ -38,7 +38,7 @@ -- -- Uses the C runtime function 'memmove', which you can override -- by defining IMSTB_TEXTEDIT_memmove before the implementation. --- (In this port: ImStb.TEXTEDIT_memmove.) +-- [Port] (In this port: ImStb.TEXTEDIT_memmove.) -- -- -- VERSION HISTORY @@ -216,7 +216,7 @@ -- efficient, but it's not horrible on modern computers. But you wouldn't -- want to edit million-line files with it. --- ALL TABLES IN THIS FILE ARE 1-BASED! +-- [Port] ALL TABLES IN THIS FILE ARE 1-BASED! -- Character Indexing: -- idx=n, the n'th char (1-based) -- Cursor Indexing: @@ -455,7 +455,7 @@ end local stb_text_locate_coord do --- only create once, reuse later +-- [Port] only create once, reuse later local r = StbTexteditRow() --- traverse the layout to locate the nearest character to a display position @@ -964,7 +964,7 @@ function stb_textedit_key(str, state, key) if not is_page and state.single_line then -- on windows, up&down in single-line behave like left&right key = bit32.bor(STB_TEXTEDIT_K_RIGHT, bit32.band(key, STB_TEXTEDIT_K_SHIFT)) - return stb_textedit_key(str, state, key) -- was `goto retry` + return stb_textedit_key(str, state, key) -- [Port] was `goto retry` end if sel then @@ -1037,7 +1037,7 @@ function stb_textedit_key(str, state, key) if not is_page and state.single_line then -- on windows, up&down become left&right key = bit32.bor(STB_TEXTEDIT_K_LEFT, bit32.band(key, STB_TEXTEDIT_K_SHIFT)) - return stb_textedit_key(str, state, key) -- was `goto retry` + return stb_textedit_key(str, state, key) -- [Port] was `goto retry` end if sel then diff --git a/imstb_truetype.lua b/imstb_truetype.lua index 31810a9..535a271 100644 --- a/imstb_truetype.lua +++ b/imstb_truetype.lua @@ -1,5 +1,5 @@ --- Dear ImGui --- This is a Lua port of original `imstb_truetype.h` +-- [Port] This is a Lua port of original `imstb_truetype.h` -- [DEAR IMGUI] -- This is a slightly modified version of stb_truetype.h 1.26. @@ -76,7 +76,7 @@ -- accurately measures pixel coverage for anti-aliasing, except in the case -- where multiple shapes overlap, in which case it overestimates the AA pixel -- coverage. Thus, anti-aliasing of intersecting shapes may look wrong. --- (This port only implements the new rasterizer.) +-- [Port] (This port only implements the new rasterizer.) -- -- ADDITIONAL DOCUMENTATION -- @@ -194,7 +194,7 @@ local STBTT_MS_EID = { -- encodingID for STBTT_PLATFORM_ID_MICROSOFT UNICODE_FULL = 10 } --- original enum doesn't have a name, so we name it +-- [Port] original enum doesn't have a name, so we name it --- @enum STBTT_VTX local STBTT_VTX = { MOVE = 1, @@ -793,7 +793,7 @@ local function stbtt_InitFont_internal(info, data, fontstart) info.fdselect = stbtt__new_buf(nil, 0) -- @TODO this should use size from table (not 512MB) - info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- PORT: 64MB here instead of 512MB + info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- [Port] 64MB here instead of 512MB local b = info.cff -- read the header @@ -1084,7 +1084,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) if numberOfContours > 0 then local endPtsOfContours = g + 10 local ins = ttUSHORT(data, endPtsOfContours + numberOfContours * 2) - local points = (endPtsOfContours + numberOfContours * 2 + 2 + ins) + 1 -- 1-based idx + local points = (endPtsOfContours + numberOfContours * 2 + 2 + ins) + 1 -- [Port] 1-based idx local n = 1 + ttUSHORT(data, endPtsOfContours + numberOfContours * 2 - 2) local m = n + 2 * numberOfContours -- a loose bound on how many vertices we might need @@ -1304,7 +1304,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) end -- Append vertices. - if num_vertices == 0 then -- LUA: No malloc + if num_vertices == 0 then -- [Port] No malloc vertices = comp_verts else for i = 1, comp_num_vertices do @@ -1454,7 +1454,7 @@ local function stbtt__run_charstring(info, glyph_index, c) local has_subrs = 0 local clear_stack - local s = {} -- size = 48, 0-based + local s = {} -- [Port] size = 48, 0-based local subr_stack = {} for i = 1, 10 do subr_stack[i] = stbtt__buf() end @@ -2185,8 +2185,8 @@ end local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y) local active = nil - local scanline = {} -- size = result.w, 0-based - local scanline2 = {} -- size = result.w + 1, 0-based + local scanline = {} -- [Port] size = result.w, 0-based + local scanline2 = {} -- [Port] size = result.w + 1, 0-based STBTT__NOTUSED(vsubsample) @@ -2271,7 +2271,7 @@ end --- @param a stbtt__edge --- @param b stbtt__edge local STBTT__COMPARE = function(a, b) - if a.y0 == nil then return false end -- sentinels on the back + if a.y0 == nil then return false end -- [Port] sentinels on the back if b.y0 == nil then return true end return a.y0 < b.y0 end @@ -2480,7 +2480,7 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) local num_contours = n if n == 0 then return nil end - local contour_lengths = {} -- size = n + local contour_lengths = {} -- [Port] size = n -- make two passes through the points so we don't need to realloc for pass = 0, 1 do diff --git a/imstd_minstdio.lua b/imstd_minstdio.lua index 7f20970..bfa8caa 100644 --- a/imstd_minstdio.lua +++ b/imstd_minstdio.lua @@ -1,13 +1,13 @@ --- Dear ImGui --- This is a minimal Lua impl of C-like sscanf, sprintf sub-set +-- [Port] This is a minimal Lua impl of C-like sscanf, sprintf sub-set --- Supports: +-- [Port] Supports: -- - %x, %X, %nx, %nX (where n is a number) -- - %d, %nd, %u, %nu (where n is a number) -- - length modifiers h, hh, l, ll, I64 on integers: ll/I64 = 64-bit range (doubles: exact only within +-2^53) -- - %f, %lf (very limited) -- --- Returns items_matched instead of EOF on error +-- [Port] Returns items_matched instead of EOF on error local _byte = string.byte @@ -40,7 +40,7 @@ local function hex_digit_to_int(c) if c >= CHAR_A and c <= CHAR_F then return c - CHAR_A + 10 end end --- we force this behavior by default +-- [Port] we force this behavior by default local function clamp_if_overflow(spec, val, is_64) if spec == CHAR_d or spec == CHAR_x or spec == CHAR_X then local max = is_64 and 9223372036854775807 or INT_MAX @@ -61,7 +61,7 @@ end --- @param result table # table to store parsed values local function sscanf(buffer, buffer_begin, format, result) local p = buffer_begin - local f = 1 -- format_begin + local f = 1 -- [Port] format_begin local format_len = #format local assigned = 0 local items_matched = 0 @@ -88,10 +88,10 @@ local function sscanf(buffer, buffer_begin, format, result) break end - -- encountered % in fmt + -- [Port] encountered % in fmt f = f + 1 - -- %% + -- [Port] %% if _byte(format, f, f) == CHAR_PERCENT then if buffer[p] == CHAR_PERCENT then p = p + 1 @@ -103,7 +103,7 @@ local function sscanf(buffer, buffer_begin, format, result) break end - -- handle optional width + -- [Port] handle optional width local width = 0 while isdigit(_byte(format, f, f)) do width = width * 10 + _byte(format, f, f) - CHAR_0 @@ -113,7 +113,7 @@ local function sscanf(buffer, buffer_begin, format, result) width = math.huge end - -- length modifiers + -- [Port] length modifiers local n_l = 0 while _byte(format, f, f) == CHAR_l or _byte(format, f, f) == CHAR_h do if _byte(format, f, f) == CHAR_l then n_l = n_l + 1 end @@ -133,7 +133,7 @@ local function sscanf(buffer, buffer_begin, format, result) elseif spec == CHAR_d or spec == CHAR_u then base = 10 elseif spec == CHAR_f or spec == CHAR_F then - is_float = true -- TODO: distinguish %lf from %f? + is_float = true -- [Port] TODO: distinguish %lf from %f? else return items_matched end @@ -153,7 +153,7 @@ local function sscanf(buffer, buffer_begin, format, result) p = p + 1 end - -- inf, nan are not handled + -- [Port] inf, nan are not handled local p_start = p local int_part = 0 @@ -181,7 +181,7 @@ local function sscanf(buffer, buffer_begin, format, result) val = sign * (int_part + frac_part / frac_div) else local sign = 1 - -- optional sign + -- [Port] optional sign if base == 10 then if buffer[p] == CHAR_PLUS then p = p + 1 @@ -200,7 +200,6 @@ local function sscanf(buffer, buffer_begin, format, result) end if p == p_start then - -- failed to match return items_matched end @@ -217,7 +216,7 @@ local function sscanf(buffer, buffer_begin, format, result) end end if spec == CHAR_u and val < 0 then - val = val + (is_64 and 18446744073709551616 or 4294967296) -- unsigned wrap-around like strtoul() + val = val + (is_64 and 18446744073709551616 or 4294967296) -- [Port] unsigned wrap-around like strtoul() end end diff --git a/tools/bundle.py b/tools/bundle.py index 8e74223..b758d75 100644 --- a/tools/bundle.py +++ b/tools/bundle.py @@ -1,12 +1,16 @@ #!/usr/bin/env python3 -# Bundles the root *.lua (library + imgui_demo.lua), backends/ and fonts/ into ONE ModuleScript: build/ImGui.luau +# Bundles the root *.lua (library + imgui_demo.lua), the target's backend folder (backends/roblox/*.lua, or +# backends/love/*.lua) and fonts/ (Roblox) into ONE ModuleScript: build/ImGui.luau # --no-demo: library only (imgui_demo.lua left out, like not compiling imgui_demo.cpp) # --target love: build/imgui_love.lua for LÖVE/LuaJIT instead (LÖVE backend, shims from the LÖVE backend's COMPAT section, @native stripped). # The default (roblox) build is unaffected by it. # Why: ModuleScripts don't share globals, and the setfenv() alternative turns off Luau's fast paths / native codegen. # Each source file becomes a function in __FILES; IM_INCLUDE(name) runs it once and caches the result. # The module returns a table with every global the library defines (ImGui, ImVec2, ImGuiConfigFlags, ImGui_ImplRoblox, ...). -# Roblox target also writes ImGuiTyped.luau (types + require(script.Impl), see tools/gen_types.py). +# Roblox target also writes ImGuiTyped.luau (types + require(script.Impl), see tools/gen_types.py) and +# ImGuiWorker.client.luau: the parallel raster Actor LocalScript (backends/roblox/worker.luau with its +# `require(...Raster...)` line replaced by backends/roblox/raster.lua itself: self-contained, no require). +# The Roblox backend's modules are inlined into one function (see "Backend modules" below). # # Build-time optimizations (token rewrites with minify.py's lexer: strings/comments are never touched, every source line # stays on its line so linemap.json still maps errors). IMGUI_BUNDLE_NOOPT=1 turns all off, IMGUI_BUNDLE_NO_=1 one: @@ -35,15 +39,39 @@ OPT = {x: os.environ.get("IMGUI_BUNDLE_NOOPT") != "1" and os.environ.get("IMGUI_ # A limits: Luau 200 locals in the main chunk (+ helpers, __FILES, ...), 200 upvalues per function; LuaJIT 60 upvalues # per function (margin left for nested functions that also capture file locals) MAX_LOCALS, MAX_UPVALUES = 160, (45 if LOVE else 150) -BACKEND = "imgui_impl_love.lua" if LOVE else "imgui_impl_roblox.lua" -SKIP = {"imgui_impl_roblox.lua", "imgui_impl_roblox_fonts.lua"} if LOVE else {"imgui_impl_love.lua"} +TARGET = "love" if LOVE else "roblox" +BACKEND = "imgui_impl_%s.lua" % TARGET +BACKEND_DIR = os.path.join(ROOT, "backends", TARGET) # every *.lua in it is bundled (*.luau, e.g. the worker, is not) FILES = {} -for d in (ROOT, os.path.join(ROOT, "backends"), os.path.join(ROOT, "fonts")): +for d in [ROOT, BACKEND_DIR] + ([] if LOVE else [os.path.join(ROOT, "fonts")]): for f in sorted(os.listdir(d)): - if f.endswith(".lua") and not (NO_DEMO and f == "imgui_demo.lua") and f not in SKIP: + if f.endswith(".lua") and not (NO_DEMO and f == "imgui_demo.lua"): src = open(os.path.join(d, f)).read() if LOVE: src = re.sub(r"^@native$", "", src, flags=re.M) # keep line numbers - FILES[f] = src + FILES[f if d != BACKEND_DIR or f == BACKEND else TARGET + "/" + f] = src + +# Backend modules (backends//*.lua besides the main file, keyed "/x.lua") are inlined into the main +# file's __FILES function: `local X = IM_INCLUDE("/x.lua")` lines become blank (X is declared once at the top of +# the function), each module body goes in its own do ... end in dependency order, its final `return M` becomes `X = M`. +# Cross-module access is then a local of the same function, no IM_INCLUDE at load time. In source, the same files work +# with plain IM_INCLUDE (each a function returning its table). +INCLUDE = re.compile(r'^local (\w+) = IM_INCLUDE\("(%s/\w+\.lua)"\)[ \t]*$' % TARGET, re.M) +MODULES, EXPORT = [], {} # inline order, key -> local name +def visit(f, stack=()): + assert f not in stack, "backend modules: circular IM_INCLUDE %s" % " -> ".join(stack + (f,)) + for name, key in INCLUDE.findall(FILES[f]): + assert EXPORT.setdefault(key, name) == name, "%s is included as both %s and %s" % (key, EXPORT[key], name) + if key not in MODULES: visit(key, stack + (f,)); MODULES.append(key) +visit(BACKEND) +unused = [f for f in FILES if f.startswith(TARGET + "/") and f not in MODULES] +assert not unused, "backend modules never included: %s" % unused +GROUP = {f: BACKEND for f in MODULES} # file -> __FILES function it is emitted in + +def inline_module(key, src): + src = INCLUDE.sub("", src) + m = re.search(r"^return (\w+)[ \t]*\n*\Z", src, re.M) + assert m and m.group(1) != EXPORT[key], "%s must end with `return M` (a name other than %s)" % (key, EXPORT[key]) + return src[:m.start()] + "%s = %s\n" % (EXPORT[key], m.group(1)) ORIG = dict(FILES) # for gen_types ENTRY = ["imgui.lua", BACKEND] + ([] if NO_DEMO else ["imgui_demo.lua"]) # run order @@ -52,6 +80,7 @@ names = set() for src in FILES.values(): names.update(re.findall(r"^function ([A-Za-z_]\w*)\s*\(", src, re.M)) names.update(re.findall(r"^([A-Za-z_]\w*)\s*=[^=]", src, re.M)) +assert not names & set(EXPORT.values()), "backend module names clash with globals: %s" % (names & set(EXPORT.values())) # ---- lexer helpers ---- KW = set("and break do else elseif end false for function goto if in local nil not or repeat return then true until while".split()) @@ -147,7 +176,7 @@ if OPT["E"]: hoisted = [rewrite_assert(s) for s in hoisted] # ---- B: enum / constant folding ---- -LUAU = shutil.which("luau") or "/nix/store/2m2ja613nndihc8qm10f2rhq6znp1nh4-luau-0.734/bin/luau" +LUAU = shutil.which("luau") or (sorted(__import__("glob").glob("/nix/store/*-luau-*/bin/luau")) or ["luau"])[-1] def header(): return ["local __FILES, __LOADED = {}, {}", @@ -234,13 +263,14 @@ if OPT["B"]: # ---- A: hot globals -> bundle locals ---- hot = [] if OPT["A"]: - count, used = {}, [] - for src in FILES.values(): + count, used = {}, {} + for f, src in FILES.items(): toks = lex(src) - used.append({t for i, (k, t, _) in enumerate(toks) if isref(toks, i)}) + used.setdefault(GROUP.get(f, f), set()).update(t for i, (k, t, _) in enumerate(toks) if isref(toks, i)) for i, (k, t, _) in enumerate(toks): if t in names and isref(toks, i): count[t] = count.get(t, 0) + 1 # greedy by reference count; each file function's upvalues (hoisted names it uses) stay <= MAX_UPVALUES + used = list(used.values()) taken = [len(u & set(hoisted_names + re.findall(r"\w+", HOIST_DEPS.split("=")[0]))) for u in used] for n in sorted((n for n in count if n not in hoisted_names), key=lambda n: (-count[n], n)): if len(hot) == MAX_LOCALS: break @@ -250,14 +280,24 @@ if OPT["A"]: out = ["--!optimize 2", "-- GENERATED by tools/bundle.py from *.lua, backends/, fonts/ - do not edit", ""] if LOVE: - out = ["-- GENERATED by tools/bundle.py --target love - do not edit", re.search(r"--@compat-begin\n(.*?)--@compat-end", open(os.path.join(ROOT, "backends", "imgui_impl_love.lua")).read(), re.S).group(1), ""] + out = ["-- GENERATED by tools/bundle.py --target love - do not edit", re.search(r"--@compat-begin\n(.*?)--@compat-end", open(os.path.join(BACKEND_DIR, BACKEND)).read(), re.S).group(1), ""] if hot: out.append("local " + ", ".join(hot)) if hoisted: out += [HOIST_DEPS] + hoisted out += header() linemap = [] # (first bundle line, file) for error -> source mapping (tools/test/run.py) +def nextline(): return sum(x.count("\n") + 1 for x in out) + 1 for name, src in sorted(FILES.items()): + if name in GROUP: continue out.append("__FILES[%r] = function()" % name) - linemap.append((sum(x.count("\n") + 1 for x in out) + 1, name)) + if name == BACKEND and MODULES: + out.append("local " + ", ".join(EXPORT[k] for k in MODULES)) + for k in MODULES: + out.append("do") + linemap.append((nextline(), k)) + out.append(inline_module(k, FILES[k]).rstrip("\n")) + out.append("end") + src = INCLUDE.sub("", src) + linemap.append((nextline(), name)) out.append(src.rstrip("\n")) out.append("end") out.append("") @@ -277,4 +317,11 @@ json.dump(linemap, open(os.path.join(OUT, NAME.rsplit(".", 1)[0] + ".linemap.jso if not LOVE: from gen_types import wrapper open(os.path.join(OUT, "ImGuiTyped.luau"), "w").write(wrapper(ORIG)) + worker = open(os.path.join(BACKEND_DIR, "worker.luau")).read() + req = re.search(r"^local Raster = require\(.*\)$", worker, re.M) + assert req, "worker: no `local Raster = require(...)` line" + raster = ORIG["roblox/raster.lua"].rstrip("\n") + open(os.path.join(OUT, "ImGuiWorker.client.luau"), "w").write( + "--!optimize 2\n-- GENERATED by tools/bundle.py from backends/roblox/worker.luau + raster.lua - do not edit\n" + + worker[:req.start()] + "local Raster = (function()\n" + raster + "\nend)()" + worker[req.end():]) print("wrote build/%s (%d files, %d exports)" % (NAME, len(FILES), len(names))) diff --git a/tools/gen_types.py b/tools/gen_types.py index 80fa169..f6155a7 100644 --- a/tools/gen_types.py +++ b/tools/gen_types.py @@ -113,15 +113,32 @@ def types_header(files): lines += [" [string]: any,", "}"] for name, keys in sorted(enums(files).items()): lines.append("export type %s = { %s, [string]: number }" % (name, ", ".join("%s: number" % k for k in keys))) - return lines + module_type(set(enums(files))) + return lines + impl_type(files) + module_type(set(enums(files))) def wrapper(files): return "\n".join(["--!strict", "-- GENERATED by tools/gen_types.py - do not edit. The library is the child ModuleScript 'Impl'.", ""] + types_header(files) + ["", "return (require(script:WaitForChild(\"Impl\")) :: any) :: ImGuiModule", ""]) +IMPL_SIGS = { # backend functions with exact types; the rest of ImGui_ImplRoblox is loose + "EnableParallel": "(opts: ImGuiParallelConfig?) -> ()", + "DisableParallel": "() -> ()", "FinishParallel": "() -> ()", "BeginParallelFrame": "() -> ()", + "GetParallelStats": "() -> { [string]: number }", + "GetParallelConfig": "() -> ImGuiParallelConfig", +} + +def impl_type(files): + """ImGui_ImplRoblox: the keys of the backend's public table (ImGui_ImplRoblox = { Name = ..., })""" + src = files.get("imgui_impl_roblox.lua", "") + m = re.search(r"^ImGui_ImplRoblox = \{\n(.*?)^\}", src, re.M | re.S) + keys = re.findall(r"^\s+(\w+)\s*=", m.group(1), re.M) if m else [] + return (["export type ImGuiParallelConfig = { Actors: number?, MinTiles: number?, MinPixels: number?," + " MaxBytesPerPixel: number?, Worker: any, Sync: boolean?, SyncDrop: boolean?, Inline: boolean?," + " [string]: any }", "export type ImGuiImplRoblox = {"] + + [" %s: %s," % (k, IMPL_SIGS.get(k, LOOSE)) for k in keys] + [" [string]: any,", "}"]) + def module_type(enum_names): # the bundle is too large for Luau to infer, so its return value is cast to this explicit type - lines = ["export type ImGuiModule = {", " ImGui: ImGuiAPI,"] + lines = ["export type ImGuiModule = {", " ImGui: ImGuiAPI,", " ImGui_ImplRoblox: ImGuiImplRoblox,"] lines += [" %s: (x: number?, y: number?, z: number?, w: number?) -> %s," % (n, n) for n in ("ImVec2", "ImVec4")] lines += [" %s: %s," % (n, n) for n in sorted(enum_names)] return lines + [" [string]: any,", "}"] diff --git a/tools/test/check_all.sh b/tools/test/check_all.sh index e26c58c..db56fd4 100755 --- a/tools/test/check_all.sh +++ b/tools/test/check_all.sh @@ -4,6 +4,8 @@ # HASHES=1 tools/test/check_all.sh (also prints the draw-data checksums, see hashes.sh) cd "$(dirname "$0")/../.." export PATH="$PATH:/nix/store/2m2ja613nndihc8qm10f2rhq6znp1nh4-luau-0.734/bin:/nix/store/4qxq4arv32ly13kl3g0m5q80gm3a35xr-luajit-2.1.1741730670/bin" +command -v luau >/dev/null || { l=$(ls -d /nix/store/*-luau-*/bin 2>/dev/null | tail -1); [ -n "$l" ] && export PATH="$PATH:$l"; } +command -v luajit >/dev/null || { l=$(ls -d /nix/store/*-luajit-2*/bin 2>/dev/null | grep -v -- -env | tail -1); [ -n "$l" ] && export PATH="$PATH:$l"; } T=$(mktemp -d /tmp/imgui_check.XXXX) R="python3 tools/test/run.py --quiet --roblox --timeout 600" @@ -36,7 +38,12 @@ CHECKS=( "demo_open|DRAWHASH|$R --main tools/test/scripts/t_drawhash.luau --frames 150 --open" "demo_random|^|python3 tools/test/run.py --roblox --timeout 600 --frames 400 --open" "pixels|PIXELS SAME|a=\$($R --main tools/test/scripts/t_pixels.luau --frames 600 | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_pixels.luau --frames 600 | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo PIXELS SAME" +"tile_bound|TILEBOUND OK|$R --main tools/test/scripts/t_tile_bound.luau --frames 200" +"parallel|PARALLEL OK|$R --main tools/test/scripts/t_parallel.luau --frames 500" +"pool_ctx|POOLCTX OK|$R --main tools/test/scripts/t_pool_ctx.luau --frames 60" +"assets_scroll|ASSETS OK|$R --main tools/test/scripts/t_assets_scroll.luau --frames 1010" "shot|wrote|python3 tools/test/shot.py /tmp/imgui_shot.png --app" +"registers|REGS OK|mkdir -p $T/regs && python3 tools/bundle.py $T/regs >/dev/null && h=\"\$(printf 'local _h%d = {} ' \$(seq 20))\" && grep -q \"^__FILES\\['imgui_impl_roblox.lua'\\] = function()\$\" $T/regs/ImGui.luau && for f in $T/regs/*.luau; do { echo \"\$h\"; sed \"/^__FILES\\['imgui_impl_roblox.lua'\\] = function()\$/a \$h\" \$f; } > \$f.h && luau-compile -O0 --null \$f.h || exit 1; done && ! grep -q require $T/regs/ImGuiWorker.client.luau && echo REGS OK" "love|DRAWHASH|python3 tools/bundle.py --target love >/dev/null && luajit tools/test/love/t_drawhash.lua 60 Widgets,Basic && luajit tools/test/love/t_examples.lua" ) diff --git a/tools/test/prof.py b/tools/test/prof.py index 8537774..c8bdf19 100644 --- a/tools/test/prof.py +++ b/tools/test/prof.py @@ -6,7 +6,7 @@ tmp = max(glob.glob("/tmp/imgui_test_*/ImGui.linemap.json"), key=os.path.getmtim lm = json.load(open(tmp)) def loc(n): if not n.isdigit(): return "C" - n = int(n) - 5 + 2; best = None + n = int(n) - 5 + 1; best = None # run.luau header lines, 1 stripped --! line (see run.py) for start, name in lm: if start <= n: best = (start, name) return "%s:%d" % (best[1], n - best[0] + 1) if best else "?" diff --git a/tools/test/roblox_mock.luau b/tools/test/roblox_mock.luau index 9388299..9138da4 100644 --- a/tools/test/roblox_mock.luau +++ b/tools/test/roblox_mock.luau @@ -58,6 +58,8 @@ end }) -- Instances local InstMethods = {} local InstMT = {} +local MOCK = { Sets = 0, Parents = 0, News = 0, EIs = 0, Uploads = 0, UploadPx = 0 } -- engine call counters (global MOCK), for perf benches +MOCK_STATS = MOCK InstMT.__index = function(t, k) if k == "Parent" then return rawget(t, "_parent") end local pv = rawget(t, "_props")[k]; if pv ~= nil then return pv end @@ -67,11 +69,13 @@ InstMT.__index = function(t, k) end InstMT.__newindex = function(t, k, v) if k == "Parent" then + MOCK.Parents += 1 local old = rawget(t, "_parent") if old then local ch = rawget(old, "_children"); for i, c in ipairs(ch) do if c == t then table.remove(ch, i) break end end end rawset(t, "_parent", v) if v then table.insert(rawget(v, "_children"), t) end else + MOCK.Sets += 1 local props = rawget(t, "_props") local old = props[k] props[k] = v @@ -96,6 +100,11 @@ end function InstMethods:WaitForChild(name) return assert(self:FindFirstChild(name), "WaitForChild would hang: " .. name) end function InstMethods:FindFirstChildOfClass(class) for _, c in ipairs(rawget(self, "_children")) do if c.ClassName == class then return c end end end function InstMethods:GetChildren() return table.clone(rawget(self, "_children")) end +function InstMethods:GetDescendants() + local out = {} + for _, c in ipairs(rawget(self, "_children")) do table.insert(out, c); for _, d in ipairs(c:GetDescendants()) do table.insert(out, d) end end + return out +end function InstMethods:IsA(class) if class == "GuiObject" then return self.ClassName == "Frame" or self.ClassName == "ImageLabel" end return self.ClassName == class @@ -124,12 +133,14 @@ local RunService = { Heartbeat = Signal(), Stepped = Signal(), PreAnimation = Si local last_pixels -- last buffer written to an EditableImage local AssetService = {} function AssetService:CreateEditableImage(opts) + MOCK.EIs += 1 local img = { Size = opts.Size, Pixels = buffer.create(opts.Size.X * opts.Size.Y * 4) } UPLOADS = 0 function img:WritePixelsBuffer(origin, size, buf) assert(buffer.len(buf) == size.X * size.Y * 4, "WritePixelsBuffer: buffer size mismatch") assert(origin.X >= 0 and origin.Y >= 0 and origin.X + size.X <= opts.Size.X and origin.Y + size.Y <= opts.Size.Y, "WritePixelsBuffer: out of bounds") for y = 0, size.Y - 1 do buffer.copy(img.Pixels, ((origin.Y + y) * opts.Size.X + origin.X) * 4, buf, y * size.X * 4, size.X * 4) end + MOCK.Uploads += 1; MOCK.UploadPx += size.X * size.Y _G_UPLOADS = (_G_UPLOADS or 0) + 1; _G_UPLOAD_PX = (_G_UPLOAD_PX or 0) + size.X * size.Y end function img:Destroy() end @@ -168,7 +179,7 @@ end ROBLOX = setmetatable({ game = game, workspace = { CurrentCamera = { ViewportSize = v2(SCREEN_W, SCREEN_H) } }, require = rbxrequire, _G = fakeG, - Instance = { new = function(class) return newInst(class) end }, + Instance = { new = function(class) MOCK.News += 1; return newInst(class) end }, Enum = Enum, Vector2 = Vector2, Vector3 = { new = function(x, y, z) return { X = x, Y = y, Z = z } end }, UDim2 = { new = function(...) return { ... } end, fromScale = function(...) return { ... } end, fromOffset = function(x, y) return { X = x, Y = y } end }, diff --git a/tools/test/run.py b/tools/test/run.py index 5d5a35f..1866e97 100644 --- a/tools/test/run.py +++ b/tools/test/run.py @@ -11,7 +11,7 @@ TMP = tempfile.mkdtemp(prefix="imgui_test_") # per process: parallel runs must HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) -LUAU = shutil.which("luau") or "/nix/store/2m2ja613nndihc8qm10f2rhq6znp1nh4-luau-0.734/bin/luau" +LUAU = shutil.which("luau") or (sorted(__import__("glob").glob("/nix/store/*-luau-*/bin/luau")) or ["luau"])[-1] G = "game, workspace, Instance, Enum, Vector2, Vector3, UDim2, Color3, Content, UDim, CFrame, warn, require, script, os" def build_run(args, flags): @@ -25,8 +25,10 @@ def build_run(args, flags): add("ImGui.luau", os.path.join(TMP, "ImGui.luau")) add("main.client.luau", args.main) out.append(open(os.path.join(HERE, "roblox_mock.luau")).read()) - global OFFSET, LAST_LINE - LAST_LINE = open(os.path.join(TMP, "ImGui.luau")).read().count("\n") + global OFFSET, LAST_LINE, STRIPPED + bundle = open(os.path.join(TMP, "ImGui.luau")).read() + LAST_LINE = bundle.count("\n") + STRIPPED = sum(l.startswith("--!") for l in bundle.split("\n")) # removed by add() (all at the top) OFFSET = 5 # lines before the ImGui function body in run.luau (flags/header lines + "function(...)" line) path = os.path.join(TMP, "run.luau") open(path, "w").write("\n".join(out)) @@ -45,8 +47,7 @@ def remap(text): import json, re lm = json.load(open(os.path.join(TMP, "ImGui.linemap.json"))) def sub(m): - n = int(m.group(1)) - OFFSET # line inside build/ImGui.luau (minus its 2 stripped --! lines) - n += 2 + n = int(m.group(1)) - OFFSET + STRIPPED # line inside build/ImGui.luau best = None if n > LAST_LINE: return ":%d" % n for start, name in lm: diff --git a/tools/test/scripts/t_assets_scroll.luau b/tools/test/scripts/t_assets_scroll.luau new file mode 100644 index 0000000..0481fc0 --- /dev/null +++ b/tools/test/scripts/t_assets_scroll.luau @@ -0,0 +1,108 @@ +-- Demo Assets Browser (10000 items) scrolled continuously for ~1000 frames in raster mode: live tiles and +-- EditableImage bytes must stay bounded by what is visible and flat (no growth trend between the 1st and 2nd half). +-- Then (no input) the screen composited from those tiles (many recycled from the free list) must equal the one after +-- rebuilding every tile from scratch: a recycled EditableImage never shows stale pixels. +-- run: python3 tools/test/run.py --main tools/test/scripts/t_assets_scroll.luau --frames 1010 --quiet --roblox +local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui")) +local ImGui, ImVec2 = G.ImGui, G.ImVec2 +local Impl = G.ImGui_ImplRoblox +ImGui.CreateContext() +Impl.Init() +Impl.SetRenderRate(0) +local io = ImGui.GetIO() +local N = 1000 +local frame, open = 0, true +local peak = { { 0, 0, 0 }, { 0, 0, 0 } } -- per half: tiles, EI count, EI bytes +local scroll_min, scroll_max = math.huge, 0 +local W, H = 1280, 760 -- (composite: copied from t_composite.luau) +local function composite(gui) + local screen = buffer.create(W * H * 3) + local function walk(inst, ox, oy, kx0, ky0, kx1, ky1) + local kids = inst:GetChildren() + table.sort(kids, function(a, b) return (a.ZIndex or 1) < (b.ZIndex or 1) end) -- table.sort isn't stable, but siblings with equal ZIndex never overlap here + for _, c in ipairs(kids) do + if c.Visible ~= false then + local x, y = ox + (c.Position and c.Position.X or 0), oy + (c.Position and c.Position.Y or 0) + local cx0, cy0, cx1, cy1 = kx0, ky0, kx1, ky1 + if c.ClipsDescendants then + cx0, cy0 = math.max(cx0, x), math.max(cy0, y) + cx1, cy1 = math.min(cx1, x + c.Size.X), math.min(cy1, y + c.Size.Y) + end + if c.ClassName == "ImageLabel" then + local img = c.ImageContent.Object + local px, sz = img.Pixels, img.Size.X + for ty = 0, sz - 1 do + local sy = y + ty + if sy >= ky0 and sy < ky1 then + for tx = 0, sz - 1 do + local sx = x + tx + if sx >= kx0 and sx < kx1 then + local o = (ty * sz + tx) * 4 + local a = buffer.readu8(px, o + 3) + if a > 0 then + local d = (sy * W + sx) * 3 + local fa = a / 255 + for ch = 0, 2 do + local v = buffer.readu8(px, o + ch) * fa + buffer.readu8(screen, d + ch) * (1 - fa) + buffer.writeu8(screen, d + ch, math.floor(v + 0.5)) + end + end + end + end + end + end + end + walk(c, x, y, cx0, cy0, cx1, cy1) + end + end + end + walk(gui, 0, 0, 0, 0, W, H) + return screen +end +local before + +game:GetService("RunService").Stepped:Connect(function() + frame += 1 + if frame > N + 10 then return end + Impl.NewFrame() + io.DeltaTime = 1 / 60 + ImGui.NewFrame() + ImGui.SetNextWindowPos(ImVec2(20, 20), G.ImGuiCond.Always) + open = G.ShowExampleAppAssetsBrowser(open) + local w = ImGui.FindWindowByName("Example: Assets Browser") + if w and frame > 2 and frame <= N then + io:AddMousePosEvent(w.Pos.x + w.Size.x / 2, w.Pos.y + w.Size.y / 2) + io:AddMouseWheelEvent(0, (frame % 400 < 250) and -2 or 3) -- down, then back up: continuous, both directions + end + ImGui.Render() + Impl.RenderDrawData(ImGui.GetDrawData()) + local s + if Impl.GetStats then s = Impl.GetStats() else -- (older backends, for before/after numbers: 1 EditableImage per tile) + local n = 0 + for _, d in ipairs(game:GetService("Players").LocalPlayer.PlayerGui:GetDescendants()) do if d.ClassName == "ImageLabel" and d.Name:sub(1, 4) == "Tile" then n += 1 end end + s = { Tiles = n, EditableImages = n, EditableImageBytes = n * 65536, EditableImageCap = math.huge } + end + assert(s.EditableImageBytes <= s.EditableImageCap) + for _, c in ipairs(w and w.DC.ChildWindows.Data or {}) do scroll_min = math.min(scroll_min, c.Scroll.y); scroll_max = math.max(scroll_max, c.Scroll.y) end + if frame > 50 then + local p = peak[frame <= 525 and 1 or 2] + p[1], p[2], p[3] = math.max(p[1], s.Tiles), math.max(p[2], s.EditableImages), math.max(p[3], s.EditableImageBytes) + end + if frame == N then + print(("ASSETS scrolled %d..%d px; peak tiles %d / %d, EditableImages %d / %d, EI bytes %d / %d (1st / 2nd half); now %d tiles"):format( + scroll_min, scroll_max, peak[1][1], peak[2][1], peak[1][2], peak[2][2], peak[1][3], peak[2][3], s.Tiles)) + assert(scroll_max - scroll_min > 5000, "assets browser did not scroll") + -- the whole demo-sized screen is ~ 10 x 6 tiles per layer; content + chrome + spares + free list stay well below 150 + assert(peak[1][1] <= 150 and peak[2][1] <= 150, "tile count not bounded by what is visible") + assert(peak[2][2] <= peak[1][2] + 4 and peak[2][3] <= peak[1][3] + 4 * 128 * 128 * 4, "EditableImage use grows over time") + end + if frame == N + 8 then + before = buffer.tostring(composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui"))) + Impl.SetRenderScale(2); Impl.SetRenderScale(1) -- (drops every tile: the next frame redraws all of them) + elseif frame == N + 9 then + local after = buffer.tostring(composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui"))) + assert(#before:gsub("%z", "") > 10000, "nothing composited") + assert(before == after, "recycled tiles show different pixels than freshly drawn ones") + print("ASSETS OK") + end +end) diff --git a/tools/test/scripts/t_parallel.luau b/tools/test/scripts/t_parallel.luau new file mode 100644 index 0000000..dd01873 --- /dev/null +++ b/tools/test/scripts/t_parallel.luau @@ -0,0 +1,171 @@ +-- Parallel raster executor (ImGui_ImplRoblox.EnableParallel) vs the inline backend, pixel for pixel. Two contexts draw the same +-- benchmark scenarios every frame: A inline (Config.Inline), B through the executor in Sync mode (the mock has no Actors: the "workers" +-- run inline, same code). Frames cycle through: dispatch window open (batches pending until Finish, like +-- PreSimulation -> PostSimulation), open with SyncDrop (half the worker results lost -> Finish falls back), and closed +-- (late RenderDrawData: rasterized + uploaded at once). The composites of A and B must match at every checkpoint. +-- Prints the executor's main-thread pack cost per frame next to A's inline raster + upload cost. +-- run: python3 tools/test/run.py --main tools/test/scripts/t_parallel.luau --frames 900 --quiet --roblox +local RS = game:GetService("ReplicatedStorage") +local G = require(RS:WaitForChild("ImGui")) +local ImGui, ImVec2 = G.ImGui, G.ImVec2 +local Impl = G.ImGui_ImplRoblox +local W, H = 1280, 760 +local N = ARG_N or 120 -- frames per scenario + +local function composite(gui) + local screen = buffer.create(W * H * 3) + local function walk(inst, ox, oy, kx0, ky0, kx1, ky1) + local kids = inst:GetChildren() + table.sort(kids, function(a, b) return (a.ZIndex or 1) < (b.ZIndex or 1) end) + for _, c in ipairs(kids) do + if c.Visible ~= false then + local x, y = ox + (c.Position and c.Position.X or 0), oy + (c.Position and c.Position.Y or 0) + local cx0, cy0, cx1, cy1 = kx0, ky0, kx1, ky1 + if c.ClipsDescendants then + cx0, cy0 = math.max(cx0, x), math.max(cy0, y) + cx1, cy1 = math.min(cx1, x + c.Size.X), math.min(cy1, y + c.Size.Y) + end + if c.ClassName == "ImageLabel" then + local px, sz = c.ImageContent.Object.Pixels, c.ImageContent.Object.Size.X + for ty = math.max(0, cy0 - y), math.min(sz, cy1 - y) - 1 do + local sy = y + ty + for tx = math.max(0, cx0 - x), math.min(sz, cx1 - x) - 1 do + local o = (ty * sz + tx) * 4 + local a = buffer.readu8(px, o + 3) + if a > 0 then + local d = (sy * W + x + tx) * 3 + local fa = a / 255 + for ch = 0, 2 do + buffer.writeu8(screen, d + ch, math.floor(buffer.readu8(px, o + ch) * fa + buffer.readu8(screen, d + ch) * (1 - fa) + 0.5)) + end + end + end + end + end + walk(c, x, y, cx0, cy0, cx1, cy1) + end + end + end + walk(gui, 0, 0, 0, 0, W, H) + local h = 0 + for i = 0, W * H * 3 - 4, 4 do h = (h * 31 + buffer.readu32(screen, i)) % 2147483647 end + return h +end + +local plot = table.create(120, 0) +local SCEN = { + { "resize", function(f) + local s = 520 + ((f % 80) < 40 and (f % 40) * 7 or (40 - f % 40) * 7) + ImGui.ShowDemoWindow() + ImGui.SetWindowPos("Dear ImGui Demo", ImVec2(30, 20)); ImGui.SetWindowSize("Dear ImGui Demo", ImVec2(s, s * 0.8 + 60)) + end }, + { "assets", function(f) + ImGui.SetNextWindowPos(ImVec2(20, 20), G.ImGuiCond.Always) + G.ShowExampleAppAssetsBrowser(true) + local w = ImGui.FindWindowByName("Example: Assets Browser") + if w and f > 2 then for _, c in ipairs(w.DC.ChildWindows.Data) do ImGui.SetScrollY(c, (f * 40) % 6000) end end + end }, + { "list", function(f) + ImGui.SetNextWindowPos(ImVec2(40, 30), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(560, 680), G.ImGuiCond.Always) + ImGui.Begin("Long list") + ImGui.SetScrollY(13 * (f <= 60 and f or 120 - f)) + local clipper = G.ImGuiListClipper() + clipper:Begin(10000) + while clipper:Step() do + for i = clipper.DisplayStart, clipper.DisplayEnd - 1 do ImGui.Text("%05d: The quick brown fox jumps over the lazy dog", i) end + end + ImGui.End() + end }, + { "plots", function(f) + for i = 1, 120 do plot[i] = math.sin((i + f) * 0.15) + 0.3 * math.sin((i * 3 + f) * 0.4) end + ImGui.SetNextWindowPos(ImVec2(40, 30), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(620, 520), G.ImGuiCond.Always) + ImGui.Begin("Plots") + ImGui.PlotLines("Lines", plot, nil, 120, 0, nil, -1.5, 1.5, ImVec2(0, 160)) + ImGui.PlotHistogram("Histogram", plot, nil, 120, 0, nil, -1.5, 1.5, ImVec2(0, 160)) + ImGui.Text("frame %d", f) + ImGui.End() + end }, +} + +local ctx, gui = {}, {} +for i = 1, 2 do + ctx[i] = ImGui.CreateContext() + ImGui.SetCurrentContext(ctx[i]) + local parent = Instance.new("Folder") + Impl.Init(parent) + Impl.SetRenderRate(0) + Impl.SetStageTiming(true) + gui[i] = parent:FindFirstChild("ImGui") +end +Impl.EnableParallel({ Sync = true, Actors = 4 }) +local C = Impl.GetParallelConfig() + +local si, f, checks, bad = 1, 0, 0, 0 +local pack, inline, flushes = {}, {}, { open = 0, drop = 0, closed = 0 } +local S = Impl.GetParallelStats() +local s0 = table.clone(S) +local kb = { 0, 0 } -- KB allocated in RenderDrawData (+ Finish for the executor context), per context +local function k_add(i, k0) local d = collectgarbage("count") - k0; if f > 5 and d > 0 then kb[i] += d end end +game:GetService("RunService").Stepped:Connect(function() + local sc = SCEN[si] + if not sc then return end + f += 1 + local mode = f % 3 -- 0 closed, 1 open, 2 open + SyncDrop + C.SyncDrop = mode == 2 + if mode ~= 0 then Impl.BeginParallelFrame() end + flushes[mode == 0 and "closed" or mode == 1 and "open" or "drop"] += 1 + for i = 1, 2 do + ImGui.SetCurrentContext(ctx[i]) + C.Inline = i == 1 + Impl.NewFrame() + local io = ImGui.GetIO() + io.DeltaTime = 1 / 60 + io:AddMousePosEvent(1270, 750) + ImGui.NewFrame() + sc[2](f) + ImGui.Render() + local fake = os.clock + os.clock = os.realclock -- (mock: os.clock is frozen; real time for the stage / pack timers) + local p0, k0 = S.Pack, collectgarbage("count") + Impl.RenderDrawData(ImGui.GetDrawData()) + k_add(i, k0) + os.clock = fake + if f > 5 then + if i == 1 then local st = Impl.GetStats().Frame; table.insert(inline, (st.Raster + st.Upload) * 1000) + else table.insert(pack, (S.Pack - p0) * 1000) end + end + end + local k0 = collectgarbage("count") + Impl.FinishParallel() + k_add(2, k0) + if f % 10 == 0 or f == N then + checks += 1 + local a, b = composite(gui[1]), composite(gui[2]) + if a ~= b then bad += 1; print("MISMATCH", sc[1], f, a, b) end + end + if f == N then + local function stats(t) + local s, m = 0, 0 + for _, v in t do s += v; m = math.max(m, v) end + return s / math.max(#t, 1), m + end + local pm, px = stats(pack) + local im, ix = stats(inline) + print(string.format("PACK %-7s mean %.3f max %.3f ms/frame | inline raster+upload mean %.3f max %.3f ms/frame | tiles %.1f rects %.1f send %d KB/frame, tex resends %d (%d KB)", + sc[1], pm, px, im, ix, (S.Tiles - s0.Tiles) / N, (S.Rects - s0.Rects) / N, (S.SendBytes - s0.SendBytes) / 1024 / N, S.TexSends - s0.TexSends, (S.TexBytes - s0.TexBytes) / 1024)) + print(string.format("ALLOC %-7s KB/frame inline %.1f executor %.1f (Sync: includes the inline worker raster)", sc[1], kb[1] / (N - 5), kb[2] / (N - 5))) + kb = { 0, 0 } + s0 = table.clone(S) + pack, inline = {}, {} + for i = 1, 2 do ImGui.SetCurrentContext(ctx[i]); Impl.SetRenderScale(2); Impl.SetRenderScale(1) end + si += 1; f = 0 + Impl.EnableParallel({ Actors = si }) -- runtime re-Enable with a different actor count (pixels must still match) + assert(C.Sync and Impl.GetParallelConfig() == C, "re-Enable kept Sync") + if not SCEN[si] then + print(string.format("STATS parallel flushes %d serial %d tiles %d fallbacks %d | frames open %d drop %d closed %d", + S.ParallelFlushes, S.SerialFlushes, S.Tiles, S.Fallbacks, flushes.open, flushes.drop, flushes.closed)) + assert(S.ParallelFlushes > 0 and S.SerialFlushes > 0 and S.Fallbacks > 0, "a path was not exercised") + if bad == 0 then print("PARALLEL OK " .. checks .. " checkpoints") else print("PARALLEL FAIL " .. bad .. "/" .. checks) end + end + end +end) diff --git a/tools/test/scripts/t_pool_ctx.luau b/tools/test/scripts/t_pool_ctx.luau new file mode 100644 index 0000000..82e3f79 --- /dev/null +++ b/tools/test/scripts/t_pool_ctx.luau @@ -0,0 +1,32 @@ +-- Two contexts sharing one font atlas (one backend module): new glyphs baked while B is current used to hit +-- UpdateTexture's assert (per-context texture tables). Textures are now module-wide. +-- run: python3 tools/test/run.py --main tools/test/scripts/t_pool_ctx.luau --frames 60 --quiet --roblox +local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui")) +local ImGui, ImVec2 = G.ImGui, G.ImVec2 +local Impl = G.ImGui_ImplRoblox +local a = ImGui.CreateContext(); ImGui.SetCurrentContext(a); Impl.Init(); Impl.SetRenderRate(0) +local b = ImGui.CreateContext(ImGui.GetIO().Fonts); ImGui.SetCurrentContext(b); Impl.Init(); Impl.SetRenderRate(0) + +local function frame(ctx, body) + ImGui.SetCurrentContext(ctx) + Impl.NewFrame(); ImGui.GetIO().DeltaTime = 1 / 60 + ImGui.NewFrame() + ImGui.SetNextWindowPos(ImVec2(10, 10), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(900, 700), G.ImGuiCond.Always) + ImGui.Begin("W"); body(); ImGui.End() + ImGui.Render(); Impl.RenderDrawData(ImGui.GetDrawData()) +end + +local n = 0 +game:GetService("RunService").Stepped:Connect(function() + n += 1 + if n > 60 then return end + frame(a, function() ImGui.Text("context A"); if n == 20 then ImGui.PushFont(nil, 33); ImGui.Text("Glyphs baked under A"); ImGui.PopFont() end end) + frame(b, function() + if n == 5 then ImGui.PushFont(nil, 41); ImGui.Text("Big glyphs baked under B"); ImGui.PopFont() end + ImGui.Text("context B") + end) + if n == 60 then + assert(Impl.GetStats().Tiles > 0) + print("POOLCTX OK") + end +end) diff --git a/tools/test/scripts/t_tile_bound.luau b/tools/test/scripts/t_tile_bound.luau new file mode 100644 index 0000000..b8a4b51 --- /dev/null +++ b/tools/test/scripts/t_tile_bound.luau @@ -0,0 +1,49 @@ +-- Scrolling a long child window must not leak tiles: scrolled-away tiles are freed (recycled), so the live tile count +-- stays bounded by what is on screen. Then with a tiny EditableImage cap (SetEditableImageCap): tiles that don't fit +-- are skipped (GetTile -> nil, no assert) and the budget is never exceeded. +-- run: python3 tools/test/run.py --main tools/test/scripts/t_tile_bound.luau --frames 200 --quiet --roblox +local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui")) +local ImGui, ImVec2 = G.ImGui, G.ImVec2 +local Impl = G.ImGui_ImplRoblox +ImGui.CreateContext() +Impl.Init() +Impl.SetRenderRate(0) +local io = ImGui.GetIO() +local P = 100 -- frames per phase +local frame, peak = 0, 0 +local TILE_BYTES = 128 * 128 * 4 + +game:GetService("RunService").Stepped:Connect(function() + frame += 1 + if frame > 2 * P then return end + local t = (frame - 1) % P + 1 + if frame == P + 1 then Impl.SetEditableImageCap(10 * TILE_BYTES); Impl.SetRenderScale(2) end -- (rebuild: shown tiles are never evicted) + Impl.NewFrame() + io.DeltaTime = 1 / 60 + ImGui.NewFrame() + ImGui.SetNextWindowPos(ImVec2(20, 20), G.ImGuiCond.Always) + ImGui.SetNextWindowSize(ImVec2(400, 400), G.ImGuiCond.Always) + ImGui.Begin("Scroll") + ImGui.BeginChild("long", ImVec2(0, 0), G.ImGuiChildFlags.Borders) + for i = 1, 3000 do ImGui.Text("row %d some text to fill the tile width ........", i) end + ImGui.SetScrollY(t * 300) -- ~30k px per phase: hundreds of distinct tiles if never freed + ImGui.EndChild() + ImGui.End() + ImGui.Render() + Impl.RenderDrawData(ImGui.GetDrawData()) + local s = Impl.GetStats() + if frame <= P or t > 1 then assert(s.EditableImageBytes <= s.EditableImageCap, "over the EditableImage budget") end -- (the free list drains on the next create) + assert(s.EditableImages >= s.Tiles) + if frame <= P and t > 20 then peak = math.max(peak, s.Tiles) end + if frame == P then + print(("raster: peak tiles %d, now %d tiles, %d EditableImages, %d Instances"):format(peak, s.Tiles, s.EditableImages, s.Instances)) + -- a 400x400 window covers ~4x4 tiles per layer (+1 row/col when unaligned) + a few spares + assert(peak <= 60, "tile count not bounded by what is on screen") + end + if frame == 2 * P then + print(("capped: %d tiles, %d EditableImages, %d / %d bytes"):format(s.Tiles, s.EditableImages, s.EditableImageBytes, s.EditableImageCap)) + assert(s.EditableImages <= 10) + Impl.SetEditableImageCap(nil) + print("TILEBOUND OK") + end +end) diff --git a/tools/test/undefined.py b/tools/test/undefined.py index 86a876c..3cdd5f0 100644 --- a/tools/test/undefined.py +++ b/tools/test/undefined.py @@ -4,11 +4,12 @@ """ import os, re, collections ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -SRC = ROOT # library *.lua at the root + backends/ (--no-demo: leave imgui_demo.lua out to check the library never needs it) +SRC = ROOT # library *.lua at the root + backends/roblox, backends/love (--no-demo: leave imgui_demo.lua out to check the library never needs it) import sys NO_DEMO = "--no-demo" in sys.argv files = {} -for dp, fn in ((ROOT, os.listdir(ROOT)), (os.path.join(ROOT, "backends"), os.listdir(os.path.join(ROOT, "backends")))): +for dp in (ROOT, os.path.join(ROOT, "backends", "roblox"), os.path.join(ROOT, "backends", "love")): + fn = os.listdir(dp) for f in fn: if f.endswith(".lua") and not (NO_DEMO and f == "imgui_demo.lua"): files[os.path.relpath(os.path.join(dp, f), SRC)] = open(os.path.join(dp, f)).read() diff --git a/wally.toml b/wally.toml index 3673734..15634fd 100644 --- a/wally.toml +++ b/wally.toml @@ -1,6 +1,6 @@ [package] name = "4dbug/imgui-luau" -version = "0.3.0" +version = "0.4.0" registry = "https://github.com/UpliftGames/wally-index" realm = "shared" license = "MIT"