From 0f81d4bb1829056901c52de642d455c0e68c3d04 Mon Sep 17 00:00:00 2001 From: 4DBug <4DBug@github.com> Date: Sat, 17 Oct 2026 13:18:53 -0500 Subject: [PATCH] 0.4.2 - Less garbage per frame: scalar text/label sizes, scratch rects/points, reused clip-stack ImVec4 and window stack entries (160 -> 56 KB/frame on demo+stress, draw hashes unchanged) - Faster glyph baking: @native rasterizer/rect packer/pixel loops, glyph shape cache, comparator-free edge sort, inline scanline conversion, table.create zero-fill; fix leaked global 'step' - Textures: new atlases convert only the packed corner, flat row conversion skipping zero pixels - Raster: uniform-region tracking, direct opaque glyph texels, inlined BlendPixel with per-texel cache - Raster: textured line quads drawn as one quad, u32 texel reads for constant-colour triangles, column walk for tall narrow triangles (plot bench Raster 4.16 -> 3.21 ms, HashVertex 0.64 -> 0.55 ms, pixels unchanged) - Parallel: send Actors only changed atlas rows / rows above FillRow (full-copy 1283 -> 619 MB on fontbench x4 Actors); dispatch small and text-heavy frames (MinTiles 1, MinPixels 2048, MaxBytesPerPixel 0) - Stage timing: Textures and Flush stages; parallel stats explain serial flushes - extensions/: submodules for imcurveedit-luau, imgradient-luau, imgui-memory-editor-luau, imsequencer-luau; all 9 submodule URLs and README links now on GitHub - new examples: example_love_extensions, example_roblox_extensions --- .github/README.md | 20 +- .gitmodules | 22 +- README.md | 20 +- backends/roblox/parallel.lua | 60 +- backends/roblox/raster.lua | 360 +++++- backends/roblox/render.lua | 38 +- backends/roblox/textures.lua | 54 +- backends/roblox/worker.luau | 23 +- build/ImGui.linemap.json | 2 +- build/ImGui.luau | 1013 ++++++++++++++--- build/ImGuiTyped.luau | 1 + build/ImGuiWorker.client.luau | 383 ++++++- build/imgui_love.linemap.json | 2 +- build/imgui_love.lua | 503 ++++++-- examples/example_love_extensions/conf.lua | 5 + examples/example_love_extensions/main.lua | 619 ++++++++++ .../main.client.luau | 656 +++++++++++ extensions/imcurveedit-luau | 1 + extensions/imgradient-luau | 1 + extensions/imgui-memory-editor-luau | 1 + extensions/imguicolortextedit-luau | 2 +- extensions/imguizmo-luau | 2 +- extensions/imnodes-luau | 2 +- extensions/implot-luau | 2 +- extensions/implot3d-luau | 2 +- extensions/imsequencer-luau | 1 + imgui.lua | 122 +- imgui_draw.lua | 67 +- imgui_internal.lua | 4 +- imgui_widgets.lua | 106 +- imstb_rectpack.lua | 13 + imstb_truetype.lua | 187 ++- wally.toml | 2 +- 33 files changed, 3814 insertions(+), 482 deletions(-) create mode 100644 examples/example_love_extensions/conf.lua create mode 100644 examples/example_love_extensions/main.lua create mode 100644 examples/example_roblox_extensions/main.client.luau create mode 160000 extensions/imcurveedit-luau create mode 160000 extensions/imgradient-luau create mode 160000 extensions/imgui-memory-editor-luau create mode 160000 extensions/imsequencer-luau diff --git a/.github/README.md b/.github/README.md index cb7f765..fa2f5e4 100644 --- a/.github/README.md +++ b/.github/README.md @@ -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.4.1"` 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.2"` 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`. @@ -184,7 +184,7 @@ Rojo layout (as in [`default.project.json`](/default.project.json)): ``` ```lua -ImGui_ImplRoblox.EnableParallel({ Actors = 4 }) -- also: MinTiles = 4, MinPixels = 16384, MaxBytesPerPixel = 3, Worker +ImGui_ImplRoblox.EnableParallel({ Actors = 4 }) -- also: MinTiles = 1, MinPixels = 2048, MaxBytesPerPixel = 0, Worker RunService.PreSimulation:Connect(function() -- NOT RenderStepped (see below) ImGui_ImplRoblox.NewFrame() @@ -198,7 +198,7 @@ end) ``` **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. +- 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, `0` = no limit, the default: measured in Studio, packing text-heavy frames costs under 0.1 ms) 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()`). @@ -316,11 +316,15 @@ See [docs/PORTING.md](/docs/PORTING.md) for the porting rules. Separate repos, included as submodules under `extensions/` (clone with `--recursive`): -- [imguicolortextedit-luau](https://git.bug.tools/bug/imguicolortextedit-luau): [ImGuiColorTextEdit](https://github.com/goossens/ImGuiColorTextEdit) (goossens fork), a syntax-highlighting text editor. -- [imguizmo-luau](https://git.bug.tools/bug/imguizmo-luau): [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo), 3D gizmos with Roblox Camera/CFrame helpers. -- [implot-luau](https://git.bug.tools/bug/implot-luau): [ImPlot](https://github.com/epezent/implot), 2D plotting. -- [implot3d-luau](https://git.bug.tools/bug/implot3d-luau): [ImPlot3D](https://github.com/brenocq/implot3d), 3D plotting. -- [imnodes-luau](https://git.bug.tools/bug/imnodes-luau): [imnodes](https://github.com/Nelarius/imnodes), a node editor. +- [imcurveedit-luau](https://github.com/4DBug/imcurveedit-luau): ImCurveEdit (from [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo)), a curve editor. +- [imgradient-luau](https://github.com/4DBug/imgradient-luau): ImGradient (from [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo)), a gradient editor. +- [imguicolortextedit-luau](https://github.com/4DBug/imguicolortextedit-luau): [ImGuiColorTextEdit](https://github.com/goossens/ImGuiColorTextEdit) (goossens fork), a syntax-highlighting text editor. +- [imguizmo-luau](https://github.com/4DBug/imguizmo-luau): [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo), 3D gizmos with Roblox Camera/CFrame helpers. +- [imgui-memory-editor-luau](https://github.com/4DBug/imgui-memory-editor-luau): [imgui_memory_editor](https://github.com/ocornut/imgui_club) (imgui_club), a hex editor for Roblox `buffer`s, LÖVE `ByteData` and byte tables. +- [implot-luau](https://github.com/4DBug/implot-luau): [ImPlot](https://github.com/epezent/implot), 2D plotting. +- [implot3d-luau](https://github.com/4DBug/implot3d-luau): [ImPlot3D](https://github.com/brenocq/implot3d), 3D plotting. +- [imnodes-luau](https://github.com/4DBug/imnodes-luau): [imnodes](https://github.com/Nelarius/imnodes), a node editor. +- [imsequencer-luau](https://github.com/4DBug/imsequencer-luau): ImSequencer (from [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo)), a timeline/sequencer. Usage: `local ImPlot = require(ImPlotModule)(require(ImGuiModule))`. diff --git a/.gitmodules b/.gitmodules index 07bd0db..cbbe7a8 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,15 +1,27 @@ [submodule "extensions/imguicolortextedit-luau"] path = extensions/imguicolortextedit-luau - url = https://git.bug.tools/bug/imguicolortextedit-luau.git + url = https://github.com/4DBug/imguicolortextedit-luau.git [submodule "extensions/imguizmo-luau"] path = extensions/imguizmo-luau - url = https://git.bug.tools/bug/imguizmo-luau.git + url = https://github.com/4DBug/imguizmo-luau.git [submodule "extensions/implot-luau"] path = extensions/implot-luau - url = https://git.bug.tools/bug/implot-luau.git + url = https://github.com/4DBug/implot-luau.git [submodule "extensions/imnodes-luau"] path = extensions/imnodes-luau - url = https://git.bug.tools/bug/imnodes-luau.git + url = https://github.com/4DBug/imnodes-luau.git [submodule "extensions/implot3d-luau"] path = extensions/implot3d-luau - url = https://git.bug.tools/bug/implot3d-luau.git + url = https://github.com/4DBug/implot3d-luau.git +[submodule "extensions/imcurveedit-luau"] + path = extensions/imcurveedit-luau + url = https://github.com/4DBug/imcurveedit-luau.git +[submodule "extensions/imgradient-luau"] + path = extensions/imgradient-luau + url = https://github.com/4DBug/imgradient-luau.git +[submodule "extensions/imgui-memory-editor-luau"] + path = extensions/imgui-memory-editor-luau + url = https://github.com/4DBug/imgui-memory-editor-luau.git +[submodule "extensions/imsequencer-luau"] + path = extensions/imsequencer-luau + url = https://github.com/4DBug/imsequencer-luau.git diff --git a/README.md b/README.md index 954b4f1..9783bb1 100644 --- a/README.md +++ b/README.md @@ -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.4.1"` 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.2"` 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`. @@ -181,7 +181,7 @@ Rojo layout (as in [`default.project.json`](default.project.json)): ``` ```lua -ImGui_ImplRoblox.EnableParallel({ Actors = 4 }) -- also: MinTiles = 4, MinPixels = 16384, MaxBytesPerPixel = 3, Worker +ImGui_ImplRoblox.EnableParallel({ Actors = 4 }) -- also: MinTiles = 1, MinPixels = 2048, MaxBytesPerPixel = 0, Worker RunService.PreSimulation:Connect(function() -- NOT RenderStepped (see below) ImGui_ImplRoblox.NewFrame() @@ -195,7 +195,7 @@ end) ``` **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. +- 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, `0` = no limit, the default: measured in Studio, packing text-heavy frames costs under 0.1 ms) 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()`). @@ -313,11 +313,15 @@ See [docs/PORTING.md](docs/PORTING.md) for the porting rules. Separate repos, included as submodules under `extensions/` (clone with `--recursive`): -- [imguicolortextedit-luau](https://git.bug.tools/bug/imguicolortextedit-luau): [ImGuiColorTextEdit](https://github.com/goossens/ImGuiColorTextEdit) (goossens fork), a syntax-highlighting text editor. -- [imguizmo-luau](https://git.bug.tools/bug/imguizmo-luau): [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo), 3D gizmos with Roblox Camera/CFrame helpers. -- [implot-luau](https://git.bug.tools/bug/implot-luau): [ImPlot](https://github.com/epezent/implot), 2D plotting. -- [implot3d-luau](https://git.bug.tools/bug/implot3d-luau): [ImPlot3D](https://github.com/brenocq/implot3d), 3D plotting. -- [imnodes-luau](https://git.bug.tools/bug/imnodes-luau): [imnodes](https://github.com/Nelarius/imnodes), a node editor. +- [imcurveedit-luau](https://github.com/4DBug/imcurveedit-luau): ImCurveEdit (from [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo)), a curve editor. +- [imgradient-luau](https://github.com/4DBug/imgradient-luau): ImGradient (from [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo)), a gradient editor. +- [imguicolortextedit-luau](https://github.com/4DBug/imguicolortextedit-luau): [ImGuiColorTextEdit](https://github.com/goossens/ImGuiColorTextEdit) (goossens fork), a syntax-highlighting text editor. +- [imguizmo-luau](https://github.com/4DBug/imguizmo-luau): [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo), 3D gizmos with Roblox Camera/CFrame helpers. +- [imgui-memory-editor-luau](https://github.com/4DBug/imgui-memory-editor-luau): [imgui_memory_editor](https://github.com/ocornut/imgui_club) (imgui_club), a hex editor for Roblox `buffer`s, LÖVE `ByteData` and byte tables. +- [implot-luau](https://github.com/4DBug/implot-luau): [ImPlot](https://github.com/epezent/implot), 2D plotting. +- [implot3d-luau](https://github.com/4DBug/implot3d-luau): [ImPlot3D](https://github.com/brenocq/implot3d), 3D plotting. +- [imnodes-luau](https://github.com/4DBug/imnodes-luau): [imnodes](https://github.com/Nelarius/imnodes), a node editor. +- [imsequencer-luau](https://github.com/4DBug/imsequencer-luau): ImSequencer (from [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo)), a timeline/sequencer. Usage: `local ImPlot = require(ImPlotModule)(require(ImGuiModule))`. diff --git a/backends/roblox/parallel.lua b/backends/roblox/parallel.lua index e28a349..8c37c1f 100644 --- a/backends/roblox/parallel.lua +++ b/backends/roblox/parallel.lua @@ -17,15 +17,18 @@ 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 +local VTX, REC, REC_A, REC_B, REC_C, REC_D, JOB = Raster.VTX, Raster.REC, Raster.REC_A, Raster.REC_B, Raster.REC_C, + Raster.REC_D, 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, +M.Config = { Actors = 4, MinTiles = 1, MinPixels = 2048, MaxBytesPerPixel = 0, 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, + -- why a flush stayed serial: dispatch window closed / Actors not ready / below MinTiles or MinPixels / over MaxBytesPerPixel + SerialClosed = 0, SerialNotReady = 0, SerialSmall = 0, SerialBytes = 0, } local Stats = M.Stats @@ -160,9 +163,10 @@ function M.Tile(img, list, count: number, x0: number, y0: number, tox: number, t 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 + if not d or gk == 3 then copy(P, pn + REC_B, vb, PrimB[p], VTX) end + if gk == 3 then copy(P, pn + REC_D, vb, d, VTX) end pn += REC end writei32(T, to, poff[p]) @@ -232,6 +236,21 @@ function M.Finish() Stats.Finish += os.clock() - t0 end +-- A whole texture for an Actor without a copy (new id: grow/repack): only the rows above FillRow, the Actor fills the +-- rest with Fill (a new atlas is mostly empty). Built once per version, shared by every Actor's SendMessage. +local function fullCopy(rec, v: number): buffer + if rec.HeadV ~= v then + local src, len = rec.Buffer, (rec.FillRow or rec.Height) * rec.Width * 4 + local head = src + if len < buffer.len(src) then + head = buffer.create(len) + copy(head, 0, src, 0, len) + end + rec.Head, rec.HeadV = head, v + end + return rec.Head +end + function M.Flush() local n = jobs.N if n == 0 then @@ -249,6 +268,11 @@ function M.Flush() bytes += Pn[a] + Tn[a] end par = bytes <= cfg.MaxBytesPerPixel * jobs.Px + if not par then Stats.SerialBytes += 1 end + elseif not par then + if not open then Stats.SerialClosed += 1 + elseif not (cfg.Sync or ready) then Stats.SerialNotReady += 1 + else Stats.SerialSmall += 1 end end batch_no += 1 local b = jobs @@ -272,14 +296,38 @@ function M.Flush() 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 + local had = s[rec] + if had ~= v then if tex == NO_TEX then tex = {} end s[rec] = v - tex[#tex + 1] = { id, rec.Buffer, rec.Width, rec.Height } + -- the Actor has version `had`: send only the rows changed since then when the log covers them + local y0, y1, log = math.huge, -1, rec.Log + if had and log then + for k = had + 1, v do + local e = log[k] + if not e then y0 = nil; break end + if e[2] > e[1] then + if e[1] < y0 then y0 = e[1] end + if e[2] > y1 then y1 = e[2] end + end + end + else + y0 = nil + end + if y0 == nil then + local buf = fullCopy(rec, v) + tex[#tex + 1] = { id, buf, rec.Width, rec.Height, rec.Fill or 0 } + Stats.TexBytes += buffer.len(buf) + elseif y1 > y0 then + local row = rec.Width * 4 + local patch = buffer.create((y1 - y0) * row) + copy(patch, 0, rec.Buffer, y0 * row, (y1 - y0) * row) + tex[#tex + 1] = { id, false, rec.Width, rec.Height, y0 * row, patch } + Stats.TexBytes += buffer.len(patch) + end Stats.TexSends += 1 - Stats.TexBytes += buffer.len(rec.Buffer) end end Stats.SendBytes += Pn[a] + tl diff --git a/backends/roblox/raster.lua b/backends/roblox/raster.lua index 7e36707..1d3acca 100644 --- a/backends/roblox/raster.lua +++ b/backends/roblox/raster.lua @@ -9,11 +9,11 @@ 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. + -- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2, 4 line quad), 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, d at REC_D. -- 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, + VTX = 36, REC = 184, REC_A = 40, REC_C = 76, REC_B = 112, REC_D = 148, JOB = 32, } local TILE = M.TILE @@ -40,6 +40,31 @@ local function RowRepeats(o: number, len: number, has_prev: boolean): boolean end local RectColumns = table.create(256, 0) +-- Uniform region: [UX0, UX1) x [UY0, UY1) of the target holds only the pixel value UV (empty when UX0 >= UX1). +-- Set by ClearRect and by solid rects; shrunk by everything drawn over it. A solid rect inside it blends one pixel and +-- fills (window/frame backgrounds over backgrounds), instead of blending every pixel. +local UX0, UY0, UX1, UY1, UV = 0, 0, 0, 0, 0 + +-- Drawing may change [x0, x1) x [y0, y1): keep the largest uniform piece outside it +@native +local function Shrink(x0: number, y0: number, x1: number, y1: number) + if x0 >= UX1 or x1 <= UX0 or y0 >= UY1 or y1 <= UY0 or UX0 >= UX1 then return end + local h, w = UY1 - UY0, UX1 - UX0 + local left, right, top, bottom = (x0 - UX0) * h, (UX1 - x1) * h, (y0 - UY0) * w, (UY1 - y1) * w + local best = max(left, right, top, bottom) + if best <= 0 then + UX1 = UX0 + elseif best == left then + UX1 = x0 + elseif best == right then + UX0 = x1 + elseif best == top then + UY1 = y0 + else + UY0 = y1 + end +end + -- 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) @@ -75,13 +100,44 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number b: number, a: number) if a <= 0 then return end local w4 = (x1 - x0 - 1) * 4 + if x0 >= UX0 and y0 >= UY0 and x1 <= UX1 and y1 <= UY1 and a < 255 then + -- over one value: FillSpan's per-pixel result for d = UV, then fill + local d, v = UV, 0 + if d < 16777216 then + v = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216 + else + local sa = a / 255 + local ns = 1 - sa + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + v = 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) * (ns / 255) + local oa = sa + k + local inv = 1 / oa + v = 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 + local first = (y0 * TargetWidth + x0) * 4 + for o = first, first + w4, 4 do writeu32(TargetBuffer, o, v) end + for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end + UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, v + return + end 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 + -- now uniform: keep whichever region is larger + local area = (x1 - x0) * (y1 - y0) + Shrink(x0, y0, x1, y1) + if area > (UX1 - UX0) * (UY1 - UY0) or UX0 >= UX1 then UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, packed end return end + Shrink(x0, y0, x1, y1) 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 @@ -146,11 +202,12 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number 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 + if a >= 255 or px1 - px0 < 32 or (px0 >= UX0 and py0 >= UY0 and px1 <= UX1 and py1 <= UY1) 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 + Shrink(px0, py0, px1, py1) local len = (px1 - px0) * 4 local prev_o = 0 for y = py0, py1 - 1 do @@ -165,11 +222,14 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number return end + Shrink(px0, py0, px1, py1) 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 + local ident = col == 4294967295 + local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 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 @@ -182,17 +242,47 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number 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) + if tv < 16777216 then + o += 4 + continue + end + if ident and tv >= 4278190080 then -- white opaque vertex colour: an opaque texel is the result + writeu32(dbuf, o, tv) + o += 4 + continue + end + -- BlendPixel inlined (same math) + if tv ~= last_tv then + last_tv = tv + sa = rshift(tv, 24) * a255 + sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255 + s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + fa = sa / 255 + fn = 1 - fa + fk = (1 - fa) / 255 + end + if sa >= 255 then + writeu32(dbuf, o, s_opaque + 4278190080) + elseif sa > 0 then + local d = readu32(dbuf, o) + if d < 16777216 then + writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216) else - BlendPixel(dbuf, o, sr, sg, sb, sa) + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 + + floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080) + else + local k = rshift(d, 24) * fk + local oa = fa + k + local inv = 1 / oa + writeu32(dbuf, o, floor((sr * fa + dr * k) * inv + 0.5) + + floor((sg * fa + dg * k) * inv + 0.5) * 256 + + floor((sb * fa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + end end end - o = o + 4 + o += 4 end end end @@ -214,6 +304,7 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, 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 + Shrink(minx, miny, maxx + 1, maxy + 1) local A0, B0 = y1 - y2, x2 - x1 local C0 = -(A0 * x1 + B0 * y1) @@ -253,6 +344,64 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, f_c1 = f_ns / 255 f_rs, f_gs, f_bs = ra * f_sa, ga * f_sa, ba * f_sa end + local cconst = 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 cconst and aa <= 0 then return end + local tw: number, th: number, tbuf: buffer = 0, 0, dbuf + local r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255 + local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 + if cconst then tw, th, tbuf = t.Width, t.Height, t.Buffer end + + if not textured and (maxx - minx) * 2 < maxy - miny then + -- tall sliver (vertical AA fringe): walk columns, same per-pixel edge and colour math as the rows below (each + -- pixel blended once, so the order does not matter): no empty-row passes + local m0, m1, m2 = B0 ~= 0 and -1 / B0 or 0, B1 ~= 0 and -1 / B1 or 0, B2 ~= 0 and -1 / B2 or 0 + local stride = TargetWidth * 4 + for x = minx, maxx do + local px = x + 0.5 + local yt, yb = miny, maxy + local f0, f1, f2 = A0 * px + C0, A1 * px + C1, A2 * px + C2 + if B0 > 0 then yt = max(yt, floor(f0 * m0 - 0.500001)) elseif B0 < 0 then yb = min(yb, ceil(f0 * m0 - 0.499999)) end + if B1 > 0 then yt = max(yt, floor(f1 * m1 - 0.500001)) elseif B1 < 0 then yb = min(yb, ceil(f1 * m1 - 0.499999)) end + if B2 > 0 then yt = max(yt, floor(f2 * m2 - 0.500001)) elseif B2 < 0 then yb = min(yb, ceil(f2 * m2 - 0.499999)) end + while yt <= yb do + local py = yt + 0.5 + local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2) + 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 + yt += 1 + end + while yb > yt do + local py = yb + 0.5 + local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2) + 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 + yb -= 1 + end + if yt > yb then continue end + local o = (yt * TargetWidth + x) * 4 + if flat then + for _ = yt, yb do + BlendPixel(dbuf, o, ra, ga, ba, aa) + o += stride + end + continue + end + for y = yt, yb do + local py = y + 0.5 + local w0, w1, w2 = (A0 * px + (B0 * py + C0)) * inv, (A1 * px + (B1 * py + C1)) * inv, + (A2 * px + (B2 * py + C2)) * inv + local a = w0 * aa + w1 * ab + w2 * ac + if 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 += stride + end + end + return + end for y = miny, maxy do local py = y + 0.5 @@ -324,6 +473,50 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, end continue end + if cconst then + -- constant vertex colour, varying uv (AA line textures): texel read as u32, blend cached per texel value + 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 tx, ty = floor((w0 * ua + w1 * ub + w2 * uc) * tw), floor((w0 * vva + w1 * vvb + w2 * vvc) * 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 tv = readu32(tbuf, (ty * tw + tx) * 4) + if tv ~= last_tv then + last_tv = tv + sa = rshift(tv, 24) * a255 + sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255 + s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + fa = sa / 255 + fn = 1 - fa + fk = (1 - fa) / 255 + end + -- BlendPixel inlined (same math) + if sa >= 255 then + writeu32(dbuf, o, s_opaque + 4278190080) + elseif sa > 0 then + local d = readu32(dbuf, o) + if d < 16777216 then + writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216) + else + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 + + floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080) + else + local k = rshift(d, 24) * fk + local oa = fa + k + local inv2 = 1 / oa + writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5) + + floor((sg * fa + dg * k) * inv2 + 0.5) * 256 + + floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + end + end + end + o += 4 + 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 @@ -343,6 +536,131 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, end end +-- Textured line quad (triangles a b c + a c d, one colour, uv a = b and c = d: ImPlot PrimLine). Same edge functions as +-- the two DrawTriangle calls (so the same pixels), uv from triangle a b c's barycentrics over the whole quad. +@native +local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number, vc: number, vd: 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 x3, y3 = readf64(vbuf, vd) - ox, readf64(vbuf, vd + 8) - oy + local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0) + local area2 = (x2 - x0) * (y3 - y0) - (y2 - y0) * (x3 - x0) + if area == 0 or area2 == 0 or (area < 0) ~= (area2 < 0) then -- degenerate or not convex: the two triangles + DrawTriangle(dbuf, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, ox, oy) + DrawTriangle(dbuf, vbuf, va, vc, vd, t, cx0, cy0, cx1, cy1, ox, oy) + return + end + local ua, vva, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) + -- outer edges P -> Q (quad order, counter-clockwise like DrawTriangle's swap): A = yP - yQ, B = xQ - xP, C from P + local px_, py_, qx_, qy_ = x1, y1, x3, y3 -- b, d + if area < 0 then + px_, py_, qx_, qy_ = x3, y3, x1, y1 + area = -area + end + -- order a -> p -> c -> q + local A0, B0 = y0 - py_, px_ - x0 + local C0 = -(A0 * x0 + B0 * y0) + local A1, B1 = py_ - y2, x2 - px_ + local C1 = -(A1 * px_ + B1 * py_) + local A2, B2 = y2 - qy_, qx_ - x2 + local C2 = -(A2 * x2 + B2 * y2) + local A3, B3 = qy_ - y0, x0 - qx_ + local C3 = -(A3 * qx_ + B3 * qy_) + 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 tl3 = A3 > 0 or (A3 == 0 and B3 > 0) + local n0, n1, n2, n3 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0, + A3 ~= 0 and -1 / A3 or 0 + -- weight of c in triangle a b c: edge a -> b over its area (same sign whichever side b is on) + local WA, WB = y0 - y1, x1 - x0 + local WC = -(WA * x0 + WB * y0) + local winv = 1 / ((x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0)) + WA, WB, WC = WA * winv, WB * winv, WC * winv + local du, dv = uc - ua, vvc - vva + + local minx, maxx = max(floor(min(x0, x1, x2, x3)), cx0), min(ceil(max(x0, x1, x2, x3)), cx1 - 1) + local miny, maxy = max(floor(min(y0, y1, y2, y3)), cy0), min(ceil(max(y0, y1, y2, y3)), cy1 - 1) + if minx > maxx or miny > maxy then return end + local ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32)) + if aa <= 0 then return end + Shrink(minx, miny, maxx + 1, maxy + 1) + local tw: number, th: number, tbuf: buffer = t.Width, t.Height, t.Buffer + local r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255 + local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 + for y = miny, maxy do + local py = y + 0.5 + local xl, xr = minx, maxx + local e0, e1, e2, e3 = B0 * py + C0, B1 * py + C1, B2 * py + C2, B3 * py + C3 + 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 + if A3 > 0 then xl = max(xl, floor(e3 * n3 - 0.500001)) elseif A3 < 0 then xr = min(xr, ceil(e3 * n3 - 0.499999)) end + while xl <= xr do + local px = xl + 0.5 + local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3 + if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) + and (w3 > 0 or (w3 == 0 and tl3)) then + break + end + xl += 1 + end + while xr > xl do + local px = xr + 0.5 + local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3 + if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) + and (w3 > 0 or (w3 == 0 and tl3)) then + break + end + xr -= 1 + end + if xl > xr then continue end + local o = (y * TargetWidth + xl) * 4 + local wrow = WB * py + WC + for x = xl, xr do + local w = WA * (x + 0.5) + wrow + local tx, ty = floor((ua + w * du) * tw), floor((vva + w * dv) * 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 tv = readu32(tbuf, (ty * tw + tx) * 4) + if tv ~= last_tv then + last_tv = tv + sa = rshift(tv, 24) * a255 + sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255 + s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + fa = sa / 255 + fn = 1 - fa + fk = (1 - fa) / 255 + end + -- BlendPixel inlined (same math) + if sa >= 255 then + writeu32(dbuf, o, s_opaque + 4278190080) + elseif sa > 0 then + local d = readu32(dbuf, o) + if d < 16777216 then + writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216) + else + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 + + floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080) + else + local k = rshift(d, 24) * fk + local oa = fa + k + local inv2 = 1 / oa + writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5) + + floor((sg * fa + dg * k) * inv2 + 0.5) * 256 + + floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + end + end + 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, @@ -350,6 +668,7 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1 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 + Shrink(px0, py0, px1, py1) local ra, ga, ba, aa = UnpackColor(ca) local rb, gb, bb, ab = UnpackColor(cb) if t then @@ -391,11 +710,13 @@ end function M.SetTarget(buf: buffer, width: number) TargetBuffer, TargetWidth = buf, width + UX1 = UX0 end @native function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number) local rw = rx1 - rx0 + UX0, UY0, UX1, UY1, UV = rx0, ry0, rx1, ry1, 0 if rw == TargetWidth then buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4) else @@ -410,13 +731,16 @@ function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: nu end end --- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2 +-- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2, 4 line quad (va vb vc vd) @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) +local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, vd: 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 + elseif kind == 4 then + DrawLineQuad(TargetBuffer, vbuf, va, vb, vc, vd, 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 @@ -435,7 +759,7 @@ 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 + local REC_A, REC_B, REC_C, REC_D = M.REC_A, M.REC_B, M.REC_C, M.REC_D M.SetTarget(Scratch, TILE) local out, no = {}, 0 local o = 0 @@ -459,7 +783,7 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } 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) + DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, q + REC_D, tox, toy, cx0, cy0, cx1, cy1) end local rw, rh = rx1 - rx0, ry1 - ry0 local sub = buffer.create(rw * rh * 4) diff --git a/backends/roblox/render.lua b/backends/roblox/render.lua index b576a3f..c7e7541 100644 --- a/backends/roblox/render.lua +++ b/backends/roblox/render.lua @@ -72,10 +72,9 @@ local function HashVertex(h1: number, h2: number, vbuf: buffer, v: number, ox: n 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 + -- one % per hash: h < 2^31, so h * 48271 + the terms (|x|, |y| < 2^15, uv < 2^14, c < 2^32) stays below 2^53 + h1 = (h1 * 48271 + (x * 4096 + y) * 31 + uv * 4096 + c) % P1 + h2 = (h2 * 16807 + (y * 4093 + x) * 17 + uv * 65521 + c * 3) % P2 return h1, h2 end @@ -122,6 +121,10 @@ local function HashTiles(layer, plist, np, lx0, ly0, ox, oy) h1 = (h1 * 48271 + gk) % P1 h2 = (h2 * 16807 + gk * 3) % P2 end + if gk == 3 then -- line quad: any shape + h1, h2 = HashVertex(h1, h2, vbuf, PrimB[p], vax, vay) + h1, h2 = HashVertex(h1, h2, vbuf, vd, vax, vay) + end else h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay) h1, h2 = HashVertex(h1, h2, vbuf, PrimB[p], vax, vay) @@ -362,7 +365,7 @@ local function RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1) 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) + DrawPrim(kind, PrimTexture[p], PrimVtxBuffer[p], PrimA[p], PrimB[p], PrimC[p], PrimD[p] or 0, tox, toy, cx0, cy0, cx1, cy1) end end @@ -604,7 +607,22 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, 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 = readu32(vbuf, va + 32) + if t and readu32(vbuf, vb + 32) == col and readu32(vbuf, vc + 32) == col + and readu32(vbuf, d + 32) == col then + -- textured line quad (ImPlot PrimLine): uv a = b, c = d, u a ~= u c (else a textured rect may match) + local tax, tay, tcx, tcy = readf64(vbuf, va + 16), readf64(vbuf, va + 24), + readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) + if tax ~= tcx and readf64(vbuf, vb + 16) == tax + and readf64(vbuf, vb + 24) == tay and readf64(vbuf, d + 16) == tcx + and readf64(vbuf, d + 24) == tcy then + vd, gk = d, 3 + bx0, by0 = floor(min(pax, pbx, pcx, pdx) - ox), floor(min(pay, pby, pcy, pdy) - oy) + bx1 = ceil(max(pax, pbx, pcx, pdx) - ox) + 1 + by1 = ceil(max(pay, pby, pcy, pdy) - oy) + 1 + end + end + if not vd and 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) @@ -748,14 +766,16 @@ function M.RenderDrawData(draw_data) 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, + EditableImages.StageFrame = { Compare = 0, Collect = 0, Hash = 0, Raster = 0, Upload = 0, Textures = 0, Flush = 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 + if EditableImages.StageTiming then EditableImages.BeginStage() end UpdateTextures(draw_data) + if EditableImages.StageTiming then EditableImages.EndStage("Textures") end if not RenderRateAllows(BackendData, draw_data) then PE() return @@ -828,13 +848,15 @@ function M.RenderDrawData(draw_data) BackendData.StaleHeartbeat = BackendData.HeartbeatCount end if Parallel.Active then + if EditableImages.StageTiming then EditableImages.BeginStage() end Parallel.Flush() + if EditableImages.StageTiming then EditableImages.EndStage("Flush") end 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 + f.Other = f.Total - f.Compare - f.Collect - f.Hash - f.Raster - f.Upload - f.Textures - f.Flush BackendData.FrameStats = f end PE() diff --git a/backends/roblox/textures.lua b/backends/roblox/textures.lua index 8a5019b..dbdd1b6 100644 --- a/backends/roblox/textures.lua +++ b/backends/roblox/textures.lua @@ -40,8 +40,19 @@ function M.GetBackendData() end @native -local function CopyTexturePixels(tex, dst, x, y, w, h) +local function CopyTexturePixels(tex, dst, x, y, w, h, dst_zero) local bpp, tex_w = tex.BytesPerPixel, tex.Width + if x == 0 and w == tex_w and bpp == 4 then -- whole rows: one flat loop; dst_zero: skip writing zero pixels + local src, s = tex:GetPixelsAt(0, y) + local d = y * tex_w * 4 + for _ = 1, w * h do + local v = src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216 + if v ~= 0 or not dst_zero then writeu32(dst, d, v) end + s += 4 + d += 4 + end + return + end for row = 0, h - 1 do local src, src_base = tex:GetPixelsAt(x, y + row) local dst_off = ((y + row) * tex_w + x) * 4 @@ -63,8 +74,34 @@ 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) + local w, h = tex.Width, tex.Height + local b = buffer.create(w * h * 4) + -- The current font atlas texture: pixels outside the packed rects (MaxRectBounds) and the queued uploads (UsedRect) + -- are still zero (repack's BlockCopy doesn't queue, but every copied rect is packed). Fill them with what zero + -- converts to, convert only the used corner. A fresh/grown atlas is mostly empty. Any other texture: everything. + local atlas = ImGui.GetCurrentContext() and ImGui.GetIO().Fonts + local cw, ch = w, h + if atlas and atlas.TexData == tex and atlas.Builder then + local u, m = tex.UsedRect, atlas.Builder.MaxRectBounds + cw = math.min(w, math.max(u.x + u.w, m.x)) + ch = math.min(h, math.max(u.y + u.h, m.y)) + end + if cw < w or ch < h then + if tex.BytesPerPixel ~= 4 then -- Alpha8 zero -> 0x00FFFFFF; RGBA zero -> 0 (buffer.create's fill) + local n, total = 4, w * h * 4 + writeu32(b, 0, 16777215) + while n < total do + local c = math.min(n, total - n) + buffer.copy(b, n, b, 0, c) + n += c + end + end + CopyTexturePixels(tex, b, 0, 0, cw, ch, tex.BytesPerPixel == 4) + else + CopyTexturePixels(tex, b, 0, 0, w, h, true) + end + -- rows FillRow.. hold only Fill (what zero converts to): parallel.lua sends Actors the rows above it + local t = { Buffer = b, Width = w, Height = h, FillRow = ch, Fill = tex.BytesPerPixel ~= 4 and 16777215 or 0 } EditableImages.LastTextureId += 1 Records[EditableImages.LastTextureId] = t tex.BackendUserData = EditableImages.LastTextureId @@ -81,10 +118,19 @@ function M.UpdateTexture(tex) CreateTextureRecord(tex) return end + local y0, y1 = math.huge, -1 for _, r in tex.Updates:iter() do CopyTexturePixels(tex, t.Buffer, r.x, r.y, r.w, r.h) + if r.y < y0 then y0 = r.y end + if r.y + r.h > y1 then y1 = r.y + r.h end end - t.V = (t.V or 0) + 1 -- parallel workers hold copies, resent when this changes + -- parallel workers hold copies, patched when this changes: Log[V] = changed rows (only the last 16 kept) + if t.FillRow and y1 > t.FillRow then t.FillRow = y1 end + local v = (t.V or 0) + 1 + t.V = v + t.Log = t.Log or {} + t.Log[v] = y1 > y0 and { y0, y1 } or { 0, 0 } + t.Log[v - 16] = nil tex:SetStatus(ImTextureStatus.OK) elseif tex.Status == ImTextureStatus.WantDestroy then if tex.BackendUserData then diff --git a/backends/roblox/worker.luau b/backends/roblox/worker.luau index cf4c992..6f1867d 100644 --- a/backends/roblox/worker.luau +++ b/backends/roblox/worker.luau @@ -10,7 +10,28 @@ 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] } + if Texture[2] then + local B, W, H, Fill = Texture[2], Texture[3], Texture[4], Texture[5] + local n, total = buffer.len(B), W * H * 4 + if n < total then -- the rows below were left out: all Fill (parallel.lua fullCopy) + local Full = buffer.create(total) + buffer.copy(Full, 0, B) + if Fill ~= 0 then + buffer.writeu32(Full, n, Fill) + local k = 4 + while k < total - n do + local c = math.min(k, total - n - k) + buffer.copy(Full, n + k, Full, n, c) + k += c + end + end + B = Full + end + Textures[Texture[1]] = { Buffer = B, Width = W, Height = H } + else -- rows changed since the copy this Actor has + local T = Textures[Texture[1]] + buffer.copy(T.Buffer, Texture[5], Texture[6]) + end end local Results = Raster.RasterJobs(Prims, Tiles, TileLength, Textures) task.synchronize() diff --git a/build/ImGui.linemap.json b/build/ImGui.linemap.json index 03ba5c9..7510496 100644 --- a/build/ImGui.linemap.json +++ b/build/ImGui.linemap.json @@ -1 +1 @@ -[[46, "imgui.lua"], [22648, "imgui_demo.lua"], [34505, "imgui_draw.lua"], [42835, "imgui_h.lua"], [45838, "roblox/raster.lua"], [46314, "roblox/textures.lua"], [46485, "roblox/layers.lua"], [46822, "roblox/overlays.lua"], [46903, "roblox/render.lua"], [47748, "roblox/parallel.lua"], [48147, "imgui_impl_roblox.lua"], [48648, "imgui_impl_roblox_fonts.lua"], [55051, "imgui_internal.lua"], [59017, "imgui_tables.lua"], [64109, "imgui_widgets.lua"], [76347, "imstb_rectpack.lua"], [77011, "imstb_textedit.lua"], [78553, "imstb_truetype.lua"], [81341, "imstd_minstdio.lua"]] \ No newline at end of file +[[46, "imgui.lua"], [22688, "imgui_demo.lua"], [34545, "imgui_draw.lua"], [42896, "imgui_h.lua"], [45899, "roblox/raster.lua"], [46699, "roblox/textures.lua"], [46916, "roblox/layers.lua"], [47253, "roblox/overlays.lua"], [47334, "roblox/render.lua"], [48201, "roblox/parallel.lua"], [48648, "imgui_impl_roblox.lua"], [49149, "imgui_impl_roblox_fonts.lua"], [55552, "imgui_internal.lua"], [59520, "imgui_tables.lua"], [64612, "imgui_widgets.lua"], [76880, "imstb_rectpack.lua"], [77557, "imstb_textedit.lua"], [79099, "imstb_truetype.lua"], [82040, "imstd_minstdio.lua"]] \ No newline at end of file diff --git a/build/ImGui.luau b/build/ImGui.luau index 0465d94..9984345 100644 --- a/build/ImGui.luau +++ b/build/ImGui.luau @@ -4917,26 +4917,33 @@ local ImGuiResizeBorderDef = { --- @param thickness float --- @return ImRect --- @nodiscard -local function GetResizeBorderRect(window, border_n, perp_padding, thickness) - local rect = window:Rect() +-- [Luau] out: optional ImRect written in place (no allocation) +local function GetResizeBorderRect(window, border_n, perp_padding, thickness, out) + local x0, y0 = window.Pos.x, window.Pos.y + local x1, y1 = x0 + window.Size.x, y0 + window.Size.y if thickness == 0.0 then - ImVec2_CopyV(rect.Max, rect.Max.x - 1, rect.Max.y - 1) + x1, y1 = x1 - 1, y1 - 1 end + local a, b, c, d if border_n == 0 --[[ImGuiDir.Left]] then - return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding) + a, b, c, d = x0 - thickness, y0 + perp_padding, x0 + thickness, y1 - perp_padding + elseif border_n == 1 --[[ImGuiDir.Right]] then + a, b, c, d = x1 - thickness, y0 + perp_padding, x1 + thickness, y1 - perp_padding + elseif border_n == 2 --[[ImGuiDir.Up]] then + a, b, c, d = x0 + perp_padding, y0 - thickness, x1 - perp_padding, y0 + thickness + elseif border_n == 3 --[[ImGuiDir.Down]] then + a, b, c, d = x0 + perp_padding, y1 - thickness, x1 - perp_padding, y1 + thickness + else + assert(false) + a, b, c, d = 0, 0, 0, 0 end - if border_n == 1 --[[ImGuiDir.Right]] then - return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding) + if out then + out.Min.x, out.Min.y, out.Max.x, out.Max.y = a, b, c, d + return out end - if border_n == 2 --[[ImGuiDir.Up]] then - return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness) - end - if border_n == 3 --[[ImGuiDir.Down]] then - return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness) - end - assert(false) - return ImRect() + return ImRect(a, b, c, d) end +local UpdateWindowManualResize_rect = ImRect() -- [Luau] scratch grip/border rect: ItemAdd() copies, ButtonBehavior() reads -- Known size hash -- It is ok to call ImHashData on a string with known length but the ### operator won't be supported. @@ -10218,10 +10225,12 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c local corner_pos = def.CornerPosN local inner_dir = def.InnerDir - local corner = ImVec2(window.Pos.x + corner_pos.x * window.Size.x, window.Pos.y + corner_pos.y * window.Size.y) + local corner_x, corner_y = window.Pos.x + corner_pos.x * window.Size.x, window.Pos.y + corner_pos.y * window.Size.y -- Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window - local resize_rect = ImRect(corner - inner_dir * grip_hover_outer_size, corner + inner_dir * grip_hover_inner_size) + local resize_rect = UpdateWindowManualResize_rect -- [Luau] scratch, scalar math + resize_rect.Min.x, resize_rect.Min.y = corner_x - inner_dir.x * grip_hover_outer_size, corner_y - inner_dir.y * grip_hover_outer_size + resize_rect.Max.x, resize_rect.Max.y = corner_x + inner_dir.x * grip_hover_inner_size, corner_y + inner_dir.y * grip_hover_inner_size if resize_rect.Min.x > resize_rect.Max.x then resize_rect.Min.x, resize_rect.Max.x = resize_rect.Max.x, resize_rect.Min.x end if resize_rect.Min.y > resize_rect.Max.y then resize_rect.Min.y, resize_rect.Max.y = resize_rect.Max.y, resize_rect.Min.y end @@ -10294,7 +10303,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c axis = 2 --[[ImGuiAxis.Y]] end - local border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding) + local border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding, UpdateWindowManualResize_rect) local border_id = window:GetID(border_n + 4) -- == GetWindowResizeBorderID() ImGui.ItemAdd(border_rect, border_id, nil, 2 --[[ImGuiItemFlags.NoNav]]) local _, hovered, held = ImGui.ButtonBehavior(border_rect, border_id, bit32.bor(2048 --[[ImGuiButtonFlags.FlattenChildren]], 262144 --[[ImGuiButtonFlags.NoNavFocus]])) @@ -10323,7 +10332,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c -- FIXME: May want to generalize this idiom at lower-level, so more widgets can use it! local just_scrolled_manually_while_resizing = (g.WheelingWindow ~= nil and g.WheelingWindowScrolledFrame == g.FrameCount and ImGui.IsWindowChildOf(window, g.WheelingWindow, false, true)) if g.ActiveIdIsJustActivated or just_scrolled_manually_while_resizing then - g.WindowResizeBorderExpectedRect = border_rect + g.WindowResizeBorderExpectedRect = ImRect(border_rect.Min, border_rect.Max) -- [Luau] copy: border_rect is scratch g.WindowResizeRelativeMode = false end @@ -10531,18 +10540,23 @@ function ImGui.RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_begin local pos = RenderTextClippedEx_pos pos.x = pos_min.x; pos.y = pos_min.y - local text_size = text_size_if_known or ImGui.CalcTextSize(text, text_display_end, false, 0.0) + local text_size_x, text_size_y -- [Luau] scalar text_size + if text_size_if_known then + text_size_x, text_size_y = text_size_if_known.x, text_size_if_known.y + else + text_size_x, text_size_y = ImGui.CalcTextSizeXY(text, 1, text_display_end, false, 0.0) + end local clip_min = clip_rect and clip_rect.Min or pos_min local clip_max = clip_rect and clip_rect.Max or pos_max - local need_clipping = (pos.x + text_size.x >= clip_max.x) or (pos.y + text_size.y >= clip_max.y) + local need_clipping = (pos.x + text_size_x >= clip_max.x) or (pos.y + text_size_y >= clip_max.y) if (clip_rect) then -- If we had no explicit clipping rectangle then pos==clip_min need_clipping = need_clipping or ((pos.x < clip_min.x) or (pos.y < clip_min.y)) end -- Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. - if (align.x > 0.0) then pos.x = math.max(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x) end - if (align.y > 0.0) then pos.y = math.max(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y) end + if (align.x > 0.0) then pos.x = math.max(pos.x, pos.x + (pos_max.x - pos.x - text_size_x) * align.x) end + if (align.y > 0.0) then pos.y = math.max(pos.y, pos.y + (pos_max.y - pos.y - text_size_y) * align.y) end -- Render if (need_clipping) then @@ -10861,6 +10875,9 @@ end --- @param handle_borders_and_resize_grips bool --- @param resize_grip_col ImU32[] --- @param resize_grip_draw_size float +-- [Luau] scratch for RenderWindowDecorations()/RenderWindowTitleBarContents(): callees only read or copy these +local WindowDecoScratch = { text_size = ImVec2(), layout_r = ImRect(), clip_r = ImRect(), bg_rect = ImRect(), p = ImVec2(), title_bar_rect = ImRect() } + local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_col, resize_grip_draw_size) local g = GImGui local style = g.Style @@ -10901,7 +10918,8 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high if bit32.band(flags, 8388608 --[[ImGuiWindowFlags.DockNodeHost]]) ~= 0 then bg_col = 0 end if bit32.band(bg_col, 4278190080 --[[IM_COL32_A_MASK]]) ~= 0 then - local bg_rect = ImRect(window.Pos + ImVec2(0, window.TitleBarHeight), window.Pos + window.Size) + local bg_rect = WindowDecoScratch.bg_rect -- [Luau] scalar, no temporaries + bg_rect.Min.x, bg_rect.Min.y, bg_rect.Max.x, bg_rect.Max.y = window.Pos.x + 0, window.Pos.y + window.TitleBarHeight, window.Pos.x + window.Size.x, window.Pos.y + window.Size.y local bg_rounding_flags if window.DockIsActive then bg_rounding_flags = ImGui.CalcRoundingFlagsForRectInRect(bg_rect, window.DockNode.HostWindow:Rect(), 0.0) @@ -10973,11 +10991,20 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high end local grip = ImGuiResizeGripDef[resize_grip_n] - local corner = ImLerp(window.Pos, window.Pos + window.Size, grip.CornerPosN) + -- [Luau] scalar corner/points, one scratch ImVec2 (the path copies points) + local pos, cpn, dir = window.Pos, grip.CornerPosN, grip.InnerDir + local corner_x = pos.x + ((pos.x + window.Size.x) - pos.x) * cpn.x + local corner_y = pos.y + ((pos.y + window.Size.y) - pos.y) * cpn.y local border_inner = IM_ROUND(window_border_size * 0.5) - window.DrawList:PathLineTo(corner + grip.InnerDir * ((resize_grip_n % 2 == 0) and ImVec2(border_inner, resize_grip_draw_size) or ImVec2(resize_grip_draw_size, border_inner))) - window.DrawList:PathLineTo(corner + grip.InnerDir * ((resize_grip_n % 2 == 0) and ImVec2(resize_grip_draw_size, border_inner) or ImVec2(border_inner, resize_grip_draw_size))) - window.DrawList:PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + border_inner), corner.y + grip.InnerDir.y * (window_rounding + border_inner)), window_rounding, grip.AngleMin12, grip.AngleMax12) + local a, b = border_inner, resize_grip_draw_size + if resize_grip_n % 2 ~= 0 then a, b = b, a end + local p = WindowDecoScratch.p + p.x, p.y = corner_x + dir.x * a, corner_y + dir.y * b + window.DrawList:PathLineTo(p) + p.x, p.y = corner_x + dir.x * b, corner_y + dir.y * a + window.DrawList:PathLineTo(p) + p.x, p.y = corner_x + dir.x * (window_rounding + border_inner), corner_y + dir.y * (window_rounding + border_inner) + window.DrawList:PathArcToFast(p, window_rounding, grip.AngleMin12, grip.AngleMax12) window.DrawList:PathFillConvex(col) until true @@ -10994,6 +11021,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high end ImGui.RenderWindowOuterBorders = RenderWindowOuterBorders + -- When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead. -- Render title text, collapse button, close button -- [Port] Returns the updated 'open' value (nil when there is no close button) @@ -11059,7 +11087,9 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) -- Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) -- FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. local marker_size_x = (bit32.band(flags, 262144 --[[ImGuiWindowFlags.UnsavedDocument]]) ~= 0) and (button_sz * 0.80) or 0.0 - local text_size = ImGui.CalcTextSize(name, nil, true) + ImVec2(marker_size_x, 0.0) + local text_size = WindowDecoScratch.text_size -- [Luau] scratch: only read below (RenderTextClipped text_size_if_known) + local text_size_x, text_size_y = ImGui.CalcTextSizeXY(name, 1, nil, true) + text_size.x = text_size_x + marker_size_x; text_size.y = text_size_y + 0.0 -- As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button, -- while uncentered title text will still reach edges correctly. @@ -11076,8 +11106,9 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) pad_r = ImMax(pad_r, pad_extend * centerness) end - local layout_r = ImRect(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y) - local clip_r = ImRect(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y) + local layout_r, clip_r = WindowDecoScratch.layout_r, WindowDecoScratch.clip_r -- [Luau] scratch, only read by callees + layout_r.Min.x, layout_r.Min.y, layout_r.Max.x, layout_r.Max.y = title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y + clip_r.Min.x, clip_r.Min.y, clip_r.Max.x, clip_r.Max.y = layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y if bit32.band(flags, 262144 --[[ImGuiWindowFlags.UnsavedDocument]]) ~= 0 then local marker_pos = ImVec2() @@ -12214,13 +12245,17 @@ function ImGui.Begin(name, open, flags) -- Add to stack g.CurrentWindow = window g.CurrentWindowStack:resize(g.CurrentWindowStack.Size + 1) - g.CurrentWindowStack.Data[g.CurrentWindowStack.Size] = ImGuiWindowStackData() + -- [Luau] reuse the slot's table left by pop_back() (C++ reuses the vector storage); every field is set below local window_stack_data = g.CurrentWindowStack.Data[g.CurrentWindowStack.Size] + if type(window_stack_data) ~= "table" or window_stack_data.ParentLastItemDataBackup == nil then + window_stack_data = ImGuiWindowStackData() + g.CurrentWindowStack.Data[g.CurrentWindowStack.Size] = window_stack_data + end window_stack_data.Window = window ImGuiLastItemData_Copy(window_stack_data.ParentLastItemDataBackup, g.LastItemData) window_stack_data.DisabledOverrideReenable = (bit32.band(flags, 33554432 --[[ImGuiWindowFlags.Tooltip]]) ~= 0) and (bit32.band(g.CurrentItemFlags, 64 --[[ImGuiItemFlags.Disabled]]) ~= 0) window_stack_data.DisabledOverrideReenableAlphaBackup = 0.0 - window_stack_data.StackSizesInBegin = ImGuiErrorRecoveryState() + window_stack_data.StackSizesInBegin = window_stack_data.StackSizesInBegin or ImGuiErrorRecoveryState() -- [Luau] reused, all fields stored ImGui.ErrorRecoveryStoreState(window_stack_data.StackSizesInBegin) g.StackSizesInBeginForCurrentWindow = window_stack_data.StackSizesInBegin if bit32.band(flags, 268435456 --[[ImGuiWindowFlags.ChildMenu]]) ~= 0 then @@ -13001,7 +13036,9 @@ function ImGui.Begin(name, open, flags) -- Title bar if bit32.band(flags, 1 --[[ImGuiWindowFlags.NoTitleBar]]) == 0 and not window.DockIsActive then - open = RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window.WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window.WindowBorderSize, title_bar_rect.Max.y), name, open) + local r = WindowDecoScratch.title_bar_rect -- [Luau] scratch, only read + r.Min.x, r.Min.y, r.Max.x, r.Max.y = title_bar_rect.Min.x + window.WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window.WindowBorderSize, title_bar_rect.Max.y + open = RenderWindowTitleBarContents(window, r, name, open) elseif bit32.band(flags, 1 --[[ImGuiWindowFlags.NoTitleBar]]) == 0 and window.DockIsActive then ImGui.LogText("%s\n", string.sub(window.Name, 1, ImGui.FindRenderedTextEnd(window.Name) - 1)) end @@ -14705,10 +14742,10 @@ end --- @param hide_text_after_double_hash? bool --- @param wrap_width? float --- @return ImVec2 +-- [Luau] scalar CalcTextSizeEx(): returns x, y without allocating an ImVec2 (hot widget paths) @native -function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double_hash, wrap_width) - if hide_text_after_double_hash == nil then hide_text_after_double_hash = false end - if wrap_width == nil then wrap_width = -1.0 end +function ImGui.CalcTextSizeXY(text, text_begin, text_end, hide_text_after_double_hash, wrap_width) + if wrap_width == nil then wrap_width = -1.0 end local g = GImGui @@ -14719,19 +14756,22 @@ function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double text_display_end = text_end end - local font = g.Font local font_size = g.FontSize if text == "" or (text_end and text_end <= text_begin) then - return ImVec2(0.0, font_size) + return 0.0, font_size end - local text_size = ImFontCalcTextSizeEx(font, font_size, 3.4028234663853e+38 --[[FLT_MAX]], wrap_width, text, text_begin, text_display_end, text_display_end, nil, 0 --[[ImDrawTextFlags.None]]) -- [Luau] inline font:CalcTextSizeA() + local x, y = ImFontCalcTextSizeXY(g.Font, font_size, 3.4028234663853e+38 --[[FLT_MAX]], wrap_width, text, text_begin, text_display_end, text_display_end, nil, 0 --[[ImDrawTextFlags.None]]) -- [Luau] inline font:CalcTextSizeA() -- Round -- (see 7b0bf230, 4622fa4b6, #791 for details about this.) -- FIXME: Add a way to disable this. - text_size.x = math.ceil(text_size.x) -- [Luau] == ImCeilFast() for all finite values, builtin + return math.ceil(x), y -- [Luau] == ImCeilFast() for all finite values, builtin +end - return text_size +@native +function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double_hash, wrap_width) + local x, y = ImGui.CalcTextSizeXY(text, text_begin, text_end, hide_text_after_double_hash, wrap_width) + return ImVec2(x, y) end -- Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() @@ -34553,6 +34593,7 @@ end --- @param buf char[] # 1-based --- @param base int # 1-based start index --- @param u32 ImU32 +@native local function write_u32(buf, base, u32) buf[base + 0] = bit32.band(u32, 0xFF) buf[base + 1] = bit32.band(bit32.rshift(u32, 8), 0xFF) @@ -35282,6 +35323,7 @@ end --- @param dst_pitch int --- @param w int --- @param h int +@native function ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst_pixels, dst_pixels_base, dst_fmt, dst_pitch, w, h) assert(src_pixels ~= nil and dst_pixels ~= nil) local src_pixels_base = 1 @@ -35299,7 +35341,8 @@ function ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst_pixe local alpha = src_pixels[src_pixels_base + 0] src_pixels_base = src_pixels_base + 1 - write_u32(dst_pixels, dst_pixels_base, IM_COL32(255, 255, 255, alpha)) + -- [Luau] inline write_u32(dst_pixels, dst_pixels_base, IM_COL32(255, 255, 255, alpha)) + dst_pixels[dst_pixels_base] = 255; dst_pixels[dst_pixels_base + 1] = 255; dst_pixels[dst_pixels_base + 2] = 255; dst_pixels[dst_pixels_base + 3] = alpha dst_pixels_base = dst_pixels_base + 4 end @@ -37205,8 +37248,13 @@ function MT.ImTextureData:Create(format, w, h) self.Height = h self.BytesPerPixel = ImTextureDataGetFormatBytesPerPixel(format) self.UseColors = false - self.Pixels = {} - ImStd.memset(self.Pixels, 0, self.Width * self.Height * self.BytesPerPixel) + local n = self.Width * self.Height * self.BytesPerPixel + if table.create then + self.Pixels = table.create(n, 0) -- [Luau] native zero fill, same contents as memset + else + self.Pixels = {} + ImStd.memset(self.Pixels, 0, n) + end self.UsedRect.x = 0 self.UsedRect.y = 0 self.UsedRect.w = 0 @@ -37970,7 +38018,8 @@ end local TEXT_SIZE_CACHE_MAX = 4096 @native -function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags) +-- [Luau] scalar core of ImFontCalcTextSizeEx(): returns size.x, size.y, remaining (no ImVec2 allocated) +function ImFontCalcTextSizeXY(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. @@ -37987,7 +38036,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end local e = cache[text] if e then - return ImVec2(e[1] * (size / baked.Size), e[2] * size), text_len1 + return e[1] * (size / baked.Size), e[2] * size, text_len1 end cache_key = text elseif cacheable and wrap_width > 0.0 then @@ -38003,7 +38052,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi if by_wrap == nil then by_wrap = {}; by_size[wrap_width] = by_wrap end local e = by_wrap[text] if e then - return ImVec2(e[1], e[2]), e[3] + return e[1], e[2], e[3] end wrap_cache = by_wrap end @@ -38018,7 +38067,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi local line_height = size local scale = line_height / baked.Size - local text_size = ImVec2() + local tx, ty = 0.0, 0.0 local line_width = 0.0 local word_wrap_enabled = (wrap_width > 0.0) @@ -38038,10 +38087,10 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end if s >= word_wrap_eol then - if text_size.x < line_width then - text_size.x = line_width + if tx < line_width then + tx = line_width end - text_size.y = text_size.y + line_height + ty = ty + line_height line_width = 0.0 s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) -- Wrapping skips upcoming blanks if bit32.band(flags, 4 --[[ImDrawTextFlags.StopOnNewLine]]) ~= 0 then @@ -38066,8 +38115,8 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end if c == 10 then -- '\n' - text_size.x = ImMax(text_size.x, line_width) - text_size.y = text_size.y + line_height + if tx < line_width then tx = line_width end + ty = ty + line_height line_width = 0.0 if bit32.band(flags, 4 --[[ImDrawTextFlags.StopOnNewLine]]) ~= 0 then stop = true; break @@ -38099,30 +38148,36 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi if stop then break end end - if (text_size.x < line_width) then - text_size.x = line_width + if (tx < line_width) then + tx = line_width end if out_offset then -- offset allow for the possibility of sitting after a trailing \n out_offset.x = line_width - out_offset.y = text_size.y + line_height + out_offset.y = ty + line_height end - if (line_width > 0 or text_size.y == 0.0) then -- whereas size.y will ignore the trailing \n - text_size.y = text_size.y + line_height + if (line_width > 0 or ty == 0.0) then -- whereas size.y will ignore the trailing \n + ty = ty + line_height end local out_remaining = s if cache_key then - baked._TextSizeCache[cache_key] = { text_size.x / scale, text_size.y / line_height } + baked._TextSizeCache[cache_key] = { tx / scale, ty / line_height } baked._TextSizeCacheN = baked._TextSizeCacheN + 1 elseif wrap_cache then - wrap_cache[text] = { text_size.x, text_size.y, out_remaining } + wrap_cache[text] = { tx, ty, out_remaining } baked._TextSizeCacheN = baked._TextSizeCacheN + 1 end - return text_size, out_remaining + return tx, ty, out_remaining +end + +-- ImVec2 version (upstream signature) +function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags) + local x, y, remaining = ImFontCalcTextSizeXY(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags) + return ImVec2(x, y), remaining end --- @param size float @@ -41492,7 +41547,15 @@ end -- Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui.PushClipRect() to affect logic (hit-testing and widget culling) function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_rect) - local cr = ImVec4(cr_min.x, cr_min.y, cr_max.x, cr_max.y) + -- [Luau] reuse the stack slot's ImVec4 left from earlier frames (each slot stays uniquely owned by the stack) + local stack = self._ClipRectStack + local n = stack.Size + 1 + local cr = n <= stack.Capacity and stack.Data[n] or nil + if cr then + cr.x = cr_min.x; cr.y = cr_min.y; cr.z = cr_max.x; cr.w = cr_max.y + else + cr = ImVec4(cr_min.x, cr_min.y, cr_max.x, cr_max.y) + end if intersect_with_current_clip_rect then local current = self._CmdHeader.ClipRect @@ -41507,8 +41570,6 @@ function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_ cr.w = math.max(cr.y, cr.w) -- [Luau] inline self._ClipRectStack:push_back(cr) - local stack = self._ClipRectStack - local n = stack.Size + 1 if n > stack.Capacity then stack:push_back(cr) else stack.Data[n] = cr; stack.Size = n end ImVec4_Copy(self._CmdHeader.ClipRect, cr) self:_OnChangedClipRect() @@ -45846,11 +45907,11 @@ 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. + -- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2, 4 line quad), 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, d at REC_D. -- 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, + VTX = 36, REC = 184, REC_A = 40, REC_C = 76, REC_B = 112, REC_D = 148, JOB = 32, } local TILE = M.TILE @@ -45877,6 +45938,31 @@ local function RowRepeats(o: number, len: number, has_prev: boolean): boolean end local RectColumns = table.create(256, 0) +-- Uniform region: [UX0, UX1) x [UY0, UY1) of the target holds only the pixel value UV (empty when UX0 >= UX1). +-- Set by ClearRect and by solid rects; shrunk by everything drawn over it. A solid rect inside it blends one pixel and +-- fills (window/frame backgrounds over backgrounds), instead of blending every pixel. +local UX0, UY0, UX1, UY1, UV = 0, 0, 0, 0, 0 + +-- Drawing may change [x0, x1) x [y0, y1): keep the largest uniform piece outside it +@native +local function Shrink(x0: number, y0: number, x1: number, y1: number) + if x0 >= UX1 or x1 <= UX0 or y0 >= UY1 or y1 <= UY0 or UX0 >= UX1 then return end + local h, w = UY1 - UY0, UX1 - UX0 + local left, right, top, bottom = (x0 - UX0) * h, (UX1 - x1) * h, (y0 - UY0) * w, (UY1 - y1) * w + local best = max(left, right, top, bottom) + if best <= 0 then + UX1 = UX0 + elseif best == left then + UX1 = x0 + elseif best == right then + UX0 = x1 + elseif best == top then + UY1 = y0 + else + UY0 = y1 + end +end + -- 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) @@ -45912,13 +45998,44 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number b: number, a: number) if a <= 0 then return end local w4 = (x1 - x0 - 1) * 4 + if x0 >= UX0 and y0 >= UY0 and x1 <= UX1 and y1 <= UY1 and a < 255 then + -- over one value: FillSpan's per-pixel result for d = UV, then fill + local d, v = UV, 0 + if d < 16777216 then + v = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216 + else + local sa = a / 255 + local ns = 1 - sa + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + v = 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) * (ns / 255) + local oa = sa + k + local inv = 1 / oa + v = 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 + local first = (y0 * TargetWidth + x0) * 4 + for o = first, first + w4, 4 do writeu32(TargetBuffer, o, v) end + for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end + UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, v + return + end 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 + -- now uniform: keep whichever region is larger + local area = (x1 - x0) * (y1 - y0) + Shrink(x0, y0, x1, y1) + if area > (UX1 - UX0) * (UY1 - UY0) or UX0 >= UX1 then UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, packed end return end + Shrink(x0, y0, x1, y1) 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 @@ -45983,11 +46100,12 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number 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 + if a >= 255 or px1 - px0 < 32 or (px0 >= UX0 and py0 >= UY0 and px1 <= UX1 and py1 <= UY1) 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 + Shrink(px0, py0, px1, py1) local len = (px1 - px0) * 4 local prev_o = 0 for y = py0, py1 - 1 do @@ -46002,11 +46120,14 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number return end + Shrink(px0, py0, px1, py1) 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 + local ident = col == 4294967295 + local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 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 @@ -46019,17 +46140,47 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number 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) + if tv < 16777216 then + o += 4 + continue + end + if ident and tv >= 4278190080 then -- white opaque vertex colour: an opaque texel is the result + writeu32(dbuf, o, tv) + o += 4 + continue + end + -- BlendPixel inlined (same math) + if tv ~= last_tv then + last_tv = tv + sa = rshift(tv, 24) * a255 + sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255 + s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + fa = sa / 255 + fn = 1 - fa + fk = (1 - fa) / 255 + end + if sa >= 255 then + writeu32(dbuf, o, s_opaque + 4278190080) + elseif sa > 0 then + local d = readu32(dbuf, o) + if d < 16777216 then + writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216) else - BlendPixel(dbuf, o, sr, sg, sb, sa) + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 + + floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080) + else + local k = rshift(d, 24) * fk + local oa = fa + k + local inv = 1 / oa + writeu32(dbuf, o, floor((sr * fa + dr * k) * inv + 0.5) + + floor((sg * fa + dg * k) * inv + 0.5) * 256 + + floor((sb * fa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + end end end - o = o + 4 + o += 4 end end end @@ -46051,6 +46202,7 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, 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 + Shrink(minx, miny, maxx + 1, maxy + 1) local A0, B0 = y1 - y2, x2 - x1 local C0 = -(A0 * x1 + B0 * y1) @@ -46090,6 +46242,64 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, f_c1 = f_ns / 255 f_rs, f_gs, f_bs = ra * f_sa, ga * f_sa, ba * f_sa end + local cconst = 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 cconst and aa <= 0 then return end + local tw: number, th: number, tbuf: buffer = 0, 0, dbuf + local r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255 + local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 + if cconst then tw, th, tbuf = t.Width, t.Height, t.Buffer end + + if not textured and (maxx - minx) * 2 < maxy - miny then + -- tall sliver (vertical AA fringe): walk columns, same per-pixel edge and colour math as the rows below (each + -- pixel blended once, so the order does not matter): no empty-row passes + local m0, m1, m2 = B0 ~= 0 and -1 / B0 or 0, B1 ~= 0 and -1 / B1 or 0, B2 ~= 0 and -1 / B2 or 0 + local stride = TargetWidth * 4 + for x = minx, maxx do + local px = x + 0.5 + local yt, yb = miny, maxy + local f0, f1, f2 = A0 * px + C0, A1 * px + C1, A2 * px + C2 + if B0 > 0 then yt = max(yt, floor(f0 * m0 - 0.500001)) elseif B0 < 0 then yb = min(yb, ceil(f0 * m0 - 0.499999)) end + if B1 > 0 then yt = max(yt, floor(f1 * m1 - 0.500001)) elseif B1 < 0 then yb = min(yb, ceil(f1 * m1 - 0.499999)) end + if B2 > 0 then yt = max(yt, floor(f2 * m2 - 0.500001)) elseif B2 < 0 then yb = min(yb, ceil(f2 * m2 - 0.499999)) end + while yt <= yb do + local py = yt + 0.5 + local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2) + 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 + yt += 1 + end + while yb > yt do + local py = yb + 0.5 + local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2) + 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 + yb -= 1 + end + if yt > yb then continue end + local o = (yt * TargetWidth + x) * 4 + if flat then + for _ = yt, yb do + BlendPixel(dbuf, o, ra, ga, ba, aa) + o += stride + end + continue + end + for y = yt, yb do + local py = y + 0.5 + local w0, w1, w2 = (A0 * px + (B0 * py + C0)) * inv, (A1 * px + (B1 * py + C1)) * inv, + (A2 * px + (B2 * py + C2)) * inv + local a = w0 * aa + w1 * ab + w2 * ac + if 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 += stride + end + end + return + end for y = miny, maxy do local py = y + 0.5 @@ -46161,6 +46371,50 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, end continue end + if cconst then + -- constant vertex colour, varying uv (AA line textures): texel read as u32, blend cached per texel value + 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 tx, ty = floor((w0 * ua + w1 * ub + w2 * uc) * tw), floor((w0 * vva + w1 * vvb + w2 * vvc) * 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 tv = readu32(tbuf, (ty * tw + tx) * 4) + if tv ~= last_tv then + last_tv = tv + sa = rshift(tv, 24) * a255 + sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255 + s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + fa = sa / 255 + fn = 1 - fa + fk = (1 - fa) / 255 + end + -- BlendPixel inlined (same math) + if sa >= 255 then + writeu32(dbuf, o, s_opaque + 4278190080) + elseif sa > 0 then + local d = readu32(dbuf, o) + if d < 16777216 then + writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216) + else + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 + + floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080) + else + local k = rshift(d, 24) * fk + local oa = fa + k + local inv2 = 1 / oa + writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5) + + floor((sg * fa + dg * k) * inv2 + 0.5) * 256 + + floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + end + end + end + o += 4 + 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 @@ -46180,6 +46434,131 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, end end +-- Textured line quad (triangles a b c + a c d, one colour, uv a = b and c = d: ImPlot PrimLine). Same edge functions as +-- the two DrawTriangle calls (so the same pixels), uv from triangle a b c's barycentrics over the whole quad. +@native +local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number, vc: number, vd: 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 x3, y3 = readf64(vbuf, vd) - ox, readf64(vbuf, vd + 8) - oy + local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0) + local area2 = (x2 - x0) * (y3 - y0) - (y2 - y0) * (x3 - x0) + if area == 0 or area2 == 0 or (area < 0) ~= (area2 < 0) then -- degenerate or not convex: the two triangles + DrawTriangle(dbuf, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, ox, oy) + DrawTriangle(dbuf, vbuf, va, vc, vd, t, cx0, cy0, cx1, cy1, ox, oy) + return + end + local ua, vva, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) + -- outer edges P -> Q (quad order, counter-clockwise like DrawTriangle's swap): A = yP - yQ, B = xQ - xP, C from P + local px_, py_, qx_, qy_ = x1, y1, x3, y3 -- b, d + if area < 0 then + px_, py_, qx_, qy_ = x3, y3, x1, y1 + area = -area + end + -- order a -> p -> c -> q + local A0, B0 = y0 - py_, px_ - x0 + local C0 = -(A0 * x0 + B0 * y0) + local A1, B1 = py_ - y2, x2 - px_ + local C1 = -(A1 * px_ + B1 * py_) + local A2, B2 = y2 - qy_, qx_ - x2 + local C2 = -(A2 * x2 + B2 * y2) + local A3, B3 = qy_ - y0, x0 - qx_ + local C3 = -(A3 * qx_ + B3 * qy_) + 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 tl3 = A3 > 0 or (A3 == 0 and B3 > 0) + local n0, n1, n2, n3 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0, + A3 ~= 0 and -1 / A3 or 0 + -- weight of c in triangle a b c: edge a -> b over its area (same sign whichever side b is on) + local WA, WB = y0 - y1, x1 - x0 + local WC = -(WA * x0 + WB * y0) + local winv = 1 / ((x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0)) + WA, WB, WC = WA * winv, WB * winv, WC * winv + local du, dv = uc - ua, vvc - vva + + local minx, maxx = max(floor(min(x0, x1, x2, x3)), cx0), min(ceil(max(x0, x1, x2, x3)), cx1 - 1) + local miny, maxy = max(floor(min(y0, y1, y2, y3)), cy0), min(ceil(max(y0, y1, y2, y3)), cy1 - 1) + if minx > maxx or miny > maxy then return end + local ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32)) + if aa <= 0 then return end + Shrink(minx, miny, maxx + 1, maxy + 1) + local tw: number, th: number, tbuf: buffer = t.Width, t.Height, t.Buffer + local r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255 + local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 + for y = miny, maxy do + local py = y + 0.5 + local xl, xr = minx, maxx + local e0, e1, e2, e3 = B0 * py + C0, B1 * py + C1, B2 * py + C2, B3 * py + C3 + 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 + if A3 > 0 then xl = max(xl, floor(e3 * n3 - 0.500001)) elseif A3 < 0 then xr = min(xr, ceil(e3 * n3 - 0.499999)) end + while xl <= xr do + local px = xl + 0.5 + local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3 + if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) + and (w3 > 0 or (w3 == 0 and tl3)) then + break + end + xl += 1 + end + while xr > xl do + local px = xr + 0.5 + local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3 + if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) + and (w3 > 0 or (w3 == 0 and tl3)) then + break + end + xr -= 1 + end + if xl > xr then continue end + local o = (y * TargetWidth + xl) * 4 + local wrow = WB * py + WC + for x = xl, xr do + local w = WA * (x + 0.5) + wrow + local tx, ty = floor((ua + w * du) * tw), floor((vva + w * dv) * 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 tv = readu32(tbuf, (ty * tw + tx) * 4) + if tv ~= last_tv then + last_tv = tv + sa = rshift(tv, 24) * a255 + sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255 + s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + fa = sa / 255 + fn = 1 - fa + fk = (1 - fa) / 255 + end + -- BlendPixel inlined (same math) + if sa >= 255 then + writeu32(dbuf, o, s_opaque + 4278190080) + elseif sa > 0 then + local d = readu32(dbuf, o) + if d < 16777216 then + writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216) + else + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 + + floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080) + else + local k = rshift(d, 24) * fk + local oa = fa + k + local inv2 = 1 / oa + writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5) + + floor((sg * fa + dg * k) * inv2 + 0.5) * 256 + + floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + end + end + 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, @@ -46187,6 +46566,7 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1 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 + Shrink(px0, py0, px1, py1) local ra, ga, ba, aa = UnpackColor(ca) local rb, gb, bb, ab = UnpackColor(cb) if t then @@ -46228,11 +46608,13 @@ end function M.SetTarget(buf: buffer, width: number) TargetBuffer, TargetWidth = buf, width + UX1 = UX0 end @native function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number) local rw = rx1 - rx0 + UX0, UY0, UX1, UY1, UV = rx0, ry0, rx1, ry1, 0 if rw == TargetWidth then buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4) else @@ -46247,13 +46629,16 @@ function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: nu end end --- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2 +-- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2, 4 line quad (va vb vc vd) @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) +local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, vd: 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 + elseif kind == 4 then + DrawLineQuad(TargetBuffer, vbuf, va, vb, vc, vd, 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 @@ -46272,7 +46657,7 @@ 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 + local REC_A, REC_B, REC_C, REC_D = M.REC_A, M.REC_B, M.REC_C, M.REC_D M.SetTarget(Scratch, TILE) local out, no = {}, 0 local o = 0 @@ -46296,7 +46681,7 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } 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) + DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, q + REC_D, tox, toy, cx0, cy0, cx1, cy1) end local rw, rh = rx1 - rx0, ry1 - ry0 local sub = buffer.create(rw * rh * 4) @@ -46353,8 +46738,19 @@ function M.GetBackendData() end @native -local function CopyTexturePixels(tex, dst, x, y, w, h) +local function CopyTexturePixels(tex, dst, x, y, w, h, dst_zero) local bpp, tex_w = tex.BytesPerPixel, tex.Width + if x == 0 and w == tex_w and bpp == 4 then -- whole rows: one flat loop; dst_zero: skip writing zero pixels + local src, s = tex:GetPixelsAt(0, y) + local d = y * tex_w * 4 + for _ = 1, w * h do + local v = src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216 + if v ~= 0 or not dst_zero then writeu32(dst, d, v) end + s += 4 + d += 4 + end + return + end for row = 0, h - 1 do local src, src_base = tex:GetPixelsAt(x, y + row) local dst_off = ((y + row) * tex_w + x) * 4 @@ -46376,8 +46772,34 @@ 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) + local w, h = tex.Width, tex.Height + local b = buffer.create(w * h * 4) + -- The current font atlas texture: pixels outside the packed rects (MaxRectBounds) and the queued uploads (UsedRect) + -- are still zero (repack's BlockCopy doesn't queue, but every copied rect is packed). Fill them with what zero + -- converts to, convert only the used corner. A fresh/grown atlas is mostly empty. Any other texture: everything. + local atlas = ImGui.GetCurrentContext() and ImGui.GetIO().Fonts + local cw, ch = w, h + if atlas and atlas.TexData == tex and atlas.Builder then + local u, m = tex.UsedRect, atlas.Builder.MaxRectBounds + cw = math.min(w, math.max(u.x + u.w, m.x)) + ch = math.min(h, math.max(u.y + u.h, m.y)) + end + if cw < w or ch < h then + if tex.BytesPerPixel ~= 4 then -- Alpha8 zero -> 0x00FFFFFF; RGBA zero -> 0 (buffer.create's fill) + local n, total = 4, w * h * 4 + writeu32(b, 0, 16777215) + while n < total do + local c = math.min(n, total - n) + buffer.copy(b, n, b, 0, c) + n += c + end + end + CopyTexturePixels(tex, b, 0, 0, cw, ch, tex.BytesPerPixel == 4) + else + CopyTexturePixels(tex, b, 0, 0, w, h, true) + end + -- rows FillRow.. hold only Fill (what zero converts to): parallel.lua sends Actors the rows above it + local t = { Buffer = b, Width = w, Height = h, FillRow = ch, Fill = tex.BytesPerPixel ~= 4 and 16777215 or 0 } EditableImages.LastTextureId += 1 Records[EditableImages.LastTextureId] = t tex.BackendUserData = EditableImages.LastTextureId @@ -46394,10 +46816,19 @@ function M.UpdateTexture(tex) CreateTextureRecord(tex) return end + local y0, y1 = math.huge, -1 for _, r in tex.Updates:iter() do CopyTexturePixels(tex, t.Buffer, r.x, r.y, r.w, r.h) + if r.y < y0 then y0 = r.y end + if r.y + r.h > y1 then y1 = r.y + r.h end end - t.V = (t.V or 0) + 1 -- parallel workers hold copies, resent when this changes + -- parallel workers hold copies, patched when this changes: Log[V] = changed rows (only the last 16 kept) + if t.FillRow and y1 > t.FillRow then t.FillRow = y1 end + local v = (t.V or 0) + 1 + t.V = v + t.Log = t.Log or {} + t.Log[v] = y1 > y0 and { y0, y1 } or { 0, 0 } + t.Log[v - 16] = nil tex:SetStatus(0 --[[ImTextureStatus.OK]]) elseif tex.Status == 4 --[[ImTextureStatus.WantDestroy]] then if tex.BackendUserData then @@ -46974,10 +47405,9 @@ local function HashVertex(h1: number, h2: number, vbuf: buffer, v: number, ox: n 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 + -- one % per hash: h < 2^31, so h * 48271 + the terms (|x|, |y| < 2^15, uv < 2^14, c < 2^32) stays below 2^53 + h1 = (h1 * 48271 + (x * 4096 + y) * 31 + uv * 4096 + c) % P1 + h2 = (h2 * 16807 + (y * 4093 + x) * 17 + uv * 65521 + c * 3) % P2 return h1, h2 end @@ -47024,6 +47454,10 @@ local function HashTiles(layer, plist, np, lx0, ly0, ox, oy) h1 = (h1 * 48271 + gk) % P1 h2 = (h2 * 16807 + gk * 3) % P2 end + if gk == 3 then -- line quad: any shape + h1, h2 = HashVertex(h1, h2, vbuf, PrimB[p], vax, vay) + h1, h2 = HashVertex(h1, h2, vbuf, vd, vax, vay) + end else h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay) h1, h2 = HashVertex(h1, h2, vbuf, PrimB[p], vax, vay) @@ -47264,7 +47698,7 @@ local function RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1) 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) + DrawPrim(kind, PrimTexture[p], PrimVtxBuffer[p], PrimA[p], PrimB[p], PrimC[p], PrimD[p] or 0, tox, toy, cx0, cy0, cx1, cy1) end end @@ -47506,7 +47940,22 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, 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 = readu32(vbuf, va + 32) + if t and readu32(vbuf, vb + 32) == col and readu32(vbuf, vc + 32) == col + and readu32(vbuf, d + 32) == col then + -- textured line quad (ImPlot PrimLine): uv a = b, c = d, u a ~= u c (else a textured rect may match) + local tax, tay, tcx, tcy = readf64(vbuf, va + 16), readf64(vbuf, va + 24), + readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) + if tax ~= tcx and readf64(vbuf, vb + 16) == tax + and readf64(vbuf, vb + 24) == tay and readf64(vbuf, d + 16) == tcx + and readf64(vbuf, d + 24) == tcy then + vd, gk = d, 3 + bx0, by0 = floor(min(pax, pbx, pcx, pdx) - ox), floor(min(pay, pby, pcy, pdy) - oy) + bx1 = ceil(max(pax, pbx, pcx, pdx) - ox) + 1 + by1 = ceil(max(pay, pby, pcy, pdy) - oy) + 1 + end + end + if not vd and 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) @@ -47650,14 +48099,16 @@ function M.RenderDrawData(draw_data) 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, + EditableImages.StageFrame = { Compare = 0, Collect = 0, Hash = 0, Raster = 0, Upload = 0, Textures = 0, Flush = 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 + if EditableImages.StageTiming then EditableImages.BeginStage() end UpdateTextures(draw_data) + if EditableImages.StageTiming then EditableImages.EndStage("Textures") end if not RenderRateAllows(BackendData, draw_data) then PE() return @@ -47730,13 +48181,15 @@ function M.RenderDrawData(draw_data) BackendData.StaleHeartbeat = BackendData.HeartbeatCount end if Parallel.Active then + if EditableImages.StageTiming then EditableImages.BeginStage() end Parallel.Flush() + if EditableImages.StageTiming then EditableImages.EndStage("Flush") end 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 + f.Other = f.Total - f.Compare - f.Collect - f.Hash - f.Raster - f.Upload - f.Textures - f.Flush BackendData.FrameStats = f end PE() @@ -47764,15 +48217,18 @@ 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 +local VTX, REC, REC_A, REC_B, REC_C, REC_D, JOB = Raster.VTX, Raster.REC, Raster.REC_A, Raster.REC_B, Raster.REC_C, + Raster.REC_D, 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, +M.Config = { Actors = 4, MinTiles = 1, MinPixels = 2048, MaxBytesPerPixel = 0, 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, + -- why a flush stayed serial: dispatch window closed / Actors not ready / below MinTiles or MinPixels / over MaxBytesPerPixel + SerialClosed = 0, SerialNotReady = 0, SerialSmall = 0, SerialBytes = 0, } local Stats = M.Stats @@ -47907,9 +48363,10 @@ function M.Tile(img, list, count: number, x0: number, y0: number, tox: number, t 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 + if not d or gk == 3 then copy(P, pn + REC_B, vb, PrimB[p], VTX) end + if gk == 3 then copy(P, pn + REC_D, vb, d, VTX) end pn += REC end writei32(T, to, poff[p]) @@ -47979,6 +48436,21 @@ function M.Finish() Stats.Finish += os.clock() - t0 end +-- A whole texture for an Actor without a copy (new id: grow/repack): only the rows above FillRow, the Actor fills the +-- rest with Fill (a new atlas is mostly empty). Built once per version, shared by every Actor's SendMessage. +local function fullCopy(rec, v: number): buffer + if rec.HeadV ~= v then + local src, len = rec.Buffer, (rec.FillRow or rec.Height) * rec.Width * 4 + local head = src + if len < buffer.len(src) then + head = buffer.create(len) + copy(head, 0, src, 0, len) + end + rec.Head, rec.HeadV = head, v + end + return rec.Head +end + function M.Flush() local n = jobs.N if n == 0 then @@ -47996,6 +48468,11 @@ function M.Flush() bytes += Pn[a] + Tn[a] end par = bytes <= cfg.MaxBytesPerPixel * jobs.Px + if not par then Stats.SerialBytes += 1 end + elseif not par then + if not open then Stats.SerialClosed += 1 + elseif not (cfg.Sync or ready) then Stats.SerialNotReady += 1 + else Stats.SerialSmall += 1 end end batch_no += 1 local b = jobs @@ -48019,14 +48496,38 @@ function M.Flush() 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 + local had = s[rec] + if had ~= v then if tex == NO_TEX then tex = {} end s[rec] = v - tex[#tex + 1] = { id, rec.Buffer, rec.Width, rec.Height } + -- the Actor has version `had`: send only the rows changed since then when the log covers them + local y0, y1, log = math.huge, -1, rec.Log + if had and log then + for k = had + 1, v do + local e = log[k] + if not e then y0 = nil; break end + if e[2] > e[1] then + if e[1] < y0 then y0 = e[1] end + if e[2] > y1 then y1 = e[2] end + end + end + else + y0 = nil + end + if y0 == nil then + local buf = fullCopy(rec, v) + tex[#tex + 1] = { id, buf, rec.Width, rec.Height, rec.Fill or 0 } + Stats.TexBytes += buffer.len(buf) + elseif y1 > y0 then + local row = rec.Width * 4 + local patch = buffer.create((y1 - y0) * row) + copy(patch, 0, rec.Buffer, y0 * row, (y1 - y0) * row) + tex[#tex + 1] = { id, false, rec.Width, rec.Height, y0 * row, patch } + Stats.TexBytes += buffer.len(patch) + end Stats.TexSends += 1 - Stats.TexBytes += buffer.len(rec.Buffer) end end Stats.SendBytes += Pn[a] + tl @@ -55369,13 +55870,15 @@ end --- @param s table # 1-based --- @param c any --- @param n int +@native function ImStd.memset(s, c, n) for i = 1, n do s[i] = c end end do -local _memmove = function(dest, dest_start, src, src_start, count) +@native +local function _memmove(dest, dest_start, src, src_start, count) if count <= 0 then return end local c = (dest == src and dest_start >= src_start) @@ -64218,13 +64721,13 @@ function ImGui.TextEx(text, text_end, flags) -- [Luau] scalar text_pos, scratch bb (ItemAdd() copies it, RenderTextWrapped() only reads it) local text_pos_x, text_pos_y = dc.CursorPos.x, dc.CursorPos.y + dc.CurrLineTextBaseOffset local wrap_width = wrap_enabled and ImGui.CalcWrapWidthForPos(dc.CursorPos, wrap_pos_x) or 0.0 - local text_size = ImGui.CalcTextSizeEx(text, 1, text_end, false, wrap_width) + local text_size_x, text_size_y = ImGui.CalcTextSizeXY(text, 1, text_end, false, wrap_width) local bb = TextEx_bb local bb_min, bb_max = bb.Min, bb.Max bb_min.x = text_pos_x; bb_min.y = text_pos_y - bb_max.x = text_pos_x + text_size.x; bb_max.y = text_pos_y + text_size.y - ImGui.ItemSize(text_size, 0.0) + bb_max.x = text_pos_x + text_size_x; bb_max.y = text_pos_y + text_size_y + ImGui.ItemSize(bb, 0.0) -- [Luau] the bb's size == text_size if not ImGui.ItemAdd(bb, 0) then return end @@ -64450,6 +64953,8 @@ end -- Text with a little bullet aligned to the typical tree node. --- @param fmt string --- @param ... any +local BulletText_bb, BulletText_pos, BulletText_size = ImRect(), ImVec2(), ImVec2() -- [Luau] scratch, only read by callees + function ImGui.BulletText(fmt, ...) local window = ImGui.GetCurrentWindow() if window.SkipItems then @@ -64461,20 +64966,26 @@ function ImGui.BulletText(fmt, ...) local text = ImFormatString(fmt, ...) local text_end = #text + 1 - local label_size = ImGui.CalcTextSize(text, text_end, false) - local total_size = ImVec2(g.FontSize + ((label_size.x > 0.0) and (label_size.x + style.FramePadding.x * 2) or 0.0), label_size.y) -- Empty text doesn't add padding + local label_size_x, label_size_y = ImGui.CalcTextSizeXY(text, 1, text_end, false) -- [Luau] scalar label_size/total_size + local total_size_x = g.FontSize + ((label_size_x > 0.0) and (label_size_x + style.FramePadding.x * 2) or 0.0) -- Empty text doesn't add padding -- [Luau] scalar pos, no temporary ImVec2 local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset + local bb = BulletText_bb + bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = pos_x, pos_y, pos_x + total_size_x, pos_y + label_size_y + local total_size = BulletText_size + total_size.x, total_size.y = total_size_x, label_size_y ImGui.ItemSize(total_size, 0.0) - local bb = ImRect(pos_x, pos_y, pos_x + total_size.x, pos_y + total_size.y) if not ImGui.ItemAdd(bb, 0) then return end -- Render local text_col = ImGui.GetColorU32(0 --[[ImGuiCol.Text]]) - ImGui.RenderBullet(window.DrawList, ImVec2(bb.Min.x + (style.FramePadding.x + g.FontSize * 0.5), bb.Min.y + g.FontSize * 0.5), text_col) - ImGui.RenderText(ImVec2(bb.Min.x + (g.FontSize + style.FramePadding.x * 2), bb.Min.y + 0.0), text, 1, text_end, false) + local p = BulletText_pos + p.x, p.y = bb.Min.x + (style.FramePadding.x + g.FontSize * 0.5), bb.Min.y + g.FontSize * 0.5 + ImGui.RenderBullet(window.DrawList, p, text_col) + p.x, p.y = bb.Min.x + (g.FontSize + style.FramePadding.x * 2), bb.Min.y + 0.0 + ImGui.RenderText(p, text, 1, text_end, false) end -- [Port] va_list variants: identical to the varargs versions in Lua @@ -64852,6 +65363,7 @@ end --- @param size_arg? ImVec2 --- @param flags? ImGuiButtonFlags --- @return bool +local ButtonEx_bb, ButtonEx_label_size, ButtonEx_size = ImRect(), ImVec2(), ImVec2() local ButtonEx_text_min, ButtonEx_text_max = ImVec2(), ImVec2() @native @@ -64868,7 +65380,8 @@ function ImGui.ButtonEx(label, size_arg, flags) local style = g.Style local id = window:GetID(label) local label_end = ImGui.FindRenderedTextEnd(label) - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size = ButtonEx_label_size -- [Luau] scratch: only read below (RenderTextClipped text_size_if_known) + label_size.x, label_size.y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar pos, no temporary ImVec2 local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y @@ -64876,9 +65389,11 @@ function ImGui.ButtonEx(label, size_arg, flags) 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 end - local size = ImGui.CalcItemSize(size_arg, label_size.x + frame_padding.x * 2.0, label_size.y + frame_padding.y * 2.0) + local size = ButtonEx_size -- [Luau] scratch + scalar CalcItemSize(): ItemSize() only reads it + size.x, size.y = ImGui._CalcItemSizeXY(size_arg.x, size_arg.y, label_size.x + frame_padding.x * 2.0, label_size.y + frame_padding.y * 2.0) - local bb = ImRect(pos_x, pos_y, pos_x + size.x, pos_y + size.y) + local bb = ButtonEx_bb -- [Luau] scratch: ItemAdd() copies it, ButtonBehavior()/Render*() only read it + bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = pos_x, pos_y, pos_x + size.x, pos_y + size.y ImGui.ItemSize(size, frame_padding.y) if not ImGui.ItemAdd(bb, id) then return false @@ -65407,6 +65922,8 @@ end --- @param v bool --- @return bool is_pressed --- @return bool is_checked # The updated `v` passed in +local Checkbox_total_bb, Checkbox_check_bb, Checkbox_label_pos = ImRect(), ImRect(), ImVec2() -- [Luau] scratch, only read by callees + @native function ImGui.Checkbox(label, v) local window = ImGui.GetCurrentWindow() @@ -65418,18 +65935,19 @@ function ImGui.Checkbox(label, v) local style = g.Style local id = window:GetID(label) local label_end = ImGui.FindRenderedTextEnd(label) - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size local square_sz = g.FontSize + style.FramePadding.y * 2.0 -- [Luau] inline GetFrameHeight() local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y -- [Luau] scalar pos, no temporary ImVec2 local total_width - if label_size.x > 0.0 then - total_width = square_sz + style.ItemInnerSpacing.x + label_size.x + if label_size_x > 0.0 then + total_width = square_sz + style.ItemInnerSpacing.x + label_size_x else total_width = square_sz end - local total_bb = ImRect(pos_x, pos_y, pos_x + total_width, pos_y + (label_size.y + style.FramePadding.y * 2.0)) + local total_bb = Checkbox_total_bb + total_bb.Min.x, total_bb.Min.y, total_bb.Max.x, total_bb.Max.y = pos_x, pos_y, pos_x + total_width, pos_y + (label_size_y + style.FramePadding.y * 2.0) ImGui.ItemSize(total_bb, style.FramePadding.y) local is_visible = ImGui.ItemAdd(total_bb, id) local is_multi_select = (bit32.band(g.LastItemData.ItemFlags, 4194304 --[[ImGuiItemFlags.IsMultiSelect]]) ~= 0) @@ -65461,7 +65979,8 @@ function ImGui.Checkbox(label, v) ImGui.MarkItemEdited(id) end - local check_bb = ImRect(pos_x, pos_y, pos_x + square_sz, pos_y + square_sz) + local check_bb = Checkbox_check_bb + check_bb.Min.x, check_bb.Min.y, check_bb.Max.x, check_bb.Max.y = pos_x, pos_y, pos_x + square_sz, pos_y + square_sz local mixed_value = (bit32.band(g.LastItemData.ItemFlags, 4096 --[[ImGuiItemFlags.MixedValue]]) ~= 0) if is_visible then ImGui.RenderNavCursor(total_bb, id) @@ -65486,8 +66005,9 @@ function ImGui.Checkbox(label, v) ImGui.LogRenderedText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), mixed_value and "[~]" or (v and "[x]" or "[ ]")) -- label_pos end - if is_visible and label_size.x > 0.0 then - local label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y) -- [Luau] only built when used + if is_visible and label_size_x > 0.0 then + local label_pos = Checkbox_label_pos + label_pos.x, label_pos.y = check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y ImGui.RenderText(label_pos, label, 1, label_end, false) end @@ -67610,7 +68130,8 @@ end -- [Luau] memo of string.format(format, value) for drag/slider value text (same values are redrawn every frame). local fmt_memo, fmt_memo_n = {}, 0 -local SliderScalar_total_bb, SliderScalar_grab_bb = ImRect(), ImRect() -- [Luau] scratch for SliderScalar()/DragScalar(), never escape +local SliderScalar_total_bb, SliderScalar_grab_bb, SliderScalar_frame_bb = ImRect(), ImRect(), ImRect() -- [Luau] scratch for SliderScalar()/DragScalar(), never escape +local SliderScalar_label_pos = ImVec2() local DRAG_TEXT_ALIGN = ImVec2(0.5, 0.5) function FormatCached(format, v) local m = fmt_memo[format] @@ -67641,12 +68162,13 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla local color_marker = (bit32.band(g.NextItemData.HasFlags, 32 --[[ImGuiNextItemDataFlags.HasColorMarker]]) ~= 0) and g.NextItemData.ColorMarker or 0 local label_end = ImGui.FindRenderedTextEnd(label) - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size local cursor = window.DC.CursorPos - local frame_bb = ImRect(cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size.y + style.FramePadding.y * 2.0)) -- [Luau] no temporary ImVec2 + local frame_bb = SliderScalar_frame_bb -- [Luau] scratch: callees only read it + frame_bb.Min.x, frame_bb.Min.y, frame_bb.Max.x, frame_bb.Max.y = cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size_y + style.FramePadding.y * 2.0) local total_bb = SliderScalar_total_bb -- [Luau] scratch: ItemSize()/ItemAdd() only read it total_bb.Min.x = frame_bb.Min.x; total_bb.Min.y = frame_bb.Min.y - total_bb.Max.x = frame_bb.Max.x + ((label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0); total_bb.Max.y = frame_bb.Max.y + 0.0 + total_bb.Max.x = frame_bb.Max.x + ((label_size_x > 0.0) and (style.ItemInnerSpacing.x + label_size_x) or 0.0); total_bb.Max.y = frame_bb.Max.y + 0.0 local temp_input_allowed = (bit32.band(flags, 128 --[[ImGuiSliderFlags.NoInput]]) == 0) ImGui.ItemSize(total_bb, style.FramePadding.y) @@ -67734,8 +68256,10 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla ImGui.PopStyleColor() end - if label_size.x > 0.0 then - ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, 1, label_end, false) + if label_size_x > 0.0 then + local label_pos = SliderScalar_label_pos + label_pos.x, label_pos.y = frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y + ImGui.RenderText(label_pos, label, 1, label_end, false) end return data, value_changed @@ -68346,10 +68870,11 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) local color_marker = (bit32.band(g.NextItemData.HasFlags, 32 --[[ImGuiNextItemDataFlags.HasColorMarker]]) ~= 0) and g.NextItemData.ColorMarker or 0 local label_end = ImGui.FindRenderedTextEnd(label) - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size local cursor = window.DC.CursorPos - local frame_bb = ImRect(cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size.y + style.FramePadding.y * 2.0)) -- [Luau] no temporary ImVec2 - local total_bb_x = frame_bb.Max.x + ((label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0) + local frame_bb = SliderScalar_frame_bb -- [Luau] scratch: callees only read it + frame_bb.Min.x, frame_bb.Min.y, frame_bb.Max.x, frame_bb.Max.y = cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size_y + style.FramePadding.y * 2.0) + local total_bb_x = frame_bb.Max.x + ((label_size_x > 0.0) and (style.ItemInnerSpacing.x + label_size_x) or 0.0) local total_bb = SliderScalar_total_bb -- [Luau] scratch: ItemSize()/ItemAdd() only read it total_bb.Min.x = frame_bb.Min.x; total_bb.Min.y = frame_bb.Min.y; total_bb.Max.x = total_bb_x; total_bb.Max.y = frame_bb.Max.y @@ -68435,8 +68960,10 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) ImGui.PopStyleColor() end - if label_size.x > 0.0 then - ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, 1, label_end, false) + if label_size_x > 0.0 then + local label_pos = SliderScalar_label_pos + label_pos.x, label_pos.y = frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y + ImGui.RenderText(label_pos, label, 1, label_end, false) end -- IMGUI_TEST_ENGINE_ITEM_INFO() @@ -71920,6 +72447,10 @@ end --- @param flags ImGuiTreeNodeFlags --- @param label string --- @param label_end? int +local TreeNode_frame_bb, TreeNode_interact_bb = ImRect(), ImRect() -- [Luau] scratch for TreeNodeBehavior(), never escape +local TreeNode_label_size, TreeNode_text_pos, TreeNode_tmp = ImVec2(), ImVec2(), ImVec2() +local function TreeNode_tmp_pos(x, y) local v = TreeNode_tmp; v.x = x; v.y = y; return v end -- [Luau] scratch pos for Render*() args + @native function ImGui.TreeNodeBehavior(id, flags, label, label_end) local window = ImGui.GetCurrentWindow() @@ -71944,7 +72475,8 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) if label_end == nil then label_end = ImGui.FindRenderedTextEnd(label) end - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size = TreeNode_label_size -- [Luau] scratch: only read below (RenderTextClipped text_size_if_known) + label_size.x, label_size.y = ImGui.CalcTextSizeXY(label, 1, label_end, false) local text_offset_x = g.FontSize + (display_frame and (padding_x * 3) or (padding_x * 2)) -- Collapsing arrow width + Spacing local text_offset_y = use_frame_padding and ImMax(style.FramePadding.y, window.DC.CurrLineTextBaseOffset) or window.DC.CurrLineTextBaseOffset -- Latch before ItemSize changes it @@ -71953,7 +72485,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local frame_height = label_size.y + padding_y * 2 local span_all_columns = bit32.band(flags, 16384 --[[ImGuiTreeNodeFlags.SpanAllColumns]]) ~= 0 and (g.CurrentTable ~= nil) local span_all_columns_label = bit32.band(flags, 32768 --[[ImGuiTreeNodeFlags.LabelSpanAllColumns]]) ~= 0 and (g.CurrentTable ~= nil) - local frame_bb = ImRect() + local frame_bb = TreeNode_frame_bb -- [Luau] scratch, fully written here; callees copy or only read it frame_bb.Min.x = span_all_columns and window.ParentWorkRect.Min.x or (bit32.band(flags, 4096 --[[ImGuiTreeNodeFlags.SpanFullWidth]]) ~= 0 and window.WorkRect.Min.x or window.DC.CursorPos.x) frame_bb.Min.y = window.DC.CursorPos.y + (text_offset_y - padding_y) frame_bb.Max.x = span_all_columns and window.ParentWorkRect.Max.x or (bit32.band(flags, 8192 --[[ImGuiTreeNodeFlags.SpanLabelWidth]]) ~= 0 and window.DC.CursorPos.x + text_width + padding_x or window.WorkRect.Max.x) @@ -71964,12 +72496,13 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) frame_bb.Max.x = frame_bb.Max.x + outer_extend end - local text_pos = ImVec2(window.DC.CursorPos.x + text_offset_x, window.DC.CursorPos.y + text_offset_y) + local text_pos = TreeNode_text_pos -- [Luau] scratch + text_pos.x, text_pos.y = window.DC.CursorPos.x + text_offset_x, window.DC.CursorPos.y + text_offset_y local item_size = LayoutHelpers_size; item_size.x = text_width; item_size.y = frame_height -- [Luau] scratch, ItemSize() only reads it ImGui.ItemSize(item_size, padding_y) -- For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing - local interact_bb = ImRect() + local interact_bb = TreeNode_interact_bb -- [Luau] scratch, ItemAdd()/ButtonBehavior()/SetNavID() copy or only read it ImRect_Copy(interact_bb, frame_bb) if bit32.band(flags, bit32.bor(2 --[[ImGuiTreeNodeFlags.Framed]], 2048 --[[ImGuiTreeNodeFlags.SpanAvailWidth]], 4096 --[[ImGuiTreeNodeFlags.SpanFullWidth]], 8192 --[[ImGuiTreeNodeFlags.SpanLabelWidth]], 16384 --[[ImGuiTreeNodeFlags.SpanAllColumns]])) == 0 then interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0 and (style.ItemSpacing.x * 2.0) or 0.0) @@ -72163,9 +72696,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.TablePopBackgroundChannel() end if bit32.band(flags, 512 --[[ImGuiTreeNodeFlags.Bullet]]) ~= 0 then - ImGui.RenderBullet(window.DrawList, ImVec2(text_pos.x - text_offset_x * 0.60, text_pos.y + g.FontSize * 0.5), text_col) + ImGui.RenderBullet(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x * 0.60, text_pos.y + g.FontSize * 0.5), text_col) elseif not is_leaf then - ImGui.RenderArrow(window.DrawList, ImVec2(text_pos.x - text_offset_x + padding_x, text_pos.y), text_col, is_open and ((bit32.band(flags, 536870912 --[[ImGuiTreeNodeFlags.UpsideDownArrow]]) ~= 0) and 2 --[[ImGuiDir.Up]] or 3 --[[ImGuiDir.Down]]) or 1 --[[ImGuiDir.Right]], 1.0) + ImGui.RenderArrow(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x + padding_x, text_pos.y), text_col, is_open and ((bit32.band(flags, 536870912 --[[ImGuiTreeNodeFlags.UpsideDownArrow]]) ~= 0) and 2 --[[ImGuiDir.Up]] or 3 --[[ImGuiDir.Down]]) or 1 --[[ImGuiDir.Right]], 1.0) else -- Leaf without bullet, left-adjusted text text_pos.x = text_pos.x - (text_offset_x - padding_x) end @@ -72186,9 +72719,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.TablePopBackgroundChannel() end if bit32.band(flags, 512 --[[ImGuiTreeNodeFlags.Bullet]]) ~= 0 then - ImGui.RenderBullet(window.DrawList, ImVec2(text_pos.x - text_offset_x * 0.5, text_pos.y + g.FontSize * 0.5), text_col) + ImGui.RenderBullet(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x * 0.5, text_pos.y + g.FontSize * 0.5), text_col) elseif not is_leaf then - ImGui.RenderArrow(window.DrawList, ImVec2(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.15), text_col, is_open and ((bit32.band(flags, 536870912 --[[ImGuiTreeNodeFlags.UpsideDownArrow]]) ~= 0) and 2 --[[ImGuiDir.Up]] or 3 --[[ImGuiDir.Down]]) or 1 --[[ImGuiDir.Right]], 0.70) + ImGui.RenderArrow(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.15), text_col, is_open and ((bit32.band(flags, 536870912 --[[ImGuiTreeNodeFlags.UpsideDownArrow]]) ~= 0) and 2 --[[ImGuiDir.Up]] or 3 --[[ImGuiDir.Down]]) or 1 --[[ImGuiDir.Right]], 0.70) end if g.LogEnabled then ImGui.LogSetNextTextDecoration(">", nil) @@ -72196,7 +72729,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) end if draw_tree_lines then - ImGui.TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.5)) + ImGui.TreeNodeDrawLineToChildNode(TreeNode_tmp_pos(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.5)) end -- Label @@ -76451,6 +76984,7 @@ local STBRP__PREV_LINK_TYPE = { --- @return stbrp_rect --- @nodiscard +@native local function stbrp_rect() return { -- reserved for your use: @@ -76474,6 +77008,7 @@ end --- @return stbrp_node --- @nodiscard +@native local function stbrp_node() return { x = 0, @@ -76495,6 +77030,7 @@ end --- @return stbrp_context --- @nodiscard +@native local function stbrp_context() return { width = 0, @@ -76517,6 +77053,7 @@ end --- @field prev_link_type? int --- @return stbrp__findresult +@native local function stbrp__findresult() return { x = 0, @@ -76537,6 +77074,7 @@ end -- If you call init again, this will be reset to the default. --- @param context stbrp_context --- @param heuristic int +@native local function stbrp_setup_heuristic(context, heuristic) if context.init_mode == STBRP__INIT_skyline then STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight or heuristic == STBRP_HEURISTIC_Skyline.BF_sortHeight) @@ -76551,6 +77089,7 @@ end -- If you call init again, this will be reset to the default (false). --- @param context stbrp_context --- @param allow_out_of_mem boolean +@native local function stbrp_setup_allow_out_of_mem(context, allow_out_of_mem) if allow_out_of_mem then -- if it's ok to run out of memory, then don't bother aligning them; @@ -76594,6 +77133,7 @@ end --- @param height int --- @param nodes stbrp_node[] --- @param num_nodes int +@native function stbrp_init_target(context, width, height, nodes, num_nodes) for i = 1, num_nodes - 1 do nodes[i].next = nodes[i + 1] @@ -76624,6 +77164,7 @@ end --- @param x0 int --- @param width int --- @return int, int +@native local function stbrp__skyline_find_min_y(c, first, x0, width) local node = first local x1 = x0 + width @@ -76671,6 +77212,7 @@ end --- @param width int --- @param height int --- @return stbrp__findresult +@native local function stbrp__skyline_find_best_pos(c, width, height) local best_waste = bit32.lshift(1, 30) local best_x = 0 @@ -76800,6 +77342,7 @@ end --- @param width int --- @param height int --- @return stbrp__findresult +@native local function stbrp__skyline_pack_rectangle(context, width, height) -- find best position according to heuristic local res = stbrp__skyline_find_best_pos(context, width, height) @@ -76868,6 +77411,7 @@ end --- @param b stbrp_rect --- @return bool --- @package +@native local function rect_height_compare(a, b) if a.h > b.h then return true @@ -76882,6 +77426,7 @@ end --- @param b stbrp_rect --- @return bool --- @package +@native local function rect_original_order(a, b) return a.was_packed < b.was_packed end @@ -76913,6 +77458,7 @@ end --- @param rects stbrp_rect[] --- @param num_rects int --- @return int +@native local function stbrp_pack_rects(context, rects, num_rects) local all_rects_packed = 1 @@ -78720,7 +79266,7 @@ local stbtt_MakeGlyphBitmapSubpixelPrefilter local stbtt_GetFontVMetrics local stbtt__GetGlyphInfoT2 local stbtt__GetGlyphShapeT2 -local stbtt_GetGlyphShape +local stbtt_GetGlyphShape, stbtt_GetGlyphShapeUncached local stbtt_GetGlyphBitmapBox local stbtt_GetGlyphBitmapBoxSubpixel local stbtt_GetGlyphHMetrics @@ -78773,6 +79319,7 @@ local trunc = function(x) end end +@native local function STBTT__NOTUSED(_) return end --- @alias stbtt_int32 int @@ -78795,6 +79342,7 @@ local unsigned_char = stbtt_uint8 --- @param initial_offset? int --- @return stbtt__buf --- @nodiscard +@native local function stbtt__buf(initial_offset) return { data = nil, @@ -78829,6 +79377,7 @@ end --- @field fdselect stbtt__buf # map from glyph to fontdict --- @return stbtt_fontinfo +@native function stbtt_fontinfo() return { data = nil, @@ -78869,6 +79418,7 @@ end --- @return stbtt_vertex --- @nodiscard +@native local function stbtt_vertex() return { x = nil, @@ -78898,6 +79448,7 @@ end --- @return stbtt__csctx --- @nodiscard +@native local function stbtt__csctx() return { bounds = false, @@ -78919,6 +79470,7 @@ end --- @param bounds bool --- @return stbtt__csctx --- @nodiscard +@native local function STBTT__CSCTX_INIT(bounds) local this = stbtt__csctx() @@ -78952,6 +79504,7 @@ end --- @return stbtt__edge --- @nodiscard +@native local function stbtt__edge() return { x0 = nil, @@ -78966,6 +79519,7 @@ end --- @return stbtt__active_edge --- @nodiscard +@native local function stbtt__active_edge() return { next = nil, @@ -78980,8 +79534,15 @@ end --- @return stbtt__active_edge --- @nodiscard +local active_pool, active_pool_n = {}, 0 -- [Luau] reused per stbtt__rasterize_sorted_edges() call (C: stbtt__hheap) +@native local function stbtt__new_active(e, off_x, start_point) - local z = stbtt__active_edge() + active_pool_n = active_pool_n + 1 + local z = active_pool[active_pool_n] + if z == nil then + z = stbtt__active_edge() + active_pool[active_pool_n] = z + end local dxdy = (e.x1 - e.x0) / (e.y1 - e.y0) z.fdx = dxdy @@ -79005,6 +79566,7 @@ end --- @return stbtt__bitmap --- @nodiscard +@native local function stbtt__bitmap() return { w = nil, @@ -79020,6 +79582,7 @@ end --- @return stbtt__point --- @nodiscard +@native local function stbtt__point() return { x = nil, y = nil } end ---------------------------------------------- @@ -79030,6 +79593,7 @@ local function stbtt__point() return { x = nil, y = nil } end --- --- @param b stbtt__buf +@native local function stbtt__buf_get8(b) if b.cursor >= b.size then return 0 end local result = b.data[b.offset + b.cursor + 1] @@ -79038,6 +79602,7 @@ local function stbtt__buf_get8(b) end --- @param b stbtt__buf +@native local function stbtt__buf_peek8(b) if b.cursor >= b.size then return 0 end return b.data[b.offset + b.cursor + 1] @@ -79045,6 +79610,7 @@ end --- @param b stbtt__buf --- @param o int +@native local function stbtt__buf_seek(b, o) STBTT_assert(not (o > b.size or o < 0)) if o > b.size or o < 0 then @@ -79056,10 +79622,12 @@ end --- @param b stbtt__buf --- @param o int +@native local function stbtt__buf_skip(b, o) stbtt__buf_seek(b, b.cursor + o) end +@native local function stbtt__buf_get(b, n) local v = 0 STBTT_assert(n >= 1 and n <= 4) @@ -79074,6 +79642,7 @@ end --- @param offset? int --- @return stbtt__buf --- @nodiscard +@native local function stbtt__new_buf(p, size, offset) local r = stbtt__buf(offset) STBTT_assert(size < 0x40000000) @@ -79084,8 +79653,10 @@ local function stbtt__new_buf(p, size, offset) end --- @param b stbtt__buf +@native local function stbtt__buf_get16(b) return stbtt__buf_get(b, 2) end --- @param b stbtt__buf +@native local function stbtt__buf_get32(b) return stbtt__buf_get(b, 4) end --- @param b stbtt__buf @@ -79093,6 +79664,7 @@ local function stbtt__buf_get32(b) return stbtt__buf_get(b, 4) end --- @param s int --- @return stbtt__buf --- @nodiscard +@native local function stbtt__buf_range(b, o, s) local r = stbtt__new_buf(nil, 0) if (o < 0 or s < 0 or o > b.size or s > (b.size - o)) then @@ -79105,6 +79677,7 @@ local function stbtt__buf_range(b, o, s) end --- @param b stbtt__buf +@native local function stbtt__cff_get_index(b) local count, start, offsize start = b.cursor @@ -79119,6 +79692,7 @@ local function stbtt__cff_get_index(b) end --- @param b stbtt__buf +@native local function stbtt__cff_int(b) local b0 = stbtt__buf_get8(b) if b0 >= 32 and b0 <= 246 then return b0 - 139 @@ -79132,6 +79706,7 @@ local function stbtt__cff_int(b) end --- @param b stbtt__buf +@native local function stbtt__cff_skip_operand(b) local v local b0 = stbtt__buf_peek8(b) @@ -79153,6 +79728,7 @@ end --- @param key int --- @return stbtt__buf --- @nodiscard +@native local function stbtt__dict_get(b, key) stbtt__buf_seek(b, 0) while b.cursor < b.size do @@ -79174,6 +79750,7 @@ end --- @param outcount int --- @return int[] --- @nodiscard +@native local function stbtt__dict_get_ints(b, key, outcount) local operands = stbtt__dict_get(b, key) local out = {} @@ -79185,6 +79762,7 @@ local function stbtt__dict_get_ints(b, key, outcount) end --- @param b stbtt__buf +@native local function stbtt__cff_index_count(b) stbtt__buf_seek(b, 0) return stbtt__buf_get16(b) @@ -79194,6 +79772,7 @@ end --- @param i int --- @return stbtt__buf --- @nodiscard +@native local function stbtt__cff_index_get(b, i) local count, offsize, start, _end stbtt__buf_seek(b, 0) @@ -79237,17 +79816,26 @@ end --- stbtt_GetNumberOfFonts_internal --- stbtt__get_svg +@native local function ttUSHORT(p, offset) return stbtt_uint16(p[offset + 1] * 256 + p[offset + 2]) end +@native local function ttSHORT(p, offset) return stbtt_int16(p[offset + 1] * 256 + p[offset + 2]) end +@native local function ttULONG(p, offset) return stbtt_uint32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end +@native local function ttLONG(p, offset) return stbtt_int32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end +@native local function ttBYTE(p, offset) return stbtt_uint8(p[offset + 1]) end +@native local function ttCHAR(p, offset) return stbtt_int8(p[offset + 1]) end +@native local function stbtt_tag4(p, c0, c1, c2, c3, offset) offset = offset or 0; return p[offset + 1] == c0 and p[offset + 2] == c1 and p[offset + 3] == c2 and p[offset + 4] == c3 end +@native local function stbtt_tag(p, str, offset) local c0, c1, c2, c3 = string.byte(str, 1, 4); return stbtt_tag4(p, c0, c1, c2, c3, offset) end +@native local function stbtt__isfont(font) -- check the version number if stbtt_tag4(font, 49, 0, 0, 0) then return true end -- TrueType 1 @@ -79259,6 +79847,7 @@ local function stbtt__isfont(font) end -- @OPTIMIZE: binary search +@native local function stbtt__find_table(data, font_start, tag) local num_tables = ttUSHORT(data, font_start + 4) local tabledir = font_start + 12 @@ -79271,6 +79860,7 @@ local function stbtt__find_table(data, font_start, tag) return 0 end +@native local function stbtt_GetFontOffsetForIndex_internal(font_collection, index) -- if it's just a font, there's only one valid index if stbtt__isfont(font_collection) then @@ -79294,6 +79884,7 @@ end --- @param cff stbtt__buf --- @param fontdict stbtt__buf +@native local function stbtt__get_subrs(cff, fontdict) local private_loc = stbtt__dict_get_ints(fontdict, 18, 2) if (private_loc[2] == 0 or private_loc[1] == 0) then @@ -79309,6 +79900,7 @@ local function stbtt__get_subrs(cff, fontdict) end --- @return bool +@native local function stbtt_InitFont_internal(info, data, fontstart) local cmap local numTables @@ -79436,6 +80028,7 @@ end -- Returns 0 if the character codepoint is not defined in the font. --- @param info stbtt_fontinfo --- @param unicode_codepoint int +@native function stbtt_FindGlyphIndex(info, unicode_codepoint) local data = info.data local index_map = info.index_map @@ -79541,6 +80134,7 @@ end --- @param y stbtt_int32 --- @param cx stbtt_int32 --- @param cy stbtt_int32 +@native local function stbtt_setvertex(v, vtx_type, x, y, cx, cy) v.type = vtx_type v.x = (stbtt_int16)(x) @@ -79549,6 +80143,7 @@ local function stbtt_setvertex(v, vtx_type, x, y, cx, cy) v.cy = (stbtt_int16)(cy) end +@native local function stbtt__GetGlyfOffset(info, glyph_index) STBTT_assert(info.cff.size == 0) @@ -79569,6 +80164,7 @@ end -- Gets the bounding box of the visible part of the glyph, in unscaled coordinates --- @return integer, integer?, integer?, integer?, integer? +@native local function stbtt_GetGlyphBox(info, glyph_index) local n, x0, y0, x1, y1 @@ -79597,6 +80193,7 @@ end --- @param scy stbtt_int32 --- @param cx stbtt_int32 --- @param cy stbtt_int32 +@native local function stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy) if start_off then if was_off then @@ -79621,6 +80218,7 @@ end --- @param glyph_index int --- @return int num_vertices --- @return stbtt_vertex[]? vertices +@native local function stbtt__GetGlyphShapeTT(info, glyph_index) local data = info.data local num_vertices @@ -79840,7 +80438,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) n = STBTT_sqrt(mtx[3] * mtx[3] + mtx[4] * mtx[4]) -- Get indexed glyph. - comp_num_vertices, comp_verts = stbtt_GetGlyphShape(info, gidx) + comp_num_vertices, comp_verts = stbtt_GetGlyphShapeUncached(info, gidx) -- [Luau] transformed in place below: must be a fresh copy if comp_num_vertices > 0 then -- Transform vertices. for i = 1, comp_num_vertices do @@ -79878,6 +80476,7 @@ end --- @param c stbtt__csctx --- @param x stbtt_int32 --- @param y stbtt_int32 +@native local function stbtt__track_vertex(c, x, y) if x > c.max_x or not c.started then c.max_x = x end if y > c.max_y or not c.started then c.max_y = y end @@ -79894,6 +80493,7 @@ end --- @param cy stbtt_int32 --- @param cx1 stbtt_int32 --- @param cy1 stbtt_int32 +@native local function stbtt__csctx_v(c, vtx_type, x, y, cx, cy, cx1, cy1) if c.bounds then stbtt__track_vertex(c, x, y) @@ -79909,6 +80509,7 @@ local function stbtt__csctx_v(c, vtx_type, x, y, cx, cy, cx1, cy1) end --- @param ctx stbtt__csctx +@native local function stbtt__csctx_close_shape(ctx) if ctx.first_x ~= ctx.x or ctx.first_y ~= ctx.y then stbtt__csctx_v(ctx, STBTT_VTX.LINE, trunc(ctx.first_x), trunc(ctx.first_y), 0, 0, 0, 0) @@ -79918,6 +80519,7 @@ end --- @param ctx stbtt__csctx --- @param dx float --- @param dy float +@native local function stbtt__csctx_rmove_to(ctx, dx, dy) stbtt__csctx_close_shape(ctx) ctx.x = ctx.x + dx @@ -79930,6 +80532,7 @@ end --- @param ctx stbtt__csctx --- @param dx float --- @param dy float +@native local function stbtt__csctx_rline_to(ctx, dx, dy) ctx.x = ctx.x + dx ctx.y = ctx.y + dy @@ -79943,6 +80546,7 @@ end --- @param dy2 float --- @param dx3 float --- @param dy3 float +@native local function stbtt__csctx_rccurve_to(ctx, dx1, dy1, dx2, dy2, dx3, dy3) local cx1 = ctx.x + dx1 local cy1 = ctx.y + dy1 @@ -79953,6 +80557,7 @@ local function stbtt__csctx_rccurve_to(ctx, dx1, dy1, dx2, dy2, dx3, dy3) stbtt__csctx_v(ctx, STBTT_VTX.CUBIC, trunc(ctx.x), trunc(ctx.y), trunc(cx1), trunc(cy1), trunc(cx2), trunc(cy2)) end +@native local function stbtt__get_subr(idx, n) local count = stbtt__cff_index_count(idx) local bias = 107 @@ -79968,6 +80573,7 @@ local function stbtt__get_subr(idx, n) return stbtt__cff_index_get(idx, n) end +@native local function stbtt__cid_get_glyph_subrs(info, glyph_index) local fdselect = info.fdselect local fdselector = -1 @@ -79998,6 +80604,7 @@ end --- @param info stbtt_fontinfo --- @param glyph_index int --- @param c stbtt__csctx +@native local function stbtt__run_charstring(info, glyph_index, c) local in_header = true local maskbits = 0 @@ -80271,6 +80878,7 @@ end --- @param glyph_index int --- @return int num_vertices --- @return stbtt_vertex[]? vertices +@native function stbtt__GetGlyphShapeT2(info, glyph_index) -- runs the charstring twice, once to count and once to output (to avoid realloc) local vertices = nil @@ -80296,6 +80904,7 @@ end --- @return int y0 --- @return int x1 --- @return int y1 +@native function stbtt__GetGlyphInfoT2(info, glyph_index) local c = STBTT__CSCTX_INIT(true) local r = stbtt__run_charstring(info, glyph_index, c) @@ -80317,7 +80926,8 @@ end -- its x,y, using cx,cy as the bezier control point. --- @param info stbtt_fontinfo --- @param glyph_index int -function stbtt_GetGlyphShape(info, glyph_index) +@native +function stbtt_GetGlyphShapeUncached(info, glyph_index) if info.cff.size == 0 then return stbtt__GetGlyphShapeTT(info, glyph_index) else @@ -80325,11 +80935,32 @@ function stbtt_GetGlyphShape(info, glyph_index) end end +@native +function stbtt_GetGlyphShape(info, glyph_index) + -- [Luau] shapes don't depend on the size: cache them per font (baking a new size re-used to re-parse every glyph). + -- Callers only read the vertices (stbtt_FreeShape is a no-op). + local cache = info._ShapeCache + if cache == nil then cache = {}; info._ShapeCache = cache end + local e = cache[glyph_index] + if e == nil then + local n, v + if info.cff.size == 0 then + n, v = stbtt__GetGlyphShapeTT(info, glyph_index) + else + n, v = stbtt__GetGlyphShapeT2(info, glyph_index) + end + e = { n, v } + cache[glyph_index] = e + end + return e[1], e[2] +end + -- leftSideBearing is the offset from the current horizontal position to the left edge of the character -- advanceWidth is the offset from the current horizontal position to the next horizontal position -- these are expressed in unscaled coordinates --- @param info stbtt_fontinfo --- @param glyph_index int +@native function stbtt_GetGlyphHMetrics(info, glyph_index) local numOfLongHorMetrics = ttUSHORT(info.data, info.hhea + 34) @@ -80352,6 +80983,7 @@ end -- these are expressed in unscaled coordinates, so you must multiply by -- the scale factor for a given size --- @param info stbtt_fontinfo +@native function stbtt_GetFontVMetrics(info) local ascent = ttSHORT(info.data, info.hhea + 4) local descent = ttSHORT(info.data, info.hhea + 6) @@ -80368,6 +81000,7 @@ end -- so if you prefer to measure height by the ascent only, use a similar calculation. --- @param info stbtt_fontinfo --- @param height float +@native function stbtt_ScaleForPixelHeight(info, height) local fheight = ttSHORT(info.data, info.hhea + 4) - ttSHORT(info.data, info.hhea + 6) return height / fheight @@ -80388,6 +81021,7 @@ end --- @param scale_y float --- @param shift_x float --- @param shift_y float +@native function stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, shift_x, shift_y) local n, x0, y0, x1, y1 = stbtt_GetGlyphBox(font, glyph) @@ -80418,6 +81052,7 @@ end --- @param glyph int --- @param scale_x float --- @param scale_y float +@native function stbtt_GetGlyphBitmapBox(font, glyph, scale_x, scale_y) return stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, 0.0, 0.0) end @@ -80445,6 +81080,7 @@ end --- @param y0 float --- @param x1 float --- @param y1 float +@native local function stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1) if y0 == y1 then return end STBTT_assert(y0 < y1) @@ -80486,6 +81122,7 @@ end --- @param height float --- @param top_width float --- @param bottom_width float +@native local function stbtt__sized_trapezoid_area(height, top_width, bottom_width) STBTT_assert(top_width >= 0) STBTT_assert(bottom_width >= 0) @@ -80497,12 +81134,14 @@ end --- @param tx1 float --- @param bx0 float --- @param bx1 float +@native local function stbtt__position_trapezoid_area(height, tx0, tx1, bx0, bx1) return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0) end --- @param height float --- @param width float +@native local function stbtt__sized_triangle_area(height, width) return height * width / 2 end @@ -80512,6 +81151,7 @@ end --- @param len int --- @param e stbtt__active_edge --- @param y_top float +@native local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_top) local y_bottom = y_top + 1 @@ -80734,11 +81374,14 @@ end --- @param vsubsample int --- @param off_x int --- @param off_y int +local rasterize_scanline, rasterize_scanline2 = {}, {} -- [Luau] reused: fully cleared per scanline below +@native local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y) local active = nil - local scanline = {} -- [Port] size = result.w, 0-based - local scanline2 = {} -- [Port] size = result.w + 1, 0-based + active_pool_n = 0 -- every active edge of the previous call is dead + local scanline = rasterize_scanline -- [Port] size = result.w, 0-based + local scanline2 = rasterize_scanline2 -- [Port] size = result.w + 1, 0-based STBTT__NOTUSED(vsubsample) @@ -80796,20 +81439,18 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of do local sum = 0 + local pixels, base = result.pixels, j * result.stride + 1 for i = 0, result.w - 1 do - local k - local m sum = sum + scanline2[i] - k = scanline[i] + sum - k = STBTT_fabs(k) * 255 + 0.5 - m = trunc(k) + -- [Luau] k >= 0: trunc == floor, and m is already 0..255 (unsigned_char() is a no-op) + local m = math.floor(math.abs(scanline[i] + sum) * 255 + 0.5) if m > 255 then m = 255 end - result.pixels[j * result.stride + i + 1] = unsigned_char(m) + pixels[base + i] = m end end -- advance all the edges - step = active + local step = active while step do step.fx = step.fx + step.fdx -- advance to position for current scanline step = step.next -- advance through list @@ -80829,10 +81470,47 @@ local STBTT__COMPARE = function(a, b) end --- @param p stbtt__edge[] +@native local function stbtt__sort_edges(p) STBTT_sort(p, STBTT__COMPARE) end +-- [Luau] sorts p[lo..hi] by y0 without a comparator callback (like upstream's stbtt__sort_edges_quicksort + ins_sort) +@native +local function stbtt__sort_edges_range(p, lo, hi) + while hi - lo > 12 do + -- median of three -> p[lo] + local m = math.floor((lo + hi) / 2) + local a, b, c = p[lo], p[m], p[hi] + if b.y0 < a.y0 then a, b = b, a end + if c.y0 < b.y0 then b, c = c, b; if b.y0 < a.y0 then a, b = b, a end end + p[lo], p[m], p[hi] = b, a, c + local pivot = p[lo].y0 + local i, j = lo + 1, hi + while true do + while p[i].y0 < pivot do i = i + 1 end + while pivot < p[j].y0 do j = j - 1 end + if i >= j then break end + p[i], p[j] = p[j], p[i] + i = i + 1; j = j - 1 + end + p[lo], p[j] = p[j], p[lo] + -- recurse into the smaller side, loop on the larger + if j - lo < hi - j then + stbtt__sort_edges_range(p, lo, j - 1); lo = j + 1 + else + stbtt__sort_edges_range(p, j + 1, hi); hi = j - 1 + end + end + for i = lo + 1, hi do + local t = p[i] + local y = t.y0 + local j = i - 1 + while j >= lo and p[j].y0 > y do p[j + 1] = p[j]; j = j - 1 end + p[j + 1] = t + end +end + --- @param result stbtt__bitmap --- @param pts stbtt__point[] --- @param wcount int[] @@ -80844,6 +81522,8 @@ end --- @param off_x int --- @param off_y int --- @param invert bool +local rasterize_edges = {} +@native local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, shift_x, shift_y, off_x, off_y, invert) local y_scale_inv = (invert) and -scale_y or scale_y local vsubsample = 1 -- STBTT_RASTERIZER_VERSION == 2 @@ -80855,7 +81535,13 @@ local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, n = n + wcount[i] end - local e = {} for i = 1, n + 1 do e[i] = stbtt__edge() end -- add an extra one as a sentinel + -- [Luau] edges reused across calls; unused entries are sentinels (y0 = nil) like the unfilled ones upstream + local e = rasterize_edges + for i = 1, n + 1 do + local ed = e[i] + if ed == nil then e[i] = stbtt__edge() else ed.y0 = nil; ed.invert = false end + end + for i = n + 2, #e do e[i].y0 = nil end n = 0 local m = 0 @@ -80899,7 +81585,7 @@ local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, end -- now sort the edges by their highest point (should snap to integer, and then by x) - stbtt__sort_edges(e) + stbtt__sort_edges_range(e, 1, n) -- [Luau] e[n + 1..] are y0 == nil sentinels, already last -- now, traverse the scanlines and find the intersections on each scanline, use xor winding rule stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y) @@ -80909,6 +81595,7 @@ end --- @param n int --- @param x float --- @param y float +@native local function stbtt__add_point(points, n, x, y) if points == nil then return end -- during first pass, it's unallocated points[n + 1].x = x @@ -80927,6 +81614,7 @@ end --- @param objspace_flatness_squared float --- @param n int --- @return int num_points # updated num_points passed in +@native local function stbtt__tesselate_curve(points, num_points, x0, y0, x1, y1, x2, y2, objspace_flatness_squared, n) -- midpoint local mx = (x0 + 2 * x1 + x2) / 4 @@ -80963,6 +81651,7 @@ end --- @param objspace_flatness_squared float --- @param n int --- @return int num_points # updated num_points passed in +@native local function stbtt__tesselate_cubic(points, num_points, x0, y0, x1, y1, x2, y2, x3, y3, objspace_flatness_squared, n) -- @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough local dx0 = x1 - x0 @@ -81014,6 +81703,8 @@ end --- @return stbtt__point[]? points --- @return int? num_contours --- @return int[]? contour_lengths +local flatten_points = {} +@native local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) local points = nil local num_points = 0 @@ -81038,8 +81729,8 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) for pass = 0, 1 do local x, y = 0, 0 if pass == 1 then - points = {} - for i = 1, num_points do points[i] = stbtt__point() end + points = flatten_points -- [Luau] reused across calls (only [1..num_points] is read) + for i = #points + 1, num_points do points[i] = stbtt__point() end end num_points = 0 n = -1 @@ -81096,6 +81787,7 @@ end --- @param x_off int --- @param y_off int --- @param invert bool +@native local function stbtt_Rasterize(result, flatness_in_pixels, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert) local scale = (scale_x > scale_y) and scale_y or scale_x @@ -81123,6 +81815,7 @@ end --- @param shift_x float --- @param shift_y float --- @param glyph int +@native local function stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, glyph) local num_verts, vertices = stbtt_GetGlyphShape(info, glyph) local gbm = stbtt__bitmap() @@ -81176,6 +81869,7 @@ local STBTT__OVER_MASK = STBTT_MAX_OVERSAMPLE - 1 --- @param h int --- @param stride_in_bytes int --- @param kernel_width unsigned_int +@native local function stbtt__h_prefilter(pixels, w, h, stride_in_bytes, kernel_width) local buffer = {} local safe_w = w - kernel_width @@ -81205,6 +81899,7 @@ end --- @param h int --- @param stride_in_bytes int --- @param kernel_width unsigned_int +@native local function stbtt__v_prefilter(pixels, w, h, stride_in_bytes, kernel_width) local buffer = {} local safe_h = h - kernel_width @@ -81231,6 +81926,7 @@ end --- @param oversample int --- @return float +@native local function stbtt__oversample_shift(oversample) if oversample == 0 then return 0.0 @@ -81257,6 +81953,7 @@ end --- @param prefilter_x int --- @param prefilter_y int --- @param glyph int +@native function stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, prefilter_x, prefilter_y, glyph) stbtt_MakeGlyphBitmapSubpixel(info, output, out_w - (prefilter_x - 1), out_h - (prefilter_y - 1), out_stride, scale_x, scale_y, shift_x, shift_y, glyph) @@ -81310,6 +82007,7 @@ end -- return '0' for index 0, and -1 for all other indices. --- @param data table --- @param index int +@native function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForIndex_internal(data, index) end -- Given an offset into the file that defines a font, this function builds @@ -81320,6 +82018,7 @@ function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForI --- @param info stbtt_fontinfo --- @param data table --- @param offset int +@native function stbtt_InitFont(info, data, offset) return stbtt_InitFont_internal(info, data, offset) end return { @@ -81855,6 +82554,7 @@ return { ImFontBaked_BuildLoadGlyph = ImFontBaked_BuildLoadGlyph, ImFontBaked_BuildLoadGlyphAdvanceX = ImFontBaked_BuildLoadGlyphAdvanceX, ImFontCalcTextSizeEx = ImFontCalcTextSizeEx, + ImFontCalcTextSizeXY = ImFontCalcTextSizeXY, ImFontCalcWordWrapPositionEx = ImFontCalcWordWrapPositionEx, ImFontCalcWordWrapPositionEx_Uncached = ImFontCalcWordWrapPositionEx_Uncached, ImFontConfig = ImFontConfig, @@ -82217,6 +82917,7 @@ return { stbtt_GetGlyphBitmapBoxSubpixel = stbtt_GetGlyphBitmapBoxSubpixel, stbtt_GetGlyphHMetrics = stbtt_GetGlyphHMetrics, stbtt_GetGlyphShape = stbtt_GetGlyphShape, + stbtt_GetGlyphShapeUncached = stbtt_GetGlyphShapeUncached, stbtt_InitFont = stbtt_InitFont, stbtt_MakeGlyphBitmapSubpixelPrefilter = stbtt_MakeGlyphBitmapSubpixelPrefilter, stbtt_ScaleForPixelHeight = stbtt_ScaleForPixelHeight, diff --git a/build/ImGuiTyped.luau b/build/ImGuiTyped.luau index cfaa28a..8aedd13 100644 --- a/build/ImGuiTyped.luau +++ b/build/ImGuiTyped.luau @@ -70,6 +70,7 @@ export type ImGuiAPI = { CalcRoundingFlagsForRectInRect: (...any) -> ...any, CalcTextSize: (text: string, text_end: string?, hide_text_after_double_hash: boolean?, wrap_width: number?) -> ImVec2, CalcTextSizeEx: (...any) -> ...any, + CalcTextSizeXY: (...any) -> ...any, CalcTypematicRepeatAmount: (...any) -> ...any, CalcWindowNextAutoFitSize: (...any) -> ...any, CalcWrapWidthForPos: (...any) -> ...any, diff --git a/build/ImGuiWorker.client.luau b/build/ImGuiWorker.client.luau index 57415e6..e88cc52 100644 --- a/build/ImGuiWorker.client.luau +++ b/build/ImGuiWorker.client.luau @@ -18,11 +18,11 @@ 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. + -- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2, 4 line quad), 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, d at REC_D. -- 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, + VTX = 36, REC = 184, REC_A = 40, REC_C = 76, REC_B = 112, REC_D = 148, JOB = 32, } local TILE = M.TILE @@ -49,6 +49,31 @@ local function RowRepeats(o: number, len: number, has_prev: boolean): boolean end local RectColumns = table.create(256, 0) +-- Uniform region: [UX0, UX1) x [UY0, UY1) of the target holds only the pixel value UV (empty when UX0 >= UX1). +-- Set by ClearRect and by solid rects; shrunk by everything drawn over it. A solid rect inside it blends one pixel and +-- fills (window/frame backgrounds over backgrounds), instead of blending every pixel. +local UX0, UY0, UX1, UY1, UV = 0, 0, 0, 0, 0 + +-- Drawing may change [x0, x1) x [y0, y1): keep the largest uniform piece outside it +@native +local function Shrink(x0: number, y0: number, x1: number, y1: number) + if x0 >= UX1 or x1 <= UX0 or y0 >= UY1 or y1 <= UY0 or UX0 >= UX1 then return end + local h, w = UY1 - UY0, UX1 - UX0 + local left, right, top, bottom = (x0 - UX0) * h, (UX1 - x1) * h, (y0 - UY0) * w, (UY1 - y1) * w + local best = max(left, right, top, bottom) + if best <= 0 then + UX1 = UX0 + elseif best == left then + UX1 = x0 + elseif best == right then + UX0 = x1 + elseif best == top then + UY1 = y0 + else + UY0 = y1 + end +end + -- 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) @@ -84,13 +109,44 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number b: number, a: number) if a <= 0 then return end local w4 = (x1 - x0 - 1) * 4 + if x0 >= UX0 and y0 >= UY0 and x1 <= UX1 and y1 <= UY1 and a < 255 then + -- over one value: FillSpan's per-pixel result for d = UV, then fill + local d, v = UV, 0 + if d < 16777216 then + v = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216 + else + local sa = a / 255 + local ns = 1 - sa + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + v = 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) * (ns / 255) + local oa = sa + k + local inv = 1 / oa + v = 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 + local first = (y0 * TargetWidth + x0) * 4 + for o = first, first + w4, 4 do writeu32(TargetBuffer, o, v) end + for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end + UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, v + return + end 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 + -- now uniform: keep whichever region is larger + local area = (x1 - x0) * (y1 - y0) + Shrink(x0, y0, x1, y1) + if area > (UX1 - UX0) * (UY1 - UY0) or UX0 >= UX1 then UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, packed end return end + Shrink(x0, y0, x1, y1) 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 @@ -155,11 +211,12 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number 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 + if a >= 255 or px1 - px0 < 32 or (px0 >= UX0 and py0 >= UY0 and px1 <= UX1 and py1 <= UY1) 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 + Shrink(px0, py0, px1, py1) local len = (px1 - px0) * 4 local prev_o = 0 for y = py0, py1 - 1 do @@ -174,11 +231,14 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number return end + Shrink(px0, py0, px1, py1) 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 + local ident = col == 4294967295 + local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 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 @@ -191,17 +251,47 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number 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) + if tv < 16777216 then + o += 4 + continue + end + if ident and tv >= 4278190080 then -- white opaque vertex colour: an opaque texel is the result + writeu32(dbuf, o, tv) + o += 4 + continue + end + -- BlendPixel inlined (same math) + if tv ~= last_tv then + last_tv = tv + sa = rshift(tv, 24) * a255 + sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255 + s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + fa = sa / 255 + fn = 1 - fa + fk = (1 - fa) / 255 + end + if sa >= 255 then + writeu32(dbuf, o, s_opaque + 4278190080) + elseif sa > 0 then + local d = readu32(dbuf, o) + if d < 16777216 then + writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216) else - BlendPixel(dbuf, o, sr, sg, sb, sa) + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 + + floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080) + else + local k = rshift(d, 24) * fk + local oa = fa + k + local inv = 1 / oa + writeu32(dbuf, o, floor((sr * fa + dr * k) * inv + 0.5) + + floor((sg * fa + dg * k) * inv + 0.5) * 256 + + floor((sb * fa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + end end end - o = o + 4 + o += 4 end end end @@ -223,6 +313,7 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, 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 + Shrink(minx, miny, maxx + 1, maxy + 1) local A0, B0 = y1 - y2, x2 - x1 local C0 = -(A0 * x1 + B0 * y1) @@ -262,6 +353,64 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, f_c1 = f_ns / 255 f_rs, f_gs, f_bs = ra * f_sa, ga * f_sa, ba * f_sa end + local cconst = 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 cconst and aa <= 0 then return end + local tw: number, th: number, tbuf: buffer = 0, 0, dbuf + local r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255 + local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 + if cconst then tw, th, tbuf = t.Width, t.Height, t.Buffer end + + if not textured and (maxx - minx) * 2 < maxy - miny then + -- tall sliver (vertical AA fringe): walk columns, same per-pixel edge and colour math as the rows below (each + -- pixel blended once, so the order does not matter): no empty-row passes + local m0, m1, m2 = B0 ~= 0 and -1 / B0 or 0, B1 ~= 0 and -1 / B1 or 0, B2 ~= 0 and -1 / B2 or 0 + local stride = TargetWidth * 4 + for x = minx, maxx do + local px = x + 0.5 + local yt, yb = miny, maxy + local f0, f1, f2 = A0 * px + C0, A1 * px + C1, A2 * px + C2 + if B0 > 0 then yt = max(yt, floor(f0 * m0 - 0.500001)) elseif B0 < 0 then yb = min(yb, ceil(f0 * m0 - 0.499999)) end + if B1 > 0 then yt = max(yt, floor(f1 * m1 - 0.500001)) elseif B1 < 0 then yb = min(yb, ceil(f1 * m1 - 0.499999)) end + if B2 > 0 then yt = max(yt, floor(f2 * m2 - 0.500001)) elseif B2 < 0 then yb = min(yb, ceil(f2 * m2 - 0.499999)) end + while yt <= yb do + local py = yt + 0.5 + local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2) + 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 + yt += 1 + end + while yb > yt do + local py = yb + 0.5 + local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2) + 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 + yb -= 1 + end + if yt > yb then continue end + local o = (yt * TargetWidth + x) * 4 + if flat then + for _ = yt, yb do + BlendPixel(dbuf, o, ra, ga, ba, aa) + o += stride + end + continue + end + for y = yt, yb do + local py = y + 0.5 + local w0, w1, w2 = (A0 * px + (B0 * py + C0)) * inv, (A1 * px + (B1 * py + C1)) * inv, + (A2 * px + (B2 * py + C2)) * inv + local a = w0 * aa + w1 * ab + w2 * ac + if 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 += stride + end + end + return + end for y = miny, maxy do local py = y + 0.5 @@ -333,6 +482,50 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, end continue end + if cconst then + -- constant vertex colour, varying uv (AA line textures): texel read as u32, blend cached per texel value + 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 tx, ty = floor((w0 * ua + w1 * ub + w2 * uc) * tw), floor((w0 * vva + w1 * vvb + w2 * vvc) * 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 tv = readu32(tbuf, (ty * tw + tx) * 4) + if tv ~= last_tv then + last_tv = tv + sa = rshift(tv, 24) * a255 + sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255 + s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + fa = sa / 255 + fn = 1 - fa + fk = (1 - fa) / 255 + end + -- BlendPixel inlined (same math) + if sa >= 255 then + writeu32(dbuf, o, s_opaque + 4278190080) + elseif sa > 0 then + local d = readu32(dbuf, o) + if d < 16777216 then + writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216) + else + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 + + floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080) + else + local k = rshift(d, 24) * fk + local oa = fa + k + local inv2 = 1 / oa + writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5) + + floor((sg * fa + dg * k) * inv2 + 0.5) * 256 + + floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + end + end + end + o += 4 + 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 @@ -352,6 +545,131 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, end end +-- Textured line quad (triangles a b c + a c d, one colour, uv a = b and c = d: ImPlot PrimLine). Same edge functions as +-- the two DrawTriangle calls (so the same pixels), uv from triangle a b c's barycentrics over the whole quad. +@native +local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number, vc: number, vd: 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 x3, y3 = readf64(vbuf, vd) - ox, readf64(vbuf, vd + 8) - oy + local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0) + local area2 = (x2 - x0) * (y3 - y0) - (y2 - y0) * (x3 - x0) + if area == 0 or area2 == 0 or (area < 0) ~= (area2 < 0) then -- degenerate or not convex: the two triangles + DrawTriangle(dbuf, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, ox, oy) + DrawTriangle(dbuf, vbuf, va, vc, vd, t, cx0, cy0, cx1, cy1, ox, oy) + return + end + local ua, vva, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) + -- outer edges P -> Q (quad order, counter-clockwise like DrawTriangle's swap): A = yP - yQ, B = xQ - xP, C from P + local px_, py_, qx_, qy_ = x1, y1, x3, y3 -- b, d + if area < 0 then + px_, py_, qx_, qy_ = x3, y3, x1, y1 + area = -area + end + -- order a -> p -> c -> q + local A0, B0 = y0 - py_, px_ - x0 + local C0 = -(A0 * x0 + B0 * y0) + local A1, B1 = py_ - y2, x2 - px_ + local C1 = -(A1 * px_ + B1 * py_) + local A2, B2 = y2 - qy_, qx_ - x2 + local C2 = -(A2 * x2 + B2 * y2) + local A3, B3 = qy_ - y0, x0 - qx_ + local C3 = -(A3 * qx_ + B3 * qy_) + 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 tl3 = A3 > 0 or (A3 == 0 and B3 > 0) + local n0, n1, n2, n3 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0, + A3 ~= 0 and -1 / A3 or 0 + -- weight of c in triangle a b c: edge a -> b over its area (same sign whichever side b is on) + local WA, WB = y0 - y1, x1 - x0 + local WC = -(WA * x0 + WB * y0) + local winv = 1 / ((x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0)) + WA, WB, WC = WA * winv, WB * winv, WC * winv + local du, dv = uc - ua, vvc - vva + + local minx, maxx = max(floor(min(x0, x1, x2, x3)), cx0), min(ceil(max(x0, x1, x2, x3)), cx1 - 1) + local miny, maxy = max(floor(min(y0, y1, y2, y3)), cy0), min(ceil(max(y0, y1, y2, y3)), cy1 - 1) + if minx > maxx or miny > maxy then return end + local ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32)) + if aa <= 0 then return end + Shrink(minx, miny, maxx + 1, maxy + 1) + local tw: number, th: number, tbuf: buffer = t.Width, t.Height, t.Buffer + local r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255 + local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 + for y = miny, maxy do + local py = y + 0.5 + local xl, xr = minx, maxx + local e0, e1, e2, e3 = B0 * py + C0, B1 * py + C1, B2 * py + C2, B3 * py + C3 + 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 + if A3 > 0 then xl = max(xl, floor(e3 * n3 - 0.500001)) elseif A3 < 0 then xr = min(xr, ceil(e3 * n3 - 0.499999)) end + while xl <= xr do + local px = xl + 0.5 + local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3 + if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) + and (w3 > 0 or (w3 == 0 and tl3)) then + break + end + xl += 1 + end + while xr > xl do + local px = xr + 0.5 + local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3 + if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) + and (w3 > 0 or (w3 == 0 and tl3)) then + break + end + xr -= 1 + end + if xl > xr then continue end + local o = (y * TargetWidth + xl) * 4 + local wrow = WB * py + WC + for x = xl, xr do + local w = WA * (x + 0.5) + wrow + local tx, ty = floor((ua + w * du) * tw), floor((vva + w * dv) * 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 tv = readu32(tbuf, (ty * tw + tx) * 4) + if tv ~= last_tv then + last_tv = tv + sa = rshift(tv, 24) * a255 + sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255 + s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + fa = sa / 255 + fn = 1 - fa + fk = (1 - fa) / 255 + end + -- BlendPixel inlined (same math) + if sa >= 255 then + writeu32(dbuf, o, s_opaque + 4278190080) + elseif sa > 0 then + local d = readu32(dbuf, o) + if d < 16777216 then + writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216) + else + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 + + floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080) + else + local k = rshift(d, 24) * fk + local oa = fa + k + local inv2 = 1 / oa + writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5) + + floor((sg * fa + dg * k) * inv2 + 0.5) * 256 + + floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + end + end + 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, @@ -359,6 +677,7 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1 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 + Shrink(px0, py0, px1, py1) local ra, ga, ba, aa = UnpackColor(ca) local rb, gb, bb, ab = UnpackColor(cb) if t then @@ -400,11 +719,13 @@ end function M.SetTarget(buf: buffer, width: number) TargetBuffer, TargetWidth = buf, width + UX1 = UX0 end @native function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number) local rw = rx1 - rx0 + UX0, UY0, UX1, UY1, UV = rx0, ry0, rx1, ry1, 0 if rw == TargetWidth then buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4) else @@ -419,13 +740,16 @@ function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: nu end end --- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2 +-- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2, 4 line quad (va vb vc vd) @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) +local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, vd: 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 + elseif kind == 4 then + DrawLineQuad(TargetBuffer, vbuf, va, vb, vc, vd, 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 @@ -444,7 +768,7 @@ 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 + local REC_A, REC_B, REC_C, REC_D = M.REC_A, M.REC_B, M.REC_C, M.REC_D M.SetTarget(Scratch, TILE) local out, no = {}, 0 local o = 0 @@ -468,7 +792,7 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } 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) + DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, q + REC_D, tox, toy, cx0, cy0, cx1, cy1) end local rw, rh = rx1 - rx0, ry1 - ry0 local sub = buffer.create(rw * rh * 4) @@ -487,7 +811,28 @@ 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] } + if Texture[2] then + local B, W, H, Fill = Texture[2], Texture[3], Texture[4], Texture[5] + local n, total = buffer.len(B), W * H * 4 + if n < total then -- the rows below were left out: all Fill (parallel.lua fullCopy) + local Full = buffer.create(total) + buffer.copy(Full, 0, B) + if Fill ~= 0 then + buffer.writeu32(Full, n, Fill) + local k = 4 + while k < total - n do + local c = math.min(k, total - n - k) + buffer.copy(Full, n + k, Full, n, c) + k += c + end + end + B = Full + end + Textures[Texture[1]] = { Buffer = B, Width = W, Height = H } + else -- rows changed since the copy this Actor has + local T = Textures[Texture[1]] + buffer.copy(T.Buffer, Texture[5], Texture[6]) + end end local Results = Raster.RasterJobs(Prims, Tiles, TileLength, Textures) task.synchronize() diff --git a/build/imgui_love.linemap.json b/build/imgui_love.linemap.json index da1731b..7b5b0a2 100644 --- a/build/imgui_love.linemap.json +++ b/build/imgui_love.linemap.json @@ -1 +1 @@ -[[183, "imgui.lua"], [22785, "imgui_demo.lua"], [34642, "imgui_draw.lua"], [42972, "imgui_h.lua"], [45973, "imgui_impl_love.lua"], [46517, "imgui_internal.lua"], [50483, "imgui_tables.lua"], [55575, "imgui_widgets.lua"], [67813, "imstb_rectpack.lua"], [68477, "imstb_textedit.lua"], [70019, "imstb_truetype.lua"], [72807, "imstd_minstdio.lua"]] \ No newline at end of file +[[183, "imgui.lua"], [22825, "imgui_demo.lua"], [34682, "imgui_draw.lua"], [43033, "imgui_h.lua"], [46034, "imgui_impl_love.lua"], [46578, "imgui_internal.lua"], [50546, "imgui_tables.lua"], [55638, "imgui_widgets.lua"], [67906, "imstb_rectpack.lua"], [68583, "imstb_textedit.lua"], [70125, "imstb_truetype.lua"], [73066, "imstd_minstdio.lua"]] \ No newline at end of file diff --git a/build/imgui_love.lua b/build/imgui_love.lua index 4359005..25d4091 100644 --- a/build/imgui_love.lua +++ b/build/imgui_love.lua @@ -138,7 +138,7 @@ if not utf8 then end -local ImGui, ImVec2, ImVec4, ImRect, ImVec2_Copy, HelpMarker, IMGUI_DEMO_MARKER, ImGuiTableFlags, ImStd, ImVector, ImGuiKey, ImDrawFlags, ImGuiInputFlags, ImRect_Copy, ImStb, ImGuiDataType, IM_TRUNC, 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, ImGuiMouseCursor, ImS64, DockSettingsRenameNodeReferences, ExampleDualListBoxMT, IM_DRAWLIST_TEX_LINES_WIDTH_MAX, ImCeil, ImFabs, ImGuiCol, ImGuiSelectionBasicStorage, ImS8, ImU8, ExampleAppPropertyEditorMT, ImGuiChildFlags, ImGuiScrollFlags, ImGui_ImplLOVE_GetBackendData, ExampleSelectionWithDeletionMT, CustomConstraints, ExampleAppLogMT, IMGUI_DEBUG_LOG_FONT, ImFontAtlasBuildInit, ImFontAtlasFontDestroyOutput, ImGuiComboFlags, ImGuiPopupFlags, ImGuiSliderFlags, ImTextClassifierSetCharClass, MyDocument, ShowExampleMenuFile, CalcCornerArcStepAndCount, ImFontAtlasBakedAddFontGlyph, ImFontAtlasPackAddRect, ImFontBaked_BuildLoadGlyph, ImFontConfig, ImGuiInputTextFlags, ImGuiStyle_Copy, ExampleAsset_s_current_sort_specs, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC, ImFontAtlasBuildNotifySetFont, ImFontAtlasBuildRenderBitmapFromString, ImFontAtlasFontDestroySourceData, ImFontAtlasFontSourceAddToFont, ImGuiTableColumn, stb_textedit_key, stbtt_GetGlyphBitmapBoxSubpixel, IM_FREE, ImDrawListSplitter, stb_text_locate_coord, stb_text_makeundo_insert, stb_text_makeundo_replace, stb_textedit_find_charpos, stbtt_GetGlyphShape, ImGuiTableColumnSortSpecs, ImGuiTableInstanceData, ImGuiTableSettings, stb_text_makeundo_delete, stb_text_redo, stb_text_undo, stb_textedit_click, stb_textedit_drag, stbtt_FindGlyphIndex, stbtt_GetFontOffsetForIndex, stbtt_GetFontVMetrics, stbtt_GetGlyphBitmapBox, stbtt_GetGlyphHMetrics, stbtt_InitFont, stbtt_MakeGlyphBitmapSubpixelPrefilter, stbtt_ScaleForPixelHeight, stbtt__GetGlyphInfoT2, stbtt__GetGlyphShapeT2, stbtt_fontinfo, ImGuiOldColumnData, ImGuiOldColumns, ImGuiTable, ImGuiTableColumnSettings, ImGuiTableSortSpecs, ImGuiTableTempData, ImGui_ImplLOVE_CreateTexture, ImGui_ImplLOVE_DestroyTexture, ImGui_ImplLOVE_Init, ImGui_ImplLOVE_NewFrame, ImGui_ImplLOVE_RenderDrawData, ImGui_ImplLOVE_Shutdown, ImGui_ImplLOVE_UpdateTexture, stbrp_init_target, IMGUI_TABLE_MAX_COLUMNS, IMSTB_TEXTEDIT_UNDOSTATECOUNT, IM_COL32_DISABLE, ImGui_ImplLove, STB_TEXTEDIT_K_BACKSPACE, STB_TEXTEDIT_K_DELETE, STB_TEXTEDIT_K_DOWN, STB_TEXTEDIT_K_LEFT, STB_TEXTEDIT_K_LINEEND, STB_TEXTEDIT_K_LINESTART, STB_TEXTEDIT_K_PGDOWN, STB_TEXTEDIT_K_PGUP, STB_TEXTEDIT_K_REDO, STB_TEXTEDIT_K_RIGHT, STB_TEXTEDIT_K_SHIFT, STB_TEXTEDIT_K_TEXTEND, STB_TEXTEDIT_K_TEXTSTART, STB_TEXTEDIT_K_UNDO, STB_TEXTEDIT_K_UP +local ImGui, ImVec2, ImVec4, ImRect, ImVec2_Copy, HelpMarker, IMGUI_DEMO_MARKER, ImGuiTableFlags, ImStd, ImVector, ImGuiKey, ImDrawFlags, ImGuiInputFlags, ImRect_Copy, ImStb, ImGuiDataType, IM_TRUNC, 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, ImGuiMouseCursor, ImS64, DockSettingsRenameNodeReferences, ExampleDualListBoxMT, IM_DRAWLIST_TEX_LINES_WIDTH_MAX, ImCeil, ImFabs, ImGuiCol, ImGuiSelectionBasicStorage, ImS8, ImU8, ExampleAppPropertyEditorMT, ImGuiChildFlags, ImGuiScrollFlags, ImGui_ImplLOVE_GetBackendData, ExampleSelectionWithDeletionMT, CustomConstraints, ExampleAppLogMT, IMGUI_DEBUG_LOG_FONT, ImFontAtlasBuildInit, ImFontAtlasFontDestroyOutput, ImGuiComboFlags, ImGuiPopupFlags, ImGuiSliderFlags, ImTextClassifierSetCharClass, MyDocument, ShowExampleMenuFile, CalcCornerArcStepAndCount, ImFontAtlasBakedAddFontGlyph, ImFontAtlasPackAddRect, ImFontBaked_BuildLoadGlyph, ImFontConfig, ImGuiInputTextFlags, ImGuiStyle_Copy, ExampleAsset_s_current_sort_specs, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC, ImFontAtlasBuildNotifySetFont, ImFontAtlasBuildRenderBitmapFromString, ImFontAtlasFontDestroySourceData, ImFontAtlasFontSourceAddToFont, ImGuiTableColumn, stb_textedit_key, stbtt_GetGlyphBitmapBoxSubpixel, IM_FREE, ImDrawListSplitter, stb_text_locate_coord, stb_text_makeundo_insert, stb_text_makeundo_replace, stb_textedit_find_charpos, stbtt__GetGlyphShapeT2, ImGuiTableColumnSortSpecs, ImGuiTableInstanceData, ImGuiTableSettings, stb_text_makeundo_delete, stb_text_redo, stb_text_undo, stb_textedit_click, stb_textedit_drag, stbtt_FindGlyphIndex, stbtt_GetFontOffsetForIndex, stbtt_GetFontVMetrics, stbtt_GetGlyphBitmapBox, stbtt_GetGlyphHMetrics, stbtt_GetGlyphShape, stbtt_GetGlyphShapeUncached, stbtt_InitFont, stbtt_MakeGlyphBitmapSubpixelPrefilter, stbtt_ScaleForPixelHeight, stbtt__GetGlyphInfoT2, stbtt_fontinfo, ImGuiOldColumnData, ImGuiOldColumns, ImGuiTable, ImGuiTableColumnSettings, ImGuiTableSortSpecs, ImGuiTableTempData, ImGui_ImplLOVE_CreateTexture, ImGui_ImplLOVE_DestroyTexture, ImGui_ImplLOVE_Init, ImGui_ImplLOVE_NewFrame, ImGui_ImplLOVE_RenderDrawData, ImGui_ImplLOVE_Shutdown, ImGui_ImplLOVE_UpdateTexture, stbrp_init_target, IMGUI_TABLE_MAX_COLUMNS, IMSTB_TEXTEDIT_UNDOSTATECOUNT, IM_COL32_DISABLE, ImGui_ImplLove, STB_TEXTEDIT_K_BACKSPACE, STB_TEXTEDIT_K_DELETE, STB_TEXTEDIT_K_DOWN, STB_TEXTEDIT_K_LEFT, STB_TEXTEDIT_K_LINEEND, STB_TEXTEDIT_K_LINESTART, STB_TEXTEDIT_K_PGDOWN, STB_TEXTEDIT_K_PGUP, STB_TEXTEDIT_K_REDO, STB_TEXTEDIT_K_RIGHT, STB_TEXTEDIT_K_SHIFT, STB_TEXTEDIT_K_TEXTEND, STB_TEXTEDIT_K_TEXTSTART, STB_TEXTEDIT_K_UNDO 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 @@ -5054,26 +5054,33 @@ local ImGuiResizeBorderDef = { --- @param thickness float --- @return ImRect --- @nodiscard -local function GetResizeBorderRect(window, border_n, perp_padding, thickness) - local rect = window:Rect() +-- [Luau] out: optional ImRect written in place (no allocation) +local function GetResizeBorderRect(window, border_n, perp_padding, thickness, out) + local x0, y0 = window.Pos.x, window.Pos.y + local x1, y1 = x0 + window.Size.x, y0 + window.Size.y if thickness == 0.0 then - ImVec2_CopyV(rect.Max, rect.Max.x - 1, rect.Max.y - 1) + x1, y1 = x1 - 1, y1 - 1 end + local a, b, c, d if border_n == 0 --[[ImGuiDir.Left]] then - return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding) + a, b, c, d = x0 - thickness, y0 + perp_padding, x0 + thickness, y1 - perp_padding + elseif border_n == 1 --[[ImGuiDir.Right]] then + a, b, c, d = x1 - thickness, y0 + perp_padding, x1 + thickness, y1 - perp_padding + elseif border_n == 2 --[[ImGuiDir.Up]] then + a, b, c, d = x0 + perp_padding, y0 - thickness, x1 - perp_padding, y0 + thickness + elseif border_n == 3 --[[ImGuiDir.Down]] then + a, b, c, d = x0 + perp_padding, y1 - thickness, x1 - perp_padding, y1 + thickness + else + assert(false) + a, b, c, d = 0, 0, 0, 0 end - if border_n == 1 --[[ImGuiDir.Right]] then - return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding) + if out then + out.Min.x, out.Min.y, out.Max.x, out.Max.y = a, b, c, d + return out end - if border_n == 2 --[[ImGuiDir.Up]] then - return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness) - end - if border_n == 3 --[[ImGuiDir.Down]] then - return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness) - end - assert(false) - return ImRect() + return ImRect(a, b, c, d) end +local UpdateWindowManualResize_rect = ImRect() -- [Luau] scratch grip/border rect: ItemAdd() copies, ButtonBehavior() reads -- Known size hash -- It is ok to call ImHashData on a string with known length but the ### operator won't be supported. @@ -10355,10 +10362,12 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c local corner_pos = def.CornerPosN local inner_dir = def.InnerDir - local corner = ImVec2(window.Pos.x + corner_pos.x * window.Size.x, window.Pos.y + corner_pos.y * window.Size.y) + local corner_x, corner_y = window.Pos.x + corner_pos.x * window.Size.x, window.Pos.y + corner_pos.y * window.Size.y -- Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window - local resize_rect = ImRect(corner - inner_dir * grip_hover_outer_size, corner + inner_dir * grip_hover_inner_size) + local resize_rect = UpdateWindowManualResize_rect -- [Luau] scratch, scalar math + resize_rect.Min.x, resize_rect.Min.y = corner_x - inner_dir.x * grip_hover_outer_size, corner_y - inner_dir.y * grip_hover_outer_size + resize_rect.Max.x, resize_rect.Max.y = corner_x + inner_dir.x * grip_hover_inner_size, corner_y + inner_dir.y * grip_hover_inner_size if resize_rect.Min.x > resize_rect.Max.x then resize_rect.Min.x, resize_rect.Max.x = resize_rect.Max.x, resize_rect.Min.x end if resize_rect.Min.y > resize_rect.Max.y then resize_rect.Min.y, resize_rect.Max.y = resize_rect.Max.y, resize_rect.Min.y end @@ -10431,7 +10440,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c axis = 2 --[[ImGuiAxis.Y]] end - local border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding) + local border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding, UpdateWindowManualResize_rect) local border_id = window:GetID(border_n + 4) -- == GetWindowResizeBorderID() ImGui.ItemAdd(border_rect, border_id, nil, 2 --[[ImGuiItemFlags.NoNav]]) local _, hovered, held = ImGui.ButtonBehavior(border_rect, border_id, bit32.bor(2048 --[[ImGuiButtonFlags.FlattenChildren]], 262144 --[[ImGuiButtonFlags.NoNavFocus]])) @@ -10460,7 +10469,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c -- FIXME: May want to generalize this idiom at lower-level, so more widgets can use it! local just_scrolled_manually_while_resizing = (g.WheelingWindow ~= nil and g.WheelingWindowScrolledFrame == g.FrameCount and ImGui.IsWindowChildOf(window, g.WheelingWindow, false, true)) if g.ActiveIdIsJustActivated or just_scrolled_manually_while_resizing then - g.WindowResizeBorderExpectedRect = border_rect + g.WindowResizeBorderExpectedRect = ImRect(border_rect.Min, border_rect.Max) -- [Luau] copy: border_rect is scratch g.WindowResizeRelativeMode = false end @@ -10668,18 +10677,23 @@ function ImGui.RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_begin local pos = RenderTextClippedEx_pos pos.x = pos_min.x; pos.y = pos_min.y - local text_size = text_size_if_known or ImGui.CalcTextSize(text, text_display_end, false, 0.0) + local text_size_x, text_size_y -- [Luau] scalar text_size + if text_size_if_known then + text_size_x, text_size_y = text_size_if_known.x, text_size_if_known.y + else + text_size_x, text_size_y = ImGui.CalcTextSizeXY(text, 1, text_display_end, false, 0.0) + end local clip_min = clip_rect and clip_rect.Min or pos_min local clip_max = clip_rect and clip_rect.Max or pos_max - local need_clipping = (pos.x + text_size.x >= clip_max.x) or (pos.y + text_size.y >= clip_max.y) + local need_clipping = (pos.x + text_size_x >= clip_max.x) or (pos.y + text_size_y >= clip_max.y) if (clip_rect) then -- If we had no explicit clipping rectangle then pos==clip_min need_clipping = need_clipping or ((pos.x < clip_min.x) or (pos.y < clip_min.y)) end -- Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. - if (align.x > 0.0) then pos.x = math.max(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x) end - if (align.y > 0.0) then pos.y = math.max(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y) end + if (align.x > 0.0) then pos.x = math.max(pos.x, pos.x + (pos_max.x - pos.x - text_size_x) * align.x) end + if (align.y > 0.0) then pos.y = math.max(pos.y, pos.y + (pos_max.y - pos.y - text_size_y) * align.y) end -- Render if (need_clipping) then @@ -10998,6 +11012,9 @@ end --- @param handle_borders_and_resize_grips bool --- @param resize_grip_col ImU32[] --- @param resize_grip_draw_size float +-- [Luau] scratch for RenderWindowDecorations()/RenderWindowTitleBarContents(): callees only read or copy these +local WindowDecoScratch = { text_size = ImVec2(), layout_r = ImRect(), clip_r = ImRect(), bg_rect = ImRect(), p = ImVec2(), title_bar_rect = ImRect() } + local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_col, resize_grip_draw_size) local g = GImGui local style = g.Style @@ -11038,7 +11055,8 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high if bit32.band(flags, 8388608 --[[ImGuiWindowFlags.DockNodeHost]]) ~= 0 then bg_col = 0 end if bit32.band(bg_col, 4278190080 --[[IM_COL32_A_MASK]]) ~= 0 then - local bg_rect = ImRect(window.Pos + ImVec2(0, window.TitleBarHeight), window.Pos + window.Size) + local bg_rect = WindowDecoScratch.bg_rect -- [Luau] scalar, no temporaries + bg_rect.Min.x, bg_rect.Min.y, bg_rect.Max.x, bg_rect.Max.y = window.Pos.x + 0, window.Pos.y + window.TitleBarHeight, window.Pos.x + window.Size.x, window.Pos.y + window.Size.y local bg_rounding_flags if window.DockIsActive then bg_rounding_flags = ImGui.CalcRoundingFlagsForRectInRect(bg_rect, window.DockNode.HostWindow:Rect(), 0.0) @@ -11110,11 +11128,20 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high end local grip = ImGuiResizeGripDef[resize_grip_n] - local corner = ImLerp(window.Pos, window.Pos + window.Size, grip.CornerPosN) + -- [Luau] scalar corner/points, one scratch ImVec2 (the path copies points) + local pos, cpn, dir = window.Pos, grip.CornerPosN, grip.InnerDir + local corner_x = pos.x + ((pos.x + window.Size.x) - pos.x) * cpn.x + local corner_y = pos.y + ((pos.y + window.Size.y) - pos.y) * cpn.y local border_inner = IM_ROUND(window_border_size * 0.5) - window.DrawList:PathLineTo(corner + grip.InnerDir * ((resize_grip_n % 2 == 0) and ImVec2(border_inner, resize_grip_draw_size) or ImVec2(resize_grip_draw_size, border_inner))) - window.DrawList:PathLineTo(corner + grip.InnerDir * ((resize_grip_n % 2 == 0) and ImVec2(resize_grip_draw_size, border_inner) or ImVec2(border_inner, resize_grip_draw_size))) - window.DrawList:PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + border_inner), corner.y + grip.InnerDir.y * (window_rounding + border_inner)), window_rounding, grip.AngleMin12, grip.AngleMax12) + local a, b = border_inner, resize_grip_draw_size + if resize_grip_n % 2 ~= 0 then a, b = b, a end + local p = WindowDecoScratch.p + p.x, p.y = corner_x + dir.x * a, corner_y + dir.y * b + window.DrawList:PathLineTo(p) + p.x, p.y = corner_x + dir.x * b, corner_y + dir.y * a + window.DrawList:PathLineTo(p) + p.x, p.y = corner_x + dir.x * (window_rounding + border_inner), corner_y + dir.y * (window_rounding + border_inner) + window.DrawList:PathArcToFast(p, window_rounding, grip.AngleMin12, grip.AngleMax12) window.DrawList:PathFillConvex(col) until true @@ -11131,6 +11158,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high end ImGui.RenderWindowOuterBorders = RenderWindowOuterBorders + -- When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead. -- Render title text, collapse button, close button -- [Port] Returns the updated 'open' value (nil when there is no close button) @@ -11196,7 +11224,9 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) -- Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) -- FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. local marker_size_x = (bit32.band(flags, 262144 --[[ImGuiWindowFlags.UnsavedDocument]]) ~= 0) and (button_sz * 0.80) or 0.0 - local text_size = ImGui.CalcTextSize(name, nil, true) + ImVec2(marker_size_x, 0.0) + local text_size = WindowDecoScratch.text_size -- [Luau] scratch: only read below (RenderTextClipped text_size_if_known) + local text_size_x, text_size_y = ImGui.CalcTextSizeXY(name, 1, nil, true) + text_size.x = text_size_x + marker_size_x; text_size.y = text_size_y + 0.0 -- As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button, -- while uncentered title text will still reach edges correctly. @@ -11213,8 +11243,9 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) pad_r = ImMax(pad_r, pad_extend * centerness) end - local layout_r = ImRect(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y) - local clip_r = ImRect(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y) + local layout_r, clip_r = WindowDecoScratch.layout_r, WindowDecoScratch.clip_r -- [Luau] scratch, only read by callees + layout_r.Min.x, layout_r.Min.y, layout_r.Max.x, layout_r.Max.y = title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y + clip_r.Min.x, clip_r.Min.y, clip_r.Max.x, clip_r.Max.y = layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y if bit32.band(flags, 262144 --[[ImGuiWindowFlags.UnsavedDocument]]) ~= 0 then local marker_pos = ImVec2() @@ -12351,13 +12382,17 @@ function ImGui.Begin(name, open, flags) -- Add to stack g.CurrentWindow = window g.CurrentWindowStack:resize(g.CurrentWindowStack.Size + 1) - g.CurrentWindowStack.Data[g.CurrentWindowStack.Size] = ImGuiWindowStackData() + -- [Luau] reuse the slot's table left by pop_back() (C++ reuses the vector storage); every field is set below local window_stack_data = g.CurrentWindowStack.Data[g.CurrentWindowStack.Size] + if type(window_stack_data) ~= "table" or window_stack_data.ParentLastItemDataBackup == nil then + window_stack_data = ImGuiWindowStackData() + g.CurrentWindowStack.Data[g.CurrentWindowStack.Size] = window_stack_data + end window_stack_data.Window = window ImGuiLastItemData_Copy(window_stack_data.ParentLastItemDataBackup, g.LastItemData) window_stack_data.DisabledOverrideReenable = (bit32.band(flags, 33554432 --[[ImGuiWindowFlags.Tooltip]]) ~= 0) and (bit32.band(g.CurrentItemFlags, 64 --[[ImGuiItemFlags.Disabled]]) ~= 0) window_stack_data.DisabledOverrideReenableAlphaBackup = 0.0 - window_stack_data.StackSizesInBegin = ImGuiErrorRecoveryState() + window_stack_data.StackSizesInBegin = window_stack_data.StackSizesInBegin or ImGuiErrorRecoveryState() -- [Luau] reused, all fields stored ImGui.ErrorRecoveryStoreState(window_stack_data.StackSizesInBegin) g.StackSizesInBeginForCurrentWindow = window_stack_data.StackSizesInBegin if bit32.band(flags, 268435456 --[[ImGuiWindowFlags.ChildMenu]]) ~= 0 then @@ -13138,7 +13173,9 @@ function ImGui.Begin(name, open, flags) -- Title bar if bit32.band(flags, 1 --[[ImGuiWindowFlags.NoTitleBar]]) == 0 and not window.DockIsActive then - open = RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window.WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window.WindowBorderSize, title_bar_rect.Max.y), name, open) + local r = WindowDecoScratch.title_bar_rect -- [Luau] scratch, only read + r.Min.x, r.Min.y, r.Max.x, r.Max.y = title_bar_rect.Min.x + window.WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window.WindowBorderSize, title_bar_rect.Max.y + open = RenderWindowTitleBarContents(window, r, name, open) elseif bit32.band(flags, 1 --[[ImGuiWindowFlags.NoTitleBar]]) == 0 and window.DockIsActive then ImGui.LogText("%s\n", string.sub(window.Name, 1, ImGui.FindRenderedTextEnd(window.Name) - 1)) end @@ -14842,10 +14879,10 @@ end --- @param hide_text_after_double_hash? bool --- @param wrap_width? float --- @return ImVec2 +-- [Luau] scalar CalcTextSizeEx(): returns x, y without allocating an ImVec2 (hot widget paths) -function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double_hash, wrap_width) - if hide_text_after_double_hash == nil then hide_text_after_double_hash = false end - if wrap_width == nil then wrap_width = -1.0 end +function ImGui.CalcTextSizeXY(text, text_begin, text_end, hide_text_after_double_hash, wrap_width) + if wrap_width == nil then wrap_width = -1.0 end local g = GImGui @@ -14856,19 +14893,22 @@ function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double text_display_end = text_end end - local font = g.Font local font_size = g.FontSize if text == "" or (text_end and text_end <= text_begin) then - return ImVec2(0.0, font_size) + return 0.0, font_size end - local text_size = ImFontCalcTextSizeEx(font, font_size, 3.4028234663853e+38 --[[FLT_MAX]], wrap_width, text, text_begin, text_display_end, text_display_end, nil, 0 --[[ImDrawTextFlags.None]]) -- [Luau] inline font:CalcTextSizeA() + local x, y = ImFontCalcTextSizeXY(g.Font, font_size, 3.4028234663853e+38 --[[FLT_MAX]], wrap_width, text, text_begin, text_display_end, text_display_end, nil, 0 --[[ImDrawTextFlags.None]]) -- [Luau] inline font:CalcTextSizeA() -- Round -- (see 7b0bf230, 4622fa4b6, #791 for details about this.) -- FIXME: Add a way to disable this. - text_size.x = math.ceil(text_size.x) -- [Luau] == ImCeilFast() for all finite values, builtin + return math.ceil(x), y -- [Luau] == ImCeilFast() for all finite values, builtin +end - return text_size + +function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double_hash, wrap_width) + local x, y = ImGui.CalcTextSizeXY(text, text_begin, text_end, hide_text_after_double_hash, wrap_width) + return ImVec2(x, y) end -- Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() @@ -34690,6 +34730,7 @@ end --- @param buf char[] # 1-based --- @param base int # 1-based start index --- @param u32 ImU32 + local function write_u32(buf, base, u32) buf[base + 0] = bit32.band(u32, 0xFF) buf[base + 1] = bit32.band(bit32.rshift(u32, 8), 0xFF) @@ -35419,6 +35460,7 @@ end --- @param dst_pitch int --- @param w int --- @param h int + function ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst_pixels, dst_pixels_base, dst_fmt, dst_pitch, w, h) assert(src_pixels ~= nil and dst_pixels ~= nil) local src_pixels_base = 1 @@ -35436,7 +35478,8 @@ function ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst_pixe local alpha = src_pixels[src_pixels_base + 0] src_pixels_base = src_pixels_base + 1 - write_u32(dst_pixels, dst_pixels_base, IM_COL32(255, 255, 255, alpha)) + -- [Luau] inline write_u32(dst_pixels, dst_pixels_base, IM_COL32(255, 255, 255, alpha)) + dst_pixels[dst_pixels_base] = 255; dst_pixels[dst_pixels_base + 1] = 255; dst_pixels[dst_pixels_base + 2] = 255; dst_pixels[dst_pixels_base + 3] = alpha dst_pixels_base = dst_pixels_base + 4 end @@ -37342,8 +37385,13 @@ function MT.ImTextureData:Create(format, w, h) self.Height = h self.BytesPerPixel = ImTextureDataGetFormatBytesPerPixel(format) self.UseColors = false - self.Pixels = {} - ImStd.memset(self.Pixels, 0, self.Width * self.Height * self.BytesPerPixel) + local n = self.Width * self.Height * self.BytesPerPixel + if table.create then + self.Pixels = table.create(n, 0) -- [Luau] native zero fill, same contents as memset + else + self.Pixels = {} + ImStd.memset(self.Pixels, 0, n) + end self.UsedRect.x = 0 self.UsedRect.y = 0 self.UsedRect.w = 0 @@ -38107,7 +38155,8 @@ end 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) +-- [Luau] scalar core of ImFontCalcTextSizeEx(): returns size.x, size.y, remaining (no ImVec2 allocated) +function ImFontCalcTextSizeXY(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. @@ -38124,7 +38173,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end local e = cache[text] if e then - return ImVec2(e[1] * (size / baked.Size), e[2] * size), text_len1 + return e[1] * (size / baked.Size), e[2] * size, text_len1 end cache_key = text elseif cacheable and wrap_width > 0.0 then @@ -38140,7 +38189,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi if by_wrap == nil then by_wrap = {}; by_size[wrap_width] = by_wrap end local e = by_wrap[text] if e then - return ImVec2(e[1], e[2]), e[3] + return e[1], e[2], e[3] end wrap_cache = by_wrap end @@ -38155,7 +38204,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi local line_height = size local scale = line_height / baked.Size - local text_size = ImVec2() + local tx, ty = 0.0, 0.0 local line_width = 0.0 local word_wrap_enabled = (wrap_width > 0.0) @@ -38175,10 +38224,10 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end if s >= word_wrap_eol then - if text_size.x < line_width then - text_size.x = line_width + if tx < line_width then + tx = line_width end - text_size.y = text_size.y + line_height + ty = ty + line_height line_width = 0.0 s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) -- Wrapping skips upcoming blanks if bit32.band(flags, 4 --[[ImDrawTextFlags.StopOnNewLine]]) ~= 0 then @@ -38203,8 +38252,8 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end if c == 10 then -- '\n' - text_size.x = ImMax(text_size.x, line_width) - text_size.y = text_size.y + line_height + if tx < line_width then tx = line_width end + ty = ty + line_height line_width = 0.0 if bit32.band(flags, 4 --[[ImDrawTextFlags.StopOnNewLine]]) ~= 0 then stop = true; break @@ -38236,30 +38285,36 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi if stop then break end end - if (text_size.x < line_width) then - text_size.x = line_width + if (tx < line_width) then + tx = line_width end if out_offset then -- offset allow for the possibility of sitting after a trailing \n out_offset.x = line_width - out_offset.y = text_size.y + line_height + out_offset.y = ty + line_height end - if (line_width > 0 or text_size.y == 0.0) then -- whereas size.y will ignore the trailing \n - text_size.y = text_size.y + line_height + if (line_width > 0 or ty == 0.0) then -- whereas size.y will ignore the trailing \n + ty = ty + line_height end local out_remaining = s if cache_key then - baked._TextSizeCache[cache_key] = { text_size.x / scale, text_size.y / line_height } + baked._TextSizeCache[cache_key] = { tx / scale, ty / line_height } baked._TextSizeCacheN = baked._TextSizeCacheN + 1 elseif wrap_cache then - wrap_cache[text] = { text_size.x, text_size.y, out_remaining } + wrap_cache[text] = { tx, ty, out_remaining } baked._TextSizeCacheN = baked._TextSizeCacheN + 1 end - return text_size, out_remaining + return tx, ty, out_remaining +end + +-- ImVec2 version (upstream signature) +function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags) + local x, y, remaining = ImFontCalcTextSizeXY(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags) + return ImVec2(x, y), remaining end --- @param size float @@ -41629,7 +41684,15 @@ end -- Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui.PushClipRect() to affect logic (hit-testing and widget culling) function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_rect) - local cr = ImVec4(cr_min.x, cr_min.y, cr_max.x, cr_max.y) + -- [Luau] reuse the stack slot's ImVec4 left from earlier frames (each slot stays uniquely owned by the stack) + local stack = self._ClipRectStack + local n = stack.Size + 1 + local cr = n <= stack.Capacity and stack.Data[n] or nil + if cr then + cr.x = cr_min.x; cr.y = cr_min.y; cr.z = cr_max.x; cr.w = cr_max.y + else + cr = ImVec4(cr_min.x, cr_min.y, cr_max.x, cr_max.y) + end if intersect_with_current_clip_rect then local current = self._CmdHeader.ClipRect @@ -41644,8 +41707,6 @@ function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_ cr.w = math.max(cr.y, cr.w) -- [Luau] inline self._ClipRectStack:push_back(cr) - local stack = self._ClipRectStack - local n = stack.Size + 1 if n > stack.Capacity then stack:push_back(cr) else stack.Data[n] = cr; stack.Size = n end ImVec4_Copy(self._CmdHeader.ClipRect, cr) self:_OnChangedClipRect() @@ -46835,13 +46896,15 @@ end --- @param s table # 1-based --- @param c any --- @param n int + function ImStd.memset(s, c, n) for i = 1, n do s[i] = c end end do -local _memmove = function(dest, dest_start, src, src_start, count) + +local function _memmove(dest, dest_start, src, src_start, count) if count <= 0 then return end local c = (dest == src and dest_start >= src_start) @@ -55684,13 +55747,13 @@ function ImGui.TextEx(text, text_end, flags) -- [Luau] scalar text_pos, scratch bb (ItemAdd() copies it, RenderTextWrapped() only reads it) local text_pos_x, text_pos_y = dc.CursorPos.x, dc.CursorPos.y + dc.CurrLineTextBaseOffset local wrap_width = wrap_enabled and ImGui.CalcWrapWidthForPos(dc.CursorPos, wrap_pos_x) or 0.0 - local text_size = ImGui.CalcTextSizeEx(text, 1, text_end, false, wrap_width) + local text_size_x, text_size_y = ImGui.CalcTextSizeXY(text, 1, text_end, false, wrap_width) local bb = TextEx_bb local bb_min, bb_max = bb.Min, bb.Max bb_min.x = text_pos_x; bb_min.y = text_pos_y - bb_max.x = text_pos_x + text_size.x; bb_max.y = text_pos_y + text_size.y - ImGui.ItemSize(text_size, 0.0) + bb_max.x = text_pos_x + text_size_x; bb_max.y = text_pos_y + text_size_y + ImGui.ItemSize(bb, 0.0) -- [Luau] the bb's size == text_size if not ImGui.ItemAdd(bb, 0) then return end @@ -55916,6 +55979,8 @@ end -- Text with a little bullet aligned to the typical tree node. --- @param fmt string --- @param ... any +local BulletText_bb, BulletText_pos, BulletText_size = ImRect(), ImVec2(), ImVec2() -- [Luau] scratch, only read by callees + function ImGui.BulletText(fmt, ...) local window = ImGui.GetCurrentWindow() if window.SkipItems then @@ -55927,20 +55992,26 @@ function ImGui.BulletText(fmt, ...) local text = ImFormatString(fmt, ...) local text_end = #text + 1 - local label_size = ImGui.CalcTextSize(text, text_end, false) - local total_size = ImVec2(g.FontSize + ((label_size.x > 0.0) and (label_size.x + style.FramePadding.x * 2) or 0.0), label_size.y) -- Empty text doesn't add padding + local label_size_x, label_size_y = ImGui.CalcTextSizeXY(text, 1, text_end, false) -- [Luau] scalar label_size/total_size + local total_size_x = g.FontSize + ((label_size_x > 0.0) and (label_size_x + style.FramePadding.x * 2) or 0.0) -- Empty text doesn't add padding -- [Luau] scalar pos, no temporary ImVec2 local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset + local bb = BulletText_bb + bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = pos_x, pos_y, pos_x + total_size_x, pos_y + label_size_y + local total_size = BulletText_size + total_size.x, total_size.y = total_size_x, label_size_y ImGui.ItemSize(total_size, 0.0) - local bb = ImRect(pos_x, pos_y, pos_x + total_size.x, pos_y + total_size.y) if not ImGui.ItemAdd(bb, 0) then return end -- Render local text_col = ImGui.GetColorU32(0 --[[ImGuiCol.Text]]) - ImGui.RenderBullet(window.DrawList, ImVec2(bb.Min.x + (style.FramePadding.x + g.FontSize * 0.5), bb.Min.y + g.FontSize * 0.5), text_col) - ImGui.RenderText(ImVec2(bb.Min.x + (g.FontSize + style.FramePadding.x * 2), bb.Min.y + 0.0), text, 1, text_end, false) + local p = BulletText_pos + p.x, p.y = bb.Min.x + (style.FramePadding.x + g.FontSize * 0.5), bb.Min.y + g.FontSize * 0.5 + ImGui.RenderBullet(window.DrawList, p, text_col) + p.x, p.y = bb.Min.x + (g.FontSize + style.FramePadding.x * 2), bb.Min.y + 0.0 + ImGui.RenderText(p, text, 1, text_end, false) end -- [Port] va_list variants: identical to the varargs versions in Lua @@ -56318,6 +56389,7 @@ end --- @param size_arg? ImVec2 --- @param flags? ImGuiButtonFlags --- @return bool +local ButtonEx_bb, ButtonEx_label_size, ButtonEx_size = ImRect(), ImVec2(), ImVec2() local ButtonEx_text_min, ButtonEx_text_max = ImVec2(), ImVec2() @@ -56334,7 +56406,8 @@ function ImGui.ButtonEx(label, size_arg, flags) local style = g.Style local id = window:GetID(label) local label_end = ImGui.FindRenderedTextEnd(label) - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size = ButtonEx_label_size -- [Luau] scratch: only read below (RenderTextClipped text_size_if_known) + label_size.x, label_size.y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar pos, no temporary ImVec2 local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y @@ -56342,9 +56415,11 @@ function ImGui.ButtonEx(label, size_arg, flags) 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 end - local size = ImGui.CalcItemSize(size_arg, label_size.x + frame_padding.x * 2.0, label_size.y + frame_padding.y * 2.0) + local size = ButtonEx_size -- [Luau] scratch + scalar CalcItemSize(): ItemSize() only reads it + size.x, size.y = ImGui._CalcItemSizeXY(size_arg.x, size_arg.y, label_size.x + frame_padding.x * 2.0, label_size.y + frame_padding.y * 2.0) - local bb = ImRect(pos_x, pos_y, pos_x + size.x, pos_y + size.y) + local bb = ButtonEx_bb -- [Luau] scratch: ItemAdd() copies it, ButtonBehavior()/Render*() only read it + bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = pos_x, pos_y, pos_x + size.x, pos_y + size.y ImGui.ItemSize(size, frame_padding.y) if not ImGui.ItemAdd(bb, id) then return false @@ -56873,6 +56948,8 @@ end --- @param v bool --- @return bool is_pressed --- @return bool is_checked # The updated `v` passed in +local Checkbox_total_bb, Checkbox_check_bb, Checkbox_label_pos = ImRect(), ImRect(), ImVec2() -- [Luau] scratch, only read by callees + function ImGui.Checkbox(label, v) local window = ImGui.GetCurrentWindow() @@ -56884,18 +56961,19 @@ function ImGui.Checkbox(label, v) local style = g.Style local id = window:GetID(label) local label_end = ImGui.FindRenderedTextEnd(label) - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size local square_sz = g.FontSize + style.FramePadding.y * 2.0 -- [Luau] inline GetFrameHeight() local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y -- [Luau] scalar pos, no temporary ImVec2 local total_width - if label_size.x > 0.0 then - total_width = square_sz + style.ItemInnerSpacing.x + label_size.x + if label_size_x > 0.0 then + total_width = square_sz + style.ItemInnerSpacing.x + label_size_x else total_width = square_sz end - local total_bb = ImRect(pos_x, pos_y, pos_x + total_width, pos_y + (label_size.y + style.FramePadding.y * 2.0)) + local total_bb = Checkbox_total_bb + total_bb.Min.x, total_bb.Min.y, total_bb.Max.x, total_bb.Max.y = pos_x, pos_y, pos_x + total_width, pos_y + (label_size_y + style.FramePadding.y * 2.0) ImGui.ItemSize(total_bb, style.FramePadding.y) local is_visible = ImGui.ItemAdd(total_bb, id) local is_multi_select = (bit32.band(g.LastItemData.ItemFlags, 4194304 --[[ImGuiItemFlags.IsMultiSelect]]) ~= 0) @@ -56927,7 +57005,8 @@ function ImGui.Checkbox(label, v) ImGui.MarkItemEdited(id) end - local check_bb = ImRect(pos_x, pos_y, pos_x + square_sz, pos_y + square_sz) + local check_bb = Checkbox_check_bb + check_bb.Min.x, check_bb.Min.y, check_bb.Max.x, check_bb.Max.y = pos_x, pos_y, pos_x + square_sz, pos_y + square_sz local mixed_value = (bit32.band(g.LastItemData.ItemFlags, 4096 --[[ImGuiItemFlags.MixedValue]]) ~= 0) if is_visible then ImGui.RenderNavCursor(total_bb, id) @@ -56952,8 +57031,9 @@ function ImGui.Checkbox(label, v) ImGui.LogRenderedText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), mixed_value and "[~]" or (v and "[x]" or "[ ]")) -- label_pos end - if is_visible and label_size.x > 0.0 then - local label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y) -- [Luau] only built when used + if is_visible and label_size_x > 0.0 then + local label_pos = Checkbox_label_pos + label_pos.x, label_pos.y = check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y ImGui.RenderText(label_pos, label, 1, label_end, false) end @@ -59076,7 +59156,8 @@ end -- [Luau] memo of string.format(format, value) for drag/slider value text (same values are redrawn every frame). local fmt_memo, fmt_memo_n = {}, 0 -local SliderScalar_total_bb, SliderScalar_grab_bb = ImRect(), ImRect() -- [Luau] scratch for SliderScalar()/DragScalar(), never escape +local SliderScalar_total_bb, SliderScalar_grab_bb, SliderScalar_frame_bb = ImRect(), ImRect(), ImRect() -- [Luau] scratch for SliderScalar()/DragScalar(), never escape +local SliderScalar_label_pos = ImVec2() local DRAG_TEXT_ALIGN = ImVec2(0.5, 0.5) function FormatCached(format, v) local m = fmt_memo[format] @@ -59107,12 +59188,13 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla local color_marker = (bit32.band(g.NextItemData.HasFlags, 32 --[[ImGuiNextItemDataFlags.HasColorMarker]]) ~= 0) and g.NextItemData.ColorMarker or 0 local label_end = ImGui.FindRenderedTextEnd(label) - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size local cursor = window.DC.CursorPos - local frame_bb = ImRect(cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size.y + style.FramePadding.y * 2.0)) -- [Luau] no temporary ImVec2 + local frame_bb = SliderScalar_frame_bb -- [Luau] scratch: callees only read it + frame_bb.Min.x, frame_bb.Min.y, frame_bb.Max.x, frame_bb.Max.y = cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size_y + style.FramePadding.y * 2.0) local total_bb = SliderScalar_total_bb -- [Luau] scratch: ItemSize()/ItemAdd() only read it total_bb.Min.x = frame_bb.Min.x; total_bb.Min.y = frame_bb.Min.y - total_bb.Max.x = frame_bb.Max.x + ((label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0); total_bb.Max.y = frame_bb.Max.y + 0.0 + total_bb.Max.x = frame_bb.Max.x + ((label_size_x > 0.0) and (style.ItemInnerSpacing.x + label_size_x) or 0.0); total_bb.Max.y = frame_bb.Max.y + 0.0 local temp_input_allowed = (bit32.band(flags, 128 --[[ImGuiSliderFlags.NoInput]]) == 0) ImGui.ItemSize(total_bb, style.FramePadding.y) @@ -59200,8 +59282,10 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla ImGui.PopStyleColor() end - if label_size.x > 0.0 then - ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, 1, label_end, false) + if label_size_x > 0.0 then + local label_pos = SliderScalar_label_pos + label_pos.x, label_pos.y = frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y + ImGui.RenderText(label_pos, label, 1, label_end, false) end return data, value_changed @@ -59812,10 +59896,11 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) local color_marker = (bit32.band(g.NextItemData.HasFlags, 32 --[[ImGuiNextItemDataFlags.HasColorMarker]]) ~= 0) and g.NextItemData.ColorMarker or 0 local label_end = ImGui.FindRenderedTextEnd(label) - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size local cursor = window.DC.CursorPos - local frame_bb = ImRect(cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size.y + style.FramePadding.y * 2.0)) -- [Luau] no temporary ImVec2 - local total_bb_x = frame_bb.Max.x + ((label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0) + local frame_bb = SliderScalar_frame_bb -- [Luau] scratch: callees only read it + frame_bb.Min.x, frame_bb.Min.y, frame_bb.Max.x, frame_bb.Max.y = cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size_y + style.FramePadding.y * 2.0) + local total_bb_x = frame_bb.Max.x + ((label_size_x > 0.0) and (style.ItemInnerSpacing.x + label_size_x) or 0.0) local total_bb = SliderScalar_total_bb -- [Luau] scratch: ItemSize()/ItemAdd() only read it total_bb.Min.x = frame_bb.Min.x; total_bb.Min.y = frame_bb.Min.y; total_bb.Max.x = total_bb_x; total_bb.Max.y = frame_bb.Max.y @@ -59901,8 +59986,10 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) ImGui.PopStyleColor() end - if label_size.x > 0.0 then - ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, 1, label_end, false) + if label_size_x > 0.0 then + local label_pos = SliderScalar_label_pos + label_pos.x, label_pos.y = frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y + ImGui.RenderText(label_pos, label, 1, label_end, false) end -- IMGUI_TEST_ENGINE_ITEM_INFO() @@ -63386,6 +63473,10 @@ end --- @param flags ImGuiTreeNodeFlags --- @param label string --- @param label_end? int +local TreeNode_frame_bb, TreeNode_interact_bb = ImRect(), ImRect() -- [Luau] scratch for TreeNodeBehavior(), never escape +local TreeNode_label_size, TreeNode_text_pos, TreeNode_tmp = ImVec2(), ImVec2(), ImVec2() +local function TreeNode_tmp_pos(x, y) local v = TreeNode_tmp; v.x = x; v.y = y; return v end -- [Luau] scratch pos for Render*() args + function ImGui.TreeNodeBehavior(id, flags, label, label_end) local window = ImGui.GetCurrentWindow() @@ -63410,7 +63501,8 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) if label_end == nil then label_end = ImGui.FindRenderedTextEnd(label) end - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size = TreeNode_label_size -- [Luau] scratch: only read below (RenderTextClipped text_size_if_known) + label_size.x, label_size.y = ImGui.CalcTextSizeXY(label, 1, label_end, false) local text_offset_x = g.FontSize + (display_frame and (padding_x * 3) or (padding_x * 2)) -- Collapsing arrow width + Spacing local text_offset_y = use_frame_padding and ImMax(style.FramePadding.y, window.DC.CurrLineTextBaseOffset) or window.DC.CurrLineTextBaseOffset -- Latch before ItemSize changes it @@ -63419,7 +63511,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local frame_height = label_size.y + padding_y * 2 local span_all_columns = bit32.band(flags, 16384 --[[ImGuiTreeNodeFlags.SpanAllColumns]]) ~= 0 and (g.CurrentTable ~= nil) local span_all_columns_label = bit32.band(flags, 32768 --[[ImGuiTreeNodeFlags.LabelSpanAllColumns]]) ~= 0 and (g.CurrentTable ~= nil) - local frame_bb = ImRect() + local frame_bb = TreeNode_frame_bb -- [Luau] scratch, fully written here; callees copy or only read it frame_bb.Min.x = span_all_columns and window.ParentWorkRect.Min.x or (bit32.band(flags, 4096 --[[ImGuiTreeNodeFlags.SpanFullWidth]]) ~= 0 and window.WorkRect.Min.x or window.DC.CursorPos.x) frame_bb.Min.y = window.DC.CursorPos.y + (text_offset_y - padding_y) frame_bb.Max.x = span_all_columns and window.ParentWorkRect.Max.x or (bit32.band(flags, 8192 --[[ImGuiTreeNodeFlags.SpanLabelWidth]]) ~= 0 and window.DC.CursorPos.x + text_width + padding_x or window.WorkRect.Max.x) @@ -63430,12 +63522,13 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) frame_bb.Max.x = frame_bb.Max.x + outer_extend end - local text_pos = ImVec2(window.DC.CursorPos.x + text_offset_x, window.DC.CursorPos.y + text_offset_y) + local text_pos = TreeNode_text_pos -- [Luau] scratch + text_pos.x, text_pos.y = window.DC.CursorPos.x + text_offset_x, window.DC.CursorPos.y + text_offset_y local item_size = LayoutHelpers_size; item_size.x = text_width; item_size.y = frame_height -- [Luau] scratch, ItemSize() only reads it ImGui.ItemSize(item_size, padding_y) -- For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing - local interact_bb = ImRect() + local interact_bb = TreeNode_interact_bb -- [Luau] scratch, ItemAdd()/ButtonBehavior()/SetNavID() copy or only read it ImRect_Copy(interact_bb, frame_bb) if bit32.band(flags, bit32.bor(2 --[[ImGuiTreeNodeFlags.Framed]], 2048 --[[ImGuiTreeNodeFlags.SpanAvailWidth]], 4096 --[[ImGuiTreeNodeFlags.SpanFullWidth]], 8192 --[[ImGuiTreeNodeFlags.SpanLabelWidth]], 16384 --[[ImGuiTreeNodeFlags.SpanAllColumns]])) == 0 then interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0 and (style.ItemSpacing.x * 2.0) or 0.0) @@ -63629,9 +63722,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.TablePopBackgroundChannel() end if bit32.band(flags, 512 --[[ImGuiTreeNodeFlags.Bullet]]) ~= 0 then - ImGui.RenderBullet(window.DrawList, ImVec2(text_pos.x - text_offset_x * 0.60, text_pos.y + g.FontSize * 0.5), text_col) + ImGui.RenderBullet(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x * 0.60, text_pos.y + g.FontSize * 0.5), text_col) elseif not is_leaf then - ImGui.RenderArrow(window.DrawList, ImVec2(text_pos.x - text_offset_x + padding_x, text_pos.y), text_col, is_open and ((bit32.band(flags, 536870912 --[[ImGuiTreeNodeFlags.UpsideDownArrow]]) ~= 0) and 2 --[[ImGuiDir.Up]] or 3 --[[ImGuiDir.Down]]) or 1 --[[ImGuiDir.Right]], 1.0) + ImGui.RenderArrow(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x + padding_x, text_pos.y), text_col, is_open and ((bit32.band(flags, 536870912 --[[ImGuiTreeNodeFlags.UpsideDownArrow]]) ~= 0) and 2 --[[ImGuiDir.Up]] or 3 --[[ImGuiDir.Down]]) or 1 --[[ImGuiDir.Right]], 1.0) else -- Leaf without bullet, left-adjusted text text_pos.x = text_pos.x - (text_offset_x - padding_x) end @@ -63652,9 +63745,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.TablePopBackgroundChannel() end if bit32.band(flags, 512 --[[ImGuiTreeNodeFlags.Bullet]]) ~= 0 then - ImGui.RenderBullet(window.DrawList, ImVec2(text_pos.x - text_offset_x * 0.5, text_pos.y + g.FontSize * 0.5), text_col) + ImGui.RenderBullet(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x * 0.5, text_pos.y + g.FontSize * 0.5), text_col) elseif not is_leaf then - ImGui.RenderArrow(window.DrawList, ImVec2(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.15), text_col, is_open and ((bit32.band(flags, 536870912 --[[ImGuiTreeNodeFlags.UpsideDownArrow]]) ~= 0) and 2 --[[ImGuiDir.Up]] or 3 --[[ImGuiDir.Down]]) or 1 --[[ImGuiDir.Right]], 0.70) + ImGui.RenderArrow(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.15), text_col, is_open and ((bit32.band(flags, 536870912 --[[ImGuiTreeNodeFlags.UpsideDownArrow]]) ~= 0) and 2 --[[ImGuiDir.Up]] or 3 --[[ImGuiDir.Down]]) or 1 --[[ImGuiDir.Right]], 0.70) end if g.LogEnabled then ImGui.LogSetNextTextDecoration(">", nil) @@ -63662,7 +63755,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) end if draw_tree_lines then - ImGui.TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.5)) + ImGui.TreeNodeDrawLineToChildNode(TreeNode_tmp_pos(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.5)) end -- Label @@ -67917,6 +68010,7 @@ local STBRP__PREV_LINK_TYPE = { --- @return stbrp_rect --- @nodiscard + local function stbrp_rect() return { -- reserved for your use: @@ -67940,6 +68034,7 @@ end --- @return stbrp_node --- @nodiscard + local function stbrp_node() return { x = 0, @@ -67961,6 +68056,7 @@ end --- @return stbrp_context --- @nodiscard + local function stbrp_context() return { width = 0, @@ -67983,6 +68079,7 @@ end --- @field prev_link_type? int --- @return stbrp__findresult + local function stbrp__findresult() return { x = 0, @@ -68003,6 +68100,7 @@ end -- If you call init again, this will be reset to the default. --- @param context stbrp_context --- @param heuristic int + local function stbrp_setup_heuristic(context, heuristic) if context.init_mode == STBRP__INIT_skyline then STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight or heuristic == STBRP_HEURISTIC_Skyline.BF_sortHeight) @@ -68017,6 +68115,7 @@ end -- If you call init again, this will be reset to the default (false). --- @param context stbrp_context --- @param allow_out_of_mem boolean + local function stbrp_setup_allow_out_of_mem(context, allow_out_of_mem) if allow_out_of_mem then -- if it's ok to run out of memory, then don't bother aligning them; @@ -68060,6 +68159,7 @@ end --- @param height int --- @param nodes stbrp_node[] --- @param num_nodes int + function stbrp_init_target(context, width, height, nodes, num_nodes) for i = 1, num_nodes - 1 do nodes[i].next = nodes[i + 1] @@ -68090,6 +68190,7 @@ end --- @param x0 int --- @param width int --- @return int, int + local function stbrp__skyline_find_min_y(c, first, x0, width) local node = first local x1 = x0 + width @@ -68137,6 +68238,7 @@ end --- @param width int --- @param height int --- @return stbrp__findresult + local function stbrp__skyline_find_best_pos(c, width, height) local best_waste = bit32.lshift(1, 30) local best_x = 0 @@ -68266,6 +68368,7 @@ end --- @param width int --- @param height int --- @return stbrp__findresult + local function stbrp__skyline_pack_rectangle(context, width, height) -- find best position according to heuristic local res = stbrp__skyline_find_best_pos(context, width, height) @@ -68334,6 +68437,7 @@ end --- @param b stbrp_rect --- @return bool --- @package + local function rect_height_compare(a, b) if a.h > b.h then return true @@ -68348,6 +68452,7 @@ end --- @param b stbrp_rect --- @return bool --- @package + local function rect_original_order(a, b) return a.was_packed < b.was_packed end @@ -68379,6 +68484,7 @@ end --- @param rects stbrp_rect[] --- @param num_rects int --- @return int + local function stbrp_pack_rects(context, rects, num_rects) local all_rects_packed = 1 @@ -70186,7 +70292,7 @@ local stbtt_MakeGlyphBitmapSubpixelPrefilter local stbtt_GetFontVMetrics local stbtt__GetGlyphInfoT2 local stbtt__GetGlyphShapeT2 -local stbtt_GetGlyphShape +local stbtt_GetGlyphShape, stbtt_GetGlyphShapeUncached local stbtt_GetGlyphBitmapBox local stbtt_GetGlyphBitmapBoxSubpixel local stbtt_GetGlyphHMetrics @@ -70239,6 +70345,7 @@ local trunc = function(x) end end + local function STBTT__NOTUSED(_) return end --- @alias stbtt_int32 int @@ -70261,6 +70368,7 @@ local unsigned_char = stbtt_uint8 --- @param initial_offset? int --- @return stbtt__buf --- @nodiscard + local function stbtt__buf(initial_offset) return { data = nil, @@ -70295,6 +70403,7 @@ end --- @field fdselect stbtt__buf # map from glyph to fontdict --- @return stbtt_fontinfo + function stbtt_fontinfo() return { data = nil, @@ -70335,6 +70444,7 @@ end --- @return stbtt_vertex --- @nodiscard + local function stbtt_vertex() return { x = nil, @@ -70364,6 +70474,7 @@ end --- @return stbtt__csctx --- @nodiscard + local function stbtt__csctx() return { bounds = false, @@ -70385,6 +70496,7 @@ end --- @param bounds bool --- @return stbtt__csctx --- @nodiscard + local function STBTT__CSCTX_INIT(bounds) local this = stbtt__csctx() @@ -70418,6 +70530,7 @@ end --- @return stbtt__edge --- @nodiscard + local function stbtt__edge() return { x0 = nil, @@ -70432,6 +70545,7 @@ end --- @return stbtt__active_edge --- @nodiscard + local function stbtt__active_edge() return { next = nil, @@ -70446,8 +70560,15 @@ end --- @return stbtt__active_edge --- @nodiscard +local active_pool, active_pool_n = {}, 0 -- [Luau] reused per stbtt__rasterize_sorted_edges() call (C: stbtt__hheap) + local function stbtt__new_active(e, off_x, start_point) - local z = stbtt__active_edge() + active_pool_n = active_pool_n + 1 + local z = active_pool[active_pool_n] + if z == nil then + z = stbtt__active_edge() + active_pool[active_pool_n] = z + end local dxdy = (e.x1 - e.x0) / (e.y1 - e.y0) z.fdx = dxdy @@ -70471,6 +70592,7 @@ end --- @return stbtt__bitmap --- @nodiscard + local function stbtt__bitmap() return { w = nil, @@ -70486,6 +70608,7 @@ end --- @return stbtt__point --- @nodiscard + local function stbtt__point() return { x = nil, y = nil } end ---------------------------------------------- @@ -70496,6 +70619,7 @@ local function stbtt__point() return { x = nil, y = nil } end --- --- @param b stbtt__buf + local function stbtt__buf_get8(b) if b.cursor >= b.size then return 0 end local result = b.data[b.offset + b.cursor + 1] @@ -70504,6 +70628,7 @@ local function stbtt__buf_get8(b) end --- @param b stbtt__buf + local function stbtt__buf_peek8(b) if b.cursor >= b.size then return 0 end return b.data[b.offset + b.cursor + 1] @@ -70511,6 +70636,7 @@ end --- @param b stbtt__buf --- @param o int + local function stbtt__buf_seek(b, o) STBTT_assert(not (o > b.size or o < 0)) if o > b.size or o < 0 then @@ -70522,10 +70648,12 @@ end --- @param b stbtt__buf --- @param o int + local function stbtt__buf_skip(b, o) stbtt__buf_seek(b, b.cursor + o) end + local function stbtt__buf_get(b, n) local v = 0 STBTT_assert(n >= 1 and n <= 4) @@ -70540,6 +70668,7 @@ end --- @param offset? int --- @return stbtt__buf --- @nodiscard + local function stbtt__new_buf(p, size, offset) local r = stbtt__buf(offset) STBTT_assert(size < 0x40000000) @@ -70550,8 +70679,10 @@ local function stbtt__new_buf(p, size, offset) end --- @param b stbtt__buf + local function stbtt__buf_get16(b) return stbtt__buf_get(b, 2) end --- @param b stbtt__buf + local function stbtt__buf_get32(b) return stbtt__buf_get(b, 4) end --- @param b stbtt__buf @@ -70559,6 +70690,7 @@ local function stbtt__buf_get32(b) return stbtt__buf_get(b, 4) end --- @param s int --- @return stbtt__buf --- @nodiscard + local function stbtt__buf_range(b, o, s) local r = stbtt__new_buf(nil, 0) if (o < 0 or s < 0 or o > b.size or s > (b.size - o)) then @@ -70571,6 +70703,7 @@ local function stbtt__buf_range(b, o, s) end --- @param b stbtt__buf + local function stbtt__cff_get_index(b) local count, start, offsize start = b.cursor @@ -70585,6 +70718,7 @@ local function stbtt__cff_get_index(b) end --- @param b stbtt__buf + local function stbtt__cff_int(b) local b0 = stbtt__buf_get8(b) if b0 >= 32 and b0 <= 246 then return b0 - 139 @@ -70598,6 +70732,7 @@ local function stbtt__cff_int(b) end --- @param b stbtt__buf + local function stbtt__cff_skip_operand(b) local v local b0 = stbtt__buf_peek8(b) @@ -70619,6 +70754,7 @@ end --- @param key int --- @return stbtt__buf --- @nodiscard + local function stbtt__dict_get(b, key) stbtt__buf_seek(b, 0) while b.cursor < b.size do @@ -70640,6 +70776,7 @@ end --- @param outcount int --- @return int[] --- @nodiscard + local function stbtt__dict_get_ints(b, key, outcount) local operands = stbtt__dict_get(b, key) local out = {} @@ -70651,6 +70788,7 @@ local function stbtt__dict_get_ints(b, key, outcount) end --- @param b stbtt__buf + local function stbtt__cff_index_count(b) stbtt__buf_seek(b, 0) return stbtt__buf_get16(b) @@ -70660,6 +70798,7 @@ end --- @param i int --- @return stbtt__buf --- @nodiscard + local function stbtt__cff_index_get(b, i) local count, offsize, start, _end stbtt__buf_seek(b, 0) @@ -70703,17 +70842,26 @@ end --- stbtt_GetNumberOfFonts_internal --- stbtt__get_svg + local function ttUSHORT(p, offset) return stbtt_uint16(p[offset + 1] * 256 + p[offset + 2]) end + local function ttSHORT(p, offset) return stbtt_int16(p[offset + 1] * 256 + p[offset + 2]) end + local function ttULONG(p, offset) return stbtt_uint32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end + local function ttLONG(p, offset) return stbtt_int32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end + local function ttBYTE(p, offset) return stbtt_uint8(p[offset + 1]) end + local function ttCHAR(p, offset) return stbtt_int8(p[offset + 1]) end + local function stbtt_tag4(p, c0, c1, c2, c3, offset) offset = offset or 0; return p[offset + 1] == c0 and p[offset + 2] == c1 and p[offset + 3] == c2 and p[offset + 4] == c3 end + local function stbtt_tag(p, str, offset) local c0, c1, c2, c3 = string.byte(str, 1, 4); return stbtt_tag4(p, c0, c1, c2, c3, offset) end + local function stbtt__isfont(font) -- check the version number if stbtt_tag4(font, 49, 0, 0, 0) then return true end -- TrueType 1 @@ -70725,6 +70873,7 @@ local function stbtt__isfont(font) end -- @OPTIMIZE: binary search + local function stbtt__find_table(data, font_start, tag) local num_tables = ttUSHORT(data, font_start + 4) local tabledir = font_start + 12 @@ -70737,6 +70886,7 @@ local function stbtt__find_table(data, font_start, tag) return 0 end + local function stbtt_GetFontOffsetForIndex_internal(font_collection, index) -- if it's just a font, there's only one valid index if stbtt__isfont(font_collection) then @@ -70760,6 +70910,7 @@ end --- @param cff stbtt__buf --- @param fontdict stbtt__buf + local function stbtt__get_subrs(cff, fontdict) local private_loc = stbtt__dict_get_ints(fontdict, 18, 2) if (private_loc[2] == 0 or private_loc[1] == 0) then @@ -70775,6 +70926,7 @@ local function stbtt__get_subrs(cff, fontdict) end --- @return bool + local function stbtt_InitFont_internal(info, data, fontstart) local cmap local numTables @@ -70902,6 +71054,7 @@ end -- Returns 0 if the character codepoint is not defined in the font. --- @param info stbtt_fontinfo --- @param unicode_codepoint int + function stbtt_FindGlyphIndex(info, unicode_codepoint) local data = info.data local index_map = info.index_map @@ -71007,6 +71160,7 @@ end --- @param y stbtt_int32 --- @param cx stbtt_int32 --- @param cy stbtt_int32 + local function stbtt_setvertex(v, vtx_type, x, y, cx, cy) v.type = vtx_type v.x = (stbtt_int16)(x) @@ -71015,6 +71169,7 @@ local function stbtt_setvertex(v, vtx_type, x, y, cx, cy) v.cy = (stbtt_int16)(cy) end + local function stbtt__GetGlyfOffset(info, glyph_index) STBTT_assert(info.cff.size == 0) @@ -71035,6 +71190,7 @@ end -- Gets the bounding box of the visible part of the glyph, in unscaled coordinates --- @return integer, integer?, integer?, integer?, integer? + local function stbtt_GetGlyphBox(info, glyph_index) local n, x0, y0, x1, y1 @@ -71063,6 +71219,7 @@ end --- @param scy stbtt_int32 --- @param cx stbtt_int32 --- @param cy stbtt_int32 + local function stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy) if start_off then if was_off then @@ -71087,6 +71244,7 @@ end --- @param glyph_index int --- @return int num_vertices --- @return stbtt_vertex[]? vertices + local function stbtt__GetGlyphShapeTT(info, glyph_index) local data = info.data local num_vertices @@ -71306,7 +71464,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) n = STBTT_sqrt(mtx[3] * mtx[3] + mtx[4] * mtx[4]) -- Get indexed glyph. - comp_num_vertices, comp_verts = stbtt_GetGlyphShape(info, gidx) + comp_num_vertices, comp_verts = stbtt_GetGlyphShapeUncached(info, gidx) -- [Luau] transformed in place below: must be a fresh copy if comp_num_vertices > 0 then -- Transform vertices. for i = 1, comp_num_vertices do @@ -71344,6 +71502,7 @@ end --- @param c stbtt__csctx --- @param x stbtt_int32 --- @param y stbtt_int32 + local function stbtt__track_vertex(c, x, y) if x > c.max_x or not c.started then c.max_x = x end if y > c.max_y or not c.started then c.max_y = y end @@ -71360,6 +71519,7 @@ end --- @param cy stbtt_int32 --- @param cx1 stbtt_int32 --- @param cy1 stbtt_int32 + local function stbtt__csctx_v(c, vtx_type, x, y, cx, cy, cx1, cy1) if c.bounds then stbtt__track_vertex(c, x, y) @@ -71375,6 +71535,7 @@ local function stbtt__csctx_v(c, vtx_type, x, y, cx, cy, cx1, cy1) end --- @param ctx stbtt__csctx + local function stbtt__csctx_close_shape(ctx) if ctx.first_x ~= ctx.x or ctx.first_y ~= ctx.y then stbtt__csctx_v(ctx, STBTT_VTX.LINE, trunc(ctx.first_x), trunc(ctx.first_y), 0, 0, 0, 0) @@ -71384,6 +71545,7 @@ end --- @param ctx stbtt__csctx --- @param dx float --- @param dy float + local function stbtt__csctx_rmove_to(ctx, dx, dy) stbtt__csctx_close_shape(ctx) ctx.x = ctx.x + dx @@ -71396,6 +71558,7 @@ end --- @param ctx stbtt__csctx --- @param dx float --- @param dy float + local function stbtt__csctx_rline_to(ctx, dx, dy) ctx.x = ctx.x + dx ctx.y = ctx.y + dy @@ -71409,6 +71572,7 @@ end --- @param dy2 float --- @param dx3 float --- @param dy3 float + local function stbtt__csctx_rccurve_to(ctx, dx1, dy1, dx2, dy2, dx3, dy3) local cx1 = ctx.x + dx1 local cy1 = ctx.y + dy1 @@ -71419,6 +71583,7 @@ local function stbtt__csctx_rccurve_to(ctx, dx1, dy1, dx2, dy2, dx3, dy3) stbtt__csctx_v(ctx, STBTT_VTX.CUBIC, trunc(ctx.x), trunc(ctx.y), trunc(cx1), trunc(cy1), trunc(cx2), trunc(cy2)) end + local function stbtt__get_subr(idx, n) local count = stbtt__cff_index_count(idx) local bias = 107 @@ -71434,6 +71599,7 @@ local function stbtt__get_subr(idx, n) return stbtt__cff_index_get(idx, n) end + local function stbtt__cid_get_glyph_subrs(info, glyph_index) local fdselect = info.fdselect local fdselector = -1 @@ -71464,6 +71630,7 @@ end --- @param info stbtt_fontinfo --- @param glyph_index int --- @param c stbtt__csctx + local function stbtt__run_charstring(info, glyph_index, c) local in_header = true local maskbits = 0 @@ -71737,6 +71904,7 @@ end --- @param glyph_index int --- @return int num_vertices --- @return stbtt_vertex[]? vertices + function stbtt__GetGlyphShapeT2(info, glyph_index) -- runs the charstring twice, once to count and once to output (to avoid realloc) local vertices = nil @@ -71762,6 +71930,7 @@ end --- @return int y0 --- @return int x1 --- @return int y1 + function stbtt__GetGlyphInfoT2(info, glyph_index) local c = STBTT__CSCTX_INIT(true) local r = stbtt__run_charstring(info, glyph_index, c) @@ -71783,7 +71952,8 @@ end -- its x,y, using cx,cy as the bezier control point. --- @param info stbtt_fontinfo --- @param glyph_index int -function stbtt_GetGlyphShape(info, glyph_index) + +function stbtt_GetGlyphShapeUncached(info, glyph_index) if info.cff.size == 0 then return stbtt__GetGlyphShapeTT(info, glyph_index) else @@ -71791,11 +71961,32 @@ function stbtt_GetGlyphShape(info, glyph_index) end end + +function stbtt_GetGlyphShape(info, glyph_index) + -- [Luau] shapes don't depend on the size: cache them per font (baking a new size re-used to re-parse every glyph). + -- Callers only read the vertices (stbtt_FreeShape is a no-op). + local cache = info._ShapeCache + if cache == nil then cache = {}; info._ShapeCache = cache end + local e = cache[glyph_index] + if e == nil then + local n, v + if info.cff.size == 0 then + n, v = stbtt__GetGlyphShapeTT(info, glyph_index) + else + n, v = stbtt__GetGlyphShapeT2(info, glyph_index) + end + e = { n, v } + cache[glyph_index] = e + end + return e[1], e[2] +end + -- leftSideBearing is the offset from the current horizontal position to the left edge of the character -- advanceWidth is the offset from the current horizontal position to the next horizontal position -- these are expressed in unscaled coordinates --- @param info stbtt_fontinfo --- @param glyph_index int + function stbtt_GetGlyphHMetrics(info, glyph_index) local numOfLongHorMetrics = ttUSHORT(info.data, info.hhea + 34) @@ -71818,6 +72009,7 @@ end -- these are expressed in unscaled coordinates, so you must multiply by -- the scale factor for a given size --- @param info stbtt_fontinfo + function stbtt_GetFontVMetrics(info) local ascent = ttSHORT(info.data, info.hhea + 4) local descent = ttSHORT(info.data, info.hhea + 6) @@ -71834,6 +72026,7 @@ end -- so if you prefer to measure height by the ascent only, use a similar calculation. --- @param info stbtt_fontinfo --- @param height float + function stbtt_ScaleForPixelHeight(info, height) local fheight = ttSHORT(info.data, info.hhea + 4) - ttSHORT(info.data, info.hhea + 6) return height / fheight @@ -71854,6 +72047,7 @@ end --- @param scale_y float --- @param shift_x float --- @param shift_y float + function stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, shift_x, shift_y) local n, x0, y0, x1, y1 = stbtt_GetGlyphBox(font, glyph) @@ -71884,6 +72078,7 @@ end --- @param glyph int --- @param scale_x float --- @param scale_y float + function stbtt_GetGlyphBitmapBox(font, glyph, scale_x, scale_y) return stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, 0.0, 0.0) end @@ -71911,6 +72106,7 @@ end --- @param y0 float --- @param x1 float --- @param y1 float + local function stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1) if y0 == y1 then return end STBTT_assert(y0 < y1) @@ -71952,6 +72148,7 @@ end --- @param height float --- @param top_width float --- @param bottom_width float + local function stbtt__sized_trapezoid_area(height, top_width, bottom_width) STBTT_assert(top_width >= 0) STBTT_assert(bottom_width >= 0) @@ -71963,12 +72160,14 @@ end --- @param tx1 float --- @param bx0 float --- @param bx1 float + local function stbtt__position_trapezoid_area(height, tx0, tx1, bx0, bx1) return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0) end --- @param height float --- @param width float + local function stbtt__sized_triangle_area(height, width) return height * width / 2 end @@ -71978,6 +72177,7 @@ end --- @param len int --- @param e stbtt__active_edge --- @param y_top float + local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_top) local y_bottom = y_top + 1 @@ -72200,11 +72400,14 @@ end --- @param vsubsample int --- @param off_x int --- @param off_y int +local rasterize_scanline, rasterize_scanline2 = {}, {} -- [Luau] reused: fully cleared per scanline below + local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y) local active = nil - local scanline = {} -- [Port] size = result.w, 0-based - local scanline2 = {} -- [Port] size = result.w + 1, 0-based + active_pool_n = 0 -- every active edge of the previous call is dead + local scanline = rasterize_scanline -- [Port] size = result.w, 0-based + local scanline2 = rasterize_scanline2 -- [Port] size = result.w + 1, 0-based STBTT__NOTUSED(vsubsample) @@ -72262,20 +72465,18 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of do local sum = 0 + local pixels, base = result.pixels, j * result.stride + 1 for i = 0, result.w - 1 do - local k - local m sum = sum + scanline2[i] - k = scanline[i] + sum - k = STBTT_fabs(k) * 255 + 0.5 - m = trunc(k) + -- [Luau] k >= 0: trunc == floor, and m is already 0..255 (unsigned_char() is a no-op) + local m = math.floor(math.abs(scanline[i] + sum) * 255 + 0.5) if m > 255 then m = 255 end - result.pixels[j * result.stride + i + 1] = unsigned_char(m) + pixels[base + i] = m end end -- advance all the edges - step = active + local step = active while step do step.fx = step.fx + step.fdx -- advance to position for current scanline step = step.next -- advance through list @@ -72295,10 +72496,47 @@ local STBTT__COMPARE = function(a, b) end --- @param p stbtt__edge[] + local function stbtt__sort_edges(p) STBTT_sort(p, STBTT__COMPARE) end +-- [Luau] sorts p[lo..hi] by y0 without a comparator callback (like upstream's stbtt__sort_edges_quicksort + ins_sort) + +local function stbtt__sort_edges_range(p, lo, hi) + while hi - lo > 12 do + -- median of three -> p[lo] + local m = math.floor((lo + hi) / 2) + local a, b, c = p[lo], p[m], p[hi] + if b.y0 < a.y0 then a, b = b, a end + if c.y0 < b.y0 then b, c = c, b; if b.y0 < a.y0 then a, b = b, a end end + p[lo], p[m], p[hi] = b, a, c + local pivot = p[lo].y0 + local i, j = lo + 1, hi + while true do + while p[i].y0 < pivot do i = i + 1 end + while pivot < p[j].y0 do j = j - 1 end + if i >= j then break end + p[i], p[j] = p[j], p[i] + i = i + 1; j = j - 1 + end + p[lo], p[j] = p[j], p[lo] + -- recurse into the smaller side, loop on the larger + if j - lo < hi - j then + stbtt__sort_edges_range(p, lo, j - 1); lo = j + 1 + else + stbtt__sort_edges_range(p, j + 1, hi); hi = j - 1 + end + end + for i = lo + 1, hi do + local t = p[i] + local y = t.y0 + local j = i - 1 + while j >= lo and p[j].y0 > y do p[j + 1] = p[j]; j = j - 1 end + p[j + 1] = t + end +end + --- @param result stbtt__bitmap --- @param pts stbtt__point[] --- @param wcount int[] @@ -72310,6 +72548,8 @@ end --- @param off_x int --- @param off_y int --- @param invert bool +local rasterize_edges = {} + local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, shift_x, shift_y, off_x, off_y, invert) local y_scale_inv = (invert) and -scale_y or scale_y local vsubsample = 1 -- STBTT_RASTERIZER_VERSION == 2 @@ -72321,7 +72561,13 @@ local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, n = n + wcount[i] end - local e = {} for i = 1, n + 1 do e[i] = stbtt__edge() end -- add an extra one as a sentinel + -- [Luau] edges reused across calls; unused entries are sentinels (y0 = nil) like the unfilled ones upstream + local e = rasterize_edges + for i = 1, n + 1 do + local ed = e[i] + if ed == nil then e[i] = stbtt__edge() else ed.y0 = nil; ed.invert = false end + end + for i = n + 2, #e do e[i].y0 = nil end n = 0 local m = 0 @@ -72365,7 +72611,7 @@ local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, end -- now sort the edges by their highest point (should snap to integer, and then by x) - stbtt__sort_edges(e) + stbtt__sort_edges_range(e, 1, n) -- [Luau] e[n + 1..] are y0 == nil sentinels, already last -- now, traverse the scanlines and find the intersections on each scanline, use xor winding rule stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y) @@ -72375,6 +72621,7 @@ end --- @param n int --- @param x float --- @param y float + local function stbtt__add_point(points, n, x, y) if points == nil then return end -- during first pass, it's unallocated points[n + 1].x = x @@ -72393,6 +72640,7 @@ end --- @param objspace_flatness_squared float --- @param n int --- @return int num_points # updated num_points passed in + local function stbtt__tesselate_curve(points, num_points, x0, y0, x1, y1, x2, y2, objspace_flatness_squared, n) -- midpoint local mx = (x0 + 2 * x1 + x2) / 4 @@ -72429,6 +72677,7 @@ end --- @param objspace_flatness_squared float --- @param n int --- @return int num_points # updated num_points passed in + local function stbtt__tesselate_cubic(points, num_points, x0, y0, x1, y1, x2, y2, x3, y3, objspace_flatness_squared, n) -- @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough local dx0 = x1 - x0 @@ -72480,6 +72729,8 @@ end --- @return stbtt__point[]? points --- @return int? num_contours --- @return int[]? contour_lengths +local flatten_points = {} + local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) local points = nil local num_points = 0 @@ -72504,8 +72755,8 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) for pass = 0, 1 do local x, y = 0, 0 if pass == 1 then - points = {} - for i = 1, num_points do points[i] = stbtt__point() end + points = flatten_points -- [Luau] reused across calls (only [1..num_points] is read) + for i = #points + 1, num_points do points[i] = stbtt__point() end end num_points = 0 n = -1 @@ -72562,6 +72813,7 @@ end --- @param x_off int --- @param y_off int --- @param invert bool + local function stbtt_Rasterize(result, flatness_in_pixels, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert) local scale = (scale_x > scale_y) and scale_y or scale_x @@ -72589,6 +72841,7 @@ end --- @param shift_x float --- @param shift_y float --- @param glyph int + local function stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, glyph) local num_verts, vertices = stbtt_GetGlyphShape(info, glyph) local gbm = stbtt__bitmap() @@ -72642,6 +72895,7 @@ local STBTT__OVER_MASK = STBTT_MAX_OVERSAMPLE - 1 --- @param h int --- @param stride_in_bytes int --- @param kernel_width unsigned_int + local function stbtt__h_prefilter(pixels, w, h, stride_in_bytes, kernel_width) local buffer = {} local safe_w = w - kernel_width @@ -72671,6 +72925,7 @@ end --- @param h int --- @param stride_in_bytes int --- @param kernel_width unsigned_int + local function stbtt__v_prefilter(pixels, w, h, stride_in_bytes, kernel_width) local buffer = {} local safe_h = h - kernel_width @@ -72697,6 +72952,7 @@ end --- @param oversample int --- @return float + local function stbtt__oversample_shift(oversample) if oversample == 0 then return 0.0 @@ -72723,6 +72979,7 @@ end --- @param prefilter_x int --- @param prefilter_y int --- @param glyph int + function stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, prefilter_x, prefilter_y, glyph) stbtt_MakeGlyphBitmapSubpixel(info, output, out_w - (prefilter_x - 1), out_h - (prefilter_y - 1), out_stride, scale_x, scale_y, shift_x, shift_y, glyph) @@ -72776,6 +73033,7 @@ end -- return '0' for index 0, and -1 for all other indices. --- @param data table --- @param index int + function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForIndex_internal(data, index) end -- Given an offset into the file that defines a font, this function builds @@ -72786,6 +73044,7 @@ function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForI --- @param info stbtt_fontinfo --- @param data table --- @param offset int + function stbtt_InitFont(info, data, offset) return stbtt_InitFont_internal(info, data, offset) end return { @@ -73321,6 +73580,7 @@ return { ImFontBaked_BuildLoadGlyph = ImFontBaked_BuildLoadGlyph, ImFontBaked_BuildLoadGlyphAdvanceX = ImFontBaked_BuildLoadGlyphAdvanceX, ImFontCalcTextSizeEx = ImFontCalcTextSizeEx, + ImFontCalcTextSizeXY = ImFontCalcTextSizeXY, ImFontCalcWordWrapPositionEx = ImFontCalcWordWrapPositionEx, ImFontCalcWordWrapPositionEx_Uncached = ImFontCalcWordWrapPositionEx_Uncached, ImFontConfig = ImFontConfig, @@ -73671,6 +73931,7 @@ return { stbtt_GetGlyphBitmapBoxSubpixel = stbtt_GetGlyphBitmapBoxSubpixel, stbtt_GetGlyphHMetrics = stbtt_GetGlyphHMetrics, stbtt_GetGlyphShape = stbtt_GetGlyphShape, + stbtt_GetGlyphShapeUncached = stbtt_GetGlyphShapeUncached, stbtt_InitFont = stbtt_InitFont, stbtt_MakeGlyphBitmapSubpixelPrefilter = stbtt_MakeGlyphBitmapSubpixelPrefilter, stbtt_ScaleForPixelHeight = stbtt_ScaleForPixelHeight, diff --git a/examples/example_love_extensions/conf.lua b/examples/example_love_extensions/conf.lua new file mode 100644 index 0000000..f381d4e --- /dev/null +++ b/examples/example_love_extensions/conf.lua @@ -0,0 +1,5 @@ +function love.conf(t) + t.window.title = "Dear ImGui - LÖVE extensions example" + t.window.width, t.window.height = 1280, 800 + t.window.resizable = true +end diff --git a/examples/example_love_extensions/main.lua b/examples/example_love_extensions/main.lua new file mode 100644 index 0000000..c9afdc2 --- /dev/null +++ b/examples/example_love_extensions/main.lua @@ -0,0 +1,619 @@ +-- Dear ImGui extensions on LÖVE: python3 tools/bundle.py --target love then love examples/example_love_extensions +local ROOT = love.filesystem.getSource() .. "/../../" -- repo root (build/, fonts/, extensions/) +local f = assert(io.open(ROOT .. "build/imgui_love.lua", "rb"), "run: python3 tools/bundle.py --target love") +local G = assert(loadstring(f:read("*a"), "@imgui_love.lua"))(); f:close() +local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4 +local _ + +-- Each extension repo ships a LÖVE/LuaJIT build in its love/ folder (regenerate with /tools/love.sh) +local function LoadExt(repo, name) + return assert(loadfile(ROOT .. "extensions/" .. repo .. "/love/" .. name))() +end + +-- catppuccin mocha mauve https://catppuccin.com/palette +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 Red, Peach, Yellow, Green, Blue, Pink = 0xf38ba8, 0xfab387, 0xf9e2af, 0xa6e3a1, 0x89b4fa, 0xf5c2e7 + +local function Col32(Value, Alpha) + return G.IM_COL32(bit32.extract(Value, 16, 8), bit32.extract(Value, 8, 8), bit32.extract(Value, 0, 8), + math.floor((Alpha or 1.0) * 255 + 0.5)) +end + +local function StyleColorsCatppuccinMocha(Style) + local function Hex(Value, Alpha) + return 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 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 _, E in ipairs(Entries) do + Style.Colors[G.ImGuiCol[E[1]]] = Hex(E[2], E[3]) + end +end + +local Demos = {} + +local CurveLabels = { "Translation", "Rotation", "Scale" } +local function NewRampEdit(ImCurveEdit, Min, Max) + local R = { + mPts = { + { ImVec2(-10, 0), ImVec2(20, 0.6), ImVec2(25, 0.2), ImVec2(70, 0.4), ImVec2(120, 1) }, + { ImVec2(-50, 0.2), ImVec2(33, 0.7), ImVec2(80, 0.2), ImVec2(82, 0.8) }, + { ImVec2(40, 0), ImVec2(60, 0.1), ImVec2(90, 0.82), ImVec2(150, 0.24), ImVec2(200, 0.34), ImVec2(250, 0.12) }, + }, + mbVisible = { true, true, true }, mMin = Min, mMax = Max, + } + function R:GetCurveCount() return 3 end + function R:IsVisible(c) return self.mbVisible[c] end + function R:GetPointCount(c) return #self.mPts[c] end + function R:GetCurveColor(c) return ({ 0xFF0000FF, 0xFF00FF00, 0xFFFF0000 })[c] end + function R:GetPoints(c) return self.mPts[c] end + function R:GetCurveType() return ImCurveEdit.CurveSmooth end + function R:SortValues(c) table.sort(self.mPts[c], function(a, b) return a.x < b.x end) end + function R:EditPoint(c, p, value) + self.mPts[c][p] = ImVec2(value.x, value.y) + self:SortValues(c) + for i, pt in ipairs(self.mPts[c]) do if pt.x == value.x then return i end end + return p + end + function R:AddPoint(c, value) + if #self.mPts[c] >= 8 then return end + table.insert(self.mPts[c], value) + self:SortValues(c) + end + function R:GetMax() return self.mMax end + function R:GetMin() return self.mMin end + function R:GetBackgroundColor() return 0 end + return R +end + +-- ImCurveEdit +do + local D = { Name = "ImCurveEdit" } + local ImCurveEdit, RampEdit, Selected + function D.Init() + ImCurveEdit = LoadExt("imcurveedit-luau", "ImCurveEdit.lua")(G) + RampEdit, Selected = NewRampEdit(ImCurveEdit, ImVec2(-100, 0), ImVec2(300, 1)), {} + end + function D.Draw() + ImGui.SetNextWindowSize(ImVec2(700, 400), G.ImGuiCond.FirstUseEver) + D.Show = ImGui.Begin("ImCurveEdit", D.Show) + for i = 1, 3 do + _, RampEdit.mbVisible[i] = ImGui.Checkbox(CurveLabels[i], RampEdit.mbVisible[i]) + ImGui.SameLine() + end + ImGui.Text("selected: %d", #Selected) + local Avail = ImGui.GetContentRegionAvail() + _, Selected = ImCurveEdit.Edit(RampEdit, ImVec2(Avail.x, Avail.y), 137, nil, Selected) + ImGui.End() + end + table.insert(Demos, D) +end + +-- ImGradient +do + local D = { Name = "ImGradient" } + local ImGradient, Gradient, Selection = nil, nil, -1 + local Size = ImVec2(400, 24) + function D.Init() + ImGradient = LoadExt("imgradient-luau", "ImGradient.lua")(G) + Gradient = { Points = { ImVec4(1, 0.2, 0.2, 0), ImVec4(1, 0.9, 0.2, 0.4), ImVec4(0.2, 0.4, 1, 1) } } + function Gradient:GetPointCount() return #self.Points end + function Gradient:GetPoints() return self.Points end + function Gradient:EditPoint(i, v) self.Points[i] = v; return i end + function Gradient:AddPoint(v) table.insert(self.Points, v) end + function Gradient:Sorted() + local s = table.clone(self.Points) + table.sort(s, function(a, b) return a.w < b.w end) + return s + end + end + function D.Draw() + D.Show = ImGui.Begin("ImGradient", D.Show) + local Pos = ImGui.GetCursorScreenPos() + local Dl, S = ImGui.GetWindowDrawList(), Gradient:Sorted() + local X0 = Pos.x + for i = 0, #S do + local a, b = S[math.max(i, 1)], S[math.min(i + 1, #S)] + local X1 = Pos.x + Size.x * (i < #S and b.w or 1) + local Ca = ImGui.ColorConvertFloat4ToU32(ImVec4(a.x, a.y, a.z, 1)) + local Cb = ImGui.ColorConvertFloat4ToU32(ImVec4(b.x, b.y, b.z, 1)) + if X1 > X0 then Dl:AddRectFilledMultiColor(ImVec2(X0, Pos.y), ImVec2(X1, Pos.y + Size.y), Ca, Cb, Cb, Ca) end + X0 = X1 + end + _, Selection = ImGradient.Edit(Gradient, Size, Selection) + ImGui.Text("points: %d selection: %d", #Gradient.Points, Selection) + local P = Gradient.Points[Selection] + if P then + local Col = ImVec4(P.x, P.y, P.z, 1) + if ImGui.ColorEdit3("color", Col) then Gradient:EditPoint(Selection, ImVec4(Col.x, Col.y, Col.z, P.w)) end + if ImGui.Button("Delete point") and #Gradient.Points > 2 then table.remove(Gradient.Points, Selection); Selection = -1 end + end + ImGui.End() + end + table.insert(Demos, D) +end + +-- ImSequencer +do + local D = { Name = "ImSequencer" } + local ImSequencer, ImCurveEdit, RampEdit, MySequence, Options + local TypeNames = { "Camera", "Music", "ScreenEffect", "FadeIn", "Animation" } + local SelectedEntry, FirstFrame, Expanded, CurrentFrame = -1, 0, true, 100 + function D.Init() + ImSequencer = LoadExt("imsequencer-luau", "ImSequencer.lua")(G) + ImCurveEdit = LoadExt("imcurveedit-luau", "ImCurveEdit.lua")(G) + RampEdit = NewRampEdit(ImCurveEdit, ImVec2(0, 0), ImVec2(1, 1)) + local function Item(t, s, e, x) return { mType = t, mFrameStart = s, mFrameEnd = e, mExpanded = x } end + MySequence = { mFrameMin = -100, mFrameMax = 1000 } + MySequence.myItems = { Item(1, 10, 30, false), Item(2, 20, 30, true), Item(4, 12, 60, false), Item(3, 61, 90, false), Item(5, 90, 99, false) } + function MySequence:GetFrameMin() return self.mFrameMin end + function MySequence:GetFrameMax() return self.mFrameMax end + function MySequence:GetItemCount() return #self.myItems end + function MySequence:GetItemTypeCount() return #TypeNames end + function MySequence:GetItemTypeName(t) return TypeNames[t] end + function MySequence:GetItemLabel(i) return string.format("[%02d] %s", i - 1, TypeNames[self.myItems[i].mType]) end + function MySequence:Get(i) + local it = self.myItems[i] + return it.mFrameStart, it.mFrameEnd, it.mType, 0xFFAA8080 + end + function MySequence:Set(i, s, e) local it = self.myItems[i]; it.mFrameStart, it.mFrameEnd = s, e end + function MySequence:Add(t) table.insert(self.myItems, Item(t, 0, 10, false)) end + function MySequence:Del(i) table.remove(self.myItems, i) end + function MySequence:Duplicate(i) table.insert(self.myItems, table.clone(self.myItems[i])) end + function MySequence:GetCustomHeight(i) return self.myItems[i].mExpanded and 300 or 0 end + function MySequence:DoubleClick(i) + if self.myItems[i].mExpanded then self.myItems[i].mExpanded = false; return end + for _, it in ipairs(self.myItems) do it.mExpanded = false end + self.myItems[i].mExpanded = true + end + function MySequence:CustomDraw(i, dl, rc, legendRect, clippingRect, legendClippingRect) + RampEdit.mMax = ImVec2(self.mFrameMax, 1) + RampEdit.mMin = ImVec2(self.mFrameMin, 0) + dl:PushClipRect(legendClippingRect.Min, legendClippingRect.Max, true) + for c = 1, 3 do + local pta = ImVec2(legendRect.Min.x + 30, legendRect.Min.y + (c - 1) * 14) + local ptb = ImVec2(legendRect.Max.x, legendRect.Min.y + c * 14) + dl:AddText(pta, RampEdit.mbVisible[c] and 0xFFFFFFFF or 0x80FFFFFF, CurveLabels[c]) + if G.ImRect(pta, ptb):Contains(ImGui.GetMousePos()) and ImGui.IsMouseClicked(0) then + RampEdit.mbVisible[c] = not RampEdit.mbVisible[c] + end + end + dl:PopClipRect() + ImGui.SetCursorScreenPos(rc.Min) + ImCurveEdit.Edit(RampEdit, ImVec2(rc.Max.x - rc.Min.x, rc.Max.y - rc.Min.y), 137 + i, clippingRect) + end + function MySequence:CustomDrawCompact(i, dl, rc, clippingRect) + RampEdit.mMax = ImVec2(self.mFrameMax, 1) + RampEdit.mMin = ImVec2(self.mFrameMin, 0) + dl:PushClipRect(clippingRect.Min, clippingRect.Max, true) + local it = self.myItems[i] + for c = 1, 3 do + for _, pt in ipairs(RampEdit.mPts[c]) do + local p = pt.x + if p >= it.mFrameStart and p <= it.mFrameEnd then + local x = rc.Min.x + (rc.Max.x - rc.Min.x) * (p - self.mFrameMin) / (self.mFrameMax - self.mFrameMin) + dl:AddLine(ImVec2(x, rc.Min.y + 6), ImVec2(x, rc.Max.y - 4), 0xAA000000, 4) + end + end + end + dl:PopClipRect() + end + local S = ImSequencer + Options = bit32.bor(S.SEQUENCER_EDIT_STARTEND, S.SEQUENCER_ADD, S.SEQUENCER_DEL, S.SEQUENCER_COPYPASTE, S.SEQUENCER_CHANGE_FRAME) + end + function D.Draw() + ImGui.SetNextWindowSize(ImVec2(900, 600), G.ImGuiCond.FirstUseEver) + D.Show = ImGui.Begin("ImSequencer", D.Show) + ImGui.PushItemWidth(130) + MySequence.mFrameMin = ImGui.InputInt("Frame Min", MySequence.mFrameMin) + ImGui.SameLine() + CurrentFrame = ImGui.InputInt("Frame ", CurrentFrame) + ImGui.SameLine() + MySequence.mFrameMax = ImGui.InputInt("Frame Max", MySequence.mFrameMax) + ImGui.PopItemWidth() + _, CurrentFrame, Expanded, SelectedEntry, FirstFrame = ImSequencer.Sequencer(MySequence, CurrentFrame, Expanded, SelectedEntry, FirstFrame, Options) + if SelectedEntry ~= -1 then + ImGui.Text("I am a %s, please edit me", TypeNames[MySequence.myItems[SelectedEntry].mType]) + end + ImGui.End() + end + table.insert(Demos, D) +end + +-- imgui_memory_editor +do + local D = { Name = "Memory Editor" } + local ffi = require("ffi") + local Data, Ptr, MemEdit, MemEdit2, Frame = nil, nil, nil, nil, 0 + function D.Init() + local MemoryEditor = LoadExt("imgui-memory-editor-luau", "MemoryEditor.lua")(G) + Data = love.data.newByteData(0x400) + Ptr = ffi.cast("uint8_t*", Data:getFFIPointer()) + ffi.cast("float*", Ptr + 0x10)[0] = math.pi + ffi.copy(Ptr + 0x20, "Hello from a LOVE ByteData!") + for i = 0x40, 0x3FF do Ptr[i] = (i * 37) % 256 end + MemEdit = MemoryEditor.new() + MemEdit.OptShowDataPreview = true + MemEdit2 = MemoryEditor.new() + MemEdit2.HighlightFn = function(_, off) return Ptr[off] % 2 == 0 end + end + function D.Draw() + Frame = Frame + 1 + ffi.cast("uint32_t*", Ptr)[0] = Frame + MemEdit:DrawWindow("Memory Editor", Data) + local Open, Visible = ImGui.Begin("Memory Editor (DrawContents)", D.Show) + D.Show = Open + if Visible then + ImGui.Text("frame = %d (the u32 at 0x00)", Frame) + MemEdit2:DrawContents(Data, 0x80, 0x1000) + end + ImGui.End() + end + table.insert(Demos, D) +end + +-- ImGuizmo (fixed camera, one cube; matrices are column-major float[16] like upstream) +do + local D = { Name = "ImGuizmo" } + local ImGuizmo, OP, MODE + local Operation, Mode + local UseSnap, ShowGrid = false, true + local Snap = { 1, 1, 1 } + local AngleSnap, ScaleSnap = 15, 0.1 + local BoundSizing, BoundSizingSnap = false, false + local Bounds = { -0.5, -0.5, -0.5, 0.5, 0.5, 0.5 } + local BoundsSnap = { 0.1, 0.1, 0.1 } + local Identity = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } + local Object = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } + local View + + local function Cross(a, b) return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } end + local function Norm(a) local l = math.sqrt(a[1] ^ 2 + a[2] ^ 2 + a[3] ^ 2); return { a[1] / l, a[2] / l, a[3] / l } end + local function Dot(a, b) return a[1] * b[1] + a[2] * b[2] + a[3] * b[3] end + -- upstream example's LookAt / Perspective + local function LookAt(eye, at, up) + local z = Norm({ eye[1] - at[1], eye[2] - at[2], eye[3] - at[3] }) + local x = Norm(Cross(up, z)) + local y = Norm(Cross(z, x)) + return { x[1], y[1], z[1], 0, x[2], y[2], z[2], 0, x[3], y[3], z[3], 0, -Dot(x, eye), -Dot(y, eye), -Dot(z, eye), 1 } + end + local function Perspective(fovy, aspect, n, fa) + local ymax = n * math.tan(fovy * math.pi / 360) + local xmax = ymax * aspect + local t2, w, h, d = 2 * n, 2 * xmax, 2 * ymax, fa - n + return { t2 / w, 0, 0, 0, 0, t2 / h, 0, 0, 0, 0, (-fa - n) / d, -1, 0, 0, (-t2 * fa) / d, 0 } + end + + function D.Init() + ImGuizmo = LoadExt("imguizmo-luau", "ImGuizmo.lua")(G) + OP, MODE = ImGuizmo.OPERATION, ImGuizmo.MODE + Operation, Mode = OP.TRANSLATE, MODE.WORLD + View = LookAt({ 6, 5, 8 }, { 0, 0, 0 }, { 0, 1, 0 }) + end + + local function EditTransform(Matrix) + local K = G.ImGuiKey + if ImGui.IsKeyPressed(K.T) then Operation = OP.TRANSLATE end + if ImGui.IsKeyPressed(K.E) then Operation = OP.ROTATE end + if ImGui.IsKeyPressed(K.R) then Operation = OP.SCALE end + _, Operation = ImGui.RadioButton("Translate", Operation, OP.TRANSLATE); ImGui.SameLine() + _, Operation = ImGui.RadioButton("Rotate", Operation, OP.ROTATE); ImGui.SameLine() + _, Operation = ImGui.RadioButton("Scale", Operation, OP.SCALE); ImGui.SameLine() + _, Operation = ImGui.RadioButton("Universal", Operation, OP.UNIVERSAL) + + local Tr, Rt, Sc = {}, {}, {} + ImGuizmo.DecomposeMatrixToComponents(Matrix, Tr, Rt, Sc) + local Edited = ImGui.DragFloat3("Tr", Tr, 0.1) + Edited = ImGui.DragFloat3("Rt", Rt, 1) or Edited + Edited = ImGui.DragFloat3("Sc", Sc, 0.01) or Edited + if Edited then ImGuizmo.RecomposeMatrixFromComponents(Tr, Rt, Sc, Matrix) end + + if Operation ~= OP.SCALE then + _, Mode = ImGui.RadioButton("Local", Mode, MODE.LOCAL); ImGui.SameLine() + _, Mode = ImGui.RadioButton("World", Mode, MODE.WORLD) + end + _, UseSnap = ImGui.Checkbox("Snap", UseSnap); ImGui.SameLine() + if Operation == OP.ROTATE then + AngleSnap = ImGui.DragFloat("Angle Snap", AngleSnap, 1) + elseif Operation == OP.SCALE then + ScaleSnap = ImGui.DragFloat("Scale Snap", ScaleSnap, 0.01) + else + ImGui.DragFloat3("Snap Value", Snap, 0.1) + end + if Operation == OP.SCALE then + _, BoundSizing = ImGui.Checkbox("Bound Sizing", BoundSizing) + if BoundSizing then + ImGui.PushID(3) + _, BoundSizingSnap = ImGui.Checkbox("Bound Snap", BoundSizingSnap); ImGui.SameLine() + ImGui.DragFloat3("Snap", BoundsSnap, 0.01) + ImGui.PopID() + end + end + _, ShowGrid = ImGui.Checkbox("Show Grid", ShowGrid) + + local SnapArg + if UseSnap then + if Operation == OP.ROTATE then SnapArg = { AngleSnap, AngleSnap, AngleSnap } + elseif Operation == OP.SCALE then SnapArg = { ScaleSnap, ScaleSnap, ScaleSnap } + else SnapArg = Snap end + end + return SnapArg + end + + function D.Draw() + ImGuizmo.BeginFrame() + local W, H = love.graphics.getDimensions() + local Proj = Perspective(45, W / H, 0.1, 100) + ImGuizmo.SetDrawlist(ImGui.GetBackgroundDrawList()) + ImGuizmo.SetRect(0, 0, W, H) + + D.Show = ImGui.Begin("ImGuizmo", D.Show) + local SnapArg = EditTransform(Object) + ImGui.End() + + if ShowGrid then ImGuizmo.DrawGrid(View, Proj, Identity, 10) end + ImGuizmo.DrawCubes(View, Proj, Object, 1) + -- Bound Sizing replaces the scale gizmo (BOUNDS draws only the bounds box) + local UseBounds = BoundSizing and Operation == OP.SCALE + ImGuizmo.Manipulate(View, Proj, UseBounds and OP.BOUNDS or Operation, Mode, Object, nil, SnapArg, + UseBounds and Bounds or nil, UseBounds and BoundSizingSnap and BoundsSnap or nil) + ImGuizmo.ViewManipulate(View, 10, ImVec2(W - 128, 0), ImVec2(128, 128), 0x10101010) + end + table.insert(Demos, D) +end + +-- ImNodes (Logic Simulator) +do + local D = { Name = "ImNodes" } + local UI + function D.Init() + local ImNodes = LoadExt("imnodes-luau", "ImNodes.lua")(G) + local LogicSim = LoadExt("imnodes-luau", "LogicSim.lua")(G, ImNodes) + UI = LoadExt("imnodes-luau", "LogicUI.lua")(G, ImNodes, LogicSim) + + ImNodes.CreateContext() + ImNodes.PushAttributeFlag(ImNodes.ImNodesAttributeFlags.EnableLinkDetachWithDragClick) + local NodesIO = ImNodes.GetIO() + local KeyCtrl = function() return ImGui.GetIO().KeyCtrl end + NodesIO.LinkDetachWithModifierClick.Modifier = KeyCtrl + NodesIO.MultipleSelectModifier.Modifier = KeyCtrl + local NodesStyle = ImNodes.GetStyle() + NodesStyle.Flags = bit32.bor(NodesStyle.Flags, ImNodes.ImNodesStyleFlags.GridLinesPrimary) + + -- catppuccin mocha + local Col, C = ImNodes.ImNodesCol, NodesStyle.Colors + C[Col.NodeBackground] = Col32(Surface0) + C[Col.NodeBackgroundHovered] = Col32(Surface1) + C[Col.NodeBackgroundSelected] = Col32(Surface1) + C[Col.NodeOutline] = Col32(Surface2) + C[Col.TitleBar] = Col32(Mantle) + C[Col.TitleBarHovered] = Col32(Surface1) + C[Col.TitleBarSelected] = Col32(Mauve, 0.6) + C[Col.Link] = Col32(Mauve, 0.8) + C[Col.LinkHovered] = Col32(Lavender) + C[Col.LinkSelected] = Col32(Lavender) + C[Col.Pin] = Col32(Mauve, 0.7) + C[Col.PinHovered] = Col32(Lavender) + C[Col.BoxSelector] = Col32(Mauve, 0.12) + C[Col.BoxSelectorOutline] = Col32(Mauve, 0.6) + C[Col.GridBackground] = Col32(Crust) + C[Col.GridLine] = Col32(Surface0, 0.6) + C[Col.GridLinePrimary] = Col32(Surface1, 0.8) + C[Col.MiniMapBackground] = Col32(Mantle, 0.6) + C[Col.MiniMapBackgroundHovered] = Col32(Mantle, 0.8) + C[Col.MiniMapOutline] = Col32(Surface1, 0.6) + C[Col.MiniMapOutlineHovered] = Col32(Surface2) + C[Col.MiniMapNodeBackground] = Col32(Surface1, 0.6) + C[Col.MiniMapNodeBackgroundHovered] = Col32(Surface2) + C[Col.MiniMapNodeBackgroundSelected] = Col32(Mauve, 0.6) + C[Col.MiniMapNodeOutline] = Col32(Overlay0, 0.6) + C[Col.MiniMapLink] = C[Col.Link] + C[Col.MiniMapLinkSelected] = C[Col.LinkSelected] + C[Col.MiniMapCanvas] = Col32(Text, 0.1) + C[Col.MiniMapCanvasOutline] = Col32(Text, 0.6) + end + function D.Draw() UI.Draw() end + table.insert(Demos, D) +end + +-- ImPlot +do + local D = { Name = "ImPlot" } + local ImPlot + function D.Init() + ImPlot = LoadExt("implot-luau", "ImPlot.lua")(G) + LoadExt("implot-luau", "ImPlotDemo.lua")(G, ImPlot) + ImPlot.CreateContext() + end + function D.Draw() ImPlot.ShowDemoWindow() end + table.insert(Demos, D) +end + +-- ImPlot3D +do + local D = { Name = "ImPlot3D" } + local ImPlot3D + function D.Init() + ImPlot3D = LoadExt("implot3d-luau", "ImPlot3D.lua")(G) + LoadExt("implot3d-luau", "ImPlot3DDemo.lua")(G, ImPlot3D) + ImPlot3D.CreateContext() + end + function D.Draw() ImPlot3D.ShowDemoWindow() end + table.insert(Demos, D) +end + +-- ImGuiColorTextEdit +do + local D = { Name = "ImGuiColorTextEdit" } + local TextEditor, Editor, SavedUndoIndex + local SampleCode = [==[ +-- Sample Lua code +local function Greet(name) + return "Hello, " .. name .. "!" +end + +for i = 1, 10 do + if i % 2 == 0 then + print(Greet("Player" .. i), 3.14 * i, 0xFF) + end +end + +--[[ block + comment ]] +local t = { a = 1, b = "two", [3] = true, nil } +]==] + -- catppuccin mocha, in TextEditor.Color order + local CatppuccinPalette = { + Col32(Text), Col32(Mauve), Col32(Yellow), Col32(Peach), Col32(Green), Col32(Overlay2), Col32(Pink), Col32(Text), + Col32(Blue), Col32(Overlay0), Col32(Base), Col32(Text), Col32(Surface2), Col32(Surface1), Col32(Surface0), Col32(Overlay0), + Col32(Yellow), Col32(Blue), Col32(Mauve), Col32(Red), Col32(Overlay0), Col32(Lavender), Col32(Text, 0.03), Col32(Text, 0.06), + } + function D.Init() + TextEditor = LoadExt("imguicolortextedit-luau", "TextEditor.lua")(G) + Editor = TextEditor.new() + Editor:SetPalette(CatppuccinPalette) + Editor:SetLanguage(TextEditor.Language.Lua()) + Editor:SetText(SampleCode) + SavedUndoIndex = Editor:GetUndoIndex() + end + function D.Draw() + ImGui.SetNextWindowSize(ImVec2(800, 600), G.ImGuiCond.FirstUseEver) + D.Show = ImGui.Begin("Text Editor Demo", D.Show, G.ImGuiWindowFlags.MenuBar) + if ImGui.BeginMenuBar() then + if ImGui.BeginMenu("File") then + if ImGui.MenuItem("Save") then SavedUndoIndex = Editor:GetUndoIndex() end -- stub: nowhere to save to + ImGui.EndMenu() + end + if ImGui.BeginMenu("Edit") then + local ReadOnly = Editor:IsReadOnlyEnabled() + if ImGui.MenuItem("Read-only mode", nil, ReadOnly) then Editor:SetReadOnlyEnabled(not ReadOnly) end + ImGui.Separator() + if ImGui.MenuItem("Undo", "Ctrl-Z", nil, Editor:CanUndo()) then Editor:Undo() end + if ImGui.MenuItem("Redo", "Ctrl-Y", nil, Editor:CanRedo()) then Editor:Redo() end + ImGui.Separator() + local HasSelection = Editor:AnyCursorHasSelection() + if ImGui.MenuItem("Copy", "Ctrl-C", nil, HasSelection) then Editor:Copy() end + if ImGui.MenuItem("Cut", "Ctrl-X", nil, not ReadOnly and HasSelection) then Editor:Cut() end + if ImGui.MenuItem("Delete", "Del", nil, not ReadOnly and HasSelection) then Editor:ReplaceTextInAllCursors("") end + if ImGui.MenuItem("Paste", "Ctrl-V", nil, not ReadOnly) then Editor:Paste() end + ImGui.Separator() + if ImGui.MenuItem("Select all", "Ctrl-A") then Editor:SelectAll() end + ImGui.EndMenu() + end + if ImGui.BeginMenu("View") then + if ImGui.MenuItem("Catppuccin palette") then Editor:SetPalette(CatppuccinPalette) end + if ImGui.MenuItem("Dark palette") then Editor:SetPalette(TextEditor.GetDarkPalette()) end + if ImGui.MenuItem("Light palette") then Editor:SetPalette(TextEditor.GetLightPalette()) end + ImGui.EndMenu() + end + ImGui.EndMenuBar() + end + local Pos = Editor:GetMainCursorPosition() + ImGui.Text(string.format("%d/%d | %d lines | %s | %s | %s", + Pos.line + 1, Pos.index + 1, Editor:GetLineCount(), + Editor:IsOverwriteEnabled() and "Ovr" or "Ins", + Editor:GetUndoIndex() ~= SavedUndoIndex and "*" or " ", + Editor:GetLanguageName())) + Editor:Render("TextEditor") + ImGui.End() + end + table.insert(Demos, D) +end + +local ShowImGuiDemo = true +local function ShowExtensionsWindow() + ImGui.Begin("Extensions") + _, ShowImGuiDemo = ImGui.Checkbox("Dear ImGui Demo", ShowImGuiDemo) + local Fr = ImGui.GetIO().Framerate + ImGui.SameLine(); ImGui.TextDisabled("%.1f FPS", Fr) + ImGui.Separator() + for _, D in ipairs(Demos) do + local Changed + Changed, D.Show = ImGui.Checkbox(D.Name, D.Show or false) + if Changed and D.Show and not D.Ready then + local Ok, Err = pcall(D.Init) + D.Ready, D.Error = Ok, (not Ok) and tostring(Err) or nil + D.Show = Ok + end + if D.Error then + ImGui.SameLine() + ImGui.TextDisabled("(failed)") + if ImGui.BeginItemTooltip() then + ImGui.TextUnformatted(D.Error) + ImGui.EndTooltip() + end + end + end + ImGui.End() +end + +function love.load() + ImGui.CreateContext() + local io = ImGui.GetIO() + io.ConfigFlags = bit32.bor(io.ConfigFlags, G.ImGuiConfigFlags.NavEnableKeyboard, G.ImGuiConfigFlags.DockingEnable) + io.IniFilename = nil + G.ImGui_ImplLove.Init({ root = ROOT }) + StyleColorsCatppuccinMocha(ImGui.GetStyle()) + io.Fonts:AddFontDefault() + for _, Name in ipairs({ "Cousine-Regular", "DroidSans", "Karla-Regular", "ProggyTiny", "Roboto-Medium" }) do + io.Fonts:AddFontFromFileTTF("fonts/" .. Name .. ".ttf", 13.0) + end +end + +function love.update(dt) + G.ImGui_ImplLove.NewFrame() + ImGui.NewFrame() + ImGui.DockSpaceOverViewport(0, nil, G.ImGuiDockNodeFlags.PassthruCentralNode) + if ShowImGuiDemo then ShowImGuiDemo = ImGui.ShowDemoWindow(ShowImGuiDemo) end + ShowExtensionsWindow() + for _, D in ipairs(Demos) do + if D.Show then + -- a throwing demo would skip Render and break every later frame: unwind its stacks and turn it off + local State = G.ImGuiErrorRecoveryState() + ImGui.ErrorRecoveryStoreState(State) + local Ok, Err = pcall(D.Draw) + if not Ok then + ImGui.ErrorRecoveryTryToRecoverState(State) + D.Show, D.Error = false, tostring(Err) + print(D.Name .. " demo error: " .. D.Error) + end + end + end + ImGui.Render() +end + +function love.draw() + local c = 0x1e1e2e + love.graphics.clear(bit32.extract(c, 16, 8) / 255, bit32.extract(c, 8, 8) / 255, bit32.extract(c, 0, 8) / 255, 1) + G.ImGui_ImplLove.RenderDrawData(ImGui.GetDrawData()) +end + +function love.mousemoved(x, y) G.ImGui_ImplLove.MouseMoved(x, y) end +function love.mousepressed(x, y, b) G.ImGui_ImplLove.MousePressed(x, y, b) end +function love.mousereleased(x, y, b) G.ImGui_ImplLove.MouseReleased(x, y, b) end +function love.wheelmoved(x, y) G.ImGui_ImplLove.WheelMoved(x, y) end +function love.keypressed(k) G.ImGui_ImplLove.KeyPressed(k) end +function love.keyreleased(k) G.ImGui_ImplLove.KeyReleased(k) end +function love.textinput(t) G.ImGui_ImplLove.TextInput(t) end +function love.focus(f) G.ImGui_ImplLove.Focus(f) end diff --git a/examples/example_roblox_extensions/main.client.luau b/examples/example_roblox_extensions/main.client.luau new file mode 100644 index 0000000..90d4753 --- /dev/null +++ b/examples/example_roblox_extensions/main.client.luau @@ -0,0 +1,656 @@ + +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 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 Red, Peach, Yellow, Green, Blue, Pink = 0xf38ba8, 0xfab387, 0xf9e2af, 0xa6e3a1, 0x89b4fa, 0xf5c2e7 + +-- IM_COL32 from a 0xRRGGBB hex and 0..1 alpha +local function Col32(Value, Alpha) + return G.IM_COL32( + bit32.extract(Value, 16, 8), + bit32.extract(Value, 8, 8), + bit32.extract(Value, 0, 8), + math.floor((Alpha or 1.0) * 255 + 0.5) + ) +end + +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 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() +ImGui_ImplRoblox.SetTextProxy(true) -- OS copy/paste for ImGuiColorTextEdit +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 + +-- Extension demos (code from extensions/*/examples/roblox). Each is required/initialized on first enable. +local RS = ReplicatedStorage +local ImVec2 = G.ImVec2 +local _ + +local Demos = {} + +-- imgui_memory_editor +do + local D = { Name = "Memory Editor" } + local Data, MemEdit, MemEdit2, Frame = nil, nil, nil, 0 + function D.Init() + local MemoryEditor = require(RS:WaitForChild("MemoryEditor"))(G) + Data = buffer.create(0x400) + buffer.writef32(Data, 0x10, math.pi) + buffer.writestring(Data, 0x20, "Hello from a Roblox buffer!") + for i = 0x40, 0x3FF do buffer.writeu8(Data, i, (i * 37) % 256) end + MemEdit = MemoryEditor.new() + MemEdit.OptShowDataPreview = true + MemEdit2 = MemoryEditor.new() + MemEdit2.HighlightFn = function(mem, off) return buffer.readu8(mem, off) % 2 == 0 end + end + function D.Draw() + Frame += 1 + buffer.writeu32(Data, 0x00, Frame) + MemEdit:DrawWindow("Memory Editor", Data) + local Open, Visible = ImGui.Begin("Memory Editor (DrawContents)", D.Show) + D.Show = Open + if Visible then + ImGui.Text("frame = %d (the u32 at 0x00)", Frame) + MemEdit2:DrawContents(Data, 0x80, 0x1000) + end + ImGui.End() + end + table.insert(Demos, D) +end + +-- ImGuizmo +do + local D = { Name = "ImGuizmo" } + local ImGuizmo, OP, MODE, Roblox, Part + local Operation, Mode + local UseSnap, ShowGrid = false, false + local Snap = { 1, 1, 1 } + local AngleSnap, ScaleSnap = 15, 0.1 + local BoundSizing, BoundSizingSnap = false, false + local Bounds = { -0.5, -0.5, -0.5, 0.5, 0.5, 0.5 } + local BoundsSnap = { 0.1, 0.1, 0.1 } + local Identity = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } + local Camera = workspace.CurrentCamera + + function D.Init() + ImGuizmo = require(RS:WaitForChild("ImGuizmo"))(G) + OP, MODE, Roblox = ImGuizmo.OPERATION, ImGuizmo.MODE, ImGuizmo.Roblox + Operation, Mode = OP.TRANSLATE, MODE.WORLD + Part = workspace:FindFirstChild("GizmoPart") + if not Part then + Part = Instance.new("Part") + Part.Name = "GizmoPart" + Part.Anchored = true + Part.Size = Vector3.new(4, 4, 4) + Part.CFrame = CFrame.new(0, 5, 0) + Part.Parent = workspace + end + end + + local function EditTransform(Matrix) + local ImGuiKey = G.ImGuiKey + if ImGui.IsKeyPressed(ImGuiKey.T) then Operation = OP.TRANSLATE end + if ImGui.IsKeyPressed(ImGuiKey.E) then Operation = OP.ROTATE end + if ImGui.IsKeyPressed(ImGuiKey.R) then Operation = OP.SCALE end + _, Operation = ImGui.RadioButton("Translate", Operation, OP.TRANSLATE) + ImGui.SameLine() + _, Operation = ImGui.RadioButton("Rotate", Operation, OP.ROTATE) + ImGui.SameLine() + _, Operation = ImGui.RadioButton("Scale", Operation, OP.SCALE) + ImGui.SameLine() + _, Operation = ImGui.RadioButton("Universal", Operation, OP.UNIVERSAL) + + local Tr, Rt, Sc = {}, {}, {} + ImGuizmo.DecomposeMatrixToComponents(Matrix, Tr, Rt, Sc) + local Edited = ImGui.DragFloat3("Tr", Tr, 0.1) + Edited = ImGui.DragFloat3("Rt", Rt, 1) or Edited + Edited = ImGui.DragFloat3("Sc", Sc, 0.01) or Edited + if Edited then ImGuizmo.RecomposeMatrixFromComponents(Tr, Rt, Sc, Matrix) end + + if Operation ~= OP.SCALE then + _, Mode = ImGui.RadioButton("Local", Mode, MODE.LOCAL) + ImGui.SameLine() + _, Mode = ImGui.RadioButton("World", Mode, MODE.WORLD) + end + + _, UseSnap = ImGui.Checkbox("Snap", UseSnap) + ImGui.SameLine() + if Operation == OP.ROTATE then + AngleSnap = ImGui.DragFloat("Angle Snap", AngleSnap, 1) + elseif Operation == OP.SCALE then + ScaleSnap = ImGui.DragFloat("Scale Snap", ScaleSnap, 0.01) + else + ImGui.DragFloat3("Snap Value", Snap, 0.1) + end + + if Operation == OP.SCALE then + _, BoundSizing = ImGui.Checkbox("Bound Sizing", BoundSizing) + end + if Operation == OP.SCALE and BoundSizing then + ImGui.PushID(3) + _, BoundSizingSnap = ImGui.Checkbox("Bound Snap", BoundSizingSnap) + ImGui.SameLine() + ImGui.DragFloat3("Snap", BoundsSnap, 0.01) + ImGui.PopID() + end + _, ShowGrid = ImGui.Checkbox("Show Grid", ShowGrid) + + local SnapArg = nil + if UseSnap then + if Operation == OP.ROTATE then + SnapArg = { AngleSnap, AngleSnap, AngleSnap } + elseif Operation == OP.SCALE then + SnapArg = { ScaleSnap, ScaleSnap, ScaleSnap } + else + SnapArg = Snap + end + end + return Edited, SnapArg + end + + function D.Draw() + ImGuizmo.BeginFrame() + local Viewport = Camera.ViewportSize + ImGuizmo.SetDrawlist(ImGui.GetForegroundDrawList()) + ImGuizmo.SetRect(0, 0, Viewport.X, Viewport.Y) + + local View = Roblox.ViewFromCamera(Camera) + local Proj = Roblox.ProjFromCamera(Camera) + + -- Part.Size is baked into the basis so SCALE / bounds edit it + local Matrix = Roblox.MatrixFromCFrame(Part.CFrame) + local Size = Part.Size + for I = 1, 3 do + Matrix[I] *= Size.X + Matrix[4 + I] *= Size.Y + Matrix[8 + I] *= Size.Z + end + + D.Show = ImGui.Begin("ImGuizmo", D.Show) + local Edited, SnapArg = EditTransform(Matrix) + ImGui.End() + + if ShowGrid then ImGuizmo.DrawGrid(View, Proj, Identity, 10) end + -- Bound Sizing replaces the scale gizmo (BOUNDS draws only the bounds box) + local UseBounds = BoundSizing and Operation == OP.SCALE + local Moved = ImGuizmo.Manipulate(View, Proj, UseBounds and OP.BOUNDS or Operation, Mode, Matrix, nil, SnapArg, + UseBounds and Bounds or nil, UseBounds and BoundSizingSnap and BoundsSnap or nil) + if Edited or Moved then + local NewCFrame, NewSize = Roblox.CFrameFromMatrix(Matrix) + Part.CFrame = NewCFrame + Part.Size = NewSize + end + + -- ViewManipulate edits View in place; the camera is its inverse + ImGuizmo.ViewManipulate(View, 10, ImVec2(Viewport.X - 128, 0), ImVec2(128, 128), 0x10101010) + if ImGuizmo.IsUsingViewManipulate() then + Camera.CameraType = Enum.CameraType.Scriptable + Camera.CFrame = Roblox.CFrameFromMatrix(View):Inverse() + end + end + table.insert(Demos, D) +end + +-- ImNodes (Logic Simulator) +do + local D = { Name = "ImNodes" } + local UI + function D.Init() + local ImNodes = require(RS:WaitForChild("ImNodes"))(G) + local Logic = RS:WaitForChild("Logic") + local LogicSim = require(Logic:WaitForChild("Simulation"))(G, ImNodes) + UI = require(Logic:WaitForChild("UI"))(G, ImNodes, LogicSim) + + ImNodes.CreateContext() + ImNodes.PushAttributeFlag(ImNodes.ImNodesAttributeFlags.EnableLinkDetachWithDragClick) + local NodesIO = ImNodes.GetIO() + local KeyCtrl = function() + return ImGui.GetIO().KeyCtrl + end + NodesIO.LinkDetachWithModifierClick.Modifier = KeyCtrl + NodesIO.MultipleSelectModifier.Modifier = KeyCtrl + local NodesStyle = ImNodes.GetStyle() + NodesStyle.Flags = bit32.bor(NodesStyle.Flags, ImNodes.ImNodesStyleFlags.GridLinesPrimary) + + -- catppuccin mocha + local Col, C = ImNodes.ImNodesCol, NodesStyle.Colors + C[Col.NodeBackground] = Col32(Surface0) + C[Col.NodeBackgroundHovered] = Col32(Surface1) + C[Col.NodeBackgroundSelected] = Col32(Surface1) + C[Col.NodeOutline] = Col32(Surface2) + C[Col.TitleBar] = Col32(Mantle) + C[Col.TitleBarHovered] = Col32(Surface1) + C[Col.TitleBarSelected] = Col32(Mauve, 0.6) + C[Col.Link] = Col32(Mauve, 0.8) + C[Col.LinkHovered] = Col32(Lavender) + C[Col.LinkSelected] = Col32(Lavender) + C[Col.Pin] = Col32(Mauve, 0.7) + C[Col.PinHovered] = Col32(Lavender) + C[Col.BoxSelector] = Col32(Mauve, 0.12) + C[Col.BoxSelectorOutline] = Col32(Mauve, 0.6) + C[Col.GridBackground] = Col32(Crust) + C[Col.GridLine] = Col32(Surface0, 0.6) + C[Col.GridLinePrimary] = Col32(Surface1, 0.8) + C[Col.MiniMapBackground] = Col32(Mantle, 0.6) + C[Col.MiniMapBackgroundHovered] = Col32(Mantle, 0.8) + C[Col.MiniMapOutline] = Col32(Surface1, 0.6) + C[Col.MiniMapOutlineHovered] = Col32(Surface2) + C[Col.MiniMapNodeBackground] = Col32(Surface1, 0.6) + C[Col.MiniMapNodeBackgroundHovered] = Col32(Surface2) + C[Col.MiniMapNodeBackgroundSelected] = Col32(Mauve, 0.6) + C[Col.MiniMapNodeOutline] = Col32(Overlay0, 0.6) + C[Col.MiniMapLink] = C[Col.Link] + C[Col.MiniMapLinkSelected] = C[Col.LinkSelected] + C[Col.MiniMapCanvas] = Col32(Text, 0.1) + C[Col.MiniMapCanvasOutline] = Col32(Text, 0.6) + end + function D.Draw() + UI.Draw() + end + table.insert(Demos, D) +end + +-- ImPlot +do + local D = { Name = "ImPlot" } + local ImPlot + function D.Init() + local Module = RS:WaitForChild("ImPlot") + ImPlot = require(Module)(G) + require(Module:WaitForChild("ImPlotDemo"))(G, ImPlot) + ImPlot.CreateContext() + end + function D.Draw() + ImPlot.ShowDemoWindow() + end + table.insert(Demos, D) +end + +-- ImPlot3D +do + local D = { Name = "ImPlot3D" } + local ImPlot3D + function D.Init() + local Module = RS:WaitForChild("ImPlot3D") + ImPlot3D = require(Module)(G) + require(Module:WaitForChild("ImPlot3DDemo"))(G, ImPlot3D) + ImPlot3D.CreateContext() + end + function D.Draw() + ImPlot3D.ShowDemoWindow() + end + table.insert(Demos, D) +end + +-- ImGuiColorTextEdit +do + local D = { Name = "ImGuiColorTextEdit" } + local Editor, SavedUndoIndex + local SampleCode = [==[ +-- Sample Lua code +local Players = game:GetService("Players") + +local function Greet(name: string): string + return "Hello, " .. name .. "!" +end + +for i = 1, 10 do + if i % 2 == 0 then + print(Greet("Player" .. i), 3.14 * i, 0xFF) + end +end + +--[[ block + comment ]] +local t = { a = 1, b = "two", [3] = true, nil } +]==] + local TextEditor + -- catppuccin mocha, in TextEditor.Color order + local CatppuccinPalette = { + Col32(Text), -- text + Col32(Mauve), -- keyword + Col32(Yellow), -- declaration + Col32(Peach), -- number + Col32(Green), -- string + Col32(Overlay2), -- punctuation + Col32(Pink), -- preprocessor + Col32(Text), -- identifier + Col32(Blue), -- known identifier + Col32(Overlay0), -- comment + Col32(Base), -- background + Col32(Text), -- cursor + Col32(Surface2), -- selection + Col32(Surface1), -- whitespace + Col32(Surface0), -- matchingBracketBackground + Col32(Overlay0), -- matchingBracketActive + Col32(Yellow), -- matchingBracketLevel1 + Col32(Blue), -- matchingBracketLevel2 + Col32(Mauve), -- matchingBracketLevel3 + Col32(Red), -- matchingBracketError + Col32(Overlay0), -- line number + Col32(Lavender), -- current line number + Col32(Text, 0.03), -- current line highlight + Col32(Text, 0.06), -- current line highlight border + } + function D.Init() + TextEditor = require(RS:WaitForChild("TextEditor"))(G) + Editor = TextEditor.new() + Editor:SetPalette(CatppuccinPalette) + Editor:SetLanguage(TextEditor.Language.Lua()) + Editor:SetText(SampleCode) + SavedUndoIndex = Editor:GetUndoIndex() + end + function D.Draw() + ImGui.SetNextWindowSize(ImVec2(800, 600), G.ImGuiCond.FirstUseEver) + D.Show = ImGui.Begin("Text Editor Demo", D.Show, G.ImGuiWindowFlags.MenuBar) + if ImGui.BeginMenuBar() then + if ImGui.BeginMenu("File") then + if ImGui.MenuItem("Save") then + SavedUndoIndex = Editor:GetUndoIndex() -- stub: nowhere to save to + end + ImGui.EndMenu() + end + if ImGui.BeginMenu("Edit") then + local ReadOnly = Editor:IsReadOnlyEnabled() + if ImGui.MenuItem("Read-only mode", nil, ReadOnly) then + Editor:SetReadOnlyEnabled(not ReadOnly) + end + ImGui.Separator() + if ImGui.MenuItem("Undo", "Ctrl-Z", nil, Editor:CanUndo()) then Editor:Undo() end + if ImGui.MenuItem("Redo", "Ctrl-Y", nil, Editor:CanRedo()) then Editor:Redo() end + ImGui.Separator() + local HasSelection = Editor:AnyCursorHasSelection() + if ImGui.MenuItem("Copy", "Ctrl-C", nil, HasSelection) then Editor:Copy() end + if ImGui.MenuItem("Cut", "Ctrl-X", nil, not ReadOnly and HasSelection) then Editor:Cut() end + if ImGui.MenuItem("Delete", "Del", nil, not ReadOnly and HasSelection) then + Editor:ReplaceTextInAllCursors("") + end + if ImGui.MenuItem("Paste", "Ctrl-V", nil, not ReadOnly) then Editor:Paste() end + ImGui.Separator() + if ImGui.MenuItem("Select all", "Ctrl-A") then Editor:SelectAll() end + ImGui.EndMenu() + end + if ImGui.BeginMenu("View") then + if ImGui.MenuItem("Catppuccin palette") then Editor:SetPalette(CatppuccinPalette) end + if ImGui.MenuItem("Dark palette") then Editor:SetPalette(TextEditor.GetDarkPalette()) end + if ImGui.MenuItem("Light palette") then Editor:SetPalette(TextEditor.GetLightPalette()) end + ImGui.EndMenu() + end + ImGui.EndMenuBar() + end + local Pos = Editor:GetMainCursorPosition() + ImGui.Text(string.format("%d/%d | %d lines | %s | %s | %s", + Pos.line + 1, Pos.index + 1, Editor:GetLineCount(), + Editor:IsOverwriteEnabled() and "Ovr" or "Ins", + Editor:GetUndoIndex() ~= SavedUndoIndex and "*" or " ", + Editor:GetLanguageName())) + Editor:Render("TextEditor") + ImGui.End() + end + table.insert(Demos, D) +end + +local ShowImGuiDemo = true +local function ShowExtensionsWindow() + ImGui.Begin("Extensions") + _, ShowImGuiDemo = ImGui.Checkbox("Dear ImGui Demo", ShowImGuiDemo) + ImGui.Separator() + for _, D in Demos do + local Changed + Changed, D.Show = ImGui.Checkbox(D.Name, D.Show or false) + if Changed and D.Show and not D.Ready then + local Ok, Err = pcall(D.Init) + D.Ready, D.Error = Ok, not Ok and tostring(Err) or nil + D.Show = Ok + end + if D.Error then + ImGui.SameLine() + ImGui.TextDisabled("(failed)") + if ImGui.BeginItemTooltip() then + ImGui.TextUnformatted(D.Error) + ImGui.EndTooltip() + end + 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) + if ShowImGuiDemo then + ImGui.ShowDemoWindow() + end + ShowParallelWindow() + ShowExtensionsWindow() + for _, D in Demos do + if D.Show then + -- a throwing demo would skip Render and break every later frame: unwind its Begin/Push stacks and turn it off + local State = G.ImGuiErrorRecoveryState() + ImGui.ErrorRecoveryStoreState(State) + local Ok, Err = pcall(D.Draw) + if not Ok then + ImGui.ErrorRecoveryTryToRecoverState(State) + D.Show, D.Error = false, tostring(Err) + warn(D.Name .. " demo error: " .. D.Error) + end + end + end + ImGui.Render() + ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData()) +end) + +script.Destroying:Connect(function() + ImGui_ImplRoblox.DisableParallel() + ImGui_ImplRoblox.Shutdown() + ImGui.DestroyContext() +end) diff --git a/extensions/imcurveedit-luau b/extensions/imcurveedit-luau new file mode 160000 index 0000000..9769fd0 --- /dev/null +++ b/extensions/imcurveedit-luau @@ -0,0 +1 @@ +Subproject commit 9769fd0839eee0ca77f9cfa445ff6a5de1c3b14f diff --git a/extensions/imgradient-luau b/extensions/imgradient-luau new file mode 160000 index 0000000..21b3b2d --- /dev/null +++ b/extensions/imgradient-luau @@ -0,0 +1 @@ +Subproject commit 21b3b2d287058b6b980acffa68689294c5b6480c diff --git a/extensions/imgui-memory-editor-luau b/extensions/imgui-memory-editor-luau new file mode 160000 index 0000000..3c9aca1 --- /dev/null +++ b/extensions/imgui-memory-editor-luau @@ -0,0 +1 @@ +Subproject commit 3c9aca1a4399b7f5886b4bb11eb80cec859d211c diff --git a/extensions/imguicolortextedit-luau b/extensions/imguicolortextedit-luau index 79c95c7..9b8f965 160000 --- a/extensions/imguicolortextedit-luau +++ b/extensions/imguicolortextedit-luau @@ -1 +1 @@ -Subproject commit 79c95c7ca41ad00f7d131b90faa2c46e2ba7ff28 +Subproject commit 9b8f9659f21751fdb324f3c41876beaea6f7cb9d diff --git a/extensions/imguizmo-luau b/extensions/imguizmo-luau index 7bef75e..ab98d60 160000 --- a/extensions/imguizmo-luau +++ b/extensions/imguizmo-luau @@ -1 +1 @@ -Subproject commit 7bef75e7cae8570f0a02b0f2b6eeb69a372133fa +Subproject commit ab98d60345a90def8a4737adde69e18df7fb2e1d diff --git a/extensions/imnodes-luau b/extensions/imnodes-luau index b882d3b..363fd65 160000 --- a/extensions/imnodes-luau +++ b/extensions/imnodes-luau @@ -1 +1 @@ -Subproject commit b882d3b1efcc18b58ce01a8b078c33c39633ef4a +Subproject commit 363fd65d98fab5254e04e888f4b32aab174b9440 diff --git a/extensions/implot-luau b/extensions/implot-luau index 4e8c21f..7fa48b0 160000 --- a/extensions/implot-luau +++ b/extensions/implot-luau @@ -1 +1 @@ -Subproject commit 4e8c21fdf8acf7108fcbf959d69a2a039bd56562 +Subproject commit 7fa48b066bb5dad5b1ca53aa38c5917dc2b25a50 diff --git a/extensions/implot3d-luau b/extensions/implot3d-luau index 8863490..41c709c 160000 --- a/extensions/implot3d-luau +++ b/extensions/implot3d-luau @@ -1 +1 @@ -Subproject commit 8863490ea7e8d5bf885a78197a435fb7ffd4a68b +Subproject commit 41c709c872af2f23706be9f77ae29a23a075d05a diff --git a/extensions/imsequencer-luau b/extensions/imsequencer-luau new file mode 160000 index 0000000..a911077 --- /dev/null +++ b/extensions/imsequencer-luau @@ -0,0 +1 @@ +Subproject commit a9110772e79f90dafd6f1aaa287d91253c4ffce6 diff --git a/imgui.lua b/imgui.lua index 37fca78..260c171 100644 --- a/imgui.lua +++ b/imgui.lua @@ -4872,26 +4872,33 @@ local ImGuiResizeBorderDef = { --- @param thickness float --- @return ImRect --- @nodiscard -local function GetResizeBorderRect(window, border_n, perp_padding, thickness) - local rect = window:Rect() +-- [Luau] out: optional ImRect written in place (no allocation) +local function GetResizeBorderRect(window, border_n, perp_padding, thickness, out) + local x0, y0 = window.Pos.x, window.Pos.y + local x1, y1 = x0 + window.Size.x, y0 + window.Size.y if thickness == 0.0 then - ImVec2_CopyV(rect.Max, rect.Max.x - 1, rect.Max.y - 1) + x1, y1 = x1 - 1, y1 - 1 end + local a, b, c, d if border_n == ImGuiDir.Left then - return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding) + a, b, c, d = x0 - thickness, y0 + perp_padding, x0 + thickness, y1 - perp_padding + elseif border_n == ImGuiDir.Right then + a, b, c, d = x1 - thickness, y0 + perp_padding, x1 + thickness, y1 - perp_padding + elseif border_n == ImGuiDir.Up then + a, b, c, d = x0 + perp_padding, y0 - thickness, x1 - perp_padding, y0 + thickness + elseif border_n == ImGuiDir.Down then + a, b, c, d = x0 + perp_padding, y1 - thickness, x1 - perp_padding, y1 + thickness + else + IM_ASSERT(false) + a, b, c, d = 0, 0, 0, 0 end - if border_n == ImGuiDir.Right then - return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding) + if out then + out.Min.x, out.Min.y, out.Max.x, out.Max.y = a, b, c, d + return out end - if border_n == ImGuiDir.Up then - return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness) - end - if border_n == ImGuiDir.Down then - return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness) - end - IM_ASSERT(false) - return ImRect() + return ImRect(a, b, c, d) end +local UpdateWindowManualResize_rect = ImRect() -- [Luau] scratch grip/border rect: ItemAdd() copies, ButtonBehavior() reads -- Known size hash -- It is ok to call ImHashData on a string with known length but the ### operator won't be supported. @@ -10173,10 +10180,12 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c local corner_pos = def.CornerPosN local inner_dir = def.InnerDir - local corner = ImVec2(window.Pos.x + corner_pos.x * window.Size.x, window.Pos.y + corner_pos.y * window.Size.y) + local corner_x, corner_y = window.Pos.x + corner_pos.x * window.Size.x, window.Pos.y + corner_pos.y * window.Size.y -- Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window - local resize_rect = ImRect(corner - inner_dir * grip_hover_outer_size, corner + inner_dir * grip_hover_inner_size) + local resize_rect = UpdateWindowManualResize_rect -- [Luau] scratch, scalar math + resize_rect.Min.x, resize_rect.Min.y = corner_x - inner_dir.x * grip_hover_outer_size, corner_y - inner_dir.y * grip_hover_outer_size + resize_rect.Max.x, resize_rect.Max.y = corner_x + inner_dir.x * grip_hover_inner_size, corner_y + inner_dir.y * grip_hover_inner_size if resize_rect.Min.x > resize_rect.Max.x then resize_rect.Min.x, resize_rect.Max.x = resize_rect.Max.x, resize_rect.Min.x end if resize_rect.Min.y > resize_rect.Max.y then resize_rect.Min.y, resize_rect.Max.y = resize_rect.Max.y, resize_rect.Min.y end @@ -10249,7 +10258,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c axis = ImGuiAxis.Y end - local border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding) + local border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding, UpdateWindowManualResize_rect) local border_id = window:GetID(border_n + 4) -- == GetWindowResizeBorderID() ImGui.ItemAdd(border_rect, border_id, nil, ImGuiItemFlags.NoNav) local _, hovered, held = ImGui.ButtonBehavior(border_rect, border_id, bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.NoNavFocus)) @@ -10278,7 +10287,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c -- FIXME: May want to generalize this idiom at lower-level, so more widgets can use it! local just_scrolled_manually_while_resizing = (g.WheelingWindow ~= nil and g.WheelingWindowScrolledFrame == g.FrameCount and ImGui.IsWindowChildOf(window, g.WheelingWindow, false, true)) if g.ActiveIdIsJustActivated or just_scrolled_manually_while_resizing then - g.WindowResizeBorderExpectedRect = border_rect + g.WindowResizeBorderExpectedRect = ImRect(border_rect.Min, border_rect.Max) -- [Luau] copy: border_rect is scratch g.WindowResizeRelativeMode = false end @@ -10486,18 +10495,23 @@ function ImGui.RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_begin local pos = RenderTextClippedEx_pos pos.x = pos_min.x; pos.y = pos_min.y - local text_size = text_size_if_known or ImGui.CalcTextSize(text, text_display_end, false, 0.0) + local text_size_x, text_size_y -- [Luau] scalar text_size + if text_size_if_known then + text_size_x, text_size_y = text_size_if_known.x, text_size_if_known.y + else + text_size_x, text_size_y = ImGui.CalcTextSizeXY(text, 1, text_display_end, false, 0.0) + end local clip_min = clip_rect and clip_rect.Min or pos_min local clip_max = clip_rect and clip_rect.Max or pos_max - local need_clipping = (pos.x + text_size.x >= clip_max.x) or (pos.y + text_size.y >= clip_max.y) + local need_clipping = (pos.x + text_size_x >= clip_max.x) or (pos.y + text_size_y >= clip_max.y) if (clip_rect) then -- If we had no explicit clipping rectangle then pos==clip_min need_clipping = need_clipping or ((pos.x < clip_min.x) or (pos.y < clip_min.y)) end -- Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. - if (align.x > 0.0) then pos.x = math.max(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x) end - if (align.y > 0.0) then pos.y = math.max(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y) end + if (align.x > 0.0) then pos.x = math.max(pos.x, pos.x + (pos_max.x - pos.x - text_size_x) * align.x) end + if (align.y > 0.0) then pos.y = math.max(pos.y, pos.y + (pos_max.y - pos.y - text_size_y) * align.y) end -- Render if (need_clipping) then @@ -10816,6 +10830,9 @@ end --- @param handle_borders_and_resize_grips bool --- @param resize_grip_col ImU32[] --- @param resize_grip_draw_size float +-- [Luau] scratch for RenderWindowDecorations()/RenderWindowTitleBarContents(): callees only read or copy these +local WindowDecoScratch = { text_size = ImVec2(), layout_r = ImRect(), clip_r = ImRect(), bg_rect = ImRect(), p = ImVec2(), title_bar_rect = ImRect() } + local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_col, resize_grip_draw_size) local g = GImGui local style = g.Style @@ -10856,7 +10873,8 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high if bit32.band(flags, ImGuiWindowFlags.DockNodeHost) ~= 0 then bg_col = 0 end if bit32.band(bg_col, IM_COL32_A_MASK) ~= 0 then - local bg_rect = ImRect(window.Pos + ImVec2(0, window.TitleBarHeight), window.Pos + window.Size) + local bg_rect = WindowDecoScratch.bg_rect -- [Luau] scalar, no temporaries + bg_rect.Min.x, bg_rect.Min.y, bg_rect.Max.x, bg_rect.Max.y = window.Pos.x + 0, window.Pos.y + window.TitleBarHeight, window.Pos.x + window.Size.x, window.Pos.y + window.Size.y local bg_rounding_flags if window.DockIsActive then bg_rounding_flags = ImGui.CalcRoundingFlagsForRectInRect(bg_rect, window.DockNode.HostWindow:Rect(), 0.0) @@ -10928,11 +10946,20 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high end local grip = ImGuiResizeGripDef[resize_grip_n] - local corner = ImLerp(window.Pos, window.Pos + window.Size, grip.CornerPosN) + -- [Luau] scalar corner/points, one scratch ImVec2 (the path copies points) + local pos, cpn, dir = window.Pos, grip.CornerPosN, grip.InnerDir + local corner_x = pos.x + ((pos.x + window.Size.x) - pos.x) * cpn.x + local corner_y = pos.y + ((pos.y + window.Size.y) - pos.y) * cpn.y local border_inner = IM_ROUND(window_border_size * 0.5) - window.DrawList:PathLineTo(corner + grip.InnerDir * ((resize_grip_n % 2 == 0) and ImVec2(border_inner, resize_grip_draw_size) or ImVec2(resize_grip_draw_size, border_inner))) - window.DrawList:PathLineTo(corner + grip.InnerDir * ((resize_grip_n % 2 == 0) and ImVec2(resize_grip_draw_size, border_inner) or ImVec2(border_inner, resize_grip_draw_size))) - window.DrawList:PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + border_inner), corner.y + grip.InnerDir.y * (window_rounding + border_inner)), window_rounding, grip.AngleMin12, grip.AngleMax12) + local a, b = border_inner, resize_grip_draw_size + if resize_grip_n % 2 ~= 0 then a, b = b, a end + local p = WindowDecoScratch.p + p.x, p.y = corner_x + dir.x * a, corner_y + dir.y * b + window.DrawList:PathLineTo(p) + p.x, p.y = corner_x + dir.x * b, corner_y + dir.y * a + window.DrawList:PathLineTo(p) + p.x, p.y = corner_x + dir.x * (window_rounding + border_inner), corner_y + dir.y * (window_rounding + border_inner) + window.DrawList:PathArcToFast(p, window_rounding, grip.AngleMin12, grip.AngleMax12) window.DrawList:PathFillConvex(col) until true @@ -10949,6 +10976,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high end ImGui.RenderWindowOuterBorders = RenderWindowOuterBorders + -- When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead. -- Render title text, collapse button, close button -- [Port] Returns the updated 'open' value (nil when there is no close button) @@ -11014,7 +11042,9 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) -- Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) -- FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. local marker_size_x = (bit32.band(flags, ImGuiWindowFlags.UnsavedDocument) ~= 0) and (button_sz * 0.80) or 0.0 - local text_size = ImGui.CalcTextSize(name, nil, true) + ImVec2(marker_size_x, 0.0) + local text_size = WindowDecoScratch.text_size -- [Luau] scratch: only read below (RenderTextClipped text_size_if_known) + local text_size_x, text_size_y = ImGui.CalcTextSizeXY(name, 1, nil, true) + text_size.x = text_size_x + marker_size_x; text_size.y = text_size_y + 0.0 -- As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button, -- while uncentered title text will still reach edges correctly. @@ -11031,8 +11061,9 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) pad_r = ImMax(pad_r, pad_extend * centerness) end - local layout_r = ImRect(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y) - local clip_r = ImRect(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y) + local layout_r, clip_r = WindowDecoScratch.layout_r, WindowDecoScratch.clip_r -- [Luau] scratch, only read by callees + layout_r.Min.x, layout_r.Min.y, layout_r.Max.x, layout_r.Max.y = title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y + clip_r.Min.x, clip_r.Min.y, clip_r.Max.x, clip_r.Max.y = layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y if bit32.band(flags, ImGuiWindowFlags.UnsavedDocument) ~= 0 then local marker_pos = ImVec2() @@ -12169,13 +12200,17 @@ function ImGui.Begin(name, open, flags) -- Add to stack g.CurrentWindow = window g.CurrentWindowStack:resize(g.CurrentWindowStack.Size + 1) - g.CurrentWindowStack.Data[g.CurrentWindowStack.Size] = ImGuiWindowStackData() + -- [Luau] reuse the slot's table left by pop_back() (C++ reuses the vector storage); every field is set below local window_stack_data = g.CurrentWindowStack.Data[g.CurrentWindowStack.Size] + if type(window_stack_data) ~= "table" or window_stack_data.ParentLastItemDataBackup == nil then + window_stack_data = ImGuiWindowStackData() + g.CurrentWindowStack.Data[g.CurrentWindowStack.Size] = window_stack_data + end window_stack_data.Window = window ImGuiLastItemData_Copy(window_stack_data.ParentLastItemDataBackup, g.LastItemData) window_stack_data.DisabledOverrideReenable = (bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0) and (bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0) window_stack_data.DisabledOverrideReenableAlphaBackup = 0.0 - window_stack_data.StackSizesInBegin = ImGuiErrorRecoveryState() + window_stack_data.StackSizesInBegin = window_stack_data.StackSizesInBegin or ImGuiErrorRecoveryState() -- [Luau] reused, all fields stored ImGui.ErrorRecoveryStoreState(window_stack_data.StackSizesInBegin) g.StackSizesInBeginForCurrentWindow = window_stack_data.StackSizesInBegin if bit32.band(flags, ImGuiWindowFlags.ChildMenu) ~= 0 then @@ -12956,7 +12991,9 @@ function ImGui.Begin(name, open, flags) -- Title bar if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and not window.DockIsActive then - open = RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window.WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window.WindowBorderSize, title_bar_rect.Max.y), name, open) + local r = WindowDecoScratch.title_bar_rect -- [Luau] scratch, only read + r.Min.x, r.Min.y, r.Max.x, r.Max.y = title_bar_rect.Min.x + window.WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window.WindowBorderSize, title_bar_rect.Max.y + open = RenderWindowTitleBarContents(window, r, name, open) elseif bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and window.DockIsActive then ImGui.LogText("%s\n", string.sub(window.Name, 1, ImGui.FindRenderedTextEnd(window.Name) - 1)) end @@ -14660,10 +14697,10 @@ end --- @param hide_text_after_double_hash? bool --- @param wrap_width? float --- @return ImVec2 +-- [Luau] scalar CalcTextSizeEx(): returns x, y without allocating an ImVec2 (hot widget paths) @native -function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double_hash, wrap_width) - if hide_text_after_double_hash == nil then hide_text_after_double_hash = false end - if wrap_width == nil then wrap_width = -1.0 end +function ImGui.CalcTextSizeXY(text, text_begin, text_end, hide_text_after_double_hash, wrap_width) + if wrap_width == nil then wrap_width = -1.0 end local g = GImGui @@ -14674,19 +14711,22 @@ function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double text_display_end = text_end end - local font = g.Font local font_size = g.FontSize if text == "" or (text_end and text_end <= text_begin) then - return ImVec2(0.0, font_size) + return 0.0, font_size end - local text_size = ImFontCalcTextSizeEx(font, font_size, FLT_MAX, wrap_width, text, text_begin, text_display_end, text_display_end, nil, ImDrawTextFlags.None) -- [Luau] inline font:CalcTextSizeA() + local x, y = ImFontCalcTextSizeXY(g.Font, font_size, FLT_MAX, wrap_width, text, text_begin, text_display_end, text_display_end, nil, ImDrawTextFlags.None) -- [Luau] inline font:CalcTextSizeA() -- Round -- (see 7b0bf230, 4622fa4b6, #791 for details about this.) -- FIXME: Add a way to disable this. - text_size.x = math.ceil(text_size.x) -- [Luau] == ImCeilFast() for all finite values, builtin + return math.ceil(x), y -- [Luau] == ImCeilFast() for all finite values, builtin +end - return text_size +@native +function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double_hash, wrap_width) + local x, y = ImGui.CalcTextSizeXY(text, text_begin, text_end, hide_text_after_double_hash, wrap_width) + return ImVec2(x, y) end -- Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() diff --git a/imgui_draw.lua b/imgui_draw.lua index a7c0176..174fe27 100644 --- a/imgui_draw.lua +++ b/imgui_draw.lua @@ -49,6 +49,7 @@ end --- @param buf char[] # 1-based --- @param base int # 1-based start index --- @param u32 ImU32 +@native local function write_u32(buf, base, u32) buf[base + 0] = bit32.band(u32, 0xFF) buf[base + 1] = bit32.band(bit32.rshift(u32, 8), 0xFF) @@ -778,6 +779,7 @@ end --- @param dst_pitch int --- @param w int --- @param h int +@native function ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst_pixels, dst_pixels_base, dst_fmt, dst_pitch, w, h) IM_ASSERT(src_pixels ~= nil and dst_pixels ~= nil) local src_pixels_base = 1 @@ -795,7 +797,8 @@ function ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst_pixe local alpha = src_pixels[src_pixels_base + 0] src_pixels_base = src_pixels_base + 1 - write_u32(dst_pixels, dst_pixels_base, IM_COL32(255, 255, 255, alpha)) + -- [Luau] inline write_u32(dst_pixels, dst_pixels_base, IM_COL32(255, 255, 255, alpha)) + dst_pixels[dst_pixels_base] = 255; dst_pixels[dst_pixels_base + 1] = 255; dst_pixels[dst_pixels_base + 2] = 255; dst_pixels[dst_pixels_base + 3] = alpha dst_pixels_base = dst_pixels_base + 4 end @@ -2701,8 +2704,13 @@ function MT.ImTextureData:Create(format, w, h) self.Height = h self.BytesPerPixel = ImTextureDataGetFormatBytesPerPixel(format) self.UseColors = false - self.Pixels = {} - ImStd.memset(self.Pixels, 0, self.Width * self.Height * self.BytesPerPixel) + local n = self.Width * self.Height * self.BytesPerPixel + if table.create then + self.Pixels = table.create(n, 0) -- [Luau] native zero fill, same contents as memset + else + self.Pixels = {} + ImStd.memset(self.Pixels, 0, n) + end self.UsedRect.x = 0 self.UsedRect.y = 0 self.UsedRect.w = 0 @@ -3466,7 +3474,8 @@ end local TEXT_SIZE_CACHE_MAX = 4096 @native -function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags) +-- [Luau] scalar core of ImFontCalcTextSizeEx(): returns size.x, size.y, remaining (no ImVec2 allocated) +function ImFontCalcTextSizeXY(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. @@ -3483,7 +3492,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end local e = cache[text] if e then - return ImVec2(e[1] * (size / baked.Size), e[2] * size), text_len1 + return e[1] * (size / baked.Size), e[2] * size, text_len1 end cache_key = text elseif cacheable and wrap_width > 0.0 then @@ -3499,7 +3508,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi if by_wrap == nil then by_wrap = {}; by_size[wrap_width] = by_wrap end local e = by_wrap[text] if e then - return ImVec2(e[1], e[2]), e[3] + return e[1], e[2], e[3] end wrap_cache = by_wrap end @@ -3514,7 +3523,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi local line_height = size local scale = line_height / baked.Size - local text_size = ImVec2() + local tx, ty = 0.0, 0.0 local line_width = 0.0 local word_wrap_enabled = (wrap_width > 0.0) @@ -3534,10 +3543,10 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end if s >= word_wrap_eol then - if text_size.x < line_width then - text_size.x = line_width + if tx < line_width then + tx = line_width end - text_size.y = text_size.y + line_height + ty = ty + line_height line_width = 0.0 s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) -- Wrapping skips upcoming blanks if bit32.band(flags, ImDrawTextFlags.StopOnNewLine) ~= 0 then @@ -3562,8 +3571,8 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end if c == 10 then -- '\n' - text_size.x = ImMax(text_size.x, line_width) - text_size.y = text_size.y + line_height + if tx < line_width then tx = line_width end + ty = ty + line_height line_width = 0.0 if bit32.band(flags, ImDrawTextFlags.StopOnNewLine) ~= 0 then stop = true; break @@ -3595,30 +3604,36 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi if stop then break end end - if (text_size.x < line_width) then - text_size.x = line_width + if (tx < line_width) then + tx = line_width end if out_offset then -- offset allow for the possibility of sitting after a trailing \n out_offset.x = line_width - out_offset.y = text_size.y + line_height + out_offset.y = ty + line_height end - if (line_width > 0 or text_size.y == 0.0) then -- whereas size.y will ignore the trailing \n - text_size.y = text_size.y + line_height + if (line_width > 0 or ty == 0.0) then -- whereas size.y will ignore the trailing \n + ty = ty + line_height end local out_remaining = s if cache_key then - baked._TextSizeCache[cache_key] = { text_size.x / scale, text_size.y / line_height } + baked._TextSizeCache[cache_key] = { tx / scale, ty / line_height } baked._TextSizeCacheN = baked._TextSizeCacheN + 1 elseif wrap_cache then - wrap_cache[text] = { text_size.x, text_size.y, out_remaining } + wrap_cache[text] = { tx, ty, out_remaining } baked._TextSizeCacheN = baked._TextSizeCacheN + 1 end - return text_size, out_remaining + return tx, ty, out_remaining +end + +-- ImVec2 version (upstream signature) +function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags) + local x, y, remaining = ImFontCalcTextSizeXY(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags) + return ImVec2(x, y), remaining end --- @param size float @@ -6988,7 +7003,15 @@ end -- Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui.PushClipRect() to affect logic (hit-testing and widget culling) function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_rect) - local cr = ImVec4(cr_min.x, cr_min.y, cr_max.x, cr_max.y) + -- [Luau] reuse the stack slot's ImVec4 left from earlier frames (each slot stays uniquely owned by the stack) + local stack = self._ClipRectStack + local n = stack.Size + 1 + local cr = n <= stack.Capacity and stack.Data[n] or nil + if cr then + cr.x = cr_min.x; cr.y = cr_min.y; cr.z = cr_max.x; cr.w = cr_max.y + else + cr = ImVec4(cr_min.x, cr_min.y, cr_max.x, cr_max.y) + end if intersect_with_current_clip_rect then local current = self._CmdHeader.ClipRect @@ -7003,8 +7026,6 @@ function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_ cr.w = math.max(cr.y, cr.w) -- [Luau] inline self._ClipRectStack:push_back(cr) - local stack = self._ClipRectStack - local n = stack.Size + 1 if n > stack.Capacity then stack:push_back(cr) else stack.Data[n] = cr; stack.Size = n end ImVec4_Copy(self._CmdHeader.ClipRect, cr) self:_OnChangedClipRect() diff --git a/imgui_internal.lua b/imgui_internal.lua index 60c19ed..e6a9a10 100644 --- a/imgui_internal.lua +++ b/imgui_internal.lua @@ -319,13 +319,15 @@ end --- @param s table # 1-based --- @param c any --- @param n int +@native function ImStd.memset(s, c, n) for i = 1, n do s[i] = c end end do -local _memmove = function(dest, dest_start, src, src_start, count) +@native +local function _memmove(dest, dest_start, src, src_start, count) if count <= 0 then return end local c = (dest == src and dest_start >= src_start) diff --git a/imgui_widgets.lua b/imgui_widgets.lua index d464e58..16cd995 100644 --- a/imgui_widgets.lua +++ b/imgui_widgets.lua @@ -110,13 +110,13 @@ function ImGui.TextEx(text, text_end, flags) -- [Luau] scalar text_pos, scratch bb (ItemAdd() copies it, RenderTextWrapped() only reads it) local text_pos_x, text_pos_y = dc.CursorPos.x, dc.CursorPos.y + dc.CurrLineTextBaseOffset local wrap_width = wrap_enabled and ImGui.CalcWrapWidthForPos(dc.CursorPos, wrap_pos_x) or 0.0 - local text_size = ImGui.CalcTextSizeEx(text, 1, text_end, false, wrap_width) + local text_size_x, text_size_y = ImGui.CalcTextSizeXY(text, 1, text_end, false, wrap_width) local bb = TextEx_bb local bb_min, bb_max = bb.Min, bb.Max bb_min.x = text_pos_x; bb_min.y = text_pos_y - bb_max.x = text_pos_x + text_size.x; bb_max.y = text_pos_y + text_size.y - ImGui.ItemSize(text_size, 0.0) + bb_max.x = text_pos_x + text_size_x; bb_max.y = text_pos_y + text_size_y + ImGui.ItemSize(bb, 0.0) -- [Luau] the bb's size == text_size if not ImGui.ItemAdd(bb, 0) then return end @@ -342,6 +342,8 @@ end -- Text with a little bullet aligned to the typical tree node. --- @param fmt string --- @param ... any +local BulletText_bb, BulletText_pos, BulletText_size = ImRect(), ImVec2(), ImVec2() -- [Luau] scratch, only read by callees + function ImGui.BulletText(fmt, ...) local window = ImGui.GetCurrentWindow() if window.SkipItems then @@ -353,20 +355,26 @@ function ImGui.BulletText(fmt, ...) local text = ImFormatString(fmt, ...) local text_end = #text + 1 - local label_size = ImGui.CalcTextSize(text, text_end, false) - local total_size = ImVec2(g.FontSize + ((label_size.x > 0.0) and (label_size.x + style.FramePadding.x * 2) or 0.0), label_size.y) -- Empty text doesn't add padding + local label_size_x, label_size_y = ImGui.CalcTextSizeXY(text, 1, text_end, false) -- [Luau] scalar label_size/total_size + local total_size_x = g.FontSize + ((label_size_x > 0.0) and (label_size_x + style.FramePadding.x * 2) or 0.0) -- Empty text doesn't add padding -- [Luau] scalar pos, no temporary ImVec2 local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset + local bb = BulletText_bb + bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = pos_x, pos_y, pos_x + total_size_x, pos_y + label_size_y + local total_size = BulletText_size + total_size.x, total_size.y = total_size_x, label_size_y ImGui.ItemSize(total_size, 0.0) - local bb = ImRect(pos_x, pos_y, pos_x + total_size.x, pos_y + total_size.y) if not ImGui.ItemAdd(bb, 0) then return end -- Render local text_col = ImGui.GetColorU32(ImGuiCol.Text) - ImGui.RenderBullet(window.DrawList, ImVec2(bb.Min.x + (style.FramePadding.x + g.FontSize * 0.5), bb.Min.y + g.FontSize * 0.5), text_col) - ImGui.RenderText(ImVec2(bb.Min.x + (g.FontSize + style.FramePadding.x * 2), bb.Min.y + 0.0), text, 1, text_end, false) + local p = BulletText_pos + p.x, p.y = bb.Min.x + (style.FramePadding.x + g.FontSize * 0.5), bb.Min.y + g.FontSize * 0.5 + ImGui.RenderBullet(window.DrawList, p, text_col) + p.x, p.y = bb.Min.x + (g.FontSize + style.FramePadding.x * 2), bb.Min.y + 0.0 + ImGui.RenderText(p, text, 1, text_end, false) end -- [Port] va_list variants: identical to the varargs versions in Lua @@ -744,6 +752,7 @@ end --- @param size_arg? ImVec2 --- @param flags? ImGuiButtonFlags --- @return bool +local ButtonEx_bb, ButtonEx_label_size, ButtonEx_size = ImRect(), ImVec2(), ImVec2() local ButtonEx_text_min, ButtonEx_text_max = ImVec2(), ImVec2() @native @@ -760,7 +769,8 @@ function ImGui.ButtonEx(label, size_arg, flags) local style = g.Style local id = window:GetID(label) local label_end = ImGui.FindRenderedTextEnd(label) - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size = ButtonEx_label_size -- [Luau] scratch: only read below (RenderTextClipped text_size_if_known) + label_size.x, label_size.y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar pos, no temporary ImVec2 local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y @@ -768,9 +778,11 @@ function ImGui.ButtonEx(label, size_arg, flags) 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 end - local size = ImGui.CalcItemSize(size_arg, label_size.x + frame_padding.x * 2.0, label_size.y + frame_padding.y * 2.0) + local size = ButtonEx_size -- [Luau] scratch + scalar CalcItemSize(): ItemSize() only reads it + size.x, size.y = ImGui._CalcItemSizeXY(size_arg.x, size_arg.y, label_size.x + frame_padding.x * 2.0, label_size.y + frame_padding.y * 2.0) - local bb = ImRect(pos_x, pos_y, pos_x + size.x, pos_y + size.y) + local bb = ButtonEx_bb -- [Luau] scratch: ItemAdd() copies it, ButtonBehavior()/Render*() only read it + bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = pos_x, pos_y, pos_x + size.x, pos_y + size.y ImGui.ItemSize(size, frame_padding.y) if not ImGui.ItemAdd(bb, id) then return false @@ -1299,6 +1311,8 @@ end --- @param v bool --- @return bool is_pressed --- @return bool is_checked # The updated `v` passed in +local Checkbox_total_bb, Checkbox_check_bb, Checkbox_label_pos = ImRect(), ImRect(), ImVec2() -- [Luau] scratch, only read by callees + @native function ImGui.Checkbox(label, v) local window = ImGui.GetCurrentWindow() @@ -1310,18 +1324,19 @@ function ImGui.Checkbox(label, v) local style = g.Style local id = window:GetID(label) local label_end = ImGui.FindRenderedTextEnd(label) - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size local square_sz = g.FontSize + style.FramePadding.y * 2.0 -- [Luau] inline GetFrameHeight() local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y -- [Luau] scalar pos, no temporary ImVec2 local total_width - if label_size.x > 0.0 then - total_width = square_sz + style.ItemInnerSpacing.x + label_size.x + if label_size_x > 0.0 then + total_width = square_sz + style.ItemInnerSpacing.x + label_size_x else total_width = square_sz end - local total_bb = ImRect(pos_x, pos_y, pos_x + total_width, pos_y + (label_size.y + style.FramePadding.y * 2.0)) + local total_bb = Checkbox_total_bb + total_bb.Min.x, total_bb.Min.y, total_bb.Max.x, total_bb.Max.y = pos_x, pos_y, pos_x + total_width, pos_y + (label_size_y + style.FramePadding.y * 2.0) ImGui.ItemSize(total_bb, style.FramePadding.y) local is_visible = ImGui.ItemAdd(total_bb, id) local is_multi_select = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0) @@ -1353,7 +1368,8 @@ function ImGui.Checkbox(label, v) ImGui.MarkItemEdited(id) end - local check_bb = ImRect(pos_x, pos_y, pos_x + square_sz, pos_y + square_sz) + local check_bb = Checkbox_check_bb + check_bb.Min.x, check_bb.Min.y, check_bb.Max.x, check_bb.Max.y = pos_x, pos_y, pos_x + square_sz, pos_y + square_sz local mixed_value = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.MixedValue) ~= 0) if is_visible then ImGui.RenderNavCursor(total_bb, id) @@ -1378,8 +1394,9 @@ function ImGui.Checkbox(label, v) ImGui.LogRenderedText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), mixed_value and "[~]" or (v and "[x]" or "[ ]")) -- label_pos end - if is_visible and label_size.x > 0.0 then - local label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y) -- [Luau] only built when used + if is_visible and label_size_x > 0.0 then + local label_pos = Checkbox_label_pos + label_pos.x, label_pos.y = check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y ImGui.RenderText(label_pos, label, 1, label_end, false) end @@ -3502,7 +3519,8 @@ end -- [Luau] memo of string.format(format, value) for drag/slider value text (same values are redrawn every frame). local fmt_memo, fmt_memo_n = {}, 0 -local SliderScalar_total_bb, SliderScalar_grab_bb = ImRect(), ImRect() -- [Luau] scratch for SliderScalar()/DragScalar(), never escape +local SliderScalar_total_bb, SliderScalar_grab_bb, SliderScalar_frame_bb = ImRect(), ImRect(), ImRect() -- [Luau] scratch for SliderScalar()/DragScalar(), never escape +local SliderScalar_label_pos = ImVec2() local DRAG_TEXT_ALIGN = ImVec2(0.5, 0.5) function FormatCached(format, v) local m = fmt_memo[format] @@ -3533,12 +3551,13 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla local color_marker = (bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasColorMarker) ~= 0) and g.NextItemData.ColorMarker or 0 local label_end = ImGui.FindRenderedTextEnd(label) - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size local cursor = window.DC.CursorPos - local frame_bb = ImRect(cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size.y + style.FramePadding.y * 2.0)) -- [Luau] no temporary ImVec2 + local frame_bb = SliderScalar_frame_bb -- [Luau] scratch: callees only read it + frame_bb.Min.x, frame_bb.Min.y, frame_bb.Max.x, frame_bb.Max.y = cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size_y + style.FramePadding.y * 2.0) local total_bb = SliderScalar_total_bb -- [Luau] scratch: ItemSize()/ItemAdd() only read it total_bb.Min.x = frame_bb.Min.x; total_bb.Min.y = frame_bb.Min.y - total_bb.Max.x = frame_bb.Max.x + ((label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0); total_bb.Max.y = frame_bb.Max.y + 0.0 + total_bb.Max.x = frame_bb.Max.x + ((label_size_x > 0.0) and (style.ItemInnerSpacing.x + label_size_x) or 0.0); total_bb.Max.y = frame_bb.Max.y + 0.0 local temp_input_allowed = (bit32.band(flags, ImGuiSliderFlags.NoInput) == 0) ImGui.ItemSize(total_bb, style.FramePadding.y) @@ -3626,8 +3645,10 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla ImGui.PopStyleColor() end - if label_size.x > 0.0 then - ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, 1, label_end, false) + if label_size_x > 0.0 then + local label_pos = SliderScalar_label_pos + label_pos.x, label_pos.y = frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y + ImGui.RenderText(label_pos, label, 1, label_end, false) end return data, value_changed @@ -4238,10 +4259,11 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) local color_marker = (bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasColorMarker) ~= 0) and g.NextItemData.ColorMarker or 0 local label_end = ImGui.FindRenderedTextEnd(label) - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size local cursor = window.DC.CursorPos - local frame_bb = ImRect(cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size.y + style.FramePadding.y * 2.0)) -- [Luau] no temporary ImVec2 - local total_bb_x = frame_bb.Max.x + ((label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0) + local frame_bb = SliderScalar_frame_bb -- [Luau] scratch: callees only read it + frame_bb.Min.x, frame_bb.Min.y, frame_bb.Max.x, frame_bb.Max.y = cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size_y + style.FramePadding.y * 2.0) + local total_bb_x = frame_bb.Max.x + ((label_size_x > 0.0) and (style.ItemInnerSpacing.x + label_size_x) or 0.0) local total_bb = SliderScalar_total_bb -- [Luau] scratch: ItemSize()/ItemAdd() only read it total_bb.Min.x = frame_bb.Min.x; total_bb.Min.y = frame_bb.Min.y; total_bb.Max.x = total_bb_x; total_bb.Max.y = frame_bb.Max.y @@ -4327,8 +4349,10 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) ImGui.PopStyleColor() end - if label_size.x > 0.0 then - ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, 1, label_end, false) + if label_size_x > 0.0 then + local label_pos = SliderScalar_label_pos + label_pos.x, label_pos.y = frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y + ImGui.RenderText(label_pos, label, 1, label_end, false) end -- IMGUI_TEST_ENGINE_ITEM_INFO() @@ -7812,6 +7836,10 @@ end --- @param flags ImGuiTreeNodeFlags --- @param label string --- @param label_end? int +local TreeNode_frame_bb, TreeNode_interact_bb = ImRect(), ImRect() -- [Luau] scratch for TreeNodeBehavior(), never escape +local TreeNode_label_size, TreeNode_text_pos, TreeNode_tmp = ImVec2(), ImVec2(), ImVec2() +local function TreeNode_tmp_pos(x, y) local v = TreeNode_tmp; v.x = x; v.y = y; return v end -- [Luau] scratch pos for Render*() args + @native function ImGui.TreeNodeBehavior(id, flags, label, label_end) local window = ImGui.GetCurrentWindow() @@ -7836,7 +7864,8 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) if label_end == nil then label_end = ImGui.FindRenderedTextEnd(label) end - local label_size = ImGui.CalcTextSize(label, label_end, false) + local label_size = TreeNode_label_size -- [Luau] scratch: only read below (RenderTextClipped text_size_if_known) + label_size.x, label_size.y = ImGui.CalcTextSizeXY(label, 1, label_end, false) local text_offset_x = g.FontSize + (display_frame and (padding_x * 3) or (padding_x * 2)) -- Collapsing arrow width + Spacing local text_offset_y = use_frame_padding and ImMax(style.FramePadding.y, window.DC.CurrLineTextBaseOffset) or window.DC.CurrLineTextBaseOffset -- Latch before ItemSize changes it @@ -7845,7 +7874,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local frame_height = label_size.y + padding_y * 2 local span_all_columns = bit32.band(flags, ImGuiTreeNodeFlags.SpanAllColumns) ~= 0 and (g.CurrentTable ~= nil) local span_all_columns_label = bit32.band(flags, ImGuiTreeNodeFlags.LabelSpanAllColumns) ~= 0 and (g.CurrentTable ~= nil) - local frame_bb = ImRect() + local frame_bb = TreeNode_frame_bb -- [Luau] scratch, fully written here; callees copy or only read it frame_bb.Min.x = span_all_columns and window.ParentWorkRect.Min.x or (bit32.band(flags, ImGuiTreeNodeFlags.SpanFullWidth) ~= 0 and window.WorkRect.Min.x or window.DC.CursorPos.x) frame_bb.Min.y = window.DC.CursorPos.y + (text_offset_y - padding_y) frame_bb.Max.x = span_all_columns and window.ParentWorkRect.Max.x or (bit32.band(flags, ImGuiTreeNodeFlags.SpanLabelWidth) ~= 0 and window.DC.CursorPos.x + text_width + padding_x or window.WorkRect.Max.x) @@ -7856,12 +7885,13 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) frame_bb.Max.x = frame_bb.Max.x + outer_extend end - local text_pos = ImVec2(window.DC.CursorPos.x + text_offset_x, window.DC.CursorPos.y + text_offset_y) + local text_pos = TreeNode_text_pos -- [Luau] scratch + text_pos.x, text_pos.y = window.DC.CursorPos.x + text_offset_x, window.DC.CursorPos.y + text_offset_y local item_size = LayoutHelpers_size; item_size.x = text_width; item_size.y = frame_height -- [Luau] scratch, ItemSize() only reads it ImGui.ItemSize(item_size, padding_y) -- For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing - local interact_bb = ImRect() + local interact_bb = TreeNode_interact_bb -- [Luau] scratch, ItemAdd()/ButtonBehavior()/SetNavID() copy or only read it ImRect_Copy(interact_bb, frame_bb) if bit32.band(flags, bit32.bor(ImGuiTreeNodeFlags.Framed, ImGuiTreeNodeFlags.SpanAvailWidth, ImGuiTreeNodeFlags.SpanFullWidth, ImGuiTreeNodeFlags.SpanLabelWidth, ImGuiTreeNodeFlags.SpanAllColumns)) == 0 then interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0 and (style.ItemSpacing.x * 2.0) or 0.0) @@ -8055,9 +8085,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.TablePopBackgroundChannel() end if bit32.band(flags, ImGuiTreeNodeFlags.Bullet) ~= 0 then - ImGui.RenderBullet(window.DrawList, ImVec2(text_pos.x - text_offset_x * 0.60, text_pos.y + g.FontSize * 0.5), text_col) + ImGui.RenderBullet(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x * 0.60, text_pos.y + g.FontSize * 0.5), text_col) elseif not is_leaf then - ImGui.RenderArrow(window.DrawList, ImVec2(text_pos.x - text_offset_x + padding_x, text_pos.y), text_col, is_open and ((bit32.band(flags, ImGuiTreeNodeFlags.UpsideDownArrow) ~= 0) and ImGuiDir.Up or ImGuiDir.Down) or ImGuiDir.Right, 1.0) + ImGui.RenderArrow(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x + padding_x, text_pos.y), text_col, is_open and ((bit32.band(flags, ImGuiTreeNodeFlags.UpsideDownArrow) ~= 0) and ImGuiDir.Up or ImGuiDir.Down) or ImGuiDir.Right, 1.0) else -- Leaf without bullet, left-adjusted text text_pos.x = text_pos.x - (text_offset_x - padding_x) end @@ -8078,9 +8108,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.TablePopBackgroundChannel() end if bit32.band(flags, ImGuiTreeNodeFlags.Bullet) ~= 0 then - ImGui.RenderBullet(window.DrawList, ImVec2(text_pos.x - text_offset_x * 0.5, text_pos.y + g.FontSize * 0.5), text_col) + ImGui.RenderBullet(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x * 0.5, text_pos.y + g.FontSize * 0.5), text_col) elseif not is_leaf then - ImGui.RenderArrow(window.DrawList, ImVec2(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.15), text_col, is_open and ((bit32.band(flags, ImGuiTreeNodeFlags.UpsideDownArrow) ~= 0) and ImGuiDir.Up or ImGuiDir.Down) or ImGuiDir.Right, 0.70) + ImGui.RenderArrow(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.15), text_col, is_open and ((bit32.band(flags, ImGuiTreeNodeFlags.UpsideDownArrow) ~= 0) and ImGuiDir.Up or ImGuiDir.Down) or ImGuiDir.Right, 0.70) end if g.LogEnabled then ImGui.LogSetNextTextDecoration(">", nil) @@ -8088,7 +8118,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) end if draw_tree_lines then - ImGui.TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.5)) + ImGui.TreeNodeDrawLineToChildNode(TreeNode_tmp_pos(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.5)) end -- Label diff --git a/imstb_rectpack.lua b/imstb_rectpack.lua index 2a6ff04..f0a8438 100644 --- a/imstb_rectpack.lua +++ b/imstb_rectpack.lua @@ -105,6 +105,7 @@ local STBRP__PREV_LINK_TYPE = { --- @return stbrp_rect --- @nodiscard +@native local function stbrp_rect() return { -- reserved for your use: @@ -128,6 +129,7 @@ end --- @return stbrp_node --- @nodiscard +@native local function stbrp_node() return { x = 0, @@ -149,6 +151,7 @@ end --- @return stbrp_context --- @nodiscard +@native local function stbrp_context() return { width = 0, @@ -171,6 +174,7 @@ end --- @field prev_link_type? int --- @return stbrp__findresult +@native local function stbrp__findresult() return { x = 0, @@ -191,6 +195,7 @@ end -- If you call init again, this will be reset to the default. --- @param context stbrp_context --- @param heuristic int +@native local function stbrp_setup_heuristic(context, heuristic) if context.init_mode == STBRP__INIT_skyline then STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight or heuristic == STBRP_HEURISTIC_Skyline.BF_sortHeight) @@ -205,6 +210,7 @@ end -- If you call init again, this will be reset to the default (false). --- @param context stbrp_context --- @param allow_out_of_mem boolean +@native local function stbrp_setup_allow_out_of_mem(context, allow_out_of_mem) if allow_out_of_mem then -- if it's ok to run out of memory, then don't bother aligning them; @@ -248,6 +254,7 @@ end --- @param height int --- @param nodes stbrp_node[] --- @param num_nodes int +@native function stbrp_init_target(context, width, height, nodes, num_nodes) for i = 1, num_nodes - 1 do nodes[i].next = nodes[i + 1] @@ -278,6 +285,7 @@ end --- @param x0 int --- @param width int --- @return int, int +@native local function stbrp__skyline_find_min_y(c, first, x0, width) local node = first local x1 = x0 + width @@ -325,6 +333,7 @@ end --- @param width int --- @param height int --- @return stbrp__findresult +@native local function stbrp__skyline_find_best_pos(c, width, height) local best_waste = bit32.lshift(1, 30) local best_x = 0 @@ -454,6 +463,7 @@ end --- @param width int --- @param height int --- @return stbrp__findresult +@native local function stbrp__skyline_pack_rectangle(context, width, height) -- find best position according to heuristic local res = stbrp__skyline_find_best_pos(context, width, height) @@ -522,6 +532,7 @@ end --- @param b stbrp_rect --- @return bool --- @package +@native local function rect_height_compare(a, b) if a.h > b.h then return true @@ -536,6 +547,7 @@ end --- @param b stbrp_rect --- @return bool --- @package +@native local function rect_original_order(a, b) return a.was_packed < b.was_packed end @@ -567,6 +579,7 @@ end --- @param rects stbrp_rect[] --- @param num_rects int --- @return int +@native local function stbrp_pack_rects(context, rects, num_rects) local all_rects_packed = 1 diff --git a/imstb_truetype.lua b/imstb_truetype.lua index 535a271..3b9d66f 100644 --- a/imstb_truetype.lua +++ b/imstb_truetype.lua @@ -168,7 +168,7 @@ local stbtt_MakeGlyphBitmapSubpixelPrefilter local stbtt_GetFontVMetrics local stbtt__GetGlyphInfoT2 local stbtt__GetGlyphShapeT2 -local stbtt_GetGlyphShape +local stbtt_GetGlyphShape, stbtt_GetGlyphShapeUncached local stbtt_GetGlyphBitmapBox local stbtt_GetGlyphBitmapBoxSubpixel local stbtt_GetGlyphHMetrics @@ -221,6 +221,7 @@ local trunc = function(x) end end +@native local function STBTT__NOTUSED(_) return end --- @alias stbtt_int32 int @@ -243,6 +244,7 @@ local unsigned_char = stbtt_uint8 --- @param initial_offset? int --- @return stbtt__buf --- @nodiscard +@native local function stbtt__buf(initial_offset) return { data = nil, @@ -277,6 +279,7 @@ end --- @field fdselect stbtt__buf # map from glyph to fontdict --- @return stbtt_fontinfo +@native function stbtt_fontinfo() return { data = nil, @@ -317,6 +320,7 @@ end --- @return stbtt_vertex --- @nodiscard +@native local function stbtt_vertex() return { x = nil, @@ -346,6 +350,7 @@ end --- @return stbtt__csctx --- @nodiscard +@native local function stbtt__csctx() return { bounds = false, @@ -367,6 +372,7 @@ end --- @param bounds bool --- @return stbtt__csctx --- @nodiscard +@native local function STBTT__CSCTX_INIT(bounds) local this = stbtt__csctx() @@ -400,6 +406,7 @@ end --- @return stbtt__edge --- @nodiscard +@native local function stbtt__edge() return { x0 = nil, @@ -414,6 +421,7 @@ end --- @return stbtt__active_edge --- @nodiscard +@native local function stbtt__active_edge() return { next = nil, @@ -428,8 +436,15 @@ end --- @return stbtt__active_edge --- @nodiscard +local active_pool, active_pool_n = {}, 0 -- [Luau] reused per stbtt__rasterize_sorted_edges() call (C: stbtt__hheap) +@native local function stbtt__new_active(e, off_x, start_point) - local z = stbtt__active_edge() + active_pool_n = active_pool_n + 1 + local z = active_pool[active_pool_n] + if z == nil then + z = stbtt__active_edge() + active_pool[active_pool_n] = z + end local dxdy = (e.x1 - e.x0) / (e.y1 - e.y0) z.fdx = dxdy @@ -453,6 +468,7 @@ end --- @return stbtt__bitmap --- @nodiscard +@native local function stbtt__bitmap() return { w = nil, @@ -468,6 +484,7 @@ end --- @return stbtt__point --- @nodiscard +@native local function stbtt__point() return { x = nil, y = nil } end ---------------------------------------------- @@ -478,6 +495,7 @@ local function stbtt__point() return { x = nil, y = nil } end --- --- @param b stbtt__buf +@native local function stbtt__buf_get8(b) if b.cursor >= b.size then return 0 end local result = b.data[b.offset + b.cursor + 1] @@ -486,6 +504,7 @@ local function stbtt__buf_get8(b) end --- @param b stbtt__buf +@native local function stbtt__buf_peek8(b) if b.cursor >= b.size then return 0 end return b.data[b.offset + b.cursor + 1] @@ -493,6 +512,7 @@ end --- @param b stbtt__buf --- @param o int +@native local function stbtt__buf_seek(b, o) STBTT_assert(not (o > b.size or o < 0)) if o > b.size or o < 0 then @@ -504,10 +524,12 @@ end --- @param b stbtt__buf --- @param o int +@native local function stbtt__buf_skip(b, o) stbtt__buf_seek(b, b.cursor + o) end +@native local function stbtt__buf_get(b, n) local v = 0 STBTT_assert(n >= 1 and n <= 4) @@ -522,6 +544,7 @@ end --- @param offset? int --- @return stbtt__buf --- @nodiscard +@native local function stbtt__new_buf(p, size, offset) local r = stbtt__buf(offset) STBTT_assert(size < 0x40000000) @@ -532,8 +555,10 @@ local function stbtt__new_buf(p, size, offset) end --- @param b stbtt__buf +@native local function stbtt__buf_get16(b) return stbtt__buf_get(b, 2) end --- @param b stbtt__buf +@native local function stbtt__buf_get32(b) return stbtt__buf_get(b, 4) end --- @param b stbtt__buf @@ -541,6 +566,7 @@ local function stbtt__buf_get32(b) return stbtt__buf_get(b, 4) end --- @param s int --- @return stbtt__buf --- @nodiscard +@native local function stbtt__buf_range(b, o, s) local r = stbtt__new_buf(nil, 0) if (o < 0 or s < 0 or o > b.size or s > (b.size - o)) then @@ -553,6 +579,7 @@ local function stbtt__buf_range(b, o, s) end --- @param b stbtt__buf +@native local function stbtt__cff_get_index(b) local count, start, offsize start = b.cursor @@ -567,6 +594,7 @@ local function stbtt__cff_get_index(b) end --- @param b stbtt__buf +@native local function stbtt__cff_int(b) local b0 = stbtt__buf_get8(b) if b0 >= 32 and b0 <= 246 then return b0 - 139 @@ -580,6 +608,7 @@ local function stbtt__cff_int(b) end --- @param b stbtt__buf +@native local function stbtt__cff_skip_operand(b) local v local b0 = stbtt__buf_peek8(b) @@ -601,6 +630,7 @@ end --- @param key int --- @return stbtt__buf --- @nodiscard +@native local function stbtt__dict_get(b, key) stbtt__buf_seek(b, 0) while b.cursor < b.size do @@ -622,6 +652,7 @@ end --- @param outcount int --- @return int[] --- @nodiscard +@native local function stbtt__dict_get_ints(b, key, outcount) local operands = stbtt__dict_get(b, key) local out = {} @@ -633,6 +664,7 @@ local function stbtt__dict_get_ints(b, key, outcount) end --- @param b stbtt__buf +@native local function stbtt__cff_index_count(b) stbtt__buf_seek(b, 0) return stbtt__buf_get16(b) @@ -642,6 +674,7 @@ end --- @param i int --- @return stbtt__buf --- @nodiscard +@native local function stbtt__cff_index_get(b, i) local count, offsize, start, _end stbtt__buf_seek(b, 0) @@ -685,17 +718,26 @@ end --- stbtt_GetNumberOfFonts_internal --- stbtt__get_svg +@native local function ttUSHORT(p, offset) return stbtt_uint16(p[offset + 1] * 256 + p[offset + 2]) end +@native local function ttSHORT(p, offset) return stbtt_int16(p[offset + 1] * 256 + p[offset + 2]) end +@native local function ttULONG(p, offset) return stbtt_uint32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end +@native local function ttLONG(p, offset) return stbtt_int32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end +@native local function ttBYTE(p, offset) return stbtt_uint8(p[offset + 1]) end +@native local function ttCHAR(p, offset) return stbtt_int8(p[offset + 1]) end +@native local function stbtt_tag4(p, c0, c1, c2, c3, offset) offset = offset or 0; return p[offset + 1] == c0 and p[offset + 2] == c1 and p[offset + 3] == c2 and p[offset + 4] == c3 end +@native local function stbtt_tag(p, str, offset) local c0, c1, c2, c3 = string.byte(str, 1, 4); return stbtt_tag4(p, c0, c1, c2, c3, offset) end +@native local function stbtt__isfont(font) -- check the version number if stbtt_tag4(font, 49, 0, 0, 0) then return true end -- TrueType 1 @@ -707,6 +749,7 @@ local function stbtt__isfont(font) end -- @OPTIMIZE: binary search +@native local function stbtt__find_table(data, font_start, tag) local num_tables = ttUSHORT(data, font_start + 4) local tabledir = font_start + 12 @@ -719,6 +762,7 @@ local function stbtt__find_table(data, font_start, tag) return 0 end +@native local function stbtt_GetFontOffsetForIndex_internal(font_collection, index) -- if it's just a font, there's only one valid index if stbtt__isfont(font_collection) then @@ -742,6 +786,7 @@ end --- @param cff stbtt__buf --- @param fontdict stbtt__buf +@native local function stbtt__get_subrs(cff, fontdict) local private_loc = stbtt__dict_get_ints(fontdict, 18, 2) if (private_loc[2] == 0 or private_loc[1] == 0) then @@ -757,6 +802,7 @@ local function stbtt__get_subrs(cff, fontdict) end --- @return bool +@native local function stbtt_InitFont_internal(info, data, fontstart) local cmap local numTables @@ -884,6 +930,7 @@ end -- Returns 0 if the character codepoint is not defined in the font. --- @param info stbtt_fontinfo --- @param unicode_codepoint int +@native function stbtt_FindGlyphIndex(info, unicode_codepoint) local data = info.data local index_map = info.index_map @@ -989,6 +1036,7 @@ end --- @param y stbtt_int32 --- @param cx stbtt_int32 --- @param cy stbtt_int32 +@native local function stbtt_setvertex(v, vtx_type, x, y, cx, cy) v.type = vtx_type v.x = (stbtt_int16)(x) @@ -997,6 +1045,7 @@ local function stbtt_setvertex(v, vtx_type, x, y, cx, cy) v.cy = (stbtt_int16)(cy) end +@native local function stbtt__GetGlyfOffset(info, glyph_index) STBTT_assert(info.cff.size == 0) @@ -1017,6 +1066,7 @@ end -- Gets the bounding box of the visible part of the glyph, in unscaled coordinates --- @return integer, integer?, integer?, integer?, integer? +@native local function stbtt_GetGlyphBox(info, glyph_index) local n, x0, y0, x1, y1 @@ -1045,6 +1095,7 @@ end --- @param scy stbtt_int32 --- @param cx stbtt_int32 --- @param cy stbtt_int32 +@native local function stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy) if start_off then if was_off then @@ -1069,6 +1120,7 @@ end --- @param glyph_index int --- @return int num_vertices --- @return stbtt_vertex[]? vertices +@native local function stbtt__GetGlyphShapeTT(info, glyph_index) local data = info.data local num_vertices @@ -1288,7 +1340,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) n = STBTT_sqrt(mtx[3] * mtx[3] + mtx[4] * mtx[4]) -- Get indexed glyph. - comp_num_vertices, comp_verts = stbtt_GetGlyphShape(info, gidx) + comp_num_vertices, comp_verts = stbtt_GetGlyphShapeUncached(info, gidx) -- [Luau] transformed in place below: must be a fresh copy if comp_num_vertices > 0 then -- Transform vertices. for i = 1, comp_num_vertices do @@ -1326,6 +1378,7 @@ end --- @param c stbtt__csctx --- @param x stbtt_int32 --- @param y stbtt_int32 +@native local function stbtt__track_vertex(c, x, y) if x > c.max_x or not c.started then c.max_x = x end if y > c.max_y or not c.started then c.max_y = y end @@ -1342,6 +1395,7 @@ end --- @param cy stbtt_int32 --- @param cx1 stbtt_int32 --- @param cy1 stbtt_int32 +@native local function stbtt__csctx_v(c, vtx_type, x, y, cx, cy, cx1, cy1) if c.bounds then stbtt__track_vertex(c, x, y) @@ -1357,6 +1411,7 @@ local function stbtt__csctx_v(c, vtx_type, x, y, cx, cy, cx1, cy1) end --- @param ctx stbtt__csctx +@native local function stbtt__csctx_close_shape(ctx) if ctx.first_x ~= ctx.x or ctx.first_y ~= ctx.y then stbtt__csctx_v(ctx, STBTT_VTX.LINE, trunc(ctx.first_x), trunc(ctx.first_y), 0, 0, 0, 0) @@ -1366,6 +1421,7 @@ end --- @param ctx stbtt__csctx --- @param dx float --- @param dy float +@native local function stbtt__csctx_rmove_to(ctx, dx, dy) stbtt__csctx_close_shape(ctx) ctx.x = ctx.x + dx @@ -1378,6 +1434,7 @@ end --- @param ctx stbtt__csctx --- @param dx float --- @param dy float +@native local function stbtt__csctx_rline_to(ctx, dx, dy) ctx.x = ctx.x + dx ctx.y = ctx.y + dy @@ -1391,6 +1448,7 @@ end --- @param dy2 float --- @param dx3 float --- @param dy3 float +@native local function stbtt__csctx_rccurve_to(ctx, dx1, dy1, dx2, dy2, dx3, dy3) local cx1 = ctx.x + dx1 local cy1 = ctx.y + dy1 @@ -1401,6 +1459,7 @@ local function stbtt__csctx_rccurve_to(ctx, dx1, dy1, dx2, dy2, dx3, dy3) stbtt__csctx_v(ctx, STBTT_VTX.CUBIC, trunc(ctx.x), trunc(ctx.y), trunc(cx1), trunc(cy1), trunc(cx2), trunc(cy2)) end +@native local function stbtt__get_subr(idx, n) local count = stbtt__cff_index_count(idx) local bias = 107 @@ -1416,6 +1475,7 @@ local function stbtt__get_subr(idx, n) return stbtt__cff_index_get(idx, n) end +@native local function stbtt__cid_get_glyph_subrs(info, glyph_index) local fdselect = info.fdselect local fdselector = -1 @@ -1446,6 +1506,7 @@ end --- @param info stbtt_fontinfo --- @param glyph_index int --- @param c stbtt__csctx +@native local function stbtt__run_charstring(info, glyph_index, c) local in_header = true local maskbits = 0 @@ -1719,6 +1780,7 @@ end --- @param glyph_index int --- @return int num_vertices --- @return stbtt_vertex[]? vertices +@native function stbtt__GetGlyphShapeT2(info, glyph_index) -- runs the charstring twice, once to count and once to output (to avoid realloc) local vertices = nil @@ -1744,6 +1806,7 @@ end --- @return int y0 --- @return int x1 --- @return int y1 +@native function stbtt__GetGlyphInfoT2(info, glyph_index) local c = STBTT__CSCTX_INIT(true) local r = stbtt__run_charstring(info, glyph_index, c) @@ -1765,7 +1828,8 @@ end -- its x,y, using cx,cy as the bezier control point. --- @param info stbtt_fontinfo --- @param glyph_index int -function stbtt_GetGlyphShape(info, glyph_index) +@native +function stbtt_GetGlyphShapeUncached(info, glyph_index) if info.cff.size == 0 then return stbtt__GetGlyphShapeTT(info, glyph_index) else @@ -1773,11 +1837,32 @@ function stbtt_GetGlyphShape(info, glyph_index) end end +@native +function stbtt_GetGlyphShape(info, glyph_index) + -- [Luau] shapes don't depend on the size: cache them per font (baking a new size re-used to re-parse every glyph). + -- Callers only read the vertices (stbtt_FreeShape is a no-op). + local cache = info._ShapeCache + if cache == nil then cache = {}; info._ShapeCache = cache end + local e = cache[glyph_index] + if e == nil then + local n, v + if info.cff.size == 0 then + n, v = stbtt__GetGlyphShapeTT(info, glyph_index) + else + n, v = stbtt__GetGlyphShapeT2(info, glyph_index) + end + e = { n, v } + cache[glyph_index] = e + end + return e[1], e[2] +end + -- leftSideBearing is the offset from the current horizontal position to the left edge of the character -- advanceWidth is the offset from the current horizontal position to the next horizontal position -- these are expressed in unscaled coordinates --- @param info stbtt_fontinfo --- @param glyph_index int +@native function stbtt_GetGlyphHMetrics(info, glyph_index) local numOfLongHorMetrics = ttUSHORT(info.data, info.hhea + 34) @@ -1800,6 +1885,7 @@ end -- these are expressed in unscaled coordinates, so you must multiply by -- the scale factor for a given size --- @param info stbtt_fontinfo +@native function stbtt_GetFontVMetrics(info) local ascent = ttSHORT(info.data, info.hhea + 4) local descent = ttSHORT(info.data, info.hhea + 6) @@ -1816,6 +1902,7 @@ end -- so if you prefer to measure height by the ascent only, use a similar calculation. --- @param info stbtt_fontinfo --- @param height float +@native function stbtt_ScaleForPixelHeight(info, height) local fheight = ttSHORT(info.data, info.hhea + 4) - ttSHORT(info.data, info.hhea + 6) return height / fheight @@ -1836,6 +1923,7 @@ end --- @param scale_y float --- @param shift_x float --- @param shift_y float +@native function stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, shift_x, shift_y) local n, x0, y0, x1, y1 = stbtt_GetGlyphBox(font, glyph) @@ -1866,6 +1954,7 @@ end --- @param glyph int --- @param scale_x float --- @param scale_y float +@native function stbtt_GetGlyphBitmapBox(font, glyph, scale_x, scale_y) return stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, 0.0, 0.0) end @@ -1893,6 +1982,7 @@ end --- @param y0 float --- @param x1 float --- @param y1 float +@native local function stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1) if y0 == y1 then return end STBTT_assert(y0 < y1) @@ -1934,6 +2024,7 @@ end --- @param height float --- @param top_width float --- @param bottom_width float +@native local function stbtt__sized_trapezoid_area(height, top_width, bottom_width) STBTT_assert(top_width >= 0) STBTT_assert(bottom_width >= 0) @@ -1945,12 +2036,14 @@ end --- @param tx1 float --- @param bx0 float --- @param bx1 float +@native local function stbtt__position_trapezoid_area(height, tx0, tx1, bx0, bx1) return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0) end --- @param height float --- @param width float +@native local function stbtt__sized_triangle_area(height, width) return height * width / 2 end @@ -1960,6 +2053,7 @@ end --- @param len int --- @param e stbtt__active_edge --- @param y_top float +@native local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_top) local y_bottom = y_top + 1 @@ -2182,11 +2276,14 @@ end --- @param vsubsample int --- @param off_x int --- @param off_y int +local rasterize_scanline, rasterize_scanline2 = {}, {} -- [Luau] reused: fully cleared per scanline below +@native local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y) local active = nil - local scanline = {} -- [Port] size = result.w, 0-based - local scanline2 = {} -- [Port] size = result.w + 1, 0-based + active_pool_n = 0 -- every active edge of the previous call is dead + local scanline = rasterize_scanline -- [Port] size = result.w, 0-based + local scanline2 = rasterize_scanline2 -- [Port] size = result.w + 1, 0-based STBTT__NOTUSED(vsubsample) @@ -2244,20 +2341,18 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of do local sum = 0 + local pixels, base = result.pixels, j * result.stride + 1 for i = 0, result.w - 1 do - local k - local m sum = sum + scanline2[i] - k = scanline[i] + sum - k = STBTT_fabs(k) * 255 + 0.5 - m = trunc(k) + -- [Luau] k >= 0: trunc == floor, and m is already 0..255 (unsigned_char() is a no-op) + local m = math.floor(math.abs(scanline[i] + sum) * 255 + 0.5) if m > 255 then m = 255 end - result.pixels[j * result.stride + i + 1] = unsigned_char(m) + pixels[base + i] = m end end -- advance all the edges - step = active + local step = active while step do step.fx = step.fx + step.fdx -- advance to position for current scanline step = step.next -- advance through list @@ -2277,10 +2372,47 @@ local STBTT__COMPARE = function(a, b) end --- @param p stbtt__edge[] +@native local function stbtt__sort_edges(p) STBTT_sort(p, STBTT__COMPARE) end +-- [Luau] sorts p[lo..hi] by y0 without a comparator callback (like upstream's stbtt__sort_edges_quicksort + ins_sort) +@native +local function stbtt__sort_edges_range(p, lo, hi) + while hi - lo > 12 do + -- median of three -> p[lo] + local m = math.floor((lo + hi) / 2) + local a, b, c = p[lo], p[m], p[hi] + if b.y0 < a.y0 then a, b = b, a end + if c.y0 < b.y0 then b, c = c, b; if b.y0 < a.y0 then a, b = b, a end end + p[lo], p[m], p[hi] = b, a, c + local pivot = p[lo].y0 + local i, j = lo + 1, hi + while true do + while p[i].y0 < pivot do i = i + 1 end + while pivot < p[j].y0 do j = j - 1 end + if i >= j then break end + p[i], p[j] = p[j], p[i] + i = i + 1; j = j - 1 + end + p[lo], p[j] = p[j], p[lo] + -- recurse into the smaller side, loop on the larger + if j - lo < hi - j then + stbtt__sort_edges_range(p, lo, j - 1); lo = j + 1 + else + stbtt__sort_edges_range(p, j + 1, hi); hi = j - 1 + end + end + for i = lo + 1, hi do + local t = p[i] + local y = t.y0 + local j = i - 1 + while j >= lo and p[j].y0 > y do p[j + 1] = p[j]; j = j - 1 end + p[j + 1] = t + end +end + --- @param result stbtt__bitmap --- @param pts stbtt__point[] --- @param wcount int[] @@ -2292,6 +2424,8 @@ end --- @param off_x int --- @param off_y int --- @param invert bool +local rasterize_edges = {} +@native local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, shift_x, shift_y, off_x, off_y, invert) local y_scale_inv = (invert) and -scale_y or scale_y local vsubsample = 1 -- STBTT_RASTERIZER_VERSION == 2 @@ -2303,7 +2437,13 @@ local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, n = n + wcount[i] end - local e = {} for i = 1, n + 1 do e[i] = stbtt__edge() end -- add an extra one as a sentinel + -- [Luau] edges reused across calls; unused entries are sentinels (y0 = nil) like the unfilled ones upstream + local e = rasterize_edges + for i = 1, n + 1 do + local ed = e[i] + if ed == nil then e[i] = stbtt__edge() else ed.y0 = nil; ed.invert = false end + end + for i = n + 2, #e do e[i].y0 = nil end n = 0 local m = 0 @@ -2347,7 +2487,7 @@ local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, end -- now sort the edges by their highest point (should snap to integer, and then by x) - stbtt__sort_edges(e) + stbtt__sort_edges_range(e, 1, n) -- [Luau] e[n + 1..] are y0 == nil sentinels, already last -- now, traverse the scanlines and find the intersections on each scanline, use xor winding rule stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y) @@ -2357,6 +2497,7 @@ end --- @param n int --- @param x float --- @param y float +@native local function stbtt__add_point(points, n, x, y) if points == nil then return end -- during first pass, it's unallocated points[n + 1].x = x @@ -2375,6 +2516,7 @@ end --- @param objspace_flatness_squared float --- @param n int --- @return int num_points # updated num_points passed in +@native local function stbtt__tesselate_curve(points, num_points, x0, y0, x1, y1, x2, y2, objspace_flatness_squared, n) -- midpoint local mx = (x0 + 2 * x1 + x2) / 4 @@ -2411,6 +2553,7 @@ end --- @param objspace_flatness_squared float --- @param n int --- @return int num_points # updated num_points passed in +@native local function stbtt__tesselate_cubic(points, num_points, x0, y0, x1, y1, x2, y2, x3, y3, objspace_flatness_squared, n) -- @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough local dx0 = x1 - x0 @@ -2462,6 +2605,8 @@ end --- @return stbtt__point[]? points --- @return int? num_contours --- @return int[]? contour_lengths +local flatten_points = {} +@native local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) local points = nil local num_points = 0 @@ -2486,8 +2631,8 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) for pass = 0, 1 do local x, y = 0, 0 if pass == 1 then - points = {} - for i = 1, num_points do points[i] = stbtt__point() end + points = flatten_points -- [Luau] reused across calls (only [1..num_points] is read) + for i = #points + 1, num_points do points[i] = stbtt__point() end end num_points = 0 n = -1 @@ -2544,6 +2689,7 @@ end --- @param x_off int --- @param y_off int --- @param invert bool +@native local function stbtt_Rasterize(result, flatness_in_pixels, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert) local scale = (scale_x > scale_y) and scale_y or scale_x @@ -2571,6 +2717,7 @@ end --- @param shift_x float --- @param shift_y float --- @param glyph int +@native local function stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, glyph) local num_verts, vertices = stbtt_GetGlyphShape(info, glyph) local gbm = stbtt__bitmap() @@ -2624,6 +2771,7 @@ local STBTT__OVER_MASK = STBTT_MAX_OVERSAMPLE - 1 --- @param h int --- @param stride_in_bytes int --- @param kernel_width unsigned_int +@native local function stbtt__h_prefilter(pixels, w, h, stride_in_bytes, kernel_width) local buffer = {} local safe_w = w - kernel_width @@ -2653,6 +2801,7 @@ end --- @param h int --- @param stride_in_bytes int --- @param kernel_width unsigned_int +@native local function stbtt__v_prefilter(pixels, w, h, stride_in_bytes, kernel_width) local buffer = {} local safe_h = h - kernel_width @@ -2679,6 +2828,7 @@ end --- @param oversample int --- @return float +@native local function stbtt__oversample_shift(oversample) if oversample == 0 then return 0.0 @@ -2705,6 +2855,7 @@ end --- @param prefilter_x int --- @param prefilter_y int --- @param glyph int +@native function stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, prefilter_x, prefilter_y, glyph) stbtt_MakeGlyphBitmapSubpixel(info, output, out_w - (prefilter_x - 1), out_h - (prefilter_y - 1), out_stride, scale_x, scale_y, shift_x, shift_y, glyph) @@ -2758,6 +2909,7 @@ end -- return '0' for index 0, and -1 for all other indices. --- @param data table --- @param index int +@native function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForIndex_internal(data, index) end -- Given an offset into the file that defines a font, this function builds @@ -2768,6 +2920,7 @@ function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForI --- @param info stbtt_fontinfo --- @param data table --- @param offset int +@native function stbtt_InitFont(info, data, offset) return stbtt_InitFont_internal(info, data, offset) end return { diff --git a/wally.toml b/wally.toml index e9ce81b..37e11dd 100644 --- a/wally.toml +++ b/wally.toml @@ -1,6 +1,6 @@ [package] name = "4dbug/imgui-luau" -version = "0.4.1" +version = "0.4.2" registry = "https://github.com/UpliftGames/wally-index" realm = "shared" license = "MIT"