Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dd9a5ef219 | ||
|
|
9b1052beed | ||
|
|
b4458195b9 | ||
|
|
9b735db59c | ||
|
|
6fc870a519 | ||
|
|
8f4e07c94a | ||
|
|
056c414112 | ||
|
|
15485b7aa4 | ||
|
|
cdb183da59 | ||
|
|
df641ad622 | ||
|
|
91931a482b | ||
|
|
c94f62a1e4 | ||
|
|
25001b0c8f | ||
|
|
f875e2b5f7 | ||
|
|
923e6cdafb | ||
|
|
720daa80d7 | ||
|
|
1b618f7230 | ||
|
|
ddbfd8fb66 | ||
|
|
25bc437635 | ||
|
|
d6bdedee85 | ||
|
|
966da7fbcf | ||
|
|
bc13bc50b8 | ||
|
|
ce0f51d9d5 | ||
|
|
7ca140665d | ||
|
|
3b28ba362b | ||
|
|
b15bdcd8b6 | ||
|
|
a0a9799efd | ||
|
|
01978e76ad | ||
|
|
1f4ae93a2e | ||
|
|
67dc6d3e18 | ||
|
|
43410ad035 | ||
|
|
0d01aaddf3 | ||
|
|
0091e0e879 |
No files matched your search
+67
-13
@@ -25,7 +25,7 @@ This port brings that to Roblox (and LÖVE): debug overlays, admin panels, in-ga
|
||||
|
||||
### Usage
|
||||
|
||||
**The core of Dear ImGui is a set of files with no dependencies**, plus one platform backend from [backends/](/backends/). `tools/bundle.py` combines them into a single file: `build/ImGui.luau` (ModuleScript, Roblox backend) or, with `--target love`, `build/imgui_love.lua` (LÖVE backend). Your UI code is the same for both.
|
||||
**The core of Dear ImGui is a set of files with no dependencies**, plus one platform backend from [backends/](/backends/) (`backends/roblox/`, `backends/love/`). `tools/bundle.py` combines them into a single file: `build/ImGui.luau` (ModuleScript, Roblox backend) or, with `--target love`, `build/imgui_love.lua` (LÖVE backend). Your UI code is the same for both.
|
||||
|
||||
Dear ImGui is **immediate mode**: you call widget functions every frame, and their return values tell you what the user did. There is no widget object to keep in sync with your state.
|
||||
|
||||
@@ -116,7 +116,7 @@ The Style Editor (`ImGui.ShowStyleEditor()`) and the Metrics/Debugger (`ImGui.Sh
|
||||
|
||||
### Getting Started & Integration (Roblox)
|
||||
|
||||
With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/imgui-luau@0.1.3"` 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`.
|
||||
@@ -151,9 +151,12 @@ Backend options:
|
||||
| --- | --- |
|
||||
| `ImGui_ImplRoblox.Init(parent, render_scale)` | `render_scale` = your OS display scale renders at physical-pixel resolution (crisper, same size as desktop imgui). |
|
||||
| `ImGui_ImplRoblox.SetRenderScale(scale)` | Change it at runtime. |
|
||||
| `ImGui_ImplRoblox.SetRenderRate(hz)` | Max tile redraws per second (default 60, `0` = every frame). Your code still runs every frame. |
|
||||
| `ImGui_ImplRoblox.SetRenderRate(hz)` | Max tile redraws per second (default `60`; `0` = every frame). Your code still runs every frame. |
|
||||
| `ImGui_ImplRoblox.SetRedrawBudget(ms)` | Max milliseconds per frame spent redrawing changed tiles (opt-in; default `0` = no limit, every change is drawn the same frame). With a budget, tiles over it keep their old pixels for a few frames, so big changes are spread over frames instead of one long frame (parts of the UI may update a frame or two apart). |
|
||||
| `ImGui_ImplRoblox.SetBusyRenderRate(hz)` | Optional lower redraw rate while scrolling, resizing or moving windows (default off). |
|
||||
| `ImGui_ImplRoblox.SetProfiling(true)` | MicroProfiler (Ctrl+F6) labels for every backend stage. |
|
||||
| `ImGui_ImplRoblox.GetStats()` | Live resource counts: `Tiles`, `EditableImages`, `EditableImageBytes`, `EditableImageCap` (all EditableImages share a 64 MB budget; scrolled-away tiles are freed/recycled), `Instances`. |
|
||||
| `ImGui_ImplRoblox.SetStageTiming(on)` | Opt-in per-stage timing of the last rendered frame in `GetStats().Frame`: seconds for `Compare`, `Collect`, `Hash`, `Raster`, `Upload`, `Other`, `Total`, plus `TilesRasterized`, `PixelsRasterized` (dirty-rect area), `Uploads`, `TilesCreated`, `TilesFreed`. Off by default (one boolean check per stage). |
|
||||
| `ImGui_ImplRoblox.AddFile(path, bytes)` | Register a file (e.g. a `.ttf`) so `io.Fonts:AddFontFromFileTTF(path, size)` can load it. |
|
||||
|
||||
Fonts: ProggyClean (default), ProggyTiny, ProggyForever, Cousine, DroidSans, Karla and Roboto are embedded from [fonts/](/fonts/):
|
||||
@@ -163,9 +166,46 @@ io.Fonts:AddFontDefault()
|
||||
io.Fonts:AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0)
|
||||
```
|
||||
|
||||
### Parallel rendering (opt-in, Roblox)
|
||||
|
||||
Changed tiles can be rasterized on Actors (parallel Luau) instead of the main thread, still uploaded **in the same frame**. It is part of the backend but off until you call `ImGui_ImplRoblox.EnableParallel` (when off, the backend only checks one field per redrawn tile).
|
||||
|
||||
- The rasterizer is [backends/roblox/raster.lua](/backends/roblox/raster.lua): pure buffer code used by both the backend and the worker, so the pixels are identical (tested by `tools/test/scripts/t_parallel.luau`).
|
||||
- `build/ImGuiWorker.client.luau` (LocalScript): the Actor script, with the rasterizer pasted in by `bundle.py` (self-contained, no `require`). It must be the child `Worker` of the `ImGui` module (or pass `{ Worker = ... }`). Scripts can't be created at runtime, so the backend clones it into each Actor it creates (under `PlayerScripts`). The template does nothing where it sits.
|
||||
|
||||
Rojo layout (as in [`default.project.json`](/default.project.json)):
|
||||
|
||||
```json
|
||||
"ImGui": {
|
||||
"$path": "build/ImGuiTyped.luau",
|
||||
"Impl": { "$path": "build/ImGui.luau" },
|
||||
"Worker": { "$path": "build/ImGuiWorker.client.luau" }
|
||||
}
|
||||
```
|
||||
|
||||
```lua
|
||||
ImGui_ImplRoblox.EnableParallel({ Actors = 4 }) -- also: MinTiles = 1, MinPixels = 2048, MaxBytesPerPixel = 0, Worker
|
||||
|
||||
RunService.PreSimulation:Connect(function() -- NOT RenderStepped (see below)
|
||||
ImGui_ImplRoblox.NewFrame()
|
||||
ImGui.NewFrame()
|
||||
-- ... your windows ...
|
||||
ImGui.Render()
|
||||
ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData()) -- collects, hashes, packs and dispatches the dirty tiles
|
||||
end)
|
||||
-- PostSimulation (connected by EnableParallel): FinishParallel() uploads every result, and rasterizes on the main
|
||||
-- thread whatever didn't come back. ImGui_ImplRoblox.DisableParallel() goes back to inline rasterization.
|
||||
```
|
||||
|
||||
**Frame ordering.** A Roblox frame runs `PreRender` (`RenderStepped`), `PreAnimation`, `PreSimulation` (`Stepped`), `PostSimulation` (`Heartbeat`). What the scripts changed up to the end of `PostSimulation` of frame N is drawn by the render that follows the next `PreRender` (N+1), together with whatever `PreRender` N+1 changes. So `RenderDrawData` in `PreSimulation` (layer `Position`/`ZIndex`/`Visible` changes) plus `Finish` in `PostSimulation` (the pixels) land in the same render: no frame shows moved layers with old pixels. Actor work requested in `PreSimulation` runs in that frame's parallel phases, and the results are back before `PostSimulation`.
|
||||
- The executor only dispatches between `PreAnimation` and its `Finish`. A `RenderDrawData` anywhere else (`RenderStepped`/`PreRender`, after `Finish`, with too little work: fewer than `MinTiles` tiles or `MinPixels` dirty pixels, or with dense primitives: more than `MaxBytesPerPixel` packed payload bytes per dirty pixel, `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()`).
|
||||
|
||||
### How it works (Roblox backend)
|
||||
|
||||
Dear ImGui itself never draws anything: every frame it produces `ImDrawData`, a list of textured, coloured triangles plus clip rectangles, and expects the backend to put them on screen. On desktop that is a few GPU draw calls. Roblox has no API to draw arbitrary triangles in 2D, so the Roblox backend ([backends/imgui_impl_roblox.lua](/backends/imgui_impl_roblox.lua)) does what a GPU would do, in Luau, and pushes the result into **EditableImages**.
|
||||
Dear ImGui itself never draws anything: every frame it produces `ImDrawData`, a list of textured, coloured triangles plus clip rectangles, and expects the backend to put them on screen. On desktop that is a few GPU draw calls. Roblox has no API to draw arbitrary triangles in 2D, so the Roblox backend ([backends/roblox/](/backends/roblox): `imgui_impl_roblox.lua` + its modules `textures`, `layers`, `render`, `parallel`, `overlays`, `raster`) does what a GPU would do, in Luau, and pushes the result into **EditableImages**.
|
||||
|
||||
**Why software rasterization?** The alternatives don't fit Dear ImGui:
|
||||
- *One GUI Instance per widget/shape* (what most Roblox UI libraries do) means re-creating, re-parenting or diffing thousands of Instances every frame, can't express anti-aliased curves, per-vertex gradients or font-atlas glyphs, and would no longer be Dear ImGui's renderer output.
|
||||
@@ -178,7 +218,7 @@ The cost is CPU time in Luau, so the backend is built around **not drawing**:
|
||||
3. **Scrolling reuses pixels.** Window content is a separate layer inside a `ClipsDescendants` frame sized to the window's visible area, positioned at the scroll offset. Scrolling moves it like dragging moves a window; only rows entering view are drawn. Decorations (title bar, borders, scrollbar) stay in their own layers.
|
||||
4. **Skipping unchanged windows.** Vertices are stored in a flat Luau `buffer` (36 bytes each) instead of tables. Before any per-tile work, a window's raw vertex/index bytes are compared with last frame's; if identical, its layers are just restacked.
|
||||
5. **Fast rasterizer.** `@native` functions; axis-aligned quads (most rects and every glyph) take a span-fill path, flat rows are copied instead of re-blended, gradient rects (color pickers) are filled per row, and only real triangles (anti-aliased edges, curves) use the generic edge-function rasterizer.
|
||||
6. **Render rate.** Tiles update at most `SetRenderRate(hz)` times per second (default 60), optionally lower while scrolling/resizing (`SetBusyRenderRate`). Your UI code and Dear ImGui's logic still run every frame, so input is never dropped.
|
||||
6. **Redraw budget.** Changed tiles are redrawn in the frame they change. Optionally, `SetRedrawBudget(ms)` caps the redraw time per frame; tiles over it keep their old pixels and follow on the next frames. Redraws are capped at 60 per second by default (`SetRenderRate(hz)`, `0` = uncapped), optionally lower while busy with `SetBusyRenderRate(hz)`. Your UI code and Dear ImGui's logic still run every frame, so input is never dropped.
|
||||
|
||||
**Input.** Mouse and keys come from `UserInputService`. While the mouse is over Dear ImGui (`io.WantCaptureMouse`), the tiles are `Active`, so clicks and the wheel don't reach the game (camera zoom). Typing comes from key codes by default (printable ASCII). Call `ImGui_ImplRoblox.SetTextProxy(true)` to opt in to a hidden `TextBox` that holds focus while a text field is active: the OS then delivers typing (any layout), paste and copy/cut through it, and its text mirrors Dear ImGui's current selection. Fonts are TTFs rasterized by the ported stb_truetype into the font atlas, which becomes a backend texture like any image (`CreateTexture` works for your own pixels too).
|
||||
|
||||
@@ -188,28 +228,26 @@ The cost is CPU time in Luau, so the backend is built around **not drawing**:
|
||||
|
||||
| Backend | File | Build | Renderer | Example |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Roblox (primary) | [backends/imgui_impl_roblox.lua](/backends/imgui_impl_roblox.lua) | `python3 tools/bundle.py` | Luau software rasterizer into EditableImage tiles | [examples/example_roblox](/examples/example_roblox) |
|
||||
| LÖVE 11.x | [backends/imgui_impl_love.lua](/backends/imgui_impl_love.lua) | `python3 tools/bundle.py --target love` | GPU, one `Mesh` per draw list | [examples/example_love](/examples/example_love) |
|
||||
| Roblox (primary) | [backends/roblox/imgui_impl_roblox.lua](/backends/roblox/imgui_impl_roblox.lua) | `python3 tools/bundle.py` | Luau software rasterizer into EditableImage tiles | [examples/example_roblox](/examples/example_roblox) |
|
||||
| LÖVE 11.x | [backends/love/imgui_impl_love.lua](/backends/love/imgui_impl_love.lua) | `python3 tools/bundle.py --target love` | GPU, one `Mesh` per draw list | [examples/example_love](/examples/example_love) |
|
||||
|
||||
A backend implements the usual Dear ImGui contract (`Init`, `NewFrame`, `RenderDrawData`, input → `io:Add*Event`, texture updates via `ImTextureData`). Adding another Lua host means a new `backends/imgui_impl_<name>.lua` plus a `--target` in `tools/bundle.py`.
|
||||
A backend implements the usual Dear ImGui contract (`Init`, `NewFrame`, `RenderDrawData`, input → `io:Add*Event`, texture updates via `ImTextureData`). Adding another Lua host means a new `backends/<name>/imgui_impl_<name>.lua` plus a `--target` in `tools/bundle.py`.
|
||||
|
||||
#### LÖVE
|
||||
|
||||
The same sources also build for [LÖVE](https://love2d.org) (LuaJIT), with a GPU renderer in [backends/imgui_impl_love.lua](/backends/imgui_impl_love.lua):
|
||||
The same sources also build for [LÖVE](https://love2d.org) (LuaJIT), with a GPU renderer in [backends/love/imgui_impl_love.lua](/backends/love/imgui_impl_love.lua):
|
||||
|
||||
```
|
||||
python3 tools/bundle.py --target love # -> build/imgui_love.lua (LÖVE backend + shims from the LÖVE backend)
|
||||
love examples/example_love
|
||||
```
|
||||
|
||||
Roblox stays the primary target: the Roblox build is untouched by this (no shims, `@native` kept); the LÖVE build strips `@native` and adds small `bit32`/`buffer`/`utf8`/`table` shims (the COMPAT section of [backends/imgui_impl_love.lua](/backends/imgui_impl_love.lua)). `tools/test/love/run.sh` checks that LuaJIT produces exactly the same draw data as Luau.
|
||||
|
||||
[examples/example_shared/app.lua](/examples/example_shared/app.lua) is one UI that runs unchanged on both: `roblox.client.luau` (Rojo: `examples/example_shared/default.project.json`) and `main.lua` (`love examples/example_shared`) are the only platform code. Write shared UI code in plain Lua 5.1 syntax (no `+=`, `//`, `continue`).
|
||||
Roblox stays the primary target: the Roblox build is untouched by this (no shims, `@native` kept); the LÖVE build strips `@native` and adds small `bit32`/`buffer`/`utf8`/`table` shims (the COMPAT section of [backends/love/imgui_impl_love.lua](/backends/love/imgui_impl_love.lua)). `tools/test/love/run.sh` checks that LuaJIT produces exactly the same draw data as Luau.
|
||||
|
||||
#### Prebuilt releases
|
||||
|
||||
Every push to `master` publishes a rolling `latest` release, and every `v*` tag a versioned release ([.github/workflows/release.yml](/.github/workflows/release.yml)), with:
|
||||
`ImGui.luau` / `ImGui-nodemo.luau` (Roblox ModuleScript), `imgui_love.lua` / `imgui_love-nodemo.lua` (LÖVE), and `imgui-luau-roblox-*.zip` / `imgui-luau-love-*.zip` (bundle + examples).
|
||||
`ImGui.luau` (Roblox ModuleScript), `imgui_love.lua` (LÖVE), their minified `.min` variants, and `imgui-luau-roblox-*.zip` / `imgui-luau-love-*.zip` (bundle + examples). For a library-only build without the demo, build it yourself with `--no-demo`.
|
||||
|
||||
### Differences from C++ Dear ImGui
|
||||
|
||||
@@ -274,6 +312,22 @@ python3 tools/test/run.py --main tools/test/scripts/t_tables.luau --frames 120 -
|
||||
|
||||
See [docs/PORTING.md](/docs/PORTING.md) for the porting rules.
|
||||
|
||||
### Extensions (work in progress)
|
||||
|
||||
Separate repos, included as submodules under `extensions/` (clone with `--recursive`):
|
||||
|
||||
- [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))`.
|
||||
|
||||
### Not ported yet
|
||||
|
||||
Multi-select / box-select, typing-select, the Assets Browser example, the Item Picker and a few smaller items. The full list is in [docs/TODO.txt](/docs/TODO.txt).
|
||||
|
||||
@@ -30,27 +30,41 @@ jobs:
|
||||
unzip -q luau.zip -d luau && chmod +x luau/* && echo "$PWD/luau" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Build
|
||||
env:
|
||||
IMGUI_BUNDLE_STRICT: "1" # fail if enum folding (needs the luau CLI above) can't run
|
||||
run: |
|
||||
mkdir -p dist
|
||||
python3 tools/bundle.py dist/roblox # ImGui.luau (library + demo)
|
||||
python3 tools/bundle.py --no-demo dist/roblox-nodemo # ImGui.luau (library only)
|
||||
python3 tools/bundle.py dist/roblox # ImGui.luau (library + demo), ImGuiTyped.luau, ImGuiWorker.client.luau
|
||||
python3 tools/bundle.py --target love dist/love # imgui_love.lua (library + demo)
|
||||
python3 tools/bundle.py --target love --no-demo dist/love-nodemo
|
||||
# minified variants (comments/whitespace stripped, same code): tools/minify.py
|
||||
python3 tools/minify.py dist/roblox/ImGui.luau dist/ImGui.min.luau
|
||||
python3 tools/minify.py dist/love/imgui_love.lua dist/imgui_love.min.lua
|
||||
|
||||
- name: Check
|
||||
run: |
|
||||
python3 tools/sync_github_readme.py --check
|
||||
luau-compile --null dist/roblox/ImGui.luau
|
||||
luau-compile --null dist/roblox-nodemo/ImGui.luau
|
||||
luau-compile --null dist/roblox/ImGuiWorker.client.luau
|
||||
! grep -n "require" dist/roblox/ImGuiWorker.client.luau # parallel worker: self-contained (worker.luau + raster.lua inlined)
|
||||
sed 's|require(script:WaitForChild("Impl"))|nil|' dist/roblox/ImGuiTyped.luau > /tmp/ImGuiTyped.luau && luau-analyze /tmp/ImGuiTyped.luau
|
||||
luajit -bl dist/love/imgui_love.lua > /dev/null
|
||||
luajit -bl dist/love-nodemo/imgui_love.lua > /dev/null
|
||||
python3 tools/minify.py --test
|
||||
luau-compile --null dist/ImGui.min.luau
|
||||
luajit -bl dist/imgui_love.min.lua > /dev/null
|
||||
python3 tools/test/run.py --main tools/test/scripts/t_readme.luau --frames 30 --quiet --roblox --timeout 300 | tee /tmp/r.txt
|
||||
grep -q "README OK" /tmp/r.txt
|
||||
python3 tools/test/run.py --main tools/test/scripts/t_cached_window.luau --frames 130 --quiet --roblox --timeout 300 | tee /tmp/c.txt
|
||||
grep -q "CACHED OK" /tmp/c.txt
|
||||
MINIFY=1 python3 tools/test/run.py --main tools/test/scripts/t_readme.luau --frames 30 --quiet --roblox --timeout 300 | tee /tmp/rm.txt
|
||||
grep -q "README OK" /tmp/rm.txt
|
||||
python3 tools/test/run.py --main tools/test/scripts/t_fixes.luau --frames 55 --quiet --roblox --timeout 300 | tee /tmp/f.txt
|
||||
grep -q "FIXES OK" /tmp/f.txt
|
||||
python3 tools/bundle.py --target love >/dev/null
|
||||
luajit tools/test/love/t_drawhash.lua 60 Widgets,Basic
|
||||
luajit tools/test/love/t_drawhash.lua 60 Widgets,Basic | tee /tmp/h.txt
|
||||
cp build/imgui_love.lua /tmp/imgui_love.lua && cp dist/imgui_love.min.lua build/imgui_love.lua
|
||||
luajit tools/test/love/t_drawhash.lua 60 Widgets,Basic | tee /tmp/hm.txt
|
||||
cp /tmp/imgui_love.lua build/imgui_love.lua
|
||||
diff /tmp/h.txt /tmp/hm.txt # minified LÖVE bundle draws exactly the same
|
||||
luajit tools/test/love/t_examples.lua
|
||||
|
||||
- name: Package
|
||||
@@ -58,16 +72,15 @@ jobs:
|
||||
V="${GITHUB_REF_NAME}"
|
||||
cd dist
|
||||
cp roblox/ImGui.luau ImGui.luau
|
||||
cp roblox-nodemo/ImGui.luau ImGui-nodemo.luau
|
||||
cp love/imgui_love.lua imgui_love.lua
|
||||
cp love-nodemo/imgui_love.lua imgui_love-nodemo.lua
|
||||
cp roblox/ImGuiWorker.client.luau ImGuiWorker.client.luau
|
||||
# Roblox: module + example LocalScript + Rojo project
|
||||
mkdir -p pkg-roblox/build && cp ImGui.luau roblox/ImGuiTyped.luau pkg-roblox/build/ && cp ../default.project.json pkg-roblox/
|
||||
mkdir -p pkg-roblox/examples && cp -r ../examples/example_roblox ../examples/example_shared pkg-roblox/examples/
|
||||
mkdir -p pkg-roblox/build && cp ImGui.luau roblox/ImGuiTyped.luau ImGuiWorker.client.luau pkg-roblox/build/ && cp ../default.project.json pkg-roblox/
|
||||
mkdir -p pkg-roblox/examples && cp -r ../examples/example_roblox ../examples/example_roblox_parallel pkg-roblox/examples/
|
||||
(cd pkg-roblox && zip -qr ../imgui-luau-roblox-$V.zip .)
|
||||
# LÖVE: bundle + fonts + examples (run: love examples/example_love)
|
||||
mkdir -p pkg-love/build && cp imgui_love.lua pkg-love/build/ && cp -r ../fonts pkg-love/ && rm -f pkg-love/fonts/*.lua
|
||||
mkdir -p pkg-love/examples && cp -r ../examples/example_love ../examples/example_shared pkg-love/examples/
|
||||
mkdir -p pkg-love/examples && cp -r ../examples/example_love pkg-love/examples/
|
||||
(cd pkg-love && zip -qr ../imgui-luau-love-$V.zip .)
|
||||
ls -la
|
||||
|
||||
@@ -77,9 +90,10 @@ jobs:
|
||||
with:
|
||||
files: |
|
||||
dist/ImGui.luau
|
||||
dist/ImGui-nodemo.luau
|
||||
dist/ImGuiWorker.client.luau
|
||||
dist/imgui_love.lua
|
||||
dist/imgui_love-nodemo.lua
|
||||
dist/*.min.luau
|
||||
dist/*.min.lua
|
||||
dist/*.zip
|
||||
generate_release_notes: true
|
||||
|
||||
@@ -92,7 +106,7 @@ jobs:
|
||||
grep -q "^version = \"${GITHUB_REF_NAME#v}\"" wally.toml || { echo "wally.toml version != tag"; exit 1; }
|
||||
curl -fsSL -o wally.zip https://github.com/UpliftGames/wally/releases/download/v0.3.2/wally-v0.3.2-linux.zip
|
||||
unzip -q wally.zip -d wallybin && chmod +x wallybin/wally
|
||||
mkdir -p dist/wally/src && cp wally.toml dist/wally/ && cp dist/roblox/ImGuiTyped.luau dist/wally/src/init.luau && cp dist/roblox/ImGui.luau dist/wally/src/Impl.luau
|
||||
mkdir -p dist/wally/src && cp wally.toml dist/wally/ && cp dist/roblox/ImGuiTyped.luau dist/wally/src/init.luau && cp dist/roblox/ImGui.luau dist/wally/src/Impl.luau && cp dist/roblox/ImGuiWorker.client.luau dist/wally/src/Worker.client.luau
|
||||
echo '{"name":"imgui-luau","tree":{"$path":"src"}}' > dist/wally/default.project.json
|
||||
wallybin/wally login --token "$WALLY_TOKEN"
|
||||
wallybin/wally publish --project-path dist/wally
|
||||
@@ -105,4 +119,4 @@ jobs:
|
||||
gh release delete latest --yes --cleanup-tag || true
|
||||
gh release create latest --latest --title "Latest build (${GITHUB_SHA::7})" \
|
||||
--notes "Automatic build of ${GITHUB_SHA} on ${GITHUB_REF_NAME}. Tag a commit v* for a versioned release." \
|
||||
dist/ImGui.luau dist/ImGui-nodemo.luau dist/imgui_love.lua dist/imgui_love-nodemo.lua dist/*.zip
|
||||
dist/ImGui.luau dist/ImGuiWorker.client.luau dist/imgui_love.lua dist/*.min.luau dist/*.min.lua dist/*.zip
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
[submodule "extensions/imguicolortextedit-luau"]
|
||||
path = extensions/imguicolortextedit-luau
|
||||
url = https://github.com/4DBug/imguicolortextedit-luau.git
|
||||
[submodule "extensions/imguizmo-luau"]
|
||||
path = extensions/imguizmo-luau
|
||||
url = https://github.com/4DBug/imguizmo-luau.git
|
||||
[submodule "extensions/implot-luau"]
|
||||
path = extensions/implot-luau
|
||||
url = https://github.com/4DBug/implot-luau.git
|
||||
[submodule "extensions/imnodes-luau"]
|
||||
path = extensions/imnodes-luau
|
||||
url = https://github.com/4DBug/imnodes-luau.git
|
||||
[submodule "extensions/implot3d-luau"]
|
||||
path = extensions/implot3d-luau
|
||||
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
|
||||
@@ -22,7 +22,7 @@ This port brings that to Roblox (and LÖVE): debug overlays, admin panels, in-ga
|
||||
|
||||
### Usage
|
||||
|
||||
**The core of Dear ImGui is a set of files with no dependencies**, plus one platform backend from [backends/](backends/). `tools/bundle.py` combines them into a single file: `build/ImGui.luau` (ModuleScript, Roblox backend) or, with `--target love`, `build/imgui_love.lua` (LÖVE backend). Your UI code is the same for both.
|
||||
**The core of Dear ImGui is a set of files with no dependencies**, plus one platform backend from [backends/](backends/) (`backends/roblox/`, `backends/love/`). `tools/bundle.py` combines them into a single file: `build/ImGui.luau` (ModuleScript, Roblox backend) or, with `--target love`, `build/imgui_love.lua` (LÖVE backend). Your UI code is the same for both.
|
||||
|
||||
Dear ImGui is **immediate mode**: you call widget functions every frame, and their return values tell you what the user did. There is no widget object to keep in sync with your state.
|
||||
|
||||
@@ -113,7 +113,7 @@ The Style Editor (`ImGui.ShowStyleEditor()`) and the Metrics/Debugger (`ImGui.Sh
|
||||
|
||||
### Getting Started & Integration (Roblox)
|
||||
|
||||
With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/imgui-luau@0.1.3"` 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`.
|
||||
@@ -148,9 +148,12 @@ Backend options:
|
||||
| --- | --- |
|
||||
| `ImGui_ImplRoblox.Init(parent, render_scale)` | `render_scale` = your OS display scale renders at physical-pixel resolution (crisper, same size as desktop imgui). |
|
||||
| `ImGui_ImplRoblox.SetRenderScale(scale)` | Change it at runtime. |
|
||||
| `ImGui_ImplRoblox.SetRenderRate(hz)` | Max tile redraws per second (default 60, `0` = every frame). Your code still runs every frame. |
|
||||
| `ImGui_ImplRoblox.SetRenderRate(hz)` | Max tile redraws per second (default `60`; `0` = every frame). Your code still runs every frame. |
|
||||
| `ImGui_ImplRoblox.SetRedrawBudget(ms)` | Max milliseconds per frame spent redrawing changed tiles (opt-in; default `0` = no limit, every change is drawn the same frame). With a budget, tiles over it keep their old pixels for a few frames, so big changes are spread over frames instead of one long frame (parts of the UI may update a frame or two apart). |
|
||||
| `ImGui_ImplRoblox.SetBusyRenderRate(hz)` | Optional lower redraw rate while scrolling, resizing or moving windows (default off). |
|
||||
| `ImGui_ImplRoblox.SetProfiling(true)` | MicroProfiler (Ctrl+F6) labels for every backend stage. |
|
||||
| `ImGui_ImplRoblox.GetStats()` | Live resource counts: `Tiles`, `EditableImages`, `EditableImageBytes`, `EditableImageCap` (all EditableImages share a 64 MB budget; scrolled-away tiles are freed/recycled), `Instances`. |
|
||||
| `ImGui_ImplRoblox.SetStageTiming(on)` | Opt-in per-stage timing of the last rendered frame in `GetStats().Frame`: seconds for `Compare`, `Collect`, `Hash`, `Raster`, `Upload`, `Other`, `Total`, plus `TilesRasterized`, `PixelsRasterized` (dirty-rect area), `Uploads`, `TilesCreated`, `TilesFreed`. Off by default (one boolean check per stage). |
|
||||
| `ImGui_ImplRoblox.AddFile(path, bytes)` | Register a file (e.g. a `.ttf`) so `io.Fonts:AddFontFromFileTTF(path, size)` can load it. |
|
||||
|
||||
Fonts: ProggyClean (default), ProggyTiny, ProggyForever, Cousine, DroidSans, Karla and Roboto are embedded from [fonts/](fonts/):
|
||||
@@ -160,9 +163,46 @@ io.Fonts:AddFontDefault()
|
||||
io.Fonts:AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0)
|
||||
```
|
||||
|
||||
### Parallel rendering (opt-in, Roblox)
|
||||
|
||||
Changed tiles can be rasterized on Actors (parallel Luau) instead of the main thread, still uploaded **in the same frame**. It is part of the backend but off until you call `ImGui_ImplRoblox.EnableParallel` (when off, the backend only checks one field per redrawn tile).
|
||||
|
||||
- The rasterizer is [backends/roblox/raster.lua](backends/roblox/raster.lua): pure buffer code used by both the backend and the worker, so the pixels are identical (tested by `tools/test/scripts/t_parallel.luau`).
|
||||
- `build/ImGuiWorker.client.luau` (LocalScript): the Actor script, with the rasterizer pasted in by `bundle.py` (self-contained, no `require`). It must be the child `Worker` of the `ImGui` module (or pass `{ Worker = ... }`). Scripts can't be created at runtime, so the backend clones it into each Actor it creates (under `PlayerScripts`). The template does nothing where it sits.
|
||||
|
||||
Rojo layout (as in [`default.project.json`](default.project.json)):
|
||||
|
||||
```json
|
||||
"ImGui": {
|
||||
"$path": "build/ImGuiTyped.luau",
|
||||
"Impl": { "$path": "build/ImGui.luau" },
|
||||
"Worker": { "$path": "build/ImGuiWorker.client.luau" }
|
||||
}
|
||||
```
|
||||
|
||||
```lua
|
||||
ImGui_ImplRoblox.EnableParallel({ Actors = 4 }) -- also: MinTiles = 1, MinPixels = 2048, MaxBytesPerPixel = 0, Worker
|
||||
|
||||
RunService.PreSimulation:Connect(function() -- NOT RenderStepped (see below)
|
||||
ImGui_ImplRoblox.NewFrame()
|
||||
ImGui.NewFrame()
|
||||
-- ... your windows ...
|
||||
ImGui.Render()
|
||||
ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData()) -- collects, hashes, packs and dispatches the dirty tiles
|
||||
end)
|
||||
-- PostSimulation (connected by EnableParallel): FinishParallel() uploads every result, and rasterizes on the main
|
||||
-- thread whatever didn't come back. ImGui_ImplRoblox.DisableParallel() goes back to inline rasterization.
|
||||
```
|
||||
|
||||
**Frame ordering.** A Roblox frame runs `PreRender` (`RenderStepped`), `PreAnimation`, `PreSimulation` (`Stepped`), `PostSimulation` (`Heartbeat`). What the scripts changed up to the end of `PostSimulation` of frame N is drawn by the render that follows the next `PreRender` (N+1), together with whatever `PreRender` N+1 changes. So `RenderDrawData` in `PreSimulation` (layer `Position`/`ZIndex`/`Visible` changes) plus `Finish` in `PostSimulation` (the pixels) land in the same render: no frame shows moved layers with old pixels. Actor work requested in `PreSimulation` runs in that frame's parallel phases, and the results are back before `PostSimulation`.
|
||||
- The executor only dispatches between `PreAnimation` and its `Finish`. A `RenderDrawData` anywhere else (`RenderStepped`/`PreRender`, after `Finish`, with too little work: fewer than `MinTiles` tiles or `MinPixels` dirty pixels, or with dense primitives: more than `MaxBytesPerPixel` packed payload bytes per dirty pixel, `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()`).
|
||||
|
||||
### How it works (Roblox backend)
|
||||
|
||||
Dear ImGui itself never draws anything: every frame it produces `ImDrawData`, a list of textured, coloured triangles plus clip rectangles, and expects the backend to put them on screen. On desktop that is a few GPU draw calls. Roblox has no API to draw arbitrary triangles in 2D, so the Roblox backend ([backends/imgui_impl_roblox.lua](backends/imgui_impl_roblox.lua)) does what a GPU would do, in Luau, and pushes the result into **EditableImages**.
|
||||
Dear ImGui itself never draws anything: every frame it produces `ImDrawData`, a list of textured, coloured triangles plus clip rectangles, and expects the backend to put them on screen. On desktop that is a few GPU draw calls. Roblox has no API to draw arbitrary triangles in 2D, so the Roblox backend ([backends/roblox/](backends/roblox): `imgui_impl_roblox.lua` + its modules `textures`, `layers`, `render`, `parallel`, `overlays`, `raster`) does what a GPU would do, in Luau, and pushes the result into **EditableImages**.
|
||||
|
||||
**Why software rasterization?** The alternatives don't fit Dear ImGui:
|
||||
- *One GUI Instance per widget/shape* (what most Roblox UI libraries do) means re-creating, re-parenting or diffing thousands of Instances every frame, can't express anti-aliased curves, per-vertex gradients or font-atlas glyphs, and would no longer be Dear ImGui's renderer output.
|
||||
@@ -175,7 +215,7 @@ The cost is CPU time in Luau, so the backend is built around **not drawing**:
|
||||
3. **Scrolling reuses pixels.** Window content is a separate layer inside a `ClipsDescendants` frame sized to the window's visible area, positioned at the scroll offset. Scrolling moves it like dragging moves a window; only rows entering view are drawn. Decorations (title bar, borders, scrollbar) stay in their own layers.
|
||||
4. **Skipping unchanged windows.** Vertices are stored in a flat Luau `buffer` (36 bytes each) instead of tables. Before any per-tile work, a window's raw vertex/index bytes are compared with last frame's; if identical, its layers are just restacked.
|
||||
5. **Fast rasterizer.** `@native` functions; axis-aligned quads (most rects and every glyph) take a span-fill path, flat rows are copied instead of re-blended, gradient rects (color pickers) are filled per row, and only real triangles (anti-aliased edges, curves) use the generic edge-function rasterizer.
|
||||
6. **Render rate.** Tiles update at most `SetRenderRate(hz)` times per second (default 60), optionally lower while scrolling/resizing (`SetBusyRenderRate`). Your UI code and Dear ImGui's logic still run every frame, so input is never dropped.
|
||||
6. **Redraw budget.** Changed tiles are redrawn in the frame they change. Optionally, `SetRedrawBudget(ms)` caps the redraw time per frame; tiles over it keep their old pixels and follow on the next frames. Redraws are capped at 60 per second by default (`SetRenderRate(hz)`, `0` = uncapped), optionally lower while busy with `SetBusyRenderRate(hz)`. Your UI code and Dear ImGui's logic still run every frame, so input is never dropped.
|
||||
|
||||
**Input.** Mouse and keys come from `UserInputService`. While the mouse is over Dear ImGui (`io.WantCaptureMouse`), the tiles are `Active`, so clicks and the wheel don't reach the game (camera zoom). Typing comes from key codes by default (printable ASCII). Call `ImGui_ImplRoblox.SetTextProxy(true)` to opt in to a hidden `TextBox` that holds focus while a text field is active: the OS then delivers typing (any layout), paste and copy/cut through it, and its text mirrors Dear ImGui's current selection. Fonts are TTFs rasterized by the ported stb_truetype into the font atlas, which becomes a backend texture like any image (`CreateTexture` works for your own pixels too).
|
||||
|
||||
@@ -185,28 +225,26 @@ The cost is CPU time in Luau, so the backend is built around **not drawing**:
|
||||
|
||||
| Backend | File | Build | Renderer | Example |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Roblox (primary) | [backends/imgui_impl_roblox.lua](backends/imgui_impl_roblox.lua) | `python3 tools/bundle.py` | Luau software rasterizer into EditableImage tiles | [examples/example_roblox](examples/example_roblox) |
|
||||
| LÖVE 11.x | [backends/imgui_impl_love.lua](backends/imgui_impl_love.lua) | `python3 tools/bundle.py --target love` | GPU, one `Mesh` per draw list | [examples/example_love](examples/example_love) |
|
||||
| Roblox (primary) | [backends/roblox/imgui_impl_roblox.lua](backends/roblox/imgui_impl_roblox.lua) | `python3 tools/bundle.py` | Luau software rasterizer into EditableImage tiles | [examples/example_roblox](examples/example_roblox) |
|
||||
| LÖVE 11.x | [backends/love/imgui_impl_love.lua](backends/love/imgui_impl_love.lua) | `python3 tools/bundle.py --target love` | GPU, one `Mesh` per draw list | [examples/example_love](examples/example_love) |
|
||||
|
||||
A backend implements the usual Dear ImGui contract (`Init`, `NewFrame`, `RenderDrawData`, input → `io:Add*Event`, texture updates via `ImTextureData`). Adding another Lua host means a new `backends/imgui_impl_<name>.lua` plus a `--target` in `tools/bundle.py`.
|
||||
A backend implements the usual Dear ImGui contract (`Init`, `NewFrame`, `RenderDrawData`, input → `io:Add*Event`, texture updates via `ImTextureData`). Adding another Lua host means a new `backends/<name>/imgui_impl_<name>.lua` plus a `--target` in `tools/bundle.py`.
|
||||
|
||||
#### LÖVE
|
||||
|
||||
The same sources also build for [LÖVE](https://love2d.org) (LuaJIT), with a GPU renderer in [backends/imgui_impl_love.lua](backends/imgui_impl_love.lua):
|
||||
The same sources also build for [LÖVE](https://love2d.org) (LuaJIT), with a GPU renderer in [backends/love/imgui_impl_love.lua](backends/love/imgui_impl_love.lua):
|
||||
|
||||
```
|
||||
python3 tools/bundle.py --target love # -> build/imgui_love.lua (LÖVE backend + shims from the LÖVE backend)
|
||||
love examples/example_love
|
||||
```
|
||||
|
||||
Roblox stays the primary target: the Roblox build is untouched by this (no shims, `@native` kept); the LÖVE build strips `@native` and adds small `bit32`/`buffer`/`utf8`/`table` shims (the COMPAT section of [backends/imgui_impl_love.lua](backends/imgui_impl_love.lua)). `tools/test/love/run.sh` checks that LuaJIT produces exactly the same draw data as Luau.
|
||||
|
||||
[examples/example_shared/app.lua](examples/example_shared/app.lua) is one UI that runs unchanged on both: `roblox.client.luau` (Rojo: `examples/example_shared/default.project.json`) and `main.lua` (`love examples/example_shared`) are the only platform code. Write shared UI code in plain Lua 5.1 syntax (no `+=`, `//`, `continue`).
|
||||
Roblox stays the primary target: the Roblox build is untouched by this (no shims, `@native` kept); the LÖVE build strips `@native` and adds small `bit32`/`buffer`/`utf8`/`table` shims (the COMPAT section of [backends/love/imgui_impl_love.lua](backends/love/imgui_impl_love.lua)). `tools/test/love/run.sh` checks that LuaJIT produces exactly the same draw data as Luau.
|
||||
|
||||
#### Prebuilt releases
|
||||
|
||||
Every push to `master` publishes a rolling `latest` release, and every `v*` tag a versioned release ([.github/workflows/release.yml](.github/workflows/release.yml)), with:
|
||||
`ImGui.luau` / `ImGui-nodemo.luau` (Roblox ModuleScript), `imgui_love.lua` / `imgui_love-nodemo.lua` (LÖVE), and `imgui-luau-roblox-*.zip` / `imgui-luau-love-*.zip` (bundle + examples).
|
||||
`ImGui.luau` (Roblox ModuleScript), `imgui_love.lua` (LÖVE), their minified `.min` variants, and `imgui-luau-roblox-*.zip` / `imgui-luau-love-*.zip` (bundle + examples). For a library-only build without the demo, build it yourself with `--no-demo`.
|
||||
|
||||
### Differences from C++ Dear ImGui
|
||||
|
||||
@@ -271,6 +309,22 @@ python3 tools/test/run.py --main tools/test/scripts/t_tables.luau --frames 120 -
|
||||
|
||||
See [docs/PORTING.md](docs/PORTING.md) for the porting rules.
|
||||
|
||||
### Extensions (work in progress)
|
||||
|
||||
Separate repos, included as submodules under `extensions/` (clone with `--recursive`):
|
||||
|
||||
- [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))`.
|
||||
|
||||
### Not ported yet
|
||||
|
||||
Multi-select / box-select, typing-select, the Assets Browser example, the Item Picker and a few smaller items. The full list is in [docs/TODO.txt](docs/TODO.txt).
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -431,6 +431,8 @@ function ImGui_ImplLOVE_Init(opts)
|
||||
local io = ImGui.GetIO()
|
||||
local bd = { Time = love.timer.getTime(), Root = opts.root or "", Textures = {}, TextureCount = 0, Meshes = {}, FrameNo = 0 }
|
||||
io.BackendPlatformUserData = bd
|
||||
io.BackendPlatformName = "imgui_impl_love"
|
||||
io.BackendRendererName = "imgui_impl_love"
|
||||
io.BackendFlags = bit32.bor(io.BackendFlags, ImGuiBackendFlags.RendererHasTextures, ImGuiBackendFlags.RendererHasVtxOffset, ImGuiBackendFlags.HasMouseCursors)
|
||||
|
||||
local platform_io = ImGui.GetPlatformIO()
|
||||
@@ -449,6 +451,8 @@ function ImGui_ImplLOVE_Shutdown()
|
||||
for _, m in pairs(bd.Meshes) do m.Mesh:release() end
|
||||
for _, t in pairs(bd.Textures) do t:release() end
|
||||
io.BackendPlatformUserData = nil
|
||||
io.BackendPlatformName = nil
|
||||
io.BackendRendererName = nil
|
||||
io.BackendFlags = bit32.band(io.BackendFlags, bit32.bnot(bit32.bor(ImGuiBackendFlags.RendererHasTextures, ImGuiBackendFlags.RendererHasVtxOffset, ImGuiBackendFlags.HasMouseCursors)))
|
||||
end
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
-- ImGui backend for Roblox: platform, input, files, Init/Shutdown and the public API; rendering in render.lua.
|
||||
-- Requires "Allow Mesh / Image APIs" (EditableImage) in game settings.
|
||||
local Textures = IM_INCLUDE("roblox/textures.lua")
|
||||
local Layers = IM_INCLUDE("roblox/layers.lua")
|
||||
local Render = IM_INCLUDE("roblox/render.lua")
|
||||
local Parallel = IM_INCLUDE("roblox/parallel.lua")
|
||||
|
||||
local UserInputService = game:GetService("UserInputService")
|
||||
local Players = game:GetService("Players")
|
||||
|
||||
local floor, min = math.floor, math.min
|
||||
local EditableImages, PB, PE = Textures.EditableImages, Textures.PB, Textures.PE
|
||||
local ImGui_ImplRoblox_GetBackendData = Textures.GetBackendData
|
||||
local ImGui_ImplRoblox_RenderDrawData = Render.RenderDrawData
|
||||
local DestroyTiles = Layers.DestroyTiles
|
||||
|
||||
local KEY_MAP = {}
|
||||
do
|
||||
local names = {
|
||||
Return = "Enter", Escape = "Escape", Backspace = "Backspace", Tab = "Tab", Space = "Space",
|
||||
KeypadEnter = "KeypadEnter",
|
||||
Up = "UpArrow", Down = "DownArrow", Left = "LeftArrow", Right = "RightArrow",
|
||||
Home = "Home", End = "End", PageUp = "PageUp", PageDown = "PageDown", Insert = "Insert", Delete = "Delete",
|
||||
LeftControl = "LeftCtrl", RightControl = "RightCtrl", LeftShift = "LeftShift", RightShift = "RightShift",
|
||||
LeftAlt = "LeftAlt", RightAlt = "RightAlt", LeftSuper = "LeftSuper", RightSuper = "RightSuper",
|
||||
Quote = "Apostrophe", Comma = "Comma", Minus = "Minus", Period = "Period", Slash = "Slash",
|
||||
Semicolon = "Semicolon",
|
||||
Equals = "Equal", LeftBracket = "LeftBracket", BackSlash = "Backslash", RightBracket = "RightBracket",
|
||||
Backquote = "GraveAccent",
|
||||
CapsLock = "CapsLock",
|
||||
KeypadPeriod = "KeypadDecimal", KeypadDivide = "KeypadDivide", KeypadMultiply = "KeypadMultiply",
|
||||
KeypadMinus = "KeypadSubtract", KeypadPlus = "KeypadAdd", KeypadEquals = "KeypadEqual",
|
||||
}
|
||||
local digits = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }
|
||||
for i = 0, 9 do
|
||||
names[digits[i + 1]] = "K" .. i
|
||||
names["Keypad" .. digits[i + 1]] = "Keypad" .. i
|
||||
end
|
||||
for i = 1, 12 do names["F" .. i] = "F" .. i end
|
||||
for c in ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"):gmatch(".") do names[c] = c end
|
||||
|
||||
for rbx_name, imgui_name in pairs(names) do
|
||||
KEY_MAP[Enum.KeyCode[rbx_name]] = ImGuiKey[imgui_name]
|
||||
end
|
||||
end
|
||||
|
||||
-- No text input event: characters come from KeyCode.Value (printable ASCII) + a US layout shift table
|
||||
local SHIFTED = {
|
||||
["1"] = "!", ["2"] = "@", ["3"] = "#", ["4"] = "$", ["5"] = "%", ["6"] = "^", ["7"] = "&", ["8"] = "*", ["9"] = "(",
|
||||
["0"] = ")",
|
||||
["-"] = "_", ["="] = "+", ["["] = "{", ["]"] = "}", ["\\"] = "|", [";"] = ":", ["'"] = "\"", [","] = "<",
|
||||
["."] = ">", ["/"] = "?", ["`"] = "~",
|
||||
}
|
||||
|
||||
local MOUSE_BUTTONS = {
|
||||
[Enum.UserInputType.MouseButton1] = 0,
|
||||
[Enum.UserInputType.MouseButton2] = 1,
|
||||
[Enum.UserInputType.MouseButton3] = 2,
|
||||
}
|
||||
|
||||
local function ImGui_ImplRoblox_UpdateKeyModifiers()
|
||||
local io = ImGui.GetIO()
|
||||
local K = Enum.KeyCode
|
||||
local ctrl = UserInputService:IsKeyDown(K.LeftControl) or UserInputService:IsKeyDown(K.RightControl)
|
||||
local shift = UserInputService:IsKeyDown(K.LeftShift) or UserInputService:IsKeyDown(K.RightShift)
|
||||
local alt = UserInputService:IsKeyDown(K.LeftAlt) or UserInputService:IsKeyDown(K.RightAlt)
|
||||
io:AddKeyEvent(ImGuiMod_Ctrl, ctrl)
|
||||
io:AddKeyEvent(ImGuiMod_Shift, shift)
|
||||
io:AddKeyEvent(ImGuiMod_Alt, alt)
|
||||
io:AddKeyEvent(ImGuiMod_Super, UserInputService:IsKeyDown(K.LeftSuper) or UserInputService:IsKeyDown(K.RightSuper))
|
||||
return ctrl, shift, alt
|
||||
end
|
||||
|
||||
local function ImGui_ImplRoblox_UpdateMonitors(w, h)
|
||||
local platform_io = ImGui.GetPlatformIO()
|
||||
platform_io.Monitors:resize(0)
|
||||
|
||||
local imgui_monitor = ImGuiPlatformMonitor()
|
||||
ImVec2_Copy(imgui_monitor.MainSize, ImVec2(w, h))
|
||||
ImVec2_Copy(imgui_monitor.WorkSize, ImVec2(w, h))
|
||||
|
||||
platform_io.Monitors:push_back(imgui_monitor)
|
||||
end
|
||||
|
||||
-- Games can't touch the OS clipboard, so copy/paste only works inside ImGui
|
||||
local Clipboard = ""
|
||||
local function ImGui_ImplRoblox_PlatformSetClipboardText(ctx, text) Clipboard = text end
|
||||
local ProxyFocused = false
|
||||
local function ImGui_ImplRoblox_PlatformGetClipboardText(ctx) if ProxyFocused then return "" end return Clipboard end
|
||||
|
||||
local VFS = {}
|
||||
|
||||
local function ImGui_ImplRoblox_AddFile(path, bytes) VFS[path] = bytes end
|
||||
|
||||
for path, hex in pairs(IM_INCLUDE("imgui_impl_roblox_fonts.lua")) do
|
||||
VFS[path] = hex:gsub("%s", ""):gsub("%x%x", function(h) return string.char(tonumber(h, 16)) end)
|
||||
end
|
||||
|
||||
function ImStd.ImFileOpen(filename, mode)
|
||||
local data = VFS[filename]
|
||||
return data and { Data = data, Pos = 0 } or nil
|
||||
end
|
||||
|
||||
function ImStd.ImFileClose(f) end
|
||||
|
||||
function ImStd.ImFileGetSize(f) return #f.Data end
|
||||
|
||||
function ImStd.ImFileRead(f, data, count)
|
||||
local s, pos = f.Data, f.Pos
|
||||
count = min(count, #s - pos)
|
||||
for i = 1, count do data[i] = string.byte(s, pos + i) end
|
||||
f.Pos = pos + count
|
||||
return count
|
||||
end
|
||||
|
||||
function ImStd.ImFileLoadToMemory(filename, mode)
|
||||
local f = ImStd.ImFileOpen(filename, mode)
|
||||
if not f or #f.Data == 0 then return end
|
||||
local file_data = {}
|
||||
local size = ImStd.ImFileRead(f, file_data, #f.Data)
|
||||
return file_data, size
|
||||
end
|
||||
|
||||
-- render_scale: imgui pixels per Roblox UI point (default 1; 1.5 on a 150% display = physical resolution)
|
||||
function ImGui_ImplRoblox_Init(parent, render_scale)
|
||||
local io = ImGui.GetIO()
|
||||
|
||||
local gui = Instance.new("ScreenGui")
|
||||
gui.Name = "ImGui"
|
||||
gui.IgnoreGuiInset = true -- so GetMouseLocation() and the tiles share the same origin
|
||||
gui.ResetOnSpawn = false
|
||||
gui.DisplayOrder = 1000
|
||||
gui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling -- layers (one Frame per draw list) stack by ZIndex
|
||||
gui.Parent = parent or Players.LocalPlayer:WaitForChild("PlayerGui")
|
||||
|
||||
local BackendData = {
|
||||
Time = os.clock(), Gui = gui, Connections = {},
|
||||
Textures = Textures.Records, MouseX = -1, MouseY = -1,
|
||||
Layers = {}, Overlays = {}, OverlayHolders = {}, OverlayShown = {}, FrameNo = 0, Scale = render_scale or 1,
|
||||
TilesActive = false, RenderRate = 60, BusyRenderRate = 0, RedrawBudget = 0, HeartbeatCount = 0,
|
||||
NextRender = 0, LastPrimCount = 0, ForceRedraw = true,
|
||||
}
|
||||
io.BackendPlatformUserData = BackendData
|
||||
EditableImages.Backends[BackendData] = true
|
||||
io.BackendPlatformName = "imgui_impl_roblox"
|
||||
io.BackendRendererName = "imgui_impl_roblox"
|
||||
|
||||
io.BackendFlags = bit32.bor(io.BackendFlags, ImGuiBackendFlags.RendererHasTextures,
|
||||
ImGuiBackendFlags.RendererHasVtxOffset)
|
||||
|
||||
local platform_io = ImGui.GetPlatformIO()
|
||||
platform_io.Platform_SetClipboardTextFn = ImGui_ImplRoblox_PlatformSetClipboardText
|
||||
platform_io.Platform_GetClipboardTextFn = ImGui_ImplRoblox_PlatformGetClipboardText
|
||||
|
||||
local screen = gui.AbsoluteSize
|
||||
ImGui_ImplRoblox_UpdateMonitors(screen.X, screen.Y)
|
||||
|
||||
local function connect(signal, fn) table.insert(BackendData.Connections, signal:Connect(fn)) end
|
||||
|
||||
connect(UserInputService.InputBegan, function(input, game_processed)
|
||||
local io = ImGui.GetIO()
|
||||
local button = MOUSE_BUTTONS[input.UserInputType]
|
||||
if button then
|
||||
io:AddMouseSourceEvent(ImGuiMouseSource.Mouse)
|
||||
io:AddMouseButtonEvent(button, true)
|
||||
elseif input.UserInputType == Enum.UserInputType.Keyboard and (not game_processed or ProxyFocused) then
|
||||
local ctrl, shift, alt = ImGui_ImplRoblox_UpdateKeyModifiers()
|
||||
local key = KEY_MAP[input.KeyCode]
|
||||
if key then io:AddKeyEvent(key, true) end
|
||||
if ProxyFocused and (key == ImGuiKey.Backspace or key == ImGuiKey.Delete) then
|
||||
ImGui_ImplRoblox_GetBackendData().DeleteKeySeen = true
|
||||
end
|
||||
|
||||
local v = input.KeyCode.Value
|
||||
if v >= 32 and v < 127 and not (ctrl or alt) then
|
||||
local c = string.char(v)
|
||||
if shift then c = SHIFTED[c] or c:upper() end
|
||||
-- while the proxy may own input, hold the char: NewFrame types it only if the proxy didn't deliver text
|
||||
if ProxyFocused then table.insert(ImGui_ImplRoblox_GetBackendData().PendingChars, string.byte(c))
|
||||
else io:AddInputCharacter(string.byte(c)) end
|
||||
end
|
||||
end
|
||||
end)
|
||||
|
||||
connect(UserInputService.InputEnded, function(input, game_processed)
|
||||
local io = ImGui.GetIO()
|
||||
local button = MOUSE_BUTTONS[input.UserInputType]
|
||||
if button then
|
||||
io:AddMouseButtonEvent(button, false)
|
||||
elseif input.UserInputType == Enum.UserInputType.Keyboard then
|
||||
ImGui_ImplRoblox_UpdateKeyModifiers()
|
||||
local key = KEY_MAP[input.KeyCode]
|
||||
if key then io:AddKeyEvent(key, false) end
|
||||
end
|
||||
end)
|
||||
|
||||
connect(UserInputService.InputChanged, function(input, game_processed)
|
||||
if input.UserInputType == Enum.UserInputType.MouseWheel then
|
||||
ImGui.GetIO():AddMouseWheelEvent(0, input.Position.Z)
|
||||
end
|
||||
end)
|
||||
|
||||
BackendData.PendingChars = {}
|
||||
|
||||
-- Render rate cap trailing edge: the last frame submitted is always drawn, even if the app then stopped rendering
|
||||
connect(game:GetService("RunService").Heartbeat, function()
|
||||
local d = BackendData.Pending
|
||||
if d and os.clock() + 0.002 >= BackendData.NextRender then
|
||||
BackendData.Pending = nil
|
||||
ImGui_ImplRoblox_RenderDrawData(d)
|
||||
elseif BackendData.Stale and BackendData.HeartbeatCount > BackendData.StaleHeartbeat then
|
||||
ImGui_ImplRoblox_RenderDrawData(BackendData.Stale)
|
||||
end
|
||||
BackendData.HeartbeatCount += 1
|
||||
end)
|
||||
|
||||
connect(UserInputService.WindowFocused, function() ImGui.GetIO():AddFocusEvent(true) end)
|
||||
connect(UserInputService.WindowFocusReleased, function() ImGui.GetIO():AddFocusEvent(false) end)
|
||||
end
|
||||
|
||||
-- Text proxy (opt-in): a hidden TextBox holds focus while a text field is active (OS typing, paste, copy/cut)
|
||||
function ImGui_ImplRoblox_SetTextProxy(enabled)
|
||||
local BackendData = ImGui_ImplRoblox_GetBackendData()
|
||||
if not enabled then
|
||||
if BackendData.Proxy then
|
||||
BackendData.Proxy:Destroy()
|
||||
BackendData.Proxy = nil
|
||||
end
|
||||
ProxyFocused = false
|
||||
return
|
||||
end
|
||||
if BackendData.Proxy then return end
|
||||
local proxy = Instance.new("TextBox")
|
||||
proxy.Name = "TextProxy"
|
||||
proxy.BackgroundTransparency = 1
|
||||
proxy.TextTransparency = 0 -- kept opaque but parked off screen: a transparent TextBox may not get native paste
|
||||
proxy.BorderSizePixel = 0
|
||||
proxy.Size = UDim2.fromOffset(200, 20)
|
||||
proxy.Position = UDim2.fromOffset(-10000, -10000)
|
||||
proxy.MultiLine = true
|
||||
proxy.ClearTextOnFocus = false
|
||||
proxy.TextEditable = true
|
||||
proxy.Text = ""
|
||||
proxy.Parent = BackendData.Gui
|
||||
BackendData.Proxy, BackendData.ProxyText = proxy, ""
|
||||
-- Text is polled in NewFrame: TextBox change signals are deferred in Roblox
|
||||
proxy.FocusLost:Connect(function()
|
||||
if BackendData.ProxyReleasing then return end
|
||||
-- Roblox drops TextBox focus on any click, also inside imgui: only a click outside imgui ends the edit
|
||||
if ImGui.GetIO().WantCaptureMouse then
|
||||
BackendData.ProxyLostId = nil
|
||||
return
|
||||
end
|
||||
BackendData.ProxyLostId = BackendData.ProxyActiveId -- don't recapture for the same field
|
||||
local g = ImGui.GetCurrentContext()
|
||||
if g and g.ActiveId ~= 0 and g.ActiveId == BackendData.ProxyActiveId then
|
||||
ImGui.ClearActiveID()
|
||||
-- the key falls back to the focused window next: the "don't recapture" covers it too
|
||||
if g.NavWindow then BackendData.ProxyActiveId = g.NavWindow.ID; BackendData.ProxyLostId = g.NavWindow.ID end
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
local function ImGui_ImplRoblox_Shutdown()
|
||||
local io = ImGui.GetIO()
|
||||
local BackendData = ImGui_ImplRoblox_GetBackendData()
|
||||
for _, c in ipairs(BackendData.Connections) do c:Disconnect() end
|
||||
DestroyTiles(BackendData)
|
||||
EditableImages.Backends[BackendData] = nil
|
||||
BackendData.Gui:Destroy()
|
||||
|
||||
io.BackendPlatformUserData = nil
|
||||
io.BackendPlatformName = nil
|
||||
io.BackendRendererName = nil
|
||||
io.BackendFlags = bit32.band(io.BackendFlags, bit32.bnot(bit32.bor(
|
||||
ImGuiBackendFlags.RendererHasTextures,
|
||||
ImGuiBackendFlags.RendererHasVtxOffset
|
||||
)))
|
||||
end
|
||||
|
||||
|
||||
function ImGui_ImplRoblox_NewFrame()
|
||||
PB("ImGui NewFrame (backend)")
|
||||
local io = ImGui.GetIO()
|
||||
local BackendData = ImGui_ImplRoblox_GetBackendData()
|
||||
if BackendData.Pending then -- skipped frame superseded (its draw lists get reset)
|
||||
BackendData.Pending = nil
|
||||
table.clear(BackendData.Overlays)
|
||||
end
|
||||
BackendData.Stale = nil
|
||||
|
||||
local screen = BackendData.Gui.AbsoluteSize
|
||||
local w, h = floor(screen.X * BackendData.Scale), floor(screen.Y * BackendData.Scale)
|
||||
if w ~= BackendData.ScreenW or h ~= BackendData.ScreenH then
|
||||
BackendData.ScreenW, BackendData.ScreenH = w, h
|
||||
ImGui_ImplRoblox_UpdateMonitors(w, h)
|
||||
end
|
||||
ImVec2_CopyV(io.DisplaySize, w, h)
|
||||
|
||||
local current_time = os.clock()
|
||||
io.DeltaTime = (current_time > BackendData.Time) and (current_time - BackendData.Time) or (1.0 / 60.0)
|
||||
BackendData.Time = current_time
|
||||
|
||||
local m = UserInputService:GetMouseLocation()
|
||||
if m.X ~= BackendData.MouseX or m.Y ~= BackendData.MouseY then
|
||||
BackendData.MouseX, BackendData.MouseY = m.X, m.Y
|
||||
io:AddMouseSourceEvent(ImGuiMouseSource.Mouse)
|
||||
io:AddMousePosEvent(m.X * BackendData.Scale, m.Y * BackendData.Scale)
|
||||
end
|
||||
|
||||
local proxy = BackendData.Proxy
|
||||
local g = ImGui.GetCurrentContext()
|
||||
local focused_box = proxy and UserInputService:GetFocusedTextBox()
|
||||
-- key: the active item (InputText), else the focused window (custom widgets setting PlatformImeData.WantTextInput)
|
||||
local proxy_key = g.ActiveId
|
||||
if proxy_key == 0 and g.NavWindow then proxy_key = g.NavWindow.ID end
|
||||
if proxy_key ~= BackendData.ProxyActiveId then BackendData.ProxyLostId = nil end -- (a "don't recapture" never outlives its field)
|
||||
if not proxy then
|
||||
elseif io.WantTextInput and proxy_key ~= 0 then
|
||||
if proxy_key ~= BackendData.ProxyActiveId or (g.ActiveId ~= 0 and g.ActiveIdIsJustActivated) or g.IO.MouseClicked[0] then
|
||||
BackendData.ProxyActiveId = proxy_key
|
||||
BackendData.ProxyLostId = nil
|
||||
end
|
||||
local mouse_up = not (io.MouseDown[0] or io.MouseDown[1] or io.MouseDown[2])
|
||||
if focused_box ~= proxy and mouse_up and BackendData.ProxyLostId ~= proxy_key and proxy.Parent
|
||||
and (focused_box == nil or not focused_box:IsDescendantOf(game)) then
|
||||
-- what it already holds is not new input (else re-typing it would collapse imgui's selection)
|
||||
BackendData.ProxyText = proxy.Text
|
||||
proxy:CaptureFocus()
|
||||
focused_box = UserInputService:GetFocusedTextBox()
|
||||
end
|
||||
elseif focused_box == proxy then
|
||||
BackendData.ProxyReleasing = true
|
||||
proxy:ReleaseFocus()
|
||||
BackendData.ProxyReleasing = false
|
||||
focused_box = nil
|
||||
end
|
||||
ProxyFocused = proxy ~= nil and focused_box == proxy
|
||||
local used_proxy_text = false
|
||||
if ProxyFocused then
|
||||
local text = proxy.Text
|
||||
if text ~= BackendData.ProxyText and text ~= BackendData.ProxyLastRaw then
|
||||
BackendData.ProxyLastRaw = text
|
||||
-- InputText ignores chars while Ctrl is held; a paste arrives with Ctrl down, so release it around them
|
||||
local ctrl = io.KeyCtrl or UserInputService:IsKeyDown(Enum.KeyCode.LeftControl)
|
||||
or UserInputService:IsKeyDown(Enum.KeyCode.RightControl)
|
||||
if ctrl then io:AddKeyEvent(ImGuiMod_Ctrl, false) end
|
||||
local prev = BackendData.ProxyText or ""
|
||||
if #text < #prev and prev:sub(1, #text) == text and text:sub(-1) ~= "\n" then
|
||||
-- the TextBox deleted from its own text (no real selection): one Backspace on imgui's selection
|
||||
if not BackendData.DeleteKeySeen then
|
||||
io:AddKeyEvent(ImGuiKey.Backspace, true)
|
||||
io:AddKeyEvent(ImGuiKey.Backspace, false)
|
||||
end
|
||||
elseif text ~= "\n" and text ~= "\r" and text ~= "\t" then -- Enter/Tab arrive as key events
|
||||
local prev = BackendData.ProxyText or ""
|
||||
if #text > 0 and (prev == "" or text:sub(1, #prev) ~= prev or #text <= #prev) then
|
||||
for _, cp in utf8.codes(text) do io:AddInputCharacter(cp) end
|
||||
elseif #text > #prev then
|
||||
for _, cp in utf8.codes(text:sub(#prev + 1)) do io:AddInputCharacter(cp) end
|
||||
end
|
||||
end
|
||||
-- re-press only if still physically held: the text can arrive after Ctrl's InputEnded, and re-pressing
|
||||
-- then left Ctrl stuck down in imgui (typing ignored, shortcuts broken until Ctrl was pressed again)
|
||||
if ctrl and (UserInputService:IsKeyDown(Enum.KeyCode.LeftControl) or UserInputService:IsKeyDown(Enum.KeyCode.RightControl)) then
|
||||
io:AddKeyEvent(ImGuiMod_Ctrl, true)
|
||||
end
|
||||
used_proxy_text = true
|
||||
BackendData.ProxyText = nil
|
||||
end
|
||||
local sel = g.PlatformImeData.SelectedText or "" -- (last frame's widget selection: ImGui.NewFrame() not run yet)
|
||||
if sel ~= BackendData.ProxyText then
|
||||
proxy.Text = sel
|
||||
BackendData.ProxyLastRaw = nil
|
||||
BackendData.ProxyText = sel
|
||||
end
|
||||
-- mirror imgui's selection, fully selected, so native Ctrl+C copies it and typing/Ctrl+V replaces it
|
||||
local want_sel, want_cur = (#sel > 0) and 1 or -1, #sel + 1
|
||||
if proxy.SelectionStart ~= want_sel then proxy.SelectionStart = want_sel end
|
||||
if proxy.CursorPosition ~= want_cur then proxy.CursorPosition = want_cur end
|
||||
end
|
||||
|
||||
BackendData.DeleteKeySeen = false
|
||||
|
||||
local pending = BackendData.PendingChars
|
||||
if used_proxy_text then
|
||||
table.clear(pending) -- the proxy delivered the text: the key-code copies would double it
|
||||
BackendData.PendingAge = 0
|
||||
elseif #pending > 0 then
|
||||
-- the TextBox's Text can update a frame or two after InputBegan: wait before falling back to key codes
|
||||
BackendData.PendingAge = (BackendData.PendingAge or 0) + 1
|
||||
if not ProxyFocused or BackendData.PendingAge > 3 then
|
||||
for _, c in ipairs(pending) do io:AddInputCharacter(c) end
|
||||
table.clear(pending)
|
||||
BackendData.PendingAge = 0
|
||||
end
|
||||
end
|
||||
|
||||
-- Tiles Active while over imgui, so Roblox stops passing clicks/wheel to the game (camera zoom etc.)
|
||||
local want = io.WantCaptureMouse
|
||||
if want ~= BackendData.TilesActive then
|
||||
BackendData.TilesActive = want
|
||||
for _, set in pairs(BackendData.Layers) do
|
||||
for kind = 1, 3 do
|
||||
local layer = set[kind]
|
||||
if layer then for _, tile in pairs(layer.Tiles) do tile.Label.Active = want end end
|
||||
end
|
||||
end
|
||||
end
|
||||
PE()
|
||||
end
|
||||
|
||||
-- Public API (documented in README.md)
|
||||
function ImGui_ImplRoblox_SetRedrawBudget(ms)
|
||||
ImGui_ImplRoblox_GetBackendData().RedrawBudget = (ms or 0) / 1000
|
||||
end
|
||||
|
||||
function ImGui_ImplRoblox_SetRenderRate(hz)
|
||||
ImGui_ImplRoblox_GetBackendData().RenderRate = hz or 0
|
||||
end
|
||||
|
||||
function ImGui_ImplRoblox_SetBusyRenderRate(hz)
|
||||
ImGui_ImplRoblox_GetBackendData().BusyRenderRate = hz or 0
|
||||
end
|
||||
|
||||
function ImGui_ImplRoblox_SetProfiling(enabled) Textures.SetProfiling(enabled) end
|
||||
local ImGui_ImplRoblox_IsProfiling = Textures.IsProfiling
|
||||
|
||||
function ImGui_ImplRoblox_SetStageTiming(enabled)
|
||||
EditableImages.StageTiming = enabled and true or false
|
||||
if not EditableImages.StageTiming then EditableImages.StageFrame = nil end
|
||||
end
|
||||
|
||||
function ImGui_ImplRoblox_SetRenderScale(scale)
|
||||
local BackendData = ImGui_ImplRoblox_GetBackendData()
|
||||
if scale == BackendData.Scale then return end
|
||||
BackendData.Scale = scale
|
||||
DestroyTiles(BackendData)
|
||||
BackendData.ForceRedraw = true
|
||||
end
|
||||
|
||||
function ImGui_ImplRoblox_GetStats()
|
||||
local BackendData = ImGui_ImplRoblox_GetBackendData()
|
||||
local tiles = 0
|
||||
for _, set in pairs(BackendData.Layers) do
|
||||
for kind = 1, 3 do if set[kind] then for _ in pairs(set[kind].Tiles) do tiles += 1 end end end
|
||||
end
|
||||
return { Tiles = tiles, EditableImages = EditableImages.Count, EditableImageBytes = EditableImages.Bytes,
|
||||
EditableImageCap = EditableImages.Cap, Instances = #BackendData.Gui:GetDescendants(),
|
||||
Frame = BackendData.FrameStats, Renders = BackendData.FrameNo }
|
||||
end
|
||||
|
||||
function ImGui_ImplRoblox_SetEditableImageCap(bytes)
|
||||
EditableImages.Cap = bytes or 64 * 1024 * 1024
|
||||
EditableImages.Evict(EditableImages.Bytes - EditableImages.Cap)
|
||||
end
|
||||
|
||||
function ImGui_ImplRoblox_EnableParallel(opts) Parallel.Enable(opts) end
|
||||
|
||||
function ImGui_ImplRoblox_DisableParallel() Parallel.Disable() end
|
||||
|
||||
function ImGui_ImplRoblox_FinishParallel() Parallel.Finish() end
|
||||
|
||||
function ImGui_ImplRoblox_BeginParallelFrame() Parallel.BeginFrame() end
|
||||
|
||||
function ImGui_ImplRoblox_GetParallelStats() return Parallel.Stats end
|
||||
|
||||
function ImGui_ImplRoblox_GetParallelConfig() return Parallel.Config end
|
||||
|
||||
ImGui_ImplRoblox = {
|
||||
Init = ImGui_ImplRoblox_Init,
|
||||
Shutdown = ImGui_ImplRoblox_Shutdown,
|
||||
NewFrame = ImGui_ImplRoblox_NewFrame,
|
||||
RenderDrawData = ImGui_ImplRoblox_RenderDrawData,
|
||||
AddFile = ImGui_ImplRoblox_AddFile,
|
||||
CreateTexture = ImGui_ImplRoblox_CreateTexture,
|
||||
DestroyTexture = ImGui_ImplRoblox_DestroyTexture,
|
||||
SetOverlay = ImGui_ImplRoblox_SetOverlay,
|
||||
SetTextProxy = ImGui_ImplRoblox_SetTextProxy,
|
||||
SetRenderScale = ImGui_ImplRoblox_SetRenderScale,
|
||||
GetRenderScale = function() return ImGui_ImplRoblox_GetBackendData().Scale end,
|
||||
SetRenderRate = ImGui_ImplRoblox_SetRenderRate,
|
||||
SetBusyRenderRate = ImGui_ImplRoblox_SetBusyRenderRate,
|
||||
SetRedrawBudget = ImGui_ImplRoblox_SetRedrawBudget,
|
||||
SetProfiling = ImGui_ImplRoblox_SetProfiling,
|
||||
IsProfiling = ImGui_ImplRoblox_IsProfiling,
|
||||
SetStageTiming = ImGui_ImplRoblox_SetStageTiming,
|
||||
GetStats = ImGui_ImplRoblox_GetStats,
|
||||
SetEditableImageCap = ImGui_ImplRoblox_SetEditableImageCap,
|
||||
EnableParallel = ImGui_ImplRoblox_EnableParallel,
|
||||
DisableParallel = ImGui_ImplRoblox_DisableParallel,
|
||||
FinishParallel = ImGui_ImplRoblox_FinishParallel,
|
||||
BeginParallelFrame = ImGui_ImplRoblox_BeginParallelFrame,
|
||||
GetParallelStats = ImGui_ImplRoblox_GetParallelStats,
|
||||
GetParallelConfig = ImGui_ImplRoblox_GetParallelConfig,
|
||||
}
|
||||
|
||||
return true -- [Roblox] ModuleScripts must return exactly one value
|
||||
@@ -0,0 +1,335 @@
|
||||
-- Layers and tiles (one Frame per draw list and kind, TILE x TILE EditableImages); draw list snapshot/compare
|
||||
local Raster = IM_INCLUDE("roblox/raster.lua")
|
||||
local Textures = IM_INCLUDE("roblox/textures.lua")
|
||||
|
||||
local floor, max = math.floor, math.max
|
||||
local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64
|
||||
local TILE = Raster.TILE
|
||||
local EditableImages = Textures.EditableImages
|
||||
|
||||
local M = {}
|
||||
-- content up to this far off screen is kept, so dragging a window past the edge doesn't redraw it
|
||||
local CLIP_PAD = 2048
|
||||
M.CLIP_PAD = CLIP_PAD
|
||||
-- per draw command, filled by CollectPrims for Snapshot: no primitive clipped, layer kind, bounds of its primitives
|
||||
local CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1 = {}, {}, {}, {}, {}, {}
|
||||
M.CmdUnclipped, M.CmdKind, M.CmdBoundsX0, M.CmdBoundsY0, M.CmdBoundsX1, M.CmdBoundsY1 =
|
||||
CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1
|
||||
-- free per-tile primitive lists, 4 at a time
|
||||
EditableImages.ListPool = {}
|
||||
|
||||
-- Kinds: 1 = before the window content (background, title bar, scrollbar), 2 = content (at the scroll origin in a
|
||||
-- ClipsDescendants frame, so scrolling just moves it), 3 = drawn after content, not clipped to it (menu bar).
|
||||
local function NewFrame(parent, clips)
|
||||
local frame = Instance.new("Frame")
|
||||
frame.Name = "Layer"
|
||||
frame.BackgroundTransparency = 1
|
||||
frame.BorderSizePixel = 0
|
||||
frame.Size = UDim2.fromOffset(0, 0)
|
||||
frame.ClipsDescendants = clips
|
||||
frame.Visible = false
|
||||
frame.Parent = parent
|
||||
return frame
|
||||
end
|
||||
|
||||
function M.GetLayer(BackendData, draw_list, kind)
|
||||
local set = BackendData.Layers[draw_list]
|
||||
if not set then
|
||||
set = { LastUsed = 0 }
|
||||
BackendData.Layers[draw_list] = set
|
||||
end
|
||||
local layer = set[kind]
|
||||
if layer then return layer end
|
||||
local root, frame
|
||||
if kind == 2 then
|
||||
root = NewFrame(BackendData.Gui, true)
|
||||
frame = NewFrame(root, false)
|
||||
frame.Visible = true
|
||||
else
|
||||
frame = NewFrame(BackendData.Gui, false)
|
||||
root = frame
|
||||
end
|
||||
layer = {
|
||||
Root = root, Frame = frame, Tiles = {},
|
||||
TileHash1 = {}, TileHash2 = {}, TileCounts = {}, TileLists = {},
|
||||
TileListHash1 = {}, TileListHash2 = {}, TileListFlat = {}, TileX = {}, TileY = {},
|
||||
Touched = {}, TouchedCount = 0,
|
||||
Visible = false, X = false, Y = false, Z = -1,
|
||||
ClipX0 = false, ClipY0 = false, ClipX1 = false, ClipY1 = false,
|
||||
}
|
||||
set[kind] = layer
|
||||
return layer
|
||||
end
|
||||
|
||||
function M.HideLayer(layer)
|
||||
if layer.Visible then
|
||||
layer.Visible = false
|
||||
layer.Root.Visible = false
|
||||
end
|
||||
end
|
||||
|
||||
-- recycle: to EditableImages.Pool. Its label stays parented (hidden): Studio reparenting costs far more than a
|
||||
-- property set, and a scrolling layer's next tile usually goes back into the same frame
|
||||
function EditableImages.FreeTile(layer, key, recycle)
|
||||
local tile = layer.Tiles[key]
|
||||
if recycle and #EditableImages.Pool < EditableImages.PoolMax then
|
||||
table.insert(EditableImages.Pool, tile)
|
||||
else
|
||||
EditableImages.Destroy(tile.Image)
|
||||
tile.Label:Destroy()
|
||||
end
|
||||
layer.Tiles[key] = nil
|
||||
if EditableImages.StageTiming then EditableImages.AddStat("TilesFreed", 1) end
|
||||
if (layer.TileCounts[key] or 0) > 0 then return end -- touched this frame: its primitive list is still needed
|
||||
local lp = EditableImages.ListPool
|
||||
if layer.TileLists[key] and #lp < 256 then
|
||||
lp[#lp + 1] = layer.TileLists[key]
|
||||
lp[#lp + 1] = layer.TileListHash1[key]
|
||||
lp[#lp + 1] = layer.TileListHash2[key]
|
||||
lp[#lp + 1] = layer.TileListFlat[key]
|
||||
end
|
||||
layer.TileLists[key], layer.TileListHash1[key], layer.TileListHash2[key], layer.TileListFlat[key] =
|
||||
nil, nil, nil, nil
|
||||
layer.TileHash1[key], layer.TileHash2[key], layer.TileCounts[key], layer.TileX[key], layer.TileY[key] =
|
||||
nil, nil, nil, nil, nil
|
||||
end
|
||||
|
||||
function M.GetTile(BackendData, layer, key, tx, ty)
|
||||
local tile = layer.Tiles[key]
|
||||
if tile then return tile end
|
||||
local scale = BackendData.Scale
|
||||
local old = table.remove(EditableImages.Pool)
|
||||
local label, img
|
||||
if old then
|
||||
label, img = old.Label, old.Image
|
||||
else
|
||||
img = EditableImages.Create(TILE, TILE)
|
||||
if not img then return nil end -- over the budget even after eviction: the caller skips this tile this frame
|
||||
label = Instance.new("ImageLabel")
|
||||
label.Name = "Tile"
|
||||
label.BackgroundTransparency = 1
|
||||
label.BorderSizePixel = 0
|
||||
label.ResampleMode = Enum.ResamplerMode.Pixelated
|
||||
label.ImageContent = Content.fromObject(img)
|
||||
label.Visible = false
|
||||
end
|
||||
if not old or old.Scale ~= scale then label.Size = UDim2.fromOffset(TILE / scale, TILE / scale) end
|
||||
label.Position = UDim2.fromOffset(tx * TILE / scale, ty * TILE / scale)
|
||||
if not old or old.Active ~= BackendData.TilesActive then label.Active = BackendData.TilesActive end
|
||||
if not old or old.Parent ~= layer.Frame then label.Parent = layer.Frame end
|
||||
-- Content*: content bounds; Valid*: where Buffer == image pixels. A recycled tile keeps both (they still describe
|
||||
-- its image): its first draw is a full one (DrawnCount -1) that only clears old + new content bounds.
|
||||
if old then
|
||||
tile = old
|
||||
tile.Hash1, tile.Hash2, tile.Visible, tile.Used, tile.Deferred, tile.DrawnCount =
|
||||
-1, -1, false, BackendData.FrameNo, nil, -1
|
||||
tile.Scale, tile.Active, tile.Parent = scale, BackendData.TilesActive, layer.Frame
|
||||
else
|
||||
tile = {
|
||||
Image = img, Label = label, Buffer = buffer.create(TILE * TILE * 4),
|
||||
Hash1 = -1, Hash2 = -1, Visible = false, Used = BackendData.FrameNo,
|
||||
ContentX0 = TILE, ContentY0 = TILE, ContentX1 = 0, ContentY1 = 0,
|
||||
ValidX0 = 0, ValidY0 = 0, ValidX1 = TILE, ValidY1 = TILE,
|
||||
Scale = scale, Active = BackendData.TilesActive, Parent = layer.Frame,
|
||||
DrawnCount = -1, DrawnHash1 = {}, DrawnHash2 = {}, DrawnFlat = {},
|
||||
DrawnX0 = {}, DrawnY0 = {}, DrawnX1 = {}, DrawnY1 = {},
|
||||
}
|
||||
end
|
||||
layer.Tiles[key] = tile
|
||||
if EditableImages.StageTiming then EditableImages.AddStat("TilesCreated", 1) end
|
||||
return tile
|
||||
end
|
||||
|
||||
function M.DestroyLayerSet(set)
|
||||
for kind = 1, 3 do
|
||||
local layer = set[kind]
|
||||
if layer then
|
||||
for _, tile in pairs(layer.Tiles) do EditableImages.Destroy(tile.Image) end
|
||||
for _, t in EditableImages.Pool do
|
||||
if t.Parent == layer.Frame then
|
||||
t.Label.Parent = nil
|
||||
t.Parent = nil
|
||||
end
|
||||
end
|
||||
layer.Root:Destroy()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function M.DestroyTiles(BackendData)
|
||||
for _, set in pairs(BackendData.Layers) do M.DestroyLayerSet(set) end
|
||||
BackendData.Layers = {}
|
||||
end
|
||||
|
||||
-- Snapshot compared exactly with the next frame's list: 1 = identical (only restack), 2 = moved by whole pixels
|
||||
-- (only move the layers), 0 = changed. Per command: clip (4 f64), ElemCount, IdxOffset, VtxOffset (u32), tex id
|
||||
-- (f64), kind (u8), unclipped (u8), bounds of its primitives (4 x i32).
|
||||
local CMD_STRIDE = 70
|
||||
|
||||
@native
|
||||
function M.Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
|
||||
local nv = draw_list.VtxBuffer.Size * VTX_STRIDE
|
||||
local idx, ni = draw_list.IdxBuffer.Data, draw_list.IdxBuffer.Size
|
||||
local ncmd = draw_list.CmdBuffer.Size
|
||||
local sv, si, sc = set.SnapVtx, set.SnapIdx, set.SnapCmds
|
||||
if not sv or buffer.len(sv) < nv then
|
||||
sv = buffer.create(max(nv, 64) * 2)
|
||||
set.SnapVtx = sv
|
||||
end
|
||||
if not si then
|
||||
si = {}
|
||||
set.SnapIdx = si
|
||||
end
|
||||
if not sc or buffer.len(sc) < ncmd * CMD_STRIDE then
|
||||
sc = buffer.create(max(ncmd, 4) * CMD_STRIDE * 2)
|
||||
set.SnapCmds = sc
|
||||
end
|
||||
buffer.copy(sv, 0, draw_list.VtxBuffer.Buf, 0, nv)
|
||||
table.move(idx, 1, ni, 1, si)
|
||||
local o, ci = 0, 0
|
||||
for _, pcmd in draw_list.CmdBuffer:iter() do
|
||||
if pcmd.UserCallback ~= nil then
|
||||
set.SnapOK = false
|
||||
return
|
||||
end
|
||||
local c = pcmd.ClipRect
|
||||
writef64(sc, o, c.x)
|
||||
writef64(sc, o + 8, c.y)
|
||||
writef64(sc, o + 16, c.z)
|
||||
writef64(sc, o + 24, c.w)
|
||||
writeu32(sc, o + 32, pcmd.ElemCount)
|
||||
writeu32(sc, o + 36, pcmd.IdxOffset)
|
||||
writeu32(sc, o + 40, pcmd.VtxOffset)
|
||||
writef64(sc, o + 44, pcmd:GetTexID())
|
||||
ci += 1
|
||||
buffer.writeu8(sc, o + 52, CmdKind[ci] or 0)
|
||||
buffer.writeu8(sc, o + 53, CmdUnclipped[ci] and 1 or 0)
|
||||
if CmdUnclipped[ci] then
|
||||
buffer.writei32(sc, o + 54, CmdBoundsX0[ci])
|
||||
buffer.writei32(sc, o + 58, CmdBoundsY0[ci])
|
||||
buffer.writei32(sc, o + 62, CmdBoundsX1[ci])
|
||||
buffer.writei32(sc, o + 66, CmdBoundsY1[ci])
|
||||
end
|
||||
o += CMD_STRIDE
|
||||
end
|
||||
set.SnapVtxBytes, set.SnapIdxCount, set.SnapCmdCount = nv, ni, ncmd
|
||||
set.SnapOriginX, set.SnapOriginY, set.SnapScreenW, set.SnapScreenH = ox, oy, ScreenWidth, ScreenHeight
|
||||
set.SnapHasContent = draw_list._ContentClipX0 ~= nil
|
||||
set.SnapContentX0, set.SnapContentY0, set.SnapContentX1, set.SnapContentY1 =
|
||||
draw_list._ContentClipX0 or 0, draw_list._ContentClipY0 or 0, draw_list._ContentClipX1 or 0,
|
||||
draw_list._ContentClipY1 or 0
|
||||
set.SnapScrollX, set.SnapScrollY = draw_list._ScrollOriginX or 0, draw_list._ScrollOriginY or 0
|
||||
set.SnapOK = true
|
||||
end
|
||||
|
||||
-- a + d == b exactly, with no rounding in a + d (so every later "x - origin" gives the same result as before the move)
|
||||
@native
|
||||
local function ShiftedExact(a, d, b)
|
||||
local s = a + d
|
||||
if s ~= b then return false end
|
||||
local bb = s - a
|
||||
return (a - (s - bb)) + (d - bb) == 0
|
||||
end
|
||||
|
||||
@native
|
||||
function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
|
||||
if not set or not set.SnapOK then return 0 end
|
||||
local nv = draw_list.VtxBuffer.Size * VTX_STRIDE
|
||||
local ni, ncmd = draw_list.IdxBuffer.Size, draw_list.CmdBuffer.Size
|
||||
if nv ~= set.SnapVtxBytes or ni ~= set.SnapIdxCount or ncmd ~= set.SnapCmdCount or ox ~= set.SnapOriginX
|
||||
or oy ~= set.SnapOriginY or ScreenWidth ~= set.SnapScreenW or ScreenHeight ~= set.SnapScreenH then
|
||||
return 0
|
||||
end
|
||||
if (draw_list._ContentClipX0 ~= nil) ~= set.SnapHasContent then return 0 end
|
||||
local vb, sv = draw_list.VtxBuffer.Buf, set.SnapVtx
|
||||
if nv == 0 then return 1 end
|
||||
-- translation from the first vertex: whole pixels only, and only with DisplayPos at 0 (so it stays exact)
|
||||
local dx, dy = readf64(vb, 0) - readf64(sv, 0), readf64(vb, 8) - readf64(sv, 8)
|
||||
if dx ~= dx or dy ~= dy then return 0 end
|
||||
if dx == 0 and dy == 0 then
|
||||
-- u32 loop, not readstring ==: that allocated 2 vertex-buffer strings per list per frame (GC spikes)
|
||||
for o = 0, nv - 4, 4 do if readu32(vb, o) ~= readu32(sv, o) then return 0 end end
|
||||
else
|
||||
if dx ~= floor(dx) or dy ~= floor(dy) or ox ~= 0 or oy ~= 0 or not set.SnapLimitFree then return 0 end
|
||||
-- everything must stay as far from the clip limits as before (nothing newly clamped)
|
||||
if set.SnapExtentX0 + dx < -CLIP_PAD or set.SnapExtentY0 + dy < -CLIP_PAD
|
||||
or set.SnapExtentX1 + dx > ScreenWidth + CLIP_PAD or set.SnapExtentY1 + dy > ScreenHeight + CLIP_PAD then
|
||||
return 0
|
||||
end
|
||||
end
|
||||
local idx, si = draw_list.IdxBuffer.Data, set.SnapIdx
|
||||
for i = 1, ni do if idx[i] ~= si[i] then return 0 end end
|
||||
local sc, o = set.SnapCmds, 0
|
||||
local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1,
|
||||
draw_list._ContentClipY1
|
||||
local seen_content = false
|
||||
for _, pcmd in draw_list.CmdBuffer:iter() do
|
||||
if pcmd.UserCallback ~= nil then return 0 end
|
||||
if pcmd.ElemCount ~= readu32(sc, o + 32) or pcmd.IdxOffset ~= readu32(sc, o + 36)
|
||||
or pcmd.VtxOffset ~= readu32(sc, o + 40) or pcmd:GetTexID() ~= readf64(sc, o + 44) then
|
||||
return 0
|
||||
end
|
||||
local c = pcmd.ClipRect
|
||||
if dx == 0 and dy == 0 then
|
||||
if c.x ~= readf64(sc, o) or c.y ~= readf64(sc, o + 8) or c.z ~= readf64(sc, o + 16)
|
||||
or c.w ~= readf64(sc, o + 24) then
|
||||
return 0
|
||||
end
|
||||
elseif not (ShiftedExact(readf64(sc, o), dx, c.x) and ShiftedExact(readf64(sc, o + 8), dy, c.y)
|
||||
and ShiftedExact(readf64(sc, o + 16), dx, c.z) and ShiftedExact(readf64(sc, o + 24), dy, c.w)) then
|
||||
-- an unchanged clip rect (e.g. the viewport) is fine if it clips none of this command's primitives
|
||||
if c.x ~= readf64(sc, o) or c.y ~= readf64(sc, o + 8) or c.z ~= readf64(sc, o + 16)
|
||||
or c.w ~= readf64(sc, o + 24)
|
||||
or buffer.readu8(sc, o + 53) == 0 then return 0 end
|
||||
if buffer.readi32(sc, o + 54) + dx < floor(c.x) or buffer.readi32(sc, o + 58) + dy < floor(c.y)
|
||||
or buffer.readi32(sc, o + 62) + dx > floor(c.z)
|
||||
or buffer.readi32(sc, o + 66) + dy > floor(c.w) then return 0 end
|
||||
end
|
||||
if pcmd.ElemCount > 0 then
|
||||
local kind = 1
|
||||
if ccx0 and c.x >= ccx0 and c.y >= ccy0 and c.z <= ccx1 and c.w <= ccy1 then
|
||||
kind = 2
|
||||
seen_content = true
|
||||
elseif seen_content then kind = 3 end
|
||||
if kind ~= buffer.readu8(sc, o + 52) then return 0 end
|
||||
end
|
||||
o += CMD_STRIDE
|
||||
end
|
||||
if dx == 0 and dy == 0 then
|
||||
if set.SnapHasContent and (draw_list._ContentClipX0 ~= set.SnapContentX0
|
||||
or draw_list._ContentClipY0 ~= set.SnapContentY0 or draw_list._ContentClipX1 ~= set.SnapContentX1
|
||||
or draw_list._ContentClipY1 ~= set.SnapContentY1 or draw_list._ScrollOriginX ~= set.SnapScrollX
|
||||
or draw_list._ScrollOriginY ~= set.SnapScrollY) then return 0 end
|
||||
return 1
|
||||
end
|
||||
if set.SnapHasContent and not (ShiftedExact(set.SnapContentX0, dx, draw_list._ContentClipX0)
|
||||
and ShiftedExact(set.SnapContentY0, dy, draw_list._ContentClipY0)
|
||||
and ShiftedExact(set.SnapContentX1, dx, draw_list._ContentClipX1)
|
||||
and ShiftedExact(set.SnapContentY1, dy, draw_list._ContentClipY1)
|
||||
and ShiftedExact(set.SnapScrollX, dx, draw_list._ScrollOriginX)
|
||||
and ShiftedExact(set.SnapScrollY, dy, draw_list._ScrollOriginY)) then return 0 end
|
||||
for v = 0, nv - VTX_STRIDE, VTX_STRIDE do
|
||||
if not ShiftedExact(readf64(sv, v), dx, readf64(vb, v))
|
||||
or not ShiftedExact(readf64(sv, v + 8), dy, readf64(vb, v + 8))
|
||||
or readf64(vb, v + 16) ~= readf64(sv, v + 16) or readf64(vb, v + 24) ~= readf64(sv, v + 24)
|
||||
or readu32(vb, v + 32) ~= readu32(sv, v + 32) then return 0 end
|
||||
end
|
||||
return 2, dx, dy
|
||||
end
|
||||
|
||||
function M.ShiftLayer(layer, dx, dy, scale)
|
||||
layer.X += dx
|
||||
layer.Y += dy
|
||||
local root = layer.Root
|
||||
if root ~= layer.Frame then
|
||||
layer.ClipX0 += dx
|
||||
layer.ClipY0 += dy
|
||||
layer.ClipX1 += dx
|
||||
layer.ClipY1 += dy
|
||||
root.Position = UDim2.fromOffset(layer.ClipX0 / scale, layer.ClipY0 / scale)
|
||||
else
|
||||
root.Position = UDim2.fromOffset(layer.X / scale, layer.Y / scale)
|
||||
end
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,79 @@
|
||||
-- Overlays: user Instances placed inside a window (SetOverlay), stacked right above its layers and moving with it.
|
||||
local Textures = IM_INCLUDE("roblox/textures.lua")
|
||||
|
||||
local M = {}
|
||||
|
||||
local function OverlayHolder(BackendData, draw_list, clip)
|
||||
local hs = BackendData.OverlayHolders[draw_list]
|
||||
if not hs then
|
||||
hs = {}
|
||||
BackendData.OverlayHolders[draw_list] = hs
|
||||
end
|
||||
local h = hs[clip]
|
||||
if not h then
|
||||
h = Instance.new("Frame")
|
||||
h.Name = clip and "OverlayClip" or "Overlay"
|
||||
h.BackgroundTransparency = 1
|
||||
h.BorderSizePixel = 0
|
||||
h.ClipsDescendants = clip
|
||||
h.Size = UDim2.fromOffset(0, 0)
|
||||
h.Parent = BackendData.Gui
|
||||
hs[clip] = h
|
||||
end
|
||||
return h
|
||||
end
|
||||
|
||||
local OverlayUsed = {}
|
||||
function M.PlaceOverlays(BackendData, draw_list, z, ox, oy)
|
||||
local list = BackendData.Overlays[draw_list]
|
||||
local hs = BackendData.OverlayHolders[draw_list]
|
||||
if not list then
|
||||
if hs then for _, h in pairs(hs) do h.Visible = false end end
|
||||
return z
|
||||
end
|
||||
local scale, frame_no = BackendData.Scale, BackendData.FrameNo
|
||||
z += 1
|
||||
local used = OverlayUsed
|
||||
table.clear(used)
|
||||
for _, o in ipairs(list) do
|
||||
local clip = o.Clip and draw_list._ContentClipX0 ~= nil
|
||||
local h = OverlayHolder(BackendData, draw_list, clip)
|
||||
local hx, hy = 0, 0
|
||||
if clip then
|
||||
hx, hy = draw_list._ContentClipX0 - ox, draw_list._ContentClipY0 - oy
|
||||
if not used[h] then
|
||||
h.Position = UDim2.fromOffset(hx / scale, hy / scale)
|
||||
h.Size = UDim2.fromOffset((draw_list._ContentClipX1 - draw_list._ContentClipX0) / scale,
|
||||
(draw_list._ContentClipY1 - draw_list._ContentClipY0) / scale)
|
||||
end
|
||||
elseif not used[h] then
|
||||
h.Position = UDim2.fromOffset(0, 0)
|
||||
end
|
||||
used[h] = true
|
||||
h.ZIndex = z
|
||||
h.Visible = true
|
||||
local f = o.Frame
|
||||
if f.Parent ~= h then f.Parent = h end
|
||||
f.Position = UDim2.fromOffset((o.X - ox - hx) / scale, (o.Y - oy - hy) / scale)
|
||||
f.Size = UDim2.fromOffset(o.W / scale, o.H / scale)
|
||||
f.Visible = true
|
||||
BackendData.OverlayShown[f] = frame_no
|
||||
end
|
||||
if hs then for _, h in pairs(hs) do if not used[h] then h.Visible = false end end end
|
||||
return z
|
||||
end
|
||||
|
||||
--- Show `frame` this frame at (x, y, w, h) (imgui coordinates) inside the current window. Call every frame it should
|
||||
--- be visible; frames not submitted are hidden. clip: clip to the window's content area (scrolls with it).
|
||||
function ImGui_ImplRoblox_SetOverlay(frame, x, y, w, h, clip)
|
||||
local BackendData = Textures.GetBackendData()
|
||||
local dl = ImGui.GetWindowDrawList()
|
||||
local list = BackendData.Overlays[dl]
|
||||
if not list then
|
||||
list = {}
|
||||
BackendData.Overlays[dl] = list
|
||||
end
|
||||
list[#list + 1] = { Frame = frame, X = x, Y = y, W = w, H = h, Clip = clip ~= false }
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,446 @@
|
||||
-- Parallel executor (opt-in, EnableParallel): Tile packs each dirty tile per Actor, Flush sends the batch while the
|
||||
-- dispatch window (PreAnimation .. Finish) is open, else rasterizes it at once; Finish uploads every result.
|
||||
local Raster = IM_INCLUDE("roblox/raster.lua")
|
||||
local Textures = IM_INCLUDE("roblox/textures.lua")
|
||||
local Render = IM_INCLUDE("roblox/render.lua")
|
||||
|
||||
local Players = game:GetService("Players")
|
||||
local EditableImages, Records = Textures.EditableImages, Textures.Records
|
||||
local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient = Render.PrimA, Render.PrimB, Render.PrimC, Render.PrimD,
|
||||
Render.PrimTexture, Render.PrimGradient
|
||||
local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = Render.PrimClipX0, Render.PrimClipY0, Render.PrimClipX1,
|
||||
Render.PrimClipY1
|
||||
local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = Render.PrimBoundsX0, Render.PrimBoundsY0,
|
||||
Render.PrimBoundsX1, Render.PrimBoundsY1
|
||||
local PrimTexId, PrimVtxBuffer = Render.PrimTexId, Render.PrimVtxBuffer
|
||||
|
||||
local M = Render.Parallel
|
||||
local writei32, writef64, copy = buffer.writei32, buffer.writef64, buffer.copy
|
||||
local RasterJobs = Raster.RasterJobs
|
||||
local VTX, REC, REC_A, REC_B, REC_C, 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 = 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
|
||||
|
||||
local NA = 1
|
||||
local Pb, Pn, Tb, Tn, load, used = {}, {}, {}, {}, {}, {}
|
||||
local stamp, poff, stamp_base = {}, {}, 0
|
||||
local free_batches, free_bufs, free_bytes = {}, {}, 0
|
||||
local function newBatch()
|
||||
return table.remove(free_batches)
|
||||
or { N = 0, Px = 0, Img = {}, Actor = {}, NR = {}, Rect = {}, P = {}, T = {}, TL = {}, Res = {} }
|
||||
end
|
||||
local function takeBuf(len: number): buffer
|
||||
local l = free_bufs[len]
|
||||
local b = l and table.remove(l)
|
||||
if b then
|
||||
free_bytes -= len
|
||||
return b
|
||||
end
|
||||
return buffer.create(len)
|
||||
end
|
||||
local function giveBuf(b: buffer)
|
||||
local len = buffer.len(b)
|
||||
local l = free_bufs[len]
|
||||
if not l then
|
||||
l = {}
|
||||
free_bufs[len] = l
|
||||
end
|
||||
if #l < 8 and free_bytes + len <= 4194304 then
|
||||
l[#l + 1] = b
|
||||
free_bytes += len
|
||||
end
|
||||
end
|
||||
local jobs = newBatch()
|
||||
local NO_TEX = {}
|
||||
local cur = {}
|
||||
local pending, by_id, batch_no = {}, {}, 0
|
||||
local open = false
|
||||
local actors, ready, conns, folder = {}, false, {}, nil
|
||||
local sent = {}
|
||||
|
||||
local function grow(b: buffer, need: number): buffer
|
||||
local n = buffer.len(b)
|
||||
if need <= n then
|
||||
return b
|
||||
end
|
||||
while n < need do
|
||||
n *= 2
|
||||
end
|
||||
local nb = buffer.create(n)
|
||||
copy(nb, 0, b)
|
||||
return nb
|
||||
end
|
||||
|
||||
local function reset()
|
||||
for a = 1, NA do
|
||||
Pn[a], Tn[a], load[a] = 0, 0, 0
|
||||
if used[a] then
|
||||
table.clear(used[a])
|
||||
end
|
||||
end
|
||||
stamp_base += 64
|
||||
jobs = newBatch()
|
||||
end
|
||||
|
||||
-- One dirty tile (rects in EditableImages.DX0..DY1[1..nr], primitives list[1..count]) -> the least loaded Actor
|
||||
@native
|
||||
function M.Tile(img, list, count: number, x0: number, y0: number, tox: number, toy: number, nr: number)
|
||||
local t0 = os.clock()
|
||||
local DX0, DY0, DX1, DY1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1
|
||||
local area = 0
|
||||
for r = 1, nr do
|
||||
area += (DX1[r] - DX0[r]) * (DY1[r] - DY0[r])
|
||||
end
|
||||
local a = 1
|
||||
for i = 2, NA do
|
||||
if load[i] < load[a] then
|
||||
a = i
|
||||
end
|
||||
end
|
||||
load[a] += area + 200
|
||||
jobs.Px += area
|
||||
local j = jobs.N + 1
|
||||
jobs.N = j
|
||||
jobs.Img[j], jobs.Actor[j], jobs.NR[j] = img, a, nr
|
||||
Stats.Rects += nr
|
||||
local R = jobs.Rect
|
||||
local ri = #R
|
||||
for r = 1, nr do
|
||||
R[ri + 1], R[ri + 2], R[ri + 3], R[ri + 4] = DX0[r], DY0[r], DX1[r], DY1[r]
|
||||
ri += 4
|
||||
end
|
||||
|
||||
local T, to = grow(Tb[a], Tn[a] + JOB + nr * 16 + count * 4), Tn[a]
|
||||
Tb[a] = T
|
||||
writef64(T, to, tox)
|
||||
writef64(T, to + 8, toy)
|
||||
writei32(T, to + 16, x0)
|
||||
writei32(T, to + 20, y0)
|
||||
writei32(T, to + 24, nr)
|
||||
writei32(T, to + 28, count)
|
||||
to += JOB
|
||||
for r = 1, nr do
|
||||
writei32(T, to, DX0[r])
|
||||
writei32(T, to + 4, DY0[r])
|
||||
writei32(T, to + 8, DX1[r])
|
||||
writei32(T, to + 12, DY1[r])
|
||||
to += 16
|
||||
end
|
||||
local P, pn = grow(Pb[a], Pn[a] + count * REC), Pn[a]
|
||||
Pb[a] = P
|
||||
local st = stamp_base + a
|
||||
local u = used[a]
|
||||
for k = 1, count do
|
||||
local p = list[k]
|
||||
if stamp[p] ~= st then
|
||||
stamp[p], poff[p] = st, pn
|
||||
local d, t = PrimD[p], PrimTexture[p]
|
||||
local gk = PrimGradient[p]
|
||||
writei32(P, pn, d and (gk and gk + 1 or 1) or 0)
|
||||
writei32(P, pn + 4, t and PrimTexId[p] or -1)
|
||||
if t then
|
||||
u[t] = PrimTexId[p]
|
||||
end
|
||||
writei32(P, pn + 8, PrimClipX0[p])
|
||||
writei32(P, pn + 12, PrimClipY0[p])
|
||||
writei32(P, pn + 16, PrimClipX1[p])
|
||||
writei32(P, pn + 20, PrimClipY1[p])
|
||||
writei32(P, pn + 24, PrimBoundsX0[p])
|
||||
writei32(P, pn + 28, PrimBoundsY0[p])
|
||||
writei32(P, pn + 32, PrimBoundsX1[p])
|
||||
writei32(P, pn + 36, PrimBoundsY1[p])
|
||||
local vb = PrimVtxBuffer[p]
|
||||
copy(P, pn + REC_A, vb, PrimA[p], VTX)
|
||||
copy(P, pn + REC_C, vb, PrimC[p], VTX)
|
||||
if not d 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])
|
||||
to += 4
|
||||
end
|
||||
Pn[a], Tn[a] = pn, to
|
||||
Stats.Pack += os.clock() - t0
|
||||
end
|
||||
|
||||
local function upload(b)
|
||||
local alive, R, ri = EditableImages.ImageBytes, b.Rect, 0
|
||||
table.clear(cur)
|
||||
for j = 1, b.N do
|
||||
local a = b.Actor[j]
|
||||
local outs, c = b.Res[a], cur[a] or 0
|
||||
local img = b.Img[j]
|
||||
for _ = 1, b.NR[j] do
|
||||
c += 1
|
||||
if alive[img] then
|
||||
local x0, y0 = R[ri + 1], R[ri + 2]
|
||||
img:WritePixelsBuffer(Vector2.new(x0, y0), Vector2.new(R[ri + 3] - x0, R[ri + 4] - y0), outs[c])
|
||||
end
|
||||
ri += 4
|
||||
end
|
||||
cur[a] = c
|
||||
end
|
||||
end
|
||||
|
||||
-- Uploads every pending batch (late worker results rasterized here) and closes the dispatch window
|
||||
function M.Finish()
|
||||
open = false
|
||||
if #pending == 0 then
|
||||
return
|
||||
end
|
||||
local t0 = os.clock()
|
||||
for _, b in pending do
|
||||
for a = 1, NA do
|
||||
if b.TL[a] > 0 and not b.Res[a] then
|
||||
b.Res[a] = RasterJobs(b.P[a], b.T[a], b.TL[a], Records)
|
||||
if b.Sent then
|
||||
Stats.Fallbacks += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
upload(b)
|
||||
by_id[b.Id] = nil
|
||||
for a = 1, NA do
|
||||
if b.P[a] then
|
||||
giveBuf(b.P[a])
|
||||
giveBuf(b.T[a])
|
||||
end
|
||||
end
|
||||
b.N, b.Px, b.Sent = 0, 0, false
|
||||
table.clear(b.Img)
|
||||
table.clear(b.Actor)
|
||||
table.clear(b.NR)
|
||||
table.clear(b.Rect)
|
||||
table.clear(b.P)
|
||||
table.clear(b.T)
|
||||
table.clear(b.TL)
|
||||
table.clear(b.Res)
|
||||
if #free_batches < 8 then
|
||||
free_batches[#free_batches + 1] = b
|
||||
end
|
||||
end
|
||||
table.clear(pending)
|
||||
Stats.Finish += os.clock() - t0
|
||||
end
|
||||
|
||||
-- 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
|
||||
if not open then
|
||||
M.Finish()
|
||||
end
|
||||
return
|
||||
end
|
||||
local t0 = os.clock()
|
||||
local cfg = M.Config
|
||||
local par = open and (cfg.Sync or ready) and n >= cfg.MinTiles and jobs.Px >= cfg.MinPixels
|
||||
if par and cfg.MaxBytesPerPixel > 0 then
|
||||
local bytes = 0
|
||||
for a = 1, NA do
|
||||
bytes += Pn[a] + Tn[a]
|
||||
end
|
||||
par = bytes <= cfg.MaxBytesPerPixel * jobs.Px
|
||||
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
|
||||
b.Id, b.Sent = batch_no, par
|
||||
for a = 1, NA do
|
||||
local tl = Tn[a]
|
||||
b.TL[a] = tl
|
||||
if tl == 0 then
|
||||
continue
|
||||
end
|
||||
if not par then
|
||||
b.Res[a] = RasterJobs(Pb[a], Tb[a], tl, Records)
|
||||
continue
|
||||
end
|
||||
-- recycled copies rounded up to 4 KB (SendMessage copies the whole buffer)
|
||||
local P, T = takeBuf(Pn[a] + 4095 - (Pn[a] + 4095) % 4096), takeBuf(tl + 4095 - (tl + 4095) % 4096)
|
||||
copy(P, 0, Pb[a], 0, Pn[a])
|
||||
copy(T, 0, Tb[a], 0, tl)
|
||||
b.P[a], b.T[a] = P, T
|
||||
|
||||
local tex, s = NO_TEX, sent[a]
|
||||
for rec, id in used[a] do
|
||||
local v = rec.V or 0
|
||||
local had = s[rec]
|
||||
if had ~= v then
|
||||
if tex == NO_TEX then
|
||||
tex = {}
|
||||
end
|
||||
s[rec] = v
|
||||
-- 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
|
||||
end
|
||||
end
|
||||
Stats.SendBytes += Pn[a] + tl
|
||||
if cfg.Sync then
|
||||
if not (cfg.SyncDrop and a % 2 == 0) then
|
||||
b.Res[a] = RasterJobs(P, T, tl, Records)
|
||||
end
|
||||
else
|
||||
actors[a]:SendMessage("job", batch_no, P, T, tex, tl)
|
||||
end
|
||||
end
|
||||
if par then
|
||||
Stats.ParallelFlushes += 1
|
||||
else
|
||||
Stats.SerialFlushes += 1
|
||||
end
|
||||
Stats.Tiles += n
|
||||
by_id[batch_no] = b
|
||||
pending[#pending + 1] = b
|
||||
reset()
|
||||
Stats.Flush += os.clock() - t0
|
||||
if not open then
|
||||
M.Finish()
|
||||
end
|
||||
end
|
||||
|
||||
function M.BeginFrame()
|
||||
open = true
|
||||
end
|
||||
|
||||
local function setActors(n)
|
||||
NA = n
|
||||
for a = 1, n do
|
||||
Pb[a] = Pb[a] or buffer.create(4096)
|
||||
Tb[a] = Tb[a] or buffer.create(1024)
|
||||
used[a] = used[a] or {}
|
||||
sent[a] = setmetatable({}, { __mode = "k" })
|
||||
end
|
||||
reset()
|
||||
end
|
||||
setActors(1)
|
||||
|
||||
function M.Disable()
|
||||
M.Finish()
|
||||
for _, c in conns do
|
||||
c:Disconnect()
|
||||
end
|
||||
table.clear(conns)
|
||||
if folder then
|
||||
folder:Destroy()
|
||||
folder = nil
|
||||
end
|
||||
table.clear(actors)
|
||||
ready, open = false, false
|
||||
M.On, M.Active = false, false
|
||||
end
|
||||
|
||||
function M.Enable(opts)
|
||||
M.Disable()
|
||||
for k, v in opts or {} do
|
||||
M.Config[k] = v
|
||||
end
|
||||
local cfg = M.Config
|
||||
setActors(math.max(1, cfg.Actors))
|
||||
M.On = true
|
||||
if cfg.Sync then
|
||||
return
|
||||
end
|
||||
local RunService = game:GetService("RunService")
|
||||
-- bundle: script is the library ModuleScript (e.g. ImGui.Impl under the typed module)
|
||||
local template = cfg.Worker or script:FindFirstChild("Worker")
|
||||
or (script.Parent and script.Parent:FindFirstChild("Worker"))
|
||||
assert(template, "ImGui_ImplRoblox.EnableParallel: no Worker LocalScript (build/ImGuiWorker.client.luau) as a"
|
||||
.. " child of the ImGui module; or pass { Worker = ... }")
|
||||
folder = Instance.new("Folder")
|
||||
folder.Name = "ImGuiRasterActors"
|
||||
for a = 1, NA do
|
||||
local actor = Instance.new("Actor")
|
||||
actor.Name = "Raster" .. a
|
||||
local done = Instance.new("BindableEvent")
|
||||
done.Name = "Done"
|
||||
done.Parent = actor
|
||||
table.insert(conns, done.Event:Connect(function(id, outs)
|
||||
local t0, b = os.clock(), by_id[id]
|
||||
if b then
|
||||
b.Res[a] = outs
|
||||
else
|
||||
Stats.Late += 1
|
||||
end
|
||||
for _, o in outs do
|
||||
Stats.RecvBytes += buffer.len(o)
|
||||
end
|
||||
Stats.Recv += os.clock() - t0
|
||||
end))
|
||||
local w = template:Clone()
|
||||
w.Parent = actor
|
||||
actor.Parent = folder
|
||||
actors[a] = actor
|
||||
end
|
||||
folder.Parent = Players.LocalPlayer:WaitForChild("PlayerScripts")
|
||||
ready = false
|
||||
table.insert(conns, RunService.PreAnimation:Connect(function()
|
||||
if not ready then
|
||||
ready = true
|
||||
for _, act in actors do
|
||||
if not act:GetAttribute("Ready") then
|
||||
ready = false
|
||||
end
|
||||
end
|
||||
end
|
||||
open = true
|
||||
end))
|
||||
table.insert(conns, RunService.PostSimulation:Connect(M.Finish))
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,798 @@
|
||||
-- Software rasterizer: pure buffer code shared by the backend and the parallel worker (inlined into ImGuiWorker).
|
||||
-- Target: RGBA8 row-major (ImU32 is already R | G<<8 | B<<16 | A<<24), non-premultiplied "over" onto transparent.
|
||||
local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max
|
||||
local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
|
||||
local readf64 = buffer.readf64
|
||||
local band, rshift = bit32.band, bit32.rshift
|
||||
local readi32 = buffer.readi32
|
||||
|
||||
local M = {
|
||||
TILE = 128,
|
||||
-- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs.
|
||||
-- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2, 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 = 184, REC_A = 40, REC_C = 76, REC_B = 112, REC_D = 148, JOB = 32,
|
||||
}
|
||||
local TILE = M.TILE
|
||||
|
||||
local TargetBuffer: buffer, TargetWidth = buffer.create(0), 0
|
||||
local PrevRow = buffer.create(1024)
|
||||
|
||||
-- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else
|
||||
-- remembers this row. u32 loop, not readstring ==: that allocated a string per row.
|
||||
@native
|
||||
local function RowRepeats(o: number, len: number, has_prev: boolean): boolean
|
||||
if has_prev then
|
||||
local same = true
|
||||
for k = 0, len - 4, 4 do
|
||||
if readu32(TargetBuffer, o + k) ~= readu32(PrevRow, k) then
|
||||
same = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if same then return true end
|
||||
end
|
||||
if buffer.len(PrevRow) < len then PrevRow = buffer.create(len) end
|
||||
buffer.copy(PrevRow, 0, TargetBuffer, o, len)
|
||||
return false
|
||||
end
|
||||
local RectColumns = table.create(256, 0)
|
||||
|
||||
-- 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)
|
||||
if a >= 255 then
|
||||
writeu32(TargetBuffer, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080)
|
||||
return
|
||||
end
|
||||
if a <= 0 then return end
|
||||
local d = readu32(TargetBuffer, o)
|
||||
if d < 16777216 then
|
||||
writeu32(TargetBuffer, o,
|
||||
floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216)
|
||||
return
|
||||
end
|
||||
local sa = a / 255
|
||||
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
|
||||
if d >= 4278190080 then
|
||||
local ns = 1 - sa
|
||||
writeu32(TargetBuffer, o,
|
||||
floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256 + floor(b * sa + db * ns + 0.5) * 65536
|
||||
+ 4278190080)
|
||||
else
|
||||
local k = rshift(d, 24) * ((1 - sa) / 255)
|
||||
local oa = sa + k
|
||||
local inv = 1 / oa
|
||||
writeu32(TargetBuffer, o, floor((r * sa + dr * k) * inv + 0.5) + floor((g * sa + dg * k) * inv + 0.5) * 256
|
||||
+ floor((b * sa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
|
||||
end
|
||||
end
|
||||
|
||||
@native
|
||||
local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number,
|
||||
b: number, a: number)
|
||||
if a <= 0 then return end
|
||||
local w4 = (x1 - x0 - 1) * 4
|
||||
if 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
|
||||
local c1 = ns / 255
|
||||
local rs, gs, bs = r * sa, g * sa, b * sa
|
||||
local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination
|
||||
for y = y0, y1 - 1 do
|
||||
local o0 = (y * TargetWidth + x0) * 4
|
||||
for o = o0, o0 + w4, 4 do
|
||||
local d = readu32(TargetBuffer, o)
|
||||
if d == last_d then
|
||||
writeu32(TargetBuffer, o, last_v)
|
||||
elseif d < 16777216 then
|
||||
writeu32(TargetBuffer, o, packed0)
|
||||
else
|
||||
last_d = d
|
||||
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
|
||||
if d >= 4278190080 then
|
||||
last_v = floor(rs + dr * ns + 0.5) + floor(gs + dg * ns + 0.5) * 256
|
||||
+ floor(bs + db * ns + 0.5) * 65536 + 4278190080
|
||||
else
|
||||
local k = rshift(d, 24) * c1
|
||||
local oa = sa + k
|
||||
local inv = 1 / oa
|
||||
last_v = floor((rs + dr * k) * inv + 0.5) + floor((gs + dg * k) * inv + 0.5) * 256
|
||||
+ floor((bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
|
||||
end
|
||||
writeu32(TargetBuffer, o, last_v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@native
|
||||
local function UnpackColor(col: number)
|
||||
return col % 256, floor(col / 256) % 256, floor(col / 65536) % 256, floor(col / 16777216) % 256
|
||||
end
|
||||
|
||||
@native
|
||||
local function SampleTexture(t, u: number, v: number)
|
||||
local tw, th = t.Width, t.Height
|
||||
local tx, ty = floor(u * tw), floor(v * th)
|
||||
if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end
|
||||
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
|
||||
local o = (ty * tw + tx) * 4
|
||||
local tb = t.Buffer
|
||||
return readu8(tb, o), readu8(tb, o + 1), readu8(tb, o + 2), readu8(tb, o + 3)
|
||||
end
|
||||
|
||||
@native
|
||||
local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, u0: number, v0: number,
|
||||
u1: number, v1: number, col: number, t, cx0: number, cy0: number, cx1: number, cy1: number)
|
||||
local r, g, b, a = UnpackColor(col)
|
||||
if a == 0 then return end
|
||||
local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0)
|
||||
local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1)
|
||||
if px0 >= px1 or py0 >= py1 then return end
|
||||
|
||||
if not t or (u0 == u1 and v0 == v1) then
|
||||
if t then
|
||||
local tr, tg, tb, ta = SampleTexture(t, u0, v0)
|
||||
r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255
|
||||
end
|
||||
if a <= 0 then return end
|
||||
if a >= 255 or px1 - px0 < 32 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
|
||||
local o = (y * TargetWidth + px0) * 4
|
||||
if RowRepeats(o, len, y > py0) then
|
||||
buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len)
|
||||
else
|
||||
FillSpan(TargetBuffer, y, y + 1, px0, px1, r, g, b, a)
|
||||
end
|
||||
prev_o = o
|
||||
end
|
||||
return
|
||||
end
|
||||
|
||||
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
|
||||
cols[c] = tx * 4
|
||||
end
|
||||
for y = py0, py1 - 1 do
|
||||
local ty = floor((v0 + (y + 0.5 - y0) * dv) * th)
|
||||
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
|
||||
local trow4 = ty * tw * 4
|
||||
local o = (y * TargetWidth + px0) * 4
|
||||
for c = 1, ncol do
|
||||
local tv = readu32(tbuf, trow4 + cols[c])
|
||||
if tv < 16777216 then
|
||||
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
|
||||
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 += 4
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@native
|
||||
local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, vc: number, t, cx0: number, cy0: number,
|
||||
cx1: number, cy1: number, ox: number, oy: number)
|
||||
local x0, y0 = readf64(vbuf, va) - ox, readf64(vbuf, va + 8) - oy
|
||||
local x1, y1 = readf64(vbuf, vb) - ox, readf64(vbuf, vb + 8) - oy
|
||||
local x2, y2 = readf64(vbuf, vc) - ox, readf64(vbuf, vc + 8) - oy
|
||||
local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0)
|
||||
if area == 0 then return end
|
||||
if area < 0 then
|
||||
vb, vc = vc, vb
|
||||
x1, y1, x2, y2 = x2, y2, x1, y1
|
||||
area = -area
|
||||
end
|
||||
|
||||
local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1)
|
||||
local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1)
|
||||
if minx > maxx or miny > maxy then return end
|
||||
Shrink(minx, miny, maxx + 1, maxy + 1)
|
||||
|
||||
local A0, B0 = y1 - y2, x2 - x1
|
||||
local C0 = -(A0 * x1 + B0 * y1)
|
||||
local A1, B1 = y2 - y0, x0 - x2
|
||||
local C1 = -(A1 * x2 + B1 * y2)
|
||||
local A2, B2 = y0 - y1, x1 - x0
|
||||
local C2 = -(A2 * x0 + B2 * y0)
|
||||
local tl0 = A0 > 0 or (A0 == 0 and B0 > 0)
|
||||
local tl1 = A1 > 0 or (A1 == 0 and B1 > 0)
|
||||
local tl2 = A2 > 0 or (A2 == 0 and B2 > 0)
|
||||
|
||||
local inv = 1 / area
|
||||
local n0, n1, n2 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0
|
||||
local ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32))
|
||||
local rb, gb, bb, ab = UnpackColor(readu32(vbuf, vb + 32))
|
||||
local rc, gc, bc, ac = UnpackColor(readu32(vbuf, vc + 32))
|
||||
local ua, vva, ub, vvb, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vb + 16),
|
||||
readf64(vbuf, vb + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24)
|
||||
|
||||
local textured = t and not (ua == ub and ua == uc and vva == vvb and vva == vvc)
|
||||
if t and not textured then -- constant uv (atlas white pixel): fold the texel into the vertex colours
|
||||
local tr, tg, tb, ta = SampleTexture(t, ua, vva)
|
||||
ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255
|
||||
rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255
|
||||
rc, gc, bc, ac = rc * tr / 255, gc * tg / 255, bc * tb / 255, ac * ta / 255
|
||||
end
|
||||
local flat = not textured and ra == rb and ra == rc and ga == gb and ga == gc and ba == bb and ba == bc and aa == ab
|
||||
and aa == ac
|
||||
if flat and aa <= 0 then return end
|
||||
local f_opaque, f_packed, f_sa, f_ns, f_c1, f_rs, f_gs, f_bs = false, 0, 0, 0, 0, 0, 0, 0
|
||||
if flat then
|
||||
f_opaque = aa >= 255
|
||||
f_packed = floor(ra + 0.5) + floor(ga + 0.5) * 256 + floor(ba + 0.5) * 65536
|
||||
+ (f_opaque and 4278190080 or floor(aa + 0.5) * 16777216)
|
||||
f_sa = aa / 255
|
||||
f_ns = 1 - f_sa
|
||||
f_c1 = f_ns / 255
|
||||
f_rs, f_gs, f_bs = ra * f_sa, ga * f_sa, ba * f_sa
|
||||
end
|
||||
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
|
||||
local xl, xr = minx, maxx
|
||||
local e0, e1, e2 = B0 * py + C0, B1 * py + C1, B2 * py + C2
|
||||
-- (e * n is -e / A within an ulp; the 1e-6 margin covers that, and the exact tests below decide)
|
||||
if A0 > 0 then
|
||||
xl = max(xl, floor(e0 * n0 - 0.500001))
|
||||
elseif A0 < 0 then
|
||||
xr = min(xr, ceil(e0 * n0 - 0.499999))
|
||||
end
|
||||
if A1 > 0 then
|
||||
xl = max(xl, floor(e1 * n1 - 0.500001))
|
||||
elseif A1 < 0 then
|
||||
xr = min(xr, ceil(e1 * n1 - 0.499999))
|
||||
end
|
||||
if A2 > 0 then
|
||||
xl = max(xl, floor(e2 * n2 - 0.500001))
|
||||
elseif A2 < 0 then
|
||||
xr = min(xr, ceil(e2 * n2 - 0.499999))
|
||||
end
|
||||
|
||||
while xl <= xr do
|
||||
local px = xl + 0.5
|
||||
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2
|
||||
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
|
||||
break
|
||||
end
|
||||
xl += 1
|
||||
end
|
||||
while xr > xl do
|
||||
local px = xr + 0.5
|
||||
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2
|
||||
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
|
||||
break
|
||||
end
|
||||
xr -= 1
|
||||
end
|
||||
if xl > xr then continue end
|
||||
local o = (y * TargetWidth + xl) * 4
|
||||
if flat then
|
||||
local o1 = o + (xr - xl) * 4
|
||||
if f_opaque then
|
||||
for oo = o, o1, 4 do writeu32(dbuf, oo, f_packed) end
|
||||
continue
|
||||
end
|
||||
local last_d, last_v = -1, 0
|
||||
for oo = o, o1, 4 do
|
||||
local d = readu32(dbuf, oo)
|
||||
if d == last_d then
|
||||
writeu32(dbuf, oo, last_v)
|
||||
elseif d < 16777216 then
|
||||
writeu32(dbuf, oo, f_packed)
|
||||
else
|
||||
last_d = d
|
||||
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
|
||||
if d >= 4278190080 then
|
||||
last_v = floor(f_rs + dr * f_ns + 0.5) + floor(f_gs + dg * f_ns + 0.5) * 256
|
||||
+ floor(f_bs + db * f_ns + 0.5) * 65536 + 4278190080
|
||||
else
|
||||
local k = rshift(d, 24) * f_c1
|
||||
local oa = f_sa + k
|
||||
local inv = 1 / oa
|
||||
last_v = floor((f_rs + dr * k) * inv + 0.5) + floor((f_gs + dg * k) * inv + 0.5) * 256
|
||||
+ floor((f_bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
|
||||
end
|
||||
writeu32(dbuf, oo, last_v)
|
||||
end
|
||||
end
|
||||
continue
|
||||
end
|
||||
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
|
||||
local a = w0 * aa + w1 * ab + w2 * ac
|
||||
if textured then
|
||||
local r = w0 * ra + w1 * rb + w2 * rc
|
||||
local g = w0 * ga + w1 * gb + w2 * gc
|
||||
local b = w0 * ba + w1 * bb + w2 * bc
|
||||
local tr, tg, tb, ta = SampleTexture(t, w0 * ua + w1 * ub + w2 * uc, w0 * vva + w1 * vvb + w2 * vvc)
|
||||
BlendPixel(dbuf, o, r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255)
|
||||
elseif a > 0 then
|
||||
BlendPixel(dbuf, o, w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc,
|
||||
w0 * ba + w1 * bb + w2 * bc, a)
|
||||
end
|
||||
o += 4
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- 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,
|
||||
cb: number, kind: number, t, u: number, v: number, cx0: number, cy0: number, cx1: number, cy1: number)
|
||||
local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0)
|
||||
local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1)
|
||||
if px0 >= px1 or py0 >= py1 then return end
|
||||
Shrink(px0, py0, px1, py1)
|
||||
local ra, ga, ba, aa = UnpackColor(ca)
|
||||
local rb, gb, bb, ab = UnpackColor(cb)
|
||||
if t then
|
||||
local tr, tg, tb, ta = SampleTexture(t, u, v)
|
||||
ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255
|
||||
rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255
|
||||
end
|
||||
if kind == 1 then
|
||||
local inv = 1 / (y1 - y0)
|
||||
for y = py0, py1 - 1 do
|
||||
local f = (y + 0.5 - y0) * inv
|
||||
local nf = 1 - f
|
||||
FillSpan(TargetBuffer, y, y + 1, px0, px1, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f,
|
||||
aa * nf + ab * f)
|
||||
end
|
||||
else
|
||||
local inv = 1 / (x1 - x0)
|
||||
local len = (px1 - px0) * 4
|
||||
local opaque = aa >= 255 and ab >= 255
|
||||
local prev_o = 0
|
||||
for y = py0, py1 - 1 do
|
||||
local o = (y * TargetWidth + px0) * 4
|
||||
if y > py0 and (opaque or RowRepeats(o, len, true))
|
||||
or (y == py0 and not opaque and RowRepeats(o, len, false)) then
|
||||
buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len)
|
||||
else
|
||||
local oo = o
|
||||
for x = px0, px1 - 1 do
|
||||
local f = (x + 0.5 - x0) * inv
|
||||
local nf = 1 - f
|
||||
BlendPixel(TargetBuffer, oo, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f)
|
||||
oo = oo + 4
|
||||
end
|
||||
end
|
||||
prev_o = o
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function M.SetTarget(buf: buffer, width: number)
|
||||
TargetBuffer, TargetWidth = buf, width
|
||||
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
|
||||
for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4, 0, rw * 4) end
|
||||
end
|
||||
end
|
||||
|
||||
@native
|
||||
function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: number)
|
||||
for y = 0, rh - 1 do
|
||||
buffer.copy(dst, y * rw * 4, TargetBuffer, ((ry0 + y) * TargetWidth + rx0) * 4, rw * 4)
|
||||
end
|
||||
end
|
||||
|
||||
-- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2, 4 line quad (va vb vc vd)
|
||||
@native
|
||||
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
|
||||
if kind == 1 then
|
||||
DrawRect(TargetBuffer, ax, ay, cx, cy, readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16),
|
||||
readf64(vbuf, vc + 24), readu32(vbuf, va + 32), t, cx0, cy0, cx1, cy1)
|
||||
else
|
||||
DrawRectGradient(TargetBuffer, ax, ay, cx, cy, readu32(vbuf, va + 32), readu32(vbuf, vc + 32), kind - 1, t,
|
||||
readf64(vbuf, va + 16), readf64(vbuf, va + 24), cx0, cy0, cx1, cy1)
|
||||
end
|
||||
end
|
||||
M.DrawPrim = DrawPrim
|
||||
|
||||
-- Packed tile jobs -> one exact-size buffer per rect, in job order (worker + main-thread fallback)
|
||||
local Scratch = buffer.create(TILE * TILE * 4)
|
||||
@native
|
||||
function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
|
||||
local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect
|
||||
local REC_A, REC_B, REC_C, 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
|
||||
while o < tlen do
|
||||
local tox, toy = readf64(T, o), readf64(T, o + 8)
|
||||
local x0, y0, nr, count = readi32(T, o + 16), readi32(T, o + 20), readi32(T, o + 24), readi32(T, o + 28)
|
||||
local ro = o + 32
|
||||
local po = ro + nr * 16
|
||||
o = po + count * 4
|
||||
for r = 0, nr - 1 do
|
||||
local rx0, ry0, rx1, ry1 = readi32(T, ro + r * 16), readi32(T, ro + r * 16 + 4),
|
||||
readi32(T, ro + r * 16 + 8), readi32(T, ro + r * 16 + 12)
|
||||
ClearRect(rx0, ry0, rx1, ry1)
|
||||
for k = 0, count - 1 do
|
||||
local q = readi32(T, po + k * 4)
|
||||
local cx0, cy0 = max(readi32(P, q + 8) - x0, rx0), max(readi32(P, q + 12) - y0, ry0)
|
||||
local cx1, cy1 = min(readi32(P, q + 16) - x0, rx1), min(readi32(P, q + 20) - y0, ry1)
|
||||
if cx0 >= cx1 or cy0 >= cy1 or readi32(P, q + 24) - x0 >= rx1 or readi32(P, q + 28) - y0 >= ry1
|
||||
or readi32(P, q + 32) - x0 <= rx0 or readi32(P, q + 36) - y0 <= ry0 then
|
||||
continue
|
||||
end
|
||||
local tid, t = readi32(P, q + 4), nil
|
||||
if tid >= 0 then t = textures[tid] end
|
||||
DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, q + REC_D, tox, toy, cx0, cy0, cx1, cy1)
|
||||
end
|
||||
local rw, rh = rx1 - rx0, ry1 - ry0
|
||||
local sub = buffer.create(rw * rh * 4)
|
||||
CopySubRect(sub, rx0, ry0, rw, rh)
|
||||
no += 1
|
||||
out[no] = sub
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,865 @@
|
||||
-- Rendering: collect primitives, hash them into tiles, redraw + upload changed tiles (RenderDrawData).
|
||||
local Raster = IM_INCLUDE("roblox/raster.lua")
|
||||
local Textures = IM_INCLUDE("roblox/textures.lua")
|
||||
local Layers = IM_INCLUDE("roblox/layers.lua")
|
||||
local Overlays = IM_INCLUDE("roblox/overlays.lua")
|
||||
|
||||
local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max
|
||||
local readu32, readf64 = buffer.readu32, buffer.readf64
|
||||
local SetTarget, ClearRect, DrawPrim, CopySubRect = Raster.SetTarget, Raster.ClearRect, Raster.DrawPrim,
|
||||
Raster.CopySubRect
|
||||
local TILE = Raster.TILE
|
||||
local TILE_SIZE = Vector2.new(TILE, TILE)
|
||||
local EditableImages, PB, PE, GetBackendData, UpdateTexture = Textures.EditableImages, Textures.PB, Textures.PE,
|
||||
Textures.GetBackendData, Textures.UpdateTexture
|
||||
local GetLayer, HideLayer, GetTile, DestroyLayerSet, Snapshot, CompareDrawList, ShiftLayer = Layers.GetLayer,
|
||||
Layers.HideLayer, Layers.GetTile, Layers.DestroyLayerSet, Layers.Snapshot, Layers.CompareDrawList, Layers.ShiftLayer
|
||||
local CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1 = Layers.CmdUnclipped, Layers.CmdKind,
|
||||
Layers.CmdBoundsX0, Layers.CmdBoundsY0, Layers.CmdBoundsX1, Layers.CmdBoundsY1
|
||||
local CLIP_PAD = Layers.CLIP_PAD
|
||||
local PlaceOverlays = Overlays.PlaceOverlays
|
||||
|
||||
local M = {}
|
||||
-- Parallel executor state; parallel.lua adds its functions. On: enabled; Active: used by the current RenderDrawData.
|
||||
local Parallel = { On = false, Active = false }
|
||||
M.Parallel = Parallel
|
||||
|
||||
local P1, P2 = 2147483647, 2147483629 -- two independent 31 bit hashes per tile (collision odds ~2^-62)
|
||||
local LAYER_KEEP_FRAMES = 120
|
||||
local MAX_DEFER_FRAMES = 8 -- a changed tile is redrawn at the latest this many frames later, even over the budget
|
||||
|
||||
local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient = {}, {}, {}, {}, {}, {}
|
||||
local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = {}, {}, {}, {}
|
||||
local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = {}, {}, {}, {}
|
||||
local PrimTexId, PrimVtxBuffer, PrimKind = {}, {}, {}
|
||||
local LayerPrims1, LayerPrims2, LayerPrims3 = {}, {}, {}
|
||||
M.PrimA, M.PrimB, M.PrimC, M.PrimD = PrimA, PrimB, PrimC, PrimD
|
||||
M.PrimTexture, M.PrimGradient = PrimTexture, PrimGradient
|
||||
M.PrimClipX0, M.PrimClipY0, M.PrimClipX1, M.PrimClipY1 = PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1
|
||||
M.PrimBoundsX0, M.PrimBoundsY0, M.PrimBoundsX1, M.PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1
|
||||
M.PrimTexId, M.PrimVtxBuffer = PrimTexId, PrimVtxBuffer
|
||||
|
||||
-- Adds [a, c) x [b, d) to the n dirty rects DX0..DY1 (merged unless that wastes area), returns the count
|
||||
EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1 = {}, {}, {}, {}
|
||||
@native
|
||||
function EditableImages.AddRect(n: number, a: number, b: number, c: number, d: number): number
|
||||
if a >= c or b >= d then return n end
|
||||
local X0, Y0, X1, Y1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1
|
||||
local best, best_grow = 1, math.huge
|
||||
for i = 1, n do
|
||||
local e, f, g, h = X0[i], Y0[i], X1[i], Y1[i]
|
||||
local ux0, uy0, ux1, uy1 = min(a, e), min(b, f), max(c, g), max(d, h)
|
||||
local box, own = (ux1 - ux0) * (uy1 - uy0), (g - e) * (h - f)
|
||||
local ov = max(min(c, g) - max(a, e), 0) * max(min(d, h) - max(b, f), 0)
|
||||
-- waste outside both rects vs. apart: the overlap twice + a primitive pass and an upload (~2048 px)
|
||||
if box - ((c - a) * (d - b) + own - ov) <= ov + 2048 then
|
||||
X0[i], Y0[i], X1[i], Y1[i] = ux0, uy0, ux1, uy1
|
||||
return n
|
||||
end
|
||||
if box - own < best_grow then best, best_grow = i, box - own end
|
||||
end
|
||||
if n < 4 then
|
||||
n += 1
|
||||
X0[n], Y0[n], X1[n], Y1[n] = a, b, c, d
|
||||
else
|
||||
X0[best], Y0[best], X1[best], Y1[best] = min(a, X0[best]), min(b, Y0[best]), max(c, X1[best]), max(d, Y1[best])
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
@native
|
||||
local function HashVertex(h1: number, h2: number, vbuf: buffer, v: number, ox: number, oy: number)
|
||||
local x, y = readf64(vbuf, v) - ox, readf64(vbuf, v + 8) - oy
|
||||
local uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24)
|
||||
local c = readu32(vbuf, v + 32)
|
||||
-- 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
|
||||
|
||||
@native
|
||||
local function HashTiles(layer, plist, np, lx0, ly0, ox, oy)
|
||||
local TileHash1, TileHash2, TileCounts, TileLists, Touched =
|
||||
layer.TileHash1, layer.TileHash2, layer.TileCounts, layer.TileLists, layer.Touched
|
||||
local TileListHash1, TileListHash2, TileListFlat = layer.TileListHash1, layer.TileListHash2, layer.TileListFlat
|
||||
for k = 1, layer.TouchedCount do TileCounts[Touched[k]] = 0 end
|
||||
local TouchedCount = 0
|
||||
local CurKey, CurCount, CurHash1, CurHash2, CurList, CurListHash1, CurListHash2, CurListFlat =
|
||||
nil, 0, 0, 0, nil, nil, nil, nil
|
||||
local TileXs, TileYs = layer.TileX, layer.TileY
|
||||
for pi = 1, np do
|
||||
local p = plist[pi]
|
||||
local tex_id = PrimTexId[p]
|
||||
-- hash the clipped bounds, not the clip: a window clipped by the fixed viewport stays hash-stable when moved
|
||||
local cx0, cy0, cx1, cy1 = PrimBoundsX0[p] - lx0, PrimBoundsY0[p] - ly0, PrimBoundsX1[p] - lx0,
|
||||
PrimBoundsY1[p] - ly0
|
||||
local vbuf = PrimVtxBuffer[p]
|
||||
local va, vd = PrimA[p], PrimD[p]
|
||||
-- flat rect: hash its clipped rect per tile, so resizing only changes the tiles its edges cross
|
||||
local FlatRect, RectColor, RectUV = false, 0, 0
|
||||
if vd and not PrimGradient[p] then
|
||||
local u0, v0 = readf64(vbuf, va + 16), readf64(vbuf, va + 24)
|
||||
local vc = PrimC[p]
|
||||
if not PrimTexture[p] or (u0 == readf64(vbuf, vc + 16) and v0 == readf64(vbuf, vc + 24)) then
|
||||
FlatRect, RectColor, RectUV = true, readu32(vbuf, va + 32), u0 * 8192 + v0
|
||||
end
|
||||
end
|
||||
local h1, h2 = 0, 0
|
||||
local FlatSig = -1
|
||||
if FlatRect then FlatSig = ((RectColor * 8191 + RectUV * 4096) % P1 * 64 + tex_id) % P1 end
|
||||
if not FlatRect then
|
||||
h1 = ((cx0 * 8191 + cy0) * 8191 + cx1) % P1
|
||||
h2 = ((cy1 * 8191 + cx1) * 8191 + cy0 + tex_id) % P2
|
||||
local vax, vay = lx0 + ox, ly0 + oy
|
||||
if vd then
|
||||
-- axis aligned quad: CollectPrims checked that TR/BL follow from TL/BR (+ kind)
|
||||
h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay)
|
||||
h1, h2 = HashVertex(h1, h2, vbuf, PrimC[p], vax, vay)
|
||||
local gk = PrimGradient[p]
|
||||
if gk then
|
||||
h1 = (h1 * 48271 + gk) % P1
|
||||
h2 = (h2 * 16807 + gk * 3) % P2
|
||||
end
|
||||
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)
|
||||
h1, h2 = HashVertex(h1, h2, vbuf, PrimC[p], vax, vay)
|
||||
end
|
||||
end
|
||||
for ty = floor((PrimBoundsY0[p] - ly0) / TILE), floor((PrimBoundsY1[p] - 1 - ly0) / TILE) do
|
||||
for tx = floor((PrimBoundsX0[p] - lx0) / TILE), floor((PrimBoundsX1[p] - 1 - lx0) / TILE) do
|
||||
if FlatRect then
|
||||
local tx0, ty0 = tx * TILE, ty * TILE
|
||||
local ix0, iy0 = max(cx0 - tx0, 0), max(cy0 - ty0, 0)
|
||||
local ix1, iy1 = min(cx1 - tx0, TILE), min(cy1 - ty0, TILE)
|
||||
local r = ((ix0 * 131 + iy0) * 131 + ix1) * 131 + iy1
|
||||
h1 = ((r * 48271 + RectColor) % P1 * 48271 + RectUV * 4096 + 7) % P1
|
||||
h2 = ((r * 16807 + RectColor + tex_id) % P2 * 16807 + RectUV * 65521 + 11) % P2
|
||||
end
|
||||
-- unique for |tx|, |ty| < 32768 (content tiles go negative)
|
||||
local key = (ty + 32768) * 65536 + tx + 32768
|
||||
if key ~= CurKey then
|
||||
if CurKey then
|
||||
TileCounts[CurKey], TileHash1[CurKey], TileHash2[CurKey] = CurCount, CurHash1, CurHash2
|
||||
end
|
||||
CurKey = key
|
||||
CurCount = TileCounts[key]
|
||||
if not CurCount or CurCount == 0 then
|
||||
CurCount, CurHash1, CurHash2 = 0, 0, 0
|
||||
if not TileLists[key] then
|
||||
local ListPool = EditableImages.ListPool
|
||||
local m = #ListPool
|
||||
if m >= 4 then
|
||||
TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key] =
|
||||
ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m]
|
||||
ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m] = nil, nil, nil, nil
|
||||
else
|
||||
TileLists[key] = {}
|
||||
TileListHash1[key] = {}
|
||||
TileListHash2[key] = {}
|
||||
TileListFlat[key] = {}
|
||||
end
|
||||
end
|
||||
TouchedCount = TouchedCount + 1
|
||||
Touched[TouchedCount] = key
|
||||
TileXs[key], TileYs[key] = tx, ty
|
||||
else
|
||||
CurHash1, CurHash2 = TileHash1[key], TileHash2[key]
|
||||
end
|
||||
CurList, CurListHash1, CurListHash2, CurListFlat =
|
||||
TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key]
|
||||
end
|
||||
CurCount += 1
|
||||
CurList[CurCount], CurListHash1[CurCount], CurListHash2[CurCount], CurListFlat[CurCount] =
|
||||
p, h1, h2, FlatSig
|
||||
CurHash1 = (CurHash1 * 48271 + h1) % P1
|
||||
CurHash2 = (CurHash2 * 16807 + h2 + CurCount) % P2
|
||||
end
|
||||
end
|
||||
end
|
||||
if CurKey then TileCounts[CurKey], TileHash1[CurKey], TileHash2[CurKey] = CurCount, CurHash1, CurHash2 end
|
||||
layer.TouchedCount = TouchedCount
|
||||
return TouchedCount
|
||||
end
|
||||
|
||||
local function PlaceLayer(layer, scale, lx0, ly0, z, clip_x0, clip_y0, clip_x1, clip_y1)
|
||||
local root = layer.Root
|
||||
if root ~= layer.Frame then
|
||||
if layer.ClipX0 ~= clip_x0 or layer.ClipY0 ~= clip_y0 or layer.ClipX1 ~= clip_x1 or layer.ClipY1 ~= clip_y1 then
|
||||
layer.ClipX0, layer.ClipY0, layer.ClipX1, layer.ClipY1 = clip_x0, clip_y0, clip_x1, clip_y1
|
||||
root.Position = UDim2.fromOffset(clip_x0 / scale, clip_y0 / scale)
|
||||
root.Size = UDim2.fromOffset((clip_x1 - clip_x0) / scale, (clip_y1 - clip_y0) / scale)
|
||||
layer.X = false
|
||||
end
|
||||
if layer.X ~= lx0 or layer.Y ~= ly0 then
|
||||
layer.X, layer.Y = lx0, ly0
|
||||
layer.Frame.Position = UDim2.fromOffset((lx0 - clip_x0) / scale, (ly0 - clip_y0) / scale)
|
||||
end
|
||||
elseif layer.X ~= lx0 or layer.Y ~= ly0 then
|
||||
layer.X, layer.Y = lx0, ly0
|
||||
root.Position = UDim2.fromOffset(lx0 / scale, ly0 / scale)
|
||||
end
|
||||
if layer.Z ~= z then
|
||||
layer.Z = z
|
||||
root.ZIndex = z
|
||||
end
|
||||
if not layer.Visible then
|
||||
layer.Visible = true
|
||||
root.Visible = true
|
||||
end
|
||||
end
|
||||
|
||||
local function SweepTiles(BackendData, layer, TouchedCount, lx0, ly0, clip_x0, clip_y0, clip_x1, clip_y1)
|
||||
local TileCounts, Touched = layer.TileCounts, layer.Touched
|
||||
-- content layer: only tiles inside its clip frame are kept, so scrolling holds the visible tiles + a few spares
|
||||
local FrameNo, VisibleCount, SpareCap = BackendData.FrameNo, TouchedCount, TouchedCount
|
||||
if layer.Root ~= layer.Frame then
|
||||
for kk = 1, TouchedCount do
|
||||
local key = Touched[kk]
|
||||
local x0, y0 = lx0 + layer.TileX[key] * TILE, ly0 + layer.TileY[key] * TILE
|
||||
if x0 >= clip_x1 or y0 >= clip_y1 or x0 + TILE <= clip_x0 or y0 + TILE <= clip_y0 then
|
||||
TileCounts[key] = 0
|
||||
VisibleCount -= 1
|
||||
end
|
||||
end
|
||||
SpareCap = min(VisibleCount, 4)
|
||||
end
|
||||
-- unused tiles stay for a quick scroll back: at most SpareCap of them, for at most KEEP_FRAMES
|
||||
local spare = 0
|
||||
for key, tile in pairs(layer.Tiles) do
|
||||
if not TileCounts[key] or TileCounts[key] == 0 then
|
||||
if tile.Visible then
|
||||
tile.Visible = false
|
||||
tile.Label.Visible = false
|
||||
tile.Hash1 = -1
|
||||
tile.DrawnCount = -1
|
||||
end
|
||||
spare += 1
|
||||
if spare > SpareCap or FrameNo - tile.Used > EditableImages.KEEP_FRAMES then
|
||||
EditableImages.FreeTile(layer, key, true)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@native
|
||||
local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, vy0, vx1, vy1)
|
||||
local qx0, qy0, qx1, qy1 = tile.ValidX0, tile.ValidY0, tile.ValidX1, tile.ValidY1
|
||||
local list, ListHash1, ListHash2 = layer.TileLists[key], layer.TileListHash1[key], layer.TileListHash2[key]
|
||||
local DrawnHash1, DrawnHash2, DrawnX0, DrawnY0, DrawnX1, DrawnY1, DrawnCount =
|
||||
tile.DrawnHash1, tile.DrawnHash2, tile.DrawnX0, tile.DrawnY0, tile.DrawnX1, tile.DrawnY1,
|
||||
tile.DrawnCount
|
||||
local nx0, ny0, nx1, ny1 = TILE, TILE, 0, 0
|
||||
for k = 1, count do
|
||||
local p = list[k]
|
||||
local a, b = PrimBoundsX0[p] - x0, PrimBoundsY0[p] - y0
|
||||
local c, d = PrimBoundsX1[p] - x0, PrimBoundsY1[p] - y0
|
||||
if a < nx0 then nx0 = a end
|
||||
if b < ny0 then ny0 = b end
|
||||
if c > nx1 then nx1 = c end
|
||||
if d > ny1 then ny1 = d end
|
||||
end
|
||||
nx0, ny0, nx1, ny1 = max(nx0, 0), max(ny0, 0), min(nx1, TILE), min(ny1, TILE)
|
||||
local DX0, DY0, DX1, DY1, AddRect = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1,
|
||||
EditableImages.DY1, EditableImages.AddRect
|
||||
local DirtyCount = 0
|
||||
if force or DrawnCount < 0 then
|
||||
-- outside the old + new content bounds the valid part is already transparent
|
||||
DirtyCount = AddRect(AddRect(0, tile.ContentX0, tile.ContentY0, tile.ContentX1, tile.ContentY1), nx0,
|
||||
ny0, nx1, ny1)
|
||||
else
|
||||
-- partial redraw: a pixel no changed primitive (old or new) touches is covered by the same primitives in the
|
||||
-- same order, so only the bounds of the changed ones are redrawn
|
||||
local i, lim = 1, min(DrawnCount, count)
|
||||
while i <= lim and DrawnHash1[i] == ListHash1[i] and DrawnHash2[i] == ListHash2[i] do i += 1 end
|
||||
local j = 0
|
||||
while j <= lim - i and DrawnHash1[DrawnCount - j] == ListHash1[count - j]
|
||||
and DrawnHash2[DrawnCount - j] == ListHash2[count - j] do
|
||||
j += 1
|
||||
end
|
||||
local of, lf = tile.DrawnFlat, layer.TileListFlat[key]
|
||||
local paired = DrawnCount - j - i == count - j - i
|
||||
for k = i, count - j do
|
||||
local p = list[k]
|
||||
local a, b, c, d = max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0),
|
||||
min(PrimBoundsX1[p] - x0, TILE), min(PrimBoundsY1[p] - y0, TILE)
|
||||
local oa, ob, oc, od = DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k]
|
||||
if paired and lf[k] >= 0 and lf[k] == of[k] then
|
||||
-- same flat rect, new bounds: only the strips between the old and new edges can differ
|
||||
local uy0, uy1 = min(b, ob), max(d, od)
|
||||
local ux0, ux1 = min(a, oa), max(c, oc)
|
||||
if a ~= oa then DirtyCount = AddRect(DirtyCount, ux0, uy0, max(a, oa), uy1) end
|
||||
if c ~= oc then DirtyCount = AddRect(DirtyCount, min(c, oc), uy0, ux1, uy1) end
|
||||
if b ~= ob then DirtyCount = AddRect(DirtyCount, ux0, uy0, ux1, max(b, ob)) end
|
||||
if d ~= od then DirtyCount = AddRect(DirtyCount, ux0, min(d, od), ux1, uy1) end
|
||||
else
|
||||
DirtyCount = AddRect(DirtyCount, a, b, c, d)
|
||||
if k <= DrawnCount - j then DirtyCount = AddRect(DirtyCount, oa, ob, oc, od) end
|
||||
end
|
||||
end
|
||||
for k = count - j + 1, DrawnCount - j do
|
||||
DirtyCount = AddRect(DirtyCount, DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k])
|
||||
end
|
||||
end
|
||||
-- clip D to V, then add the exposed part that isn't valid. cut: part of D inside the valid rect was clipped away
|
||||
local cut, RectCount = false, 0
|
||||
for r = 1, DirtyCount do
|
||||
local a, b, c, d = DX0[r], DY0[r], DX1[r], DY1[r]
|
||||
local ix0, iy0, ix1, iy1 = max(a, qx0), max(b, qy0), min(c, qx1), min(d, qy1)
|
||||
if ix0 < ix1 and iy0 < iy1 and (ix0 < vx0 or iy0 < vy0 or ix1 > vx1 or iy1 > vy1) then cut = true end
|
||||
a, b, c, d = max(a, vx0), max(b, vy0), min(c, vx1), min(d, vy1)
|
||||
if a < c and b < d then
|
||||
RectCount += 1
|
||||
DX0[RectCount], DY0[RectCount], DX1[RectCount], DY1[RectCount] = a, b, c, d
|
||||
end
|
||||
end
|
||||
if exposed then
|
||||
local ex0, ey0, ex1, ey1 = vx0, vy0, vx1, vy1
|
||||
if qx0 <= vx0 and qx1 >= vx1 then
|
||||
if qy0 <= vy0 and qy1 > vy0 then ey0 = qy1 elseif qy1 >= vy1 and qy0 < vy1 then ey1 = qy0 end
|
||||
elseif qy0 <= vy0 and qy1 >= vy1 then
|
||||
if qx0 <= vx0 and qx1 > vx0 then ex0 = qx1 elseif qx1 >= vx1 and qx0 < vx1 then ex1 = qx0 end
|
||||
end
|
||||
RectCount = AddRect(RectCount, ex0, ey0, ex1, ey1)
|
||||
end
|
||||
if cut then
|
||||
qx0, qy0, qx1, qy1 = vx0, vy0, vx1, vy1
|
||||
elseif exposed then
|
||||
if (qx0 == vx0 and qx1 == vx1 and qy0 <= vy1 and vy0 <= qy1)
|
||||
or (qy0 == vy0 and qy1 == vy1 and qx0 <= vx1 and vx0 <= qx1)
|
||||
or (qx0 >= vx0 and qy0 >= vy0 and qx1 <= vx1 and qy1 <= vy1) then
|
||||
qx0, qy0, qx1, qy1 = min(qx0, vx0), min(qy0, vy0), max(qx1, vx1), max(qy1, vy1)
|
||||
else
|
||||
qx0, qy0, qx1, qy1 = vx0, vy0, vx1, vy1
|
||||
end
|
||||
end
|
||||
tile.ValidX0, tile.ValidY0, tile.ValidX1, tile.ValidY1 = qx0, qy0, qx1, qy1
|
||||
tile.ContentX0, tile.ContentY0, tile.ContentX1, tile.ContentY1 = nx0, ny0, nx1, ny1
|
||||
local DrawnFlat, ListFlat = tile.DrawnFlat, layer.TileListFlat[key]
|
||||
for k = 1, count do
|
||||
local p = list[k]
|
||||
DrawnHash1[k], DrawnHash2[k], DrawnFlat[k] = ListHash1[k], ListHash2[k], ListFlat[k]
|
||||
DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k] =
|
||||
max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0), min(PrimBoundsX1[p] - x0, TILE),
|
||||
min(PrimBoundsY1[p] - y0, TILE)
|
||||
end
|
||||
tile.DrawnCount = count
|
||||
return RectCount
|
||||
end
|
||||
|
||||
@native
|
||||
local function RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1)
|
||||
ClearRect(rx0, ry0, rx1, ry1)
|
||||
for k = 1, count do
|
||||
local p = list[k]
|
||||
local cx0, cy0 = max(PrimClipX0[p] - x0, rx0), max(PrimClipY0[p] - y0, ry0)
|
||||
local cx1, cy1 = min(PrimClipX1[p] - x0, rx1), min(PrimClipY1[p] - y0, ry1)
|
||||
if cx0 >= cx1 or cy0 >= cy1 or PrimBoundsX0[p] - x0 >= rx1 or PrimBoundsY0[p] - y0 >= ry1
|
||||
or PrimBoundsX1[p] - x0 <= rx0 or PrimBoundsY1[p] - y0 <= ry0 then
|
||||
continue
|
||||
end
|
||||
local kind, gk = 0, PrimGradient[p]
|
||||
if PrimD[p] then kind = gk and gk + 1 or 1 end
|
||||
DrawPrim(kind, PrimTexture[p], PrimVtxBuffer[p], PrimA[p], PrimB[p], PrimC[p], PrimD[p] or 0, tox, toy, cx0, cy0, cx1, cy1)
|
||||
end
|
||||
end
|
||||
|
||||
-- WritePixelsBuffer needs the exact size: partial upload buffers are reused by size
|
||||
local SubBuffers, SubBufferCount = {}, 0
|
||||
local function UploadRect(img, buf, rx0, ry0, rx1, ry1)
|
||||
local rw, rh = rx1 - rx0, ry1 - ry0
|
||||
if rw == TILE and rh == TILE then
|
||||
img:WritePixelsBuffer(Vector2.zero, TILE_SIZE, buf)
|
||||
return
|
||||
end
|
||||
local sk = rw * 1024 + rh
|
||||
local sub = SubBuffers[sk]
|
||||
if not sub then
|
||||
if SubBufferCount >= 256 then
|
||||
table.clear(SubBuffers)
|
||||
SubBufferCount = 0
|
||||
end
|
||||
sub = buffer.create(rw * rh * 4)
|
||||
SubBuffers[sk] = sub
|
||||
SubBufferCount += 1
|
||||
end
|
||||
CopySubRect(sub, rx0, ry0, rw, rh)
|
||||
img:WritePixelsBuffer(Vector2.new(rx0, ry0), Vector2.new(rw, rh), sub)
|
||||
end
|
||||
|
||||
local function RedrawTile(BackendData, layer, key, tile, count, x0, y0, ox, oy, force, exposed, vx0, vy0, vx1, vy1)
|
||||
BackendData.RedrawStarted = true
|
||||
BackendData.FrameTiles += 1
|
||||
tile.Deferred = 0
|
||||
tile.Hash1, tile.Hash2 = layer.TileHash1[key], layer.TileHash2[key]
|
||||
local RectCount = DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, vy0, vx1, vy1)
|
||||
local list = layer.TileLists[key]
|
||||
local tox, toy = ox + x0, oy + y0
|
||||
local Timing = EditableImages.StageTiming and EditableImages.StageFrame
|
||||
if Timing and RectCount > 0 then Timing.TilesRasterized += 1 end
|
||||
-- parallel: rasterized + uploaded later in the frame (pixels outside the rects are never read)
|
||||
if Parallel.Active and RectCount > 0 then
|
||||
Parallel.Tile(tile.Image, list, count, x0, y0, tox, toy, RectCount)
|
||||
return
|
||||
end
|
||||
SetTarget(tile.Buffer, TILE)
|
||||
local DX0, DY0, DX1, DY1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1
|
||||
for r = 1, RectCount do
|
||||
local rx0, ry0, rx1, ry1 = DX0[r], DY0[r], DX1[r], DY1[r]
|
||||
RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1)
|
||||
PB("ImGui upload")
|
||||
local t_up = Timing and os.clock()
|
||||
if Timing then
|
||||
Timing.PixelsRasterized += (rx1 - rx0) * (ry1 - ry0)
|
||||
Timing.Uploads += 1
|
||||
end
|
||||
UploadRect(tile.Image, tile.Buffer, rx0, ry0, rx1, ry1)
|
||||
if Timing then Timing.Upload += os.clock() - t_up end
|
||||
PE()
|
||||
end
|
||||
end
|
||||
|
||||
local function DrawLayer(BackendData, layer, plist, np, lx0, ly0, ox, oy, force, z, clip_x0, clip_y0, clip_x1, clip_y1)
|
||||
PB("ImGui tile hash")
|
||||
if EditableImages.StageTiming then EditableImages.BeginStage() end
|
||||
local TouchedCount = HashTiles(layer, plist, np, lx0, ly0, ox, oy)
|
||||
if EditableImages.StageTiming then EditableImages.EndStage("Hash") end
|
||||
PE()
|
||||
|
||||
PlaceLayer(layer, BackendData.Scale, lx0, ly0, z, clip_x0, clip_y0, clip_x1, clip_y1)
|
||||
|
||||
PB("ImGui raster+upload")
|
||||
if EditableImages.StageTiming then EditableImages.BeginStage() end
|
||||
SweepTiles(BackendData, layer, TouchedCount, lx0, ly0, clip_x0, clip_y0, clip_x1, clip_y1)
|
||||
local TileCounts, Touched, TileHash1, TileHash2 = layer.TileCounts, layer.Touched, layer.TileHash1, layer.TileHash2
|
||||
local content = layer.Root ~= layer.Frame
|
||||
local FrameNo, deferred = BackendData.FrameNo, false
|
||||
for kk = 1, TouchedCount do
|
||||
local key = Touched[kk]
|
||||
local count = TileCounts[key]
|
||||
if not count or count == 0 then continue end -- outside the content clip, or list freed
|
||||
local tx, ty = layer.TileX[key], layer.TileY[key]
|
||||
local tile = GetTile(BackendData, layer, key, tx, ty)
|
||||
if not tile then continue end
|
||||
tile.Used = FrameNo
|
||||
local x0, y0 = lx0 + tx * TILE, ly0 + ty * TILE
|
||||
-- redraws are clipped to the visible part; a part scrolled into view that isn't valid is redrawn then
|
||||
local vx0, vy0, vx1, vy1 = 0, 0, TILE, TILE
|
||||
if content then
|
||||
vx0, vy0, vx1, vy1 = max(clip_x0 - x0, 0), max(clip_y0 - y0, 0), min(clip_x1 - x0, TILE), min(clip_y1 - y0,
|
||||
TILE)
|
||||
end
|
||||
local exposed = vx0 < tile.ValidX0 or vy0 < tile.ValidY0 or vx1 > tile.ValidX1 or vy1 > tile.ValidY1
|
||||
local dirty = force or exposed or tile.Hash1 ~= TileHash1[key] or tile.Hash2 ~= TileHash2[key]
|
||||
if dirty and BackendData.RedrawStarted and (tile.Deferred or 0) < MAX_DEFER_FRAMES
|
||||
and ((BackendData.RedrawBudget > 0 and os.clock() - BackendData.FrameStartTime >= BackendData.RedrawBudget)
|
||||
or (BackendData.TileLimit and BackendData.FrameTiles >= BackendData.TileLimit)) then
|
||||
-- over budget (TileLimit: t_pixels hook): keep the old pixels (the stored hashes describe them)
|
||||
tile.Deferred = (tile.Deferred or 0) + 1
|
||||
if force then
|
||||
tile.Hash1 = -1
|
||||
tile.DrawnCount = -1
|
||||
end
|
||||
deferred = true
|
||||
dirty = false
|
||||
end
|
||||
if dirty then RedrawTile(BackendData, layer, key, tile, count, x0, y0, ox, oy, force, exposed, vx0, vy0, vx1, vy1) end
|
||||
-- a deferred tile that was hidden holds old pixels: stays hidden until drawn
|
||||
if not tile.Visible and (tile.Deferred or 0) == 0 then
|
||||
tile.Visible = true
|
||||
tile.Label.Visible = true
|
||||
end
|
||||
end
|
||||
if EditableImages.StageTiming then
|
||||
EditableImages.EndStage("Raster")
|
||||
end
|
||||
PE()
|
||||
return deferred
|
||||
end
|
||||
|
||||
local function UpdateTextures(draw_data)
|
||||
PB("ImGui textures")
|
||||
if draw_data.Textures ~= nil then
|
||||
for _, tex in draw_data.Textures:iter() do
|
||||
if tex.Status ~= ImTextureStatus.OK then
|
||||
-- WantUpdates only writes regions no tile has sampled yet: no redraw needed
|
||||
UpdateTexture(tex)
|
||||
end
|
||||
end
|
||||
end
|
||||
PE()
|
||||
end
|
||||
|
||||
local function RenderRateAllows(BackendData, draw_data)
|
||||
local rate = BackendData.RenderRate
|
||||
if BackendData.BusyRenderRate > 0 then
|
||||
local g = ImGui.GetCurrentContext()
|
||||
local busy = g.WheelingWindow ~= nil or g.MovingWindow ~= nil -- (io.MouseWheel is already cleared by EndFrame)
|
||||
if not busy and g.ActiveId ~= 0 then
|
||||
local w = g.ActiveIdWindow
|
||||
local cur = g.MouseCursor
|
||||
busy = (cur >= ImGuiMouseCursor.ResizeAll and cur <= ImGuiMouseCursor.ResizeNWSE)
|
||||
or (w ~= nil and (g.ActiveId == ImGui.GetWindowScrollbarID(w, ImGuiAxis.X)
|
||||
or g.ActiveId == ImGui.GetWindowScrollbarID(w, ImGuiAxis.Y)))
|
||||
end
|
||||
if busy and (rate <= 0 or BackendData.BusyRenderRate < rate) then rate = BackendData.BusyRenderRate end
|
||||
end
|
||||
if rate > 0 then
|
||||
local now = os.clock()
|
||||
-- skipped: kept pending, Heartbeat draws it if no new frame comes
|
||||
if now + 0.002 < BackendData.NextRender then
|
||||
BackendData.Pending = draw_data
|
||||
return false
|
||||
end
|
||||
BackendData.NextRender = math.max(BackendData.NextRender + 1 / rate, now)
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function ReuseDrawList(BackendData, set, draw_list, same, sdx, sdy, z, ox, oy, ScreenWidth, ScreenHeight)
|
||||
for kind = 1, 3 do
|
||||
local layer = set[kind]
|
||||
if layer and layer.Visible then
|
||||
if same == 2 then ShiftLayer(layer, sdx, sdy, BackendData.Scale) end
|
||||
z += 1
|
||||
if layer.Z ~= z then
|
||||
layer.Z = z
|
||||
layer.Root.ZIndex = z
|
||||
end
|
||||
end
|
||||
end
|
||||
if same == 2 then
|
||||
Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
|
||||
set.SnapExtentX0 += sdx
|
||||
set.SnapExtentY0 += sdy
|
||||
set.SnapExtentX1 += sdx
|
||||
set.SnapExtentY1 += sdy
|
||||
end
|
||||
set.LastUsed = BackendData.FrameNo
|
||||
return PlaceOverlays(BackendData, draw_list, z, ox, oy)
|
||||
end
|
||||
|
||||
-- Collects primitives into Prim* (from n + 1) and commands into Cmd*; returns n, LimitFree and the extents
|
||||
@native
|
||||
local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, LimitX1, LimitY1)
|
||||
local vbuf, idx = draw_list.VtxBuffer.Buf, draw_list.IdxBuffer.Data
|
||||
local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1,
|
||||
draw_list._ContentClipY1
|
||||
local SeenContent = false
|
||||
local ex0, ey0, ex1, ey1 = math.huge, math.huge, -math.huge, -math.huge
|
||||
local LimitFree = true
|
||||
if ccx0 then
|
||||
local a, b, c, d = floor(ccx0 - ox), floor(ccy0 - oy), floor(ccx1 - ox), floor(ccy1 - oy)
|
||||
if a < LimitX0 or b < LimitY0 or c > LimitX1 or d > LimitY1 then LimitFree = false end
|
||||
ex0, ey0, ex1, ey1 = min(ex0, a), min(ey0, b), max(ex1, c), max(ey1, d)
|
||||
end
|
||||
local ci = 0
|
||||
for _, pcmd in draw_list.CmdBuffer:iter() do
|
||||
ci += 1
|
||||
CmdUnclipped[ci], CmdKind[ci] = false, 0
|
||||
if pcmd.UserCallback ~= nil then
|
||||
pcmd.UserCallback(draw_list, pcmd)
|
||||
elseif pcmd.ElemCount > 0 then
|
||||
local clip = pcmd.ClipRect
|
||||
local rcx0, rcy0, rcx1, rcy1 = floor(clip.x - ox), floor(clip.y - oy), floor(clip.z - ox),
|
||||
floor(clip.w - oy)
|
||||
if rcx0 < LimitX0 or rcy0 < LimitY0 or rcx1 > LimitX1 or rcy1 > LimitY1 then LimitFree = false end
|
||||
if rcx0 < ex0 then ex0 = rcx0 end
|
||||
if rcy0 < ey0 then ey0 = rcy0 end
|
||||
if rcx1 > ex1 then ex1 = rcx1 end
|
||||
if rcy1 > ey1 then ey1 = rcy1 end
|
||||
local cx0, cy0 = max(rcx0, LimitX0), max(rcy0, LimitY0)
|
||||
local cx1, cy1 = min(rcx1, LimitX1), min(rcy1, LimitY1)
|
||||
local kind = 1
|
||||
if ccx0 and clip.x >= ccx0 and clip.y >= ccy0 and clip.z <= ccx1 and clip.w <= ccy1 then
|
||||
kind = 2
|
||||
SeenContent = true
|
||||
if clip.x == ccx0 and clip.y == ccy0 and clip.z == ccx1 and clip.w == ccy1 then
|
||||
-- clipped by the layer's clip frame instead: partly visible rows stay hash-stable while scrolling
|
||||
cx0, cy0, cx1, cy1 = LimitX0, LimitY0, LimitX1, LimitY1
|
||||
end
|
||||
elseif SeenContent then
|
||||
kind = 3
|
||||
end
|
||||
CmdKind[ci] = kind
|
||||
local CmdFree, cex0, cey0, cex1, cey1 =
|
||||
cx1 > cx0 and cy1 > cy0, math.huge, math.huge, -math.huge, -math.huge
|
||||
if cx1 > cx0 and cy1 > cy0 then
|
||||
local tex_id = pcmd:GetTexID()
|
||||
local t = BackendData.Textures[tex_id]
|
||||
local vo = pcmd.VtxOffset
|
||||
local i, last = pcmd.IdxOffset + 1, pcmd.IdxOffset + pcmd.ElemCount
|
||||
while i <= last do
|
||||
local ia, ic = idx[i], idx[i + 2]
|
||||
local va, vb, vc = (vo + ia - 1) * VTX_STRIDE, (vo + idx[i + 1] - 1) * VTX_STRIDE,
|
||||
(vo + ic - 1) * VTX_STRIDE
|
||||
local vd = false
|
||||
local gk = false
|
||||
local pax, pay = readf64(vbuf, va), readf64(vbuf, va + 8)
|
||||
local pbx, pby = readf64(vbuf, vb), readf64(vbuf, vb + 8)
|
||||
local pcx, pcy = readf64(vbuf, vc), readf64(vbuf, vc + 8)
|
||||
local bx0, by0, bx1, by1
|
||||
if i + 5 <= last and idx[i + 3] == ia and idx[i + 4] == ic then
|
||||
local d = (vo + idx[i + 5] - 1) * VTX_STRIDE
|
||||
local pdx, pdy = readf64(vbuf, d), readf64(vbuf, d + 8)
|
||||
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)
|
||||
local tbx, tby = readf64(vbuf, vb + 16), readf64(vbuf, vb + 24)
|
||||
local tcx, tcy = readf64(vbuf, vc + 16), readf64(vbuf, vc + 24)
|
||||
local tdx, tdy = readf64(vbuf, d + 16), readf64(vbuf, d + 24)
|
||||
if colb == col and colc == col and cold == col then
|
||||
if tbx == tcx and tby == tay and tdx == tax and tdy == tcy then vd = d end
|
||||
elseif tax == tbx and tax == tcx and tax == tdx and tay == tby and tay == tcy
|
||||
and tay == tdy then
|
||||
if colb == col and cold == colc then
|
||||
vd = d
|
||||
gk = 1
|
||||
elseif cold == col and colb == colc then
|
||||
vd = d
|
||||
gk = 2
|
||||
end
|
||||
end
|
||||
if vd then
|
||||
bx0, by0 = ceil(pax - ox - 0.5), ceil(pay - oy - 0.5)
|
||||
bx1, by1 = ceil(pcx - ox - 0.5), ceil(pcy - oy - 0.5)
|
||||
end
|
||||
end
|
||||
end
|
||||
if vd then
|
||||
i = i + 6
|
||||
else
|
||||
bx0, by0 = floor(min(pax, pbx, pcx) - ox), floor(min(pay, pby, pcy) - oy)
|
||||
bx1, by1 = ceil(max(pax, pbx, pcx) - ox) + 1, ceil(max(pay, pby, pcy) - oy) + 1
|
||||
i = i + 3
|
||||
end
|
||||
if bx0 < cx0 or by0 < cy0 or bx1 > cx1 or by1 > cy1 then CmdFree = false end
|
||||
if bx0 < cex0 then cex0 = bx0 end
|
||||
if by0 < cey0 then cey0 = by0 end
|
||||
if bx1 > cex1 then cex1 = bx1 end
|
||||
if by1 > cey1 then cey1 = by1 end
|
||||
if bx0 < ex0 then ex0 = bx0 end
|
||||
if by0 < ey0 then ey0 = by0 end
|
||||
if bx1 > ex1 then ex1 = bx1 end
|
||||
if by1 > ey1 then ey1 = by1 end
|
||||
if bx0 < LimitX0 or by0 < LimitY0 or bx1 > LimitX1 or by1 > LimitY1 then LimitFree = false end
|
||||
if bx0 < cx0 then bx0 = cx0 end
|
||||
if by0 < cy0 then by0 = cy0 end
|
||||
if bx1 > cx1 then bx1 = cx1 end
|
||||
if by1 > cy1 then by1 = cy1 end
|
||||
if bx0 < bx1 and by0 < by1 then
|
||||
n = n + 1
|
||||
PrimA[n], PrimB[n], PrimC[n], PrimD[n], PrimTexture[n], PrimGradient[n], PrimTexId[n],
|
||||
PrimVtxBuffer[n] = va, vb, vc, vd, t, gk, tex_id, vbuf
|
||||
PrimClipX0[n], PrimClipY0[n], PrimClipX1[n], PrimClipY1[n] = cx0, cy0, cx1, cy1
|
||||
PrimBoundsX0[n], PrimBoundsY0[n], PrimBoundsX1[n], PrimBoundsY1[n] = bx0, by0, bx1, by1
|
||||
PrimKind[n] = kind
|
||||
end
|
||||
end
|
||||
end
|
||||
if cex0 > cex1 then cex0, cey0, cex1, cey1 = 0, 0, 0, 0 end
|
||||
CmdUnclipped[ci] = CmdFree
|
||||
CmdBoundsX0[ci], CmdBoundsY0[ci], CmdBoundsX1[ci], CmdBoundsY1[ci] = cex0, cey0, cex1, cey1
|
||||
end
|
||||
end
|
||||
return n, LimitFree, ex0, ey0, ex1, ey1
|
||||
end
|
||||
|
||||
@native
|
||||
local function DrawLists(BackendData, draw_list, first, n, z, ox, oy, force, LimitX0, LimitY0, LimitX1, LimitY1)
|
||||
local set = BackendData.Layers[draw_list]
|
||||
local ListDeferred = false
|
||||
local Kind1Count, Kind2Count, Kind3Count = 0, 0, 0
|
||||
local Kind1X, Kind1Y, Kind3X, Kind3Y = math.huge, math.huge, math.huge, math.huge
|
||||
for p = first, n do
|
||||
local k = PrimKind[p]
|
||||
if k == 1 then
|
||||
Kind1Count += 1
|
||||
LayerPrims1[Kind1Count] = p
|
||||
if PrimBoundsX0[p] < Kind1X then Kind1X = PrimBoundsX0[p] end
|
||||
if PrimBoundsY0[p] < Kind1Y then Kind1Y = PrimBoundsY0[p] end
|
||||
elseif k == 2 then
|
||||
Kind2Count += 1
|
||||
LayerPrims2[Kind2Count] = p
|
||||
else
|
||||
Kind3Count += 1
|
||||
LayerPrims3[Kind3Count] = p
|
||||
if PrimBoundsX0[p] < Kind3X then Kind3X = PrimBoundsX0[p] end
|
||||
if PrimBoundsY0[p] < Kind3Y then Kind3Y = PrimBoundsY0[p] end
|
||||
end
|
||||
end
|
||||
if Kind1Count > 0 then
|
||||
z += 1
|
||||
if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 1), LayerPrims1, Kind1Count, Kind1X, Kind1Y, ox,
|
||||
oy, force, z) then
|
||||
ListDeferred = true
|
||||
end
|
||||
elseif set and set[1] then HideLayer(set[1]) end
|
||||
if Kind2Count > 0 then
|
||||
local ccx0 = draw_list._ContentClipX0
|
||||
local ContentX0, ContentY0, ContentX1, ContentY1
|
||||
if ccx0 then
|
||||
ContentX0, ContentY0 = max(floor(ccx0 - ox), LimitX0), max(floor(draw_list._ContentClipY0 - oy), LimitY0)
|
||||
ContentX1, ContentY1 = min(floor(draw_list._ContentClipX1 - ox), LimitX1),
|
||||
min(floor(draw_list._ContentClipY1 - oy), LimitY1)
|
||||
end
|
||||
z += 1
|
||||
if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 2), LayerPrims2, Kind2Count,
|
||||
floor(draw_list._ScrollOriginX - ox), floor(draw_list._ScrollOriginY - oy), ox, oy, force, z,
|
||||
ContentX0, ContentY0, ContentX1, ContentY1) then ListDeferred = true end
|
||||
elseif set and set[2] then HideLayer(set[2]) end
|
||||
if Kind3Count > 0 then
|
||||
z += 1
|
||||
if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 3), LayerPrims3, Kind3Count, Kind3X, Kind3Y, ox,
|
||||
oy, force, z) then
|
||||
ListDeferred = true
|
||||
end
|
||||
elseif set and set[3] then HideLayer(set[3]) end
|
||||
return z, ListDeferred
|
||||
end
|
||||
|
||||
-- Overlay frames are only hidden (the user owns them); unused layers hidden, long unused ones freed
|
||||
local function SweepLayers(BackendData, FrameNo)
|
||||
for frame, shown in pairs(BackendData.OverlayShown) do
|
||||
if shown ~= FrameNo then
|
||||
frame.Visible = false
|
||||
BackendData.OverlayShown[frame] = nil
|
||||
end
|
||||
end
|
||||
table.clear(BackendData.Overlays)
|
||||
|
||||
for draw_list, set in pairs(BackendData.Layers) do
|
||||
if set.LastUsed ~= FrameNo then
|
||||
set.SnapOK = false
|
||||
for kind = 1, 3 do if set[kind] then HideLayer(set[kind]) end end
|
||||
if FrameNo - set.LastUsed > LAYER_KEEP_FRAMES then
|
||||
DestroyLayerSet(set)
|
||||
BackendData.Layers[draw_list] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function M.RenderDrawData(draw_data)
|
||||
local BackendData = GetBackendData()
|
||||
PB("ImGui RenderDrawData")
|
||||
BackendData.FrameStartTime = os.clock()
|
||||
if EditableImages.StageTiming then
|
||||
EditableImages.StageFrame = { Compare = 0, Collect = 0, Hash = 0, Raster = 0, Upload = 0, 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
|
||||
end
|
||||
|
||||
local ScreenWidth, ScreenHeight = floor(draw_data.DisplaySize.x), floor(draw_data.DisplaySize.y)
|
||||
if ScreenWidth <= 0 or ScreenHeight <= 0 then
|
||||
PE()
|
||||
return
|
||||
end
|
||||
local ox, oy = draw_data.DisplayPos.x, draw_data.DisplayPos.y
|
||||
local LimitX0, LimitY0, LimitX1, LimitY1 = -CLIP_PAD, -CLIP_PAD, ScreenWidth + CLIP_PAD, ScreenHeight + CLIP_PAD
|
||||
BackendData.FrameNo += 1
|
||||
local FrameNo = BackendData.FrameNo
|
||||
local force = BackendData.ForceRedraw
|
||||
BackendData.ForceRedraw = false
|
||||
Parallel.Active = Parallel.On and not Parallel.Config.Inline
|
||||
|
||||
local n = 0
|
||||
local z = 0
|
||||
local AnyDeferred = false
|
||||
for _, draw_list in draw_data.CmdLists:iter() do
|
||||
PB("ImGui unchanged check")
|
||||
if EditableImages.StageTiming then EditableImages.BeginStage() end
|
||||
local set = BackendData.Layers[draw_list]
|
||||
local same, sdx, sdy = 0, 0, 0
|
||||
if not force then same, sdx, sdy = CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) end
|
||||
if same ~= 0 then
|
||||
z = ReuseDrawList(BackendData, set, draw_list, same, sdx, sdy, z, ox, oy, ScreenWidth, ScreenHeight)
|
||||
if EditableImages.StageTiming then EditableImages.EndStage("Compare") end
|
||||
PE()
|
||||
continue
|
||||
end
|
||||
if EditableImages.StageTiming then EditableImages.EndStage("Compare") end
|
||||
PE()
|
||||
|
||||
PB("ImGui collect")
|
||||
if EditableImages.StageTiming then EditableImages.BeginStage() end
|
||||
local first = n + 1
|
||||
local LimitFree, ex0, ey0, ex1, ey1
|
||||
n, LimitFree, ex0, ey0, ex1, ey1 = CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, LimitX1,
|
||||
LimitY1)
|
||||
if EditableImages.StageTiming then EditableImages.EndStage("Collect") end
|
||||
PE()
|
||||
|
||||
local ListDeferred
|
||||
z, ListDeferred = DrawLists(BackendData, draw_list, first, n, z, ox, oy, force, LimitX0, LimitY0, LimitX1,
|
||||
LimitY1)
|
||||
set = BackendData.Layers[draw_list]
|
||||
-- deferred tiles: not "unchanged" next frame, so they get redrawn
|
||||
if set then
|
||||
set.LastUsed = FrameNo
|
||||
if ListDeferred then set.SnapOK = false else
|
||||
Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
|
||||
set.SnapLimitFree = LimitFree
|
||||
set.SnapExtentX0, set.SnapExtentY0, set.SnapExtentX1, set.SnapExtentY1 = ex0, ey0, ex1, ey1
|
||||
end
|
||||
end
|
||||
if ListDeferred then AnyDeferred = true end
|
||||
z = PlaceOverlays(BackendData, draw_list, z, ox, oy)
|
||||
end
|
||||
|
||||
SweepLayers(BackendData, FrameNo)
|
||||
-- drop references so old vertex tables can be collected
|
||||
for k = n + 1, BackendData.LastPrimCount do PrimTexture[k], PrimVtxBuffer[k] = nil, nil end
|
||||
BackendData.LastPrimCount = n
|
||||
-- Tiles left for later: if the app doesn't submit a new frame, Heartbeat finishes them from this draw data
|
||||
if AnyDeferred then
|
||||
BackendData.Stale = draw_data
|
||||
BackendData.StaleHeartbeat = BackendData.HeartbeatCount
|
||||
end
|
||||
if Parallel.Active then
|
||||
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.Textures - f.Flush
|
||||
BackendData.FrameStats = f
|
||||
end
|
||||
PE()
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,215 @@
|
||||
-- Texture records, the module-wide EditableImage budget, profiling labels and stage timing stats.
|
||||
local Raster = IM_INCLUDE("roblox/raster.lua")
|
||||
|
||||
local AssetService = game:GetService("AssetService")
|
||||
local writeu32 = buffer.writeu32
|
||||
local TILE = Raster.TILE
|
||||
|
||||
local M = {}
|
||||
|
||||
-- One table, not locals: shared by every context and module. FreeTile is set by layers.lua (Evict needs it).
|
||||
local EditableImages = {
|
||||
Cap = 64 * 1024 * 1024, Bytes = 0, Count = 0, ImageBytes = setmetatable({}, { __mode = "k" }),
|
||||
Pool = {}, PoolMax = 16,
|
||||
Backends = setmetatable({}, { __mode = "k" }),
|
||||
LastTextureId = 0, KEEP_FRAMES = 30,
|
||||
StageTiming = false,
|
||||
}
|
||||
M.EditableImages = EditableImages
|
||||
|
||||
local ProfileBegin, ProfileEnd = debug.profilebegin, debug.profileend
|
||||
local Profiling = false
|
||||
function M.PB(name) if Profiling then ProfileBegin(name) end end
|
||||
function M.PE() if Profiling then ProfileEnd() end end
|
||||
function M.SetProfiling(enabled) Profiling = enabled and true or false end
|
||||
function M.IsProfiling() return Profiling end
|
||||
|
||||
-- StageTiming on: RenderDrawData accumulates os.clock per stage into StageFrame (GetStats().Frame)
|
||||
function EditableImages.BeginStage() EditableImages.StageStart = os.clock() end
|
||||
function EditableImages.EndStage(stage)
|
||||
local f = EditableImages.StageFrame
|
||||
if f then f[stage] += os.clock() - EditableImages.StageStart end
|
||||
end
|
||||
function EditableImages.AddStat(name, n)
|
||||
local f = EditableImages.StageFrame
|
||||
if f then f[name] += n end
|
||||
end
|
||||
|
||||
function M.GetBackendData()
|
||||
return ImGui.GetCurrentContext() and ImGui.GetIO().BackendPlatformUserData or nil
|
||||
end
|
||||
|
||||
@native
|
||||
local function CopyTexturePixels(tex, dst, x, y, w, h, 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
|
||||
if bpp == 4 then
|
||||
for i = 0, w - 1 do
|
||||
local s = src_base + i * 4
|
||||
writeu32(dst, dst_off + i * 4, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216)
|
||||
end
|
||||
else -- Alpha8: white with alpha
|
||||
for i = 0, w - 1 do
|
||||
writeu32(dst, dst_off + i * 4, 16777215 + src[src_base + i] * 16777216)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Shared by every context: a font atlas shared between contexts is created under one, drawn under the others
|
||||
local Records = {}
|
||||
M.Records = Records
|
||||
|
||||
local function CreateTextureRecord(tex)
|
||||
local 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
|
||||
tex:SetTexID(EditableImages.LastTextureId)
|
||||
tex:SetStatus(ImTextureStatus.OK)
|
||||
end
|
||||
|
||||
function M.UpdateTexture(tex)
|
||||
if tex.Status == ImTextureStatus.WantCreate then
|
||||
CreateTextureRecord(tex)
|
||||
elseif tex.Status == ImTextureStatus.WantUpdates then
|
||||
local t = Records[tex.BackendUserData]
|
||||
if t == nil or t.Width ~= tex.Width or t.Height ~= tex.Height then
|
||||
CreateTextureRecord(tex)
|
||||
return
|
||||
end
|
||||
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
|
||||
-- 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
|
||||
Records[tex.BackendUserData] = nil
|
||||
tex.BackendUserData = nil
|
||||
end
|
||||
tex:SetTexID(ImTextureID_Invalid)
|
||||
tex:SetStatus(ImTextureStatus.Destroyed)
|
||||
end
|
||||
end
|
||||
|
||||
-- User texture from RGBA8 pixels. Ids are never reused, so cached tiles can't show a stale image.
|
||||
function ImGui_ImplRoblox_CreateTexture(pixels, w, h)
|
||||
EditableImages.LastTextureId += 1
|
||||
Records[EditableImages.LastTextureId] = { Buffer = pixels, Width = w, Height = h }
|
||||
return ImTextureRef(EditableImages.LastTextureId)
|
||||
end
|
||||
|
||||
function ImGui_ImplRoblox_DestroyTexture(tex_ref)
|
||||
Records[tex_ref._TexID] = nil
|
||||
end
|
||||
|
||||
-- Every EditableImage goes through Create/Destroy, counted against Cap. Over the cap (or CreateEditableImage failing):
|
||||
-- evict idle tiles, retry once; still nothing -> nil, the caller skips the tile this frame.
|
||||
function EditableImages.Create(w, h)
|
||||
local need = w * h * 4
|
||||
if need > EditableImages.Cap then return nil end
|
||||
for attempt = 1, 2 do
|
||||
if EditableImages.Bytes + need <= EditableImages.Cap then
|
||||
local ok, img = pcall(AssetService.CreateEditableImage, AssetService, { Size = Vector2.new(w, h) })
|
||||
if ok and img then
|
||||
EditableImages.ImageBytes[img] = need
|
||||
EditableImages.Bytes += need
|
||||
EditableImages.Count += 1
|
||||
return img
|
||||
end
|
||||
if attempt == 1 then EditableImages.Evict(math.huge) end -- engine refused: free everything evictable
|
||||
elseif attempt == 1 then
|
||||
EditableImages.Evict(EditableImages.Bytes + need - EditableImages.Cap)
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function EditableImages.Destroy(img)
|
||||
local s = EditableImages.ImageBytes[img]
|
||||
if s then
|
||||
EditableImages.ImageBytes[img] = nil
|
||||
EditableImages.Bytes -= s
|
||||
EditableImages.Count -= 1
|
||||
end
|
||||
img:Destroy()
|
||||
end
|
||||
|
||||
-- The free list first, then idle tiles (not shown, not used this frame) of every context
|
||||
function EditableImages.Evict(need)
|
||||
local freed = 0
|
||||
while freed < need and #EditableImages.Pool > 0 do
|
||||
local t = table.remove(EditableImages.Pool)
|
||||
EditableImages.Destroy(t.Image)
|
||||
t.Label:Destroy()
|
||||
freed += TILE * TILE * 4
|
||||
end
|
||||
if freed >= need then return end
|
||||
for BackendData in EditableImages.Backends do
|
||||
for _, set in pairs(BackendData.Layers) do
|
||||
for kind = 1, 3 do
|
||||
local l = set[kind]
|
||||
if l then
|
||||
for k, t in pairs(l.Tiles) do
|
||||
if t.Used ~= BackendData.FrameNo and not (t.Visible and l.Visible) then
|
||||
EditableImages.FreeTile(l, k)
|
||||
freed += TILE * TILE * 4
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,41 @@
|
||||
-- Parallel raster worker (Actor LocalScript). The build inlines raster.lua for the Raster line.
|
||||
local Actor = script:GetActor()
|
||||
if not Actor then
|
||||
return
|
||||
end
|
||||
|
||||
local Raster = require(script.Parent:WaitForChild("Raster"))
|
||||
local Done = Actor:WaitForChild("Done")
|
||||
local Textures = {}
|
||||
|
||||
Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength)
|
||||
for _, Texture in TexUpdates do
|
||||
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()
|
||||
Done:Fire(Id, Results)
|
||||
end)
|
||||
|
||||
Actor:SetAttribute("Ready", true)
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
[[12, "imgui.lua"], [18514, "imgui_demo.lua"], [25799, "imgui_draw.lua"], [31037, "imgui_h.lua"], [33235, "imgui_impl_roblox.lua"], [34587, "imgui_impl_roblox_fonts.lua"], [40990, "imgui_internal.lua"], [44166, "imgui_tables.lua"], [48513, "imgui_widgets.lua"], [58268, "imstb_rectpack.lua"], [58714, "imstb_textedit.lua"], [59955, "imstb_truetype.lua"], [62423, "imstd_minstdio.lua"]]
|
||||
[[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"]]
|
||||
Generated
+35289
-15537
File diff suppressed because it is too large.
Load diff
Generated
+108
-3
@@ -6,6 +6,7 @@ export type ImVec4 = { x: number, y: number, z: number, w: number, [any]: any }
|
||||
export type ImGuiAPI = {
|
||||
AcceptDragDropPayload: (type: string, flags: number?) -> any,
|
||||
ActivateItemByID: (...any) -> ...any,
|
||||
AddContextHook: (...any) -> ...any,
|
||||
AddDrawListToDrawDataEx: (...any) -> ...any,
|
||||
AddSettingsHandler: (...any) -> ...any,
|
||||
AddUpdateViewport: (...any) -> ...any,
|
||||
@@ -13,6 +14,7 @@ export type ImGuiAPI = {
|
||||
ArrowButton: (str_id: string, dir: number) -> boolean,
|
||||
ArrowButtonEx: (...any) -> ...any,
|
||||
Begin: (name: string, open: boolean?, flags: number?) -> (boolean, boolean?),
|
||||
BeginBoxSelect: (...any) -> ...any,
|
||||
BeginChild: (...any) -> ...any,
|
||||
BeginChildEx: (...any) -> ...any,
|
||||
BeginColumns: (...any) -> ...any,
|
||||
@@ -36,6 +38,7 @@ export type ImGuiAPI = {
|
||||
BeginMenu: (label: string, enabled: boolean?) -> boolean,
|
||||
BeginMenuBar: () -> boolean,
|
||||
BeginMenuEx: (...any) -> ...any,
|
||||
BeginMultiSelect: (flags: number, selection_size: number?, items_count: number?) -> any,
|
||||
BeginPopup: (str_id: string, flags: number?) -> boolean,
|
||||
BeginPopupContextItem: (str_id: string?, popup_flags: number?) -> boolean,
|
||||
BeginPopupContextVoid: (str_id: string?, popup_flags: number?) -> boolean,
|
||||
@@ -67,9 +70,11 @@ 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,
|
||||
CallContextHooks: (...any) -> ...any,
|
||||
Checkbox: (label: string, v: boolean?) -> (boolean, boolean?),
|
||||
CheckboxFlags: (...any) -> ...any,
|
||||
CleanupIniSettings: (...any) -> ...any,
|
||||
@@ -109,26 +114,47 @@ export type ImGuiAPI = {
|
||||
DataTypeGetInfo: (...any) -> ...any,
|
||||
DataTypeIsZero: (...any) -> ...any,
|
||||
DebugAllocHook: (...any) -> ...any,
|
||||
DebugBreakButton: (...any) -> ...any,
|
||||
DebugBreakButtonTooltip: (...any) -> ...any,
|
||||
DebugBreakClearData: (...any) -> ...any,
|
||||
DebugDrawCursorPos: (...any) -> ...any,
|
||||
DebugDrawItemRect: (...any) -> ...any,
|
||||
DebugDrawLineExtents: (...any) -> ...any,
|
||||
DebugFlashStyleColor: (idx: number) -> (),
|
||||
DebugHookIdInfo: (...any) -> ...any,
|
||||
DebugLocateItem: (...any) -> ...any,
|
||||
DebugLocateItemOnHover: (...any) -> ...any,
|
||||
DebugLocateItemResolveWithLastItem: (...any) -> ...any,
|
||||
DebugLog: (fmt: string, ...any) -> (),
|
||||
DebugLogV: (fmt: string, ...any) -> (),
|
||||
DebugNodeColumns: (...any) -> ...any,
|
||||
DebugNodeDockNode: (...any) -> ...any,
|
||||
DebugNodeDrawCmdShowMeshAndBoundingBox: (...any) -> ...any,
|
||||
DebugNodeDrawList: (...any) -> ...any,
|
||||
DebugNodeFont: (...any) -> ...any,
|
||||
DebugNodeFontGlyph: (...any) -> ...any,
|
||||
DebugNodeFontGlyphsForSrcMask: (...any) -> ...any,
|
||||
DebugNodeInputTextState: (...any) -> ...any,
|
||||
DebugNodeMultiSelectState: (...any) -> ...any,
|
||||
DebugNodePlatformMonitor: (...any) -> ...any,
|
||||
DebugNodeStorage: (...any) -> ...any,
|
||||
DebugNodeTabBar: (...any) -> ...any,
|
||||
DebugNodeTable: (...any) -> ...any,
|
||||
DebugNodeTableSettings: (...any) -> ...any,
|
||||
DebugNodeTexture: (...any) -> ...any,
|
||||
DebugNodeTypingSelectState: (...any) -> ...any,
|
||||
DebugNodeViewport: (...any) -> ...any,
|
||||
DebugNodeWindow: (...any) -> ...any,
|
||||
DebugNodeWindowSettings: (...any) -> ...any,
|
||||
DebugNodeWindowsList: (...any) -> ...any,
|
||||
DebugNodeWindowsListByBeginStackParent: (...any) -> ...any,
|
||||
DebugRenderKeyboardPreview: (...any) -> ...any,
|
||||
DebugRenderViewportThumbnail: (...any) -> ...any,
|
||||
DebugStartItemPicker: () -> (),
|
||||
DebugTextEncoding: (str: string) -> (),
|
||||
DebugTextUnformattedWithLocateItem: (...any) -> ...any,
|
||||
DebugTextureIDToU64: (...any) -> ...any,
|
||||
DemoMarker: (...any) -> ...any,
|
||||
DestroyContext: (ctx: any) -> ...any,
|
||||
DestroyPlatformWindow: (...any) -> ...any,
|
||||
DestroyPlatformWindows: () -> (),
|
||||
@@ -220,6 +246,7 @@ export type ImGuiAPI = {
|
||||
DragScalarN: (label: string, data_type: number, v: any, components: number, v_speed: number?, v_min: any, v_max: any, format: string?, flags: number?) -> ...any,
|
||||
Dummy: (size: ImVec2) -> (),
|
||||
End: () -> (),
|
||||
EndBoxSelect: (...any) -> ...any,
|
||||
EndChild: () -> (),
|
||||
EndColumns: (...any) -> ...any,
|
||||
EndCombo: () -> (),
|
||||
@@ -235,12 +262,15 @@ export type ImGuiAPI = {
|
||||
EndMainMenuBar: () -> (),
|
||||
EndMenu: () -> (),
|
||||
EndMenuBar: () -> (),
|
||||
EndMultiSelect: () -> any,
|
||||
EndPopup: () -> (),
|
||||
EndTabBar: () -> (),
|
||||
EndTabItem: () -> (),
|
||||
EndTable: () -> (),
|
||||
EndTooltip: () -> (),
|
||||
ErrorCheckEndFrameFinalizeErrorTooltip: (...any) -> ...any,
|
||||
ErrorCheckEndFrameSanityChecks: (...any) -> ...any,
|
||||
ErrorCheckNewFrameSanityChecks: (...any) -> ...any,
|
||||
ErrorCheckUsingSetCursorPosToExtendParentBoundaries: (...any) -> ...any,
|
||||
ErrorLog: (...any) -> ...any,
|
||||
ErrorRecoveryStoreState: (...any) -> ...any,
|
||||
@@ -259,6 +289,7 @@ export type ImGuiAPI = {
|
||||
FindRenderedTextEnd: (...any) -> ...any,
|
||||
FindSettingsHandler: (...any) -> ...any,
|
||||
FindViewportByID: (viewport_id: number) -> any,
|
||||
FindViewportByPlatformHandle: (platform_handle: any) -> ...any,
|
||||
FindWindowByID: (...any) -> ...any,
|
||||
FindWindowByName: (...any) -> ...any,
|
||||
FindWindowDisplayIndex: (...any) -> ...any,
|
||||
@@ -273,7 +304,9 @@ export type ImGuiAPI = {
|
||||
GcAwakeTransientWindowBuffers: (...any) -> ...any,
|
||||
GcCompactTransientMiscBuffers: (...any) -> ...any,
|
||||
GcCompactTransientWindowBuffers: (...any) -> ...any,
|
||||
GetActiveID: (...any) -> ...any,
|
||||
GetBackgroundDrawList: (viewport: any) -> ...any,
|
||||
GetBoxSelectState: (...any) -> ...any,
|
||||
GetClipboardText: () -> any,
|
||||
GetColorU32: (...any) -> ...any,
|
||||
GetColumnIndex: () -> number,
|
||||
@@ -286,6 +319,9 @@ export type ImGuiAPI = {
|
||||
GetContentRegionAvail: () -> ImVec2,
|
||||
GetContentRegionMax: (...any) -> ...any,
|
||||
GetCurrentContext: () -> any,
|
||||
GetCurrentFocusScope: (...any) -> ...any,
|
||||
GetCurrentTabBar: (...any) -> ...any,
|
||||
GetCurrentTable: (...any) -> ...any,
|
||||
GetCurrentWindow: (...any) -> ...any,
|
||||
GetCurrentWindowRead: (...any) -> ...any,
|
||||
GetCursorPos: () -> ImVec2,
|
||||
@@ -297,7 +333,9 @@ export type ImGuiAPI = {
|
||||
GetDragDropPayload: () -> any,
|
||||
GetDrawData: () -> any,
|
||||
GetDrawListSharedData: () -> any,
|
||||
GetFocusID: (...any) -> ...any,
|
||||
GetFont: () -> any,
|
||||
GetFontBaked: () -> any,
|
||||
GetFontSize: () -> number,
|
||||
GetFontTexUvWhitePixel: () -> ImVec2,
|
||||
GetForegroundDrawList: (viewport: any) -> ...any,
|
||||
@@ -315,6 +353,7 @@ export type ImGuiAPI = {
|
||||
GetItemRectMax: () -> ImVec2,
|
||||
GetItemRectMin: () -> ImVec2,
|
||||
GetItemRectSize: () -> ImVec2,
|
||||
GetItemStatusFlags: (...any) -> ...any,
|
||||
GetKeyChordName: (...any) -> ...any,
|
||||
GetKeyData: (...any) -> ...any,
|
||||
GetKeyMagnitude2d: (...any) -> ...any,
|
||||
@@ -331,7 +370,9 @@ export type ImGuiAPI = {
|
||||
GetMouseDragDelta: (button: number?, lock_threshold: number?) -> ImVec2,
|
||||
GetMousePos: () -> ImVec2,
|
||||
GetMousePosOnOpeningCurrentPopup: () -> ImVec2,
|
||||
GetMultiSelectState: (...any) -> ...any,
|
||||
GetNavTweakPressedAmount: (...any) -> ...any,
|
||||
GetPixelDensity: (...any) -> ...any,
|
||||
GetPlatformIO: () -> any,
|
||||
GetPopupAllowedExtentRect: (...any) -> ...any,
|
||||
GetRoundedFontSize: (...any) -> ...any,
|
||||
@@ -353,6 +394,7 @@ export type ImGuiAPI = {
|
||||
GetTopMostPopupModal: (...any) -> ...any,
|
||||
GetTreeNodeToLabelSpacing: () -> number,
|
||||
GetTypematicRepeatRate: (...any) -> ...any,
|
||||
GetTypingSelectRequest: (...any) -> ...any,
|
||||
GetVersion: () -> any,
|
||||
GetViewportPlatformMonitor: (...any) -> ...any,
|
||||
GetWindowAlwaysWantOwnTabBar: (...any) -> ...any,
|
||||
@@ -360,10 +402,13 @@ export type ImGuiAPI = {
|
||||
GetWindowContentRegionMax: (...any) -> ...any,
|
||||
GetWindowContentRegionMin: (...any) -> ...any,
|
||||
GetWindowDockID: () -> number,
|
||||
GetWindowDockNode: (...any) -> ...any,
|
||||
GetWindowDpiScale: () -> number,
|
||||
GetWindowDrawList: () -> any,
|
||||
GetWindowHeight: () -> number,
|
||||
GetWindowPos: () -> ImVec2,
|
||||
GetWindowResizeBorderID: (...any) -> ...any,
|
||||
GetWindowResizeCornerID: (...any) -> ...any,
|
||||
GetWindowScrollbarID: (...any) -> ...any,
|
||||
GetWindowScrollbarRect: (...any) -> ...any,
|
||||
GetWindowSize: () -> ImVec2,
|
||||
@@ -405,6 +450,7 @@ export type ImGuiAPI = {
|
||||
IsInNavFocusRoute: (...any) -> ...any,
|
||||
IsItemActivated: () -> boolean,
|
||||
IsItemActive: () -> boolean,
|
||||
IsItemActiveAsInputText: (...any) -> ...any,
|
||||
IsItemClicked: (mouse_button: number?) -> boolean,
|
||||
IsItemDeactivated: () -> boolean,
|
||||
IsItemDeactivatedAfterEdit: () -> boolean,
|
||||
@@ -421,6 +467,7 @@ export type ImGuiAPI = {
|
||||
IsKeyReleased: (...any) -> ...any,
|
||||
IsKeyboardKey: (...any) -> ...any,
|
||||
IsLRModKey: (...any) -> ...any,
|
||||
IsLegacyKey: (...any) -> ...any,
|
||||
IsMouseClicked: (button: number, is_repeat: boolean?) -> boolean,
|
||||
IsMouseClickedEx: (...any) -> ...any,
|
||||
IsMouseDoubleClicked: (...any) -> ...any,
|
||||
@@ -479,6 +526,10 @@ export type ImGuiAPI = {
|
||||
MenuItem: (...any) -> ...any,
|
||||
MenuItemEx: (...any) -> ...any,
|
||||
MouseButtonToKey: (...any) -> ...any,
|
||||
MultiSelectAddSetAll: (...any) -> ...any,
|
||||
MultiSelectAddSetRange: (...any) -> ...any,
|
||||
MultiSelectItemFooter: (...any) -> ...any,
|
||||
MultiSelectItemHeader: (...any) -> ...any,
|
||||
NavApplyItemToResult: (...any) -> ...any,
|
||||
NavBiasScoringRect: (...any) -> ...any,
|
||||
NavCalcPreferredRefPos: (...any) -> ...any,
|
||||
@@ -556,6 +607,8 @@ export type ImGuiAPI = {
|
||||
RadioButton: (...any) -> ...any,
|
||||
RadioButtonEx: (...any) -> ...any,
|
||||
RegisterFontAtlas: (...any) -> ...any,
|
||||
RegisterUserTexture: (...any) -> ...any,
|
||||
RemoveContextHook: (...any) -> ...any,
|
||||
RemoveSettingsHandler: (...any) -> ...any,
|
||||
Render: () -> (),
|
||||
RenderArrow: (...any) -> ...any,
|
||||
@@ -591,6 +644,7 @@ export type ImGuiAPI = {
|
||||
ScaleRatioFromValueT: (...any) -> ...any,
|
||||
ScaleValueFromRatioT: (...any) -> ...any,
|
||||
ScaleWindowsInViewport: (...any) -> ...any,
|
||||
ScrollToBringRectIntoView: (...any) -> ...any,
|
||||
ScrollToItem: (...any) -> ...any,
|
||||
ScrollToRect: (...any) -> ...any,
|
||||
ScrollToRectEx: (...any) -> ...any,
|
||||
@@ -608,6 +662,7 @@ export type ImGuiAPI = {
|
||||
SetColorEditOptions: (...any) -> ...any,
|
||||
SetColumnOffset: (column_index: number, offset: number) -> (),
|
||||
SetColumnWidth: (column_index: number, width: number) -> (),
|
||||
SetContextName: (...any) -> ...any,
|
||||
SetCurrentContext: (ctx: any) -> ...any,
|
||||
SetCurrentFont: (...any) -> ...any,
|
||||
SetCurrentViewport: (...any) -> ...any,
|
||||
@@ -621,6 +676,7 @@ export type ImGuiAPI = {
|
||||
SetItemDefaultFocus: () -> (),
|
||||
SetItemKeyOwner: (...any) -> ...any,
|
||||
SetItemTooltip: (fmt: string, ...any) -> (),
|
||||
SetItemTooltipV: (fmt: string, ...any) -> (),
|
||||
SetKeyOwner: (...any) -> ...any,
|
||||
SetKeyOwnersForKeyChord: (...any) -> ...any,
|
||||
SetKeyboardFocusHere: (offset: number?) -> (),
|
||||
@@ -639,6 +695,7 @@ export type ImGuiAPI = {
|
||||
SetNextItemColorMarker: (...any) -> ...any,
|
||||
SetNextItemOpen: (is_open: boolean, cond: number?) -> (),
|
||||
SetNextItemRefVal: (...any) -> ...any,
|
||||
SetNextItemSelectionUserData: (selection_user_data: any) -> (),
|
||||
SetNextItemShortcut: (key_chord: any, flags: number?) -> (),
|
||||
SetNextItemStorageID: (storage_id: number) -> (),
|
||||
SetNextItemWidth: (item_width: number) -> (),
|
||||
@@ -657,6 +714,7 @@ export type ImGuiAPI = {
|
||||
SetNextWindowSize: (size: ImVec2, cond: number?) -> (),
|
||||
SetNextWindowSizeConstraints: (size_min: ImVec2, size_max: ImVec2, custom_callback: any, custom_callback_user_data: any) -> ...any,
|
||||
SetNextWindowViewport: (id: number) -> (),
|
||||
SetPixelDensity: (...any) -> ...any,
|
||||
SetScrollFromPosX: (...any) -> ...any,
|
||||
SetScrollFromPosY: (...any) -> ...any,
|
||||
SetScrollHereX: (center_x_ratio: number?) -> (),
|
||||
@@ -667,6 +725,7 @@ export type ImGuiAPI = {
|
||||
SetStateStorage: (tree: any) -> ...any,
|
||||
SetTabItemClosed: (label: string) -> (),
|
||||
SetTooltip: (fmt: string, ...any) -> (),
|
||||
SetTooltipV: (fmt: string, ...any) -> (),
|
||||
SetWindowClipRectBeforeSetChannel: (...any) -> ...any,
|
||||
SetWindowCollapsed: (...any) -> ...any,
|
||||
SetWindowDock: (...any) -> ...any,
|
||||
@@ -674,6 +733,7 @@ export type ImGuiAPI = {
|
||||
SetWindowFontScale: (...any) -> ...any,
|
||||
SetWindowHiddenAndSkipItemsForCurrentFrame: (...any) -> ...any,
|
||||
SetWindowHitTestHole: (...any) -> ...any,
|
||||
SetWindowParentWindowForFocusRoute: (...any) -> ...any,
|
||||
SetWindowPos: (...any) -> ...any,
|
||||
SetWindowSize: (...any) -> ...any,
|
||||
SetWindowViewport: (...any) -> ...any,
|
||||
@@ -822,6 +882,7 @@ export type ImGuiAPI = {
|
||||
TempInputScalar: (...any) -> ...any,
|
||||
TempInputText: (...any) -> ...any,
|
||||
TestKeyOwner: (...any) -> ...any,
|
||||
TestShortcutRouting: (...any) -> ...any,
|
||||
Text: (fmt: string, ...any) -> (),
|
||||
TextAligned: (...any) -> ...any,
|
||||
TextBufferToString: (buf: {number}) -> string,
|
||||
@@ -848,11 +909,17 @@ export type ImGuiAPI = {
|
||||
TreePop: () -> (),
|
||||
TreePush: (...any) -> ...any,
|
||||
TreePushOverrideID: (...any) -> ...any,
|
||||
TypingSelectFindBestLeadingMatch: (...any) -> ...any,
|
||||
TypingSelectFindMatch: (...any) -> ...any,
|
||||
TypingSelectFindNextSingleCharMatch: (...any) -> ...any,
|
||||
Unindent: (indent_w: number?) -> (),
|
||||
UnregisterFontAtlas: (...any) -> ...any,
|
||||
UnregisterUserTexture: (...any) -> ...any,
|
||||
UpdateAliasKey: (...any) -> ...any,
|
||||
UpdateCurrentFontSize: (...any) -> ...any,
|
||||
UpdateDebugToolFlashStyleColor: (...any) -> ...any,
|
||||
UpdateDebugToolItemPathQuery: (...any) -> ...any,
|
||||
UpdateDebugToolItemPicker: (...any) -> ...any,
|
||||
UpdateFontsEndFrame: (...any) -> ...any,
|
||||
UpdateFontsNewFrame: (...any) -> ...any,
|
||||
UpdateHoveredWindowAndCaptureFlags: (...any) -> ...any,
|
||||
@@ -880,20 +947,22 @@ export type ImGuiAPI = {
|
||||
VSliderScalar: (label: string, size: ImVec2, data_type: number, data: any, min: any, max: any, format: string?, flags: number?) -> ...any,
|
||||
Value: (...any) -> ...any,
|
||||
WindowPosAbsToRel: (...any) -> ...any,
|
||||
WindowPosRelToAbs: (...any) -> ...any,
|
||||
WindowRectAbsToRel: (...any) -> ...any,
|
||||
WindowRectRelToAbs: (...any) -> ...any,
|
||||
WindowSelectViewport: (...any) -> ...any,
|
||||
WindowSettingsAddSettingsHandler: (...any) -> ...any,
|
||||
WindowSyncOwnedViewport: (...any) -> ...any,
|
||||
_ByteArrayToString: (...any) -> ...any,
|
||||
_CalcItemSizeXY: (...any) -> ...any,
|
||||
_GetTypeFunc: (...any) -> ...any,
|
||||
_SetCurrentContext_Internal: (...any) -> ...any,
|
||||
_SetCurrentContext_Tables: (...any) -> ...any,
|
||||
_SetCurrentContext_Widgets: (...any) -> ...any,
|
||||
[string]: any,
|
||||
}
|
||||
export type ImDrawFlags = { None: number, RoundCornersTopLeft: number, RoundCornersTopRight: number, RoundCornersBottomLeft: number, RoundCornersBottomRight: number, RoundCornersNone: number, Closed: number, RoundCornersTop: number, RoundCornersBottom: number, RoundCornersLeft: number, RoundCornersRight: number, RoundCornersAll: number, RoundCornersDefault_: number, RoundCornersMask_: number, InvalidMask_: number, [string]: number }
|
||||
export type ImDrawListFlags = { None: number, AntiAliasedLines: number, AntiAliasedLinesUseTex: number, AntiAliasedFill: number, AllowVtxOffset: number, TextNoPixelSnap: number, [string]: number }
|
||||
export type ImDrawFlags = { None: number, RoundTopLeft: number, RoundTopRight: number, RoundBottomLeft: number, RoundBottomRight: number, RoundNone: number, Closed: number, JoinMiter: number, CapSquare: number, AAFill: number, AALines: number, AALineEnds: number, StrokeInside: number, StrokeCenter: number, StrokeCenterBiased: number, StrokeOutside: number, StrokeLegacy: number, TextNoPixelSnap: number, UseTexForRoundCorners: number, UseVtxOffset: number, AllowTexForRoundCorners_: number, RoundAll: number, RoundTop: number, RoundBottom: number, RoundLeft: number, RoundRight: number, RoundMask_: number, AllowInPushScope_: number, AllowInFrameScope_: number, StrokeMask_: number, InvalidMask_: number, RoundCornersTopLeft: number, RoundCornersTopRight: number, RoundCornersBottomLeft: number, RoundCornersBottomRight: number, RoundCornersNone: number, RoundCornersAll: number, RoundCornersTop: number, RoundCornersBottom: number, RoundCornersLeft: number, RoundCornersRight: number, [string]: number }
|
||||
export type ImDrawListFlags = { None: number, AntiAliasedFill: number, AntiAliasedLines: number, AntiAliasedLinesUseTex: number, AllowVtxOffset: number, TextNoPixelSnap: number, [string]: number }
|
||||
export type ImFontFlags = { None: number, NoLoadError: number, NoLoadGlyphs: number, LockBakedSizes: number, ImplicitRefSize: number, [string]: number }
|
||||
export type ImGuiBackendFlags = { None: number, HasGamepad: number, HasMouseCursors: number, HasSetMousePos: number, RendererHasVtxOffset: number, RendererHasTextures: number, RendererHasViewports: number, PlatformHasViewports: number, HasMouseHoveredViewport: number, HasParentViewport: number, [string]: number }
|
||||
export type ImGuiButtonFlags = { None: number, MouseButtonLeft: number, MouseButtonRight: number, MouseButtonMiddle: number, EnableNav: number, PressedOnClick: number, PressedOnClickRelease: number, PressedOnClickReleaseAnywhere: number, PressedOnRelease: number, PressedOnDoubleClick: number, PressedOnDragDropHold: number, FlattenChildren: number, AllowOverlap: number, AlignTextBaseLine: number, NoKeyModsAllowed: number, NoHoldingActiveId: number, NoNavFocus: number, NoHoveredOnFocus: number, NoSetKeyOwner: number, NoTestKeyOwner: number, NoFocus: number, MouseButtonMask_: number, PressedOnMask_: number, PressedOnDefault_: number, NoKeyModifiers: number, [string]: number }
|
||||
@@ -911,17 +980,50 @@ export type ImGuiInputTextFlags = { None: number, CharsDecimal: number, CharsHex
|
||||
export type ImGuiItemFlags = { None: number, NoTabStop: number, NoNav: number, NoNavDefaultFocus: number, ButtonRepeat: number, AutoClosePopups: number, AllowDuplicateId: number, Disabled: number, LiveEditOnInputText: number, LiveEditOnInputScalar: number, LiveEditOnInput: number, ReadOnly: number, MixedValue: number, NoWindowHoverableCheck: number, AllowOverlap: number, NoNavDisableMouseHover: number, NoMarkEdited: number, NoFocus: number, Inputable: number, HasSelectionUserData: number, IsMultiSelect: number, Default_: number, [string]: number }
|
||||
export type ImGuiItemStatusFlags = { None: number, HoveredRect: number, HasDisplayRect: number, Edited: number, ToggledSelection: number, ToggledOpen: number, HasDeactivated: number, Deactivated: number, HoveredWindow: number, Visible: number, HasClipRect: number, HasShortcut: number, EditedInternal: number, [string]: number }
|
||||
export type ImGuiKey = { None: number, NamedKey_BEGIN: number, Tab: number, LeftArrow: number, RightArrow: number, UpArrow: number, DownArrow: number, PageUp: number, PageDown: number, Home: number, End: number, Insert: number, Delete: number, Backspace: number, Space: number, Enter: number, Escape: number, LeftCtrl: number, RightCtrl: number, Menu: number, K0: number, A: number, K: number, U: number, F1: number, F7: number, F13: number, F19: number, Apostrophe: number, CapsLock: number, Keypad0: number, KeypadDecimal: number, AppBack: number, AppForward: number, Oem102: number, GamepadStart: number, GamepadFaceLeft: number, GamepadDpadLeft: number, GamepadL1: number, GamepadL2: number, GamepadL3: number, GamepadLStickLeft: number, GamepadRStickLeft: number, MouseLeft: number, ReservedForModCtrl: number, NamedKey_END: number, NamedKey_COUNT: number, NavKeyboardTweakSlow: number, NavKeyboardTweakFast: number, NavGamepadTweakSlow: number, NavGamepadTweakFast: number, NavGamepadMenu: number, NavGamepadContextMenu: number, [string]: number }
|
||||
export type ImGuiListClipperFlags = { None: number, NoSetTableRowCounters: number, [string]: number }
|
||||
export type ImGuiMouseSource = { Mouse: number, TouchScreen: number, Pen: number, COUNT: number, [string]: number }
|
||||
export type ImGuiMultiSelectFlags = { None: number, SingleSelect: number, NoSelectAll: number, NoRangeSelect: number, NoAutoSelect: number, NoAutoClear: number, NoAutoClearOnReselect: number, BoxSelect1d: number, BoxSelect2d: number, BoxSelectNoScroll: number, ClearOnEscape: number, ClearOnClickVoid: number, ScopeWindow: number, ScopeRect: number, SelectOnAuto: number, SelectOnClickAlways: number, SelectOnClickRelease: number, NavWrapX: number, NoSelectOnRightClick: number, CheckboxMode_: number, SelectOnMask_: number, SelectOnClick: number, [string]: number }
|
||||
export type ImGuiNextItemDataFlags = { None: number, HasWidth: number, HasOpen: number, HasShortcut: number, HasRefVal: number, HasStorageID: number, HasColorMarker: number, [string]: number }
|
||||
export type ImGuiPopupFlags = { None: number, MouseButtonLeft: number, MouseButtonRight: number, MouseButtonMiddle: number, NoReopen: number, NoOpenOverExistingPopup: number, NoOpenOverItems: number, AnyPopupId: number, AnyPopupLevel: number, AnyPopup: number, MouseButtonShift_: number, MouseButtonMask_: number, InvalidMask_: number, [string]: number }
|
||||
export type ImGuiSelectableFlags = { None: number, NoAutoClosePopups: number, SpanAllColumns: number, AllowDoubleClick: number, Disabled: number, AllowOverlap: number, Highlight: number, SelectOnNav: number, NoHoldingActiveID: number, SelectOnClick: number, SelectOnRelease: number, SpanAvailWidth: number, SetNavIdOnHover: number, NoPadWithHalfSpacing: number, NoSetKeyOwner: number, [string]: number }
|
||||
export type ImGuiSelectionRequestType = { None: number, SetAll: number, SetRange: number, [string]: number }
|
||||
export type ImGuiSliderFlags = { None: number, Logarithmic: number, NoRoundToFormat: number, NoInput: number, WrapAround: number, ClampOnInput: number, ClampZeroRange: number, NoSpeedTweaks: number, ColorMarkers: number, InvalidMask_: number, AlwaysClamp: number, Vertical: number, ReadOnly: number, [string]: number }
|
||||
export type ImGuiStyleVar = { Alpha: number, DisabledAlpha: number, WindowPadding: number, WindowRounding: number, WindowBorderSize: number, WindowMinSize: number, WindowTitleAlign: number, ChildRounding: number, ChildBorderSize: number, PopupRounding: number, PopupBorderSize: number, FramePadding: number, FrameRounding: number, FrameBorderSize: number, ItemSpacing: number, ItemInnerSpacing: number, IndentSpacing: number, CellPadding: number, ScrollbarSize: number, ScrollbarRounding: number, ScrollbarPadding: number, GrabMinSize: number, GrabRounding: number, ImageRounding: number, ImageBorderSize: number, TabRounding: number, TabBorderSize: number, TabMinWidthBase: number, TabMinWidthShrink: number, TabBarBorderSize: number, TabBarOverlineSize: number, TableAngledHeadersAngle: number, TableAngledHeadersTextAlign: number, TreeLinesSize: number, TreeLinesRounding: number, MenuItemRounding: number, SelectableRounding: number, DragDropTargetRounding: number, ButtonTextAlign: number, SelectableTextAlign: number, SeparatorTextBorderSize: number, SeparatorTextAlign: number, SeparatorTextPadding: number, COUNT: number, [string]: number }
|
||||
export type ImGuiStyleVar = { Alpha: number, DisabledAlpha: number, WindowPadding: number, WindowRounding: number, WindowBorderSize: number, WindowMinSize: number, WindowTitleAlign: number, ChildRounding: number, ChildBorderSize: number, PopupRounding: number, PopupBorderSize: number, FramePadding: number, FrameRounding: number, FrameBorderSize: number, ItemSpacing: number, ItemInnerSpacing: number, IndentSpacing: number, CellPadding: number, ScrollbarSize: number, ScrollbarRounding: number, ScrollbarPadding: number, GrabMinSize: number, GrabRounding: number, ImageRounding: number, ImageBorderSize: number, TabRounding: number, TabBorderSize: number, TabMinWidthBase: number, TabMinWidthShrink: number, TabBarBorderSize: number, TabBarOverlineSize: number, TableAngledHeadersAngle: number, TableAngledHeadersTextAlign: number, TreeLinesSize: number, TreeLinesRounding: number, MenuItemRounding: number, SelectableRounding: number, DragDropTargetRounding: number, ButtonTextAlign: number, SelectableTextAlign: number, SeparatorSize: number, SeparatorTextBorderSize: number, SeparatorTextAlign: number, SeparatorTextPadding: number, DockingSeparatorSize: number, COUNT: number, [string]: number }
|
||||
export type ImGuiTreeNodeFlags = { None: number, Selected: number, Framed: number, AllowOverlap: number, NoTreePushOnOpen: number, NoAutoOpenOnLog: number, DefaultOpen: number, OpenOnDoubleClick: number, OpenOnArrow: number, Leaf: number, Bullet: number, FramePadding: number, SpanAvailWidth: number, SpanFullWidth: number, SpanLabelWidth: number, SpanAllColumns: number, LabelSpanAllColumns: number, NavLeftJumpsToParent: number, DrawLinesNone: number, DrawLinesFull: number, DrawLinesToNodes: number, NoNavFocus: number, ClipLabelForTrailingButton: number, UpsideDownArrow: number, CollapsingHeader: number, OpenOnMask_: number, DrawLinesMask_: number, [string]: number }
|
||||
export type ImGuiViewportFlags = { None: number, IsPlatformWindow: number, IsPlatformMonitor: number, OwnedByApp: number, NoDecoration: number, NoTaskBarIcon: number, NoFocusOnAppearing: number, NoFocusOnClick: number, NoInputs: number, NoRendererClear: number, NoAutoMerge: number, TopMost: number, CanHostOtherWindows: number, IsMinimized: number, IsFocused: number, [string]: number }
|
||||
export type ImGuiWindowFlags = { None: number, NoTitleBar: number, NoResize: number, NoMove: number, NoScrollbar: number, NoScrollWithMouse: number, NoCollapse: number, AlwaysAutoResize: number, NoBackground: number, NoSavedSettings: number, NoMouseInputs: number, MenuBar: number, HorizontalScrollbar: number, NoFocusOnAppearing: number, NoBringToFrontOnFocus: number, AlwaysVerticalScrollbar: number, AlwaysHorizontalScrollbar: number, NoNavInputs: number, NoNavFocus: number, UnsavedDocument: number, NoDocking: number, DockNodeHost: number, ChildWindow: number, Tooltip: number, Popup: number, Modal: number, ChildMenu: number, NoNav: number, NoDecoration: number, NoInputs: number, [string]: number }
|
||||
export type ImGuiParallelConfig = { Actors: number?, MinTiles: number?, MinPixels: number?, MaxBytesPerPixel: number?, Worker: any, Sync: boolean?, SyncDrop: boolean?, Inline: boolean?, [string]: any }
|
||||
export type ImGuiImplRoblox = {
|
||||
Init: (...any) -> ...any,
|
||||
Shutdown: (...any) -> ...any,
|
||||
NewFrame: (...any) -> ...any,
|
||||
RenderDrawData: (...any) -> ...any,
|
||||
AddFile: (...any) -> ...any,
|
||||
CreateTexture: (...any) -> ...any,
|
||||
DestroyTexture: (...any) -> ...any,
|
||||
SetOverlay: (...any) -> ...any,
|
||||
SetTextProxy: (...any) -> ...any,
|
||||
SetRenderScale: (...any) -> ...any,
|
||||
GetRenderScale: (...any) -> ...any,
|
||||
SetRenderRate: (...any) -> ...any,
|
||||
SetBusyRenderRate: (...any) -> ...any,
|
||||
SetRedrawBudget: (...any) -> ...any,
|
||||
SetProfiling: (...any) -> ...any,
|
||||
IsProfiling: (...any) -> ...any,
|
||||
SetStageTiming: (...any) -> ...any,
|
||||
GetStats: (...any) -> ...any,
|
||||
SetEditableImageCap: (...any) -> ...any,
|
||||
EnableParallel: (opts: ImGuiParallelConfig?) -> (),
|
||||
DisableParallel: () -> (),
|
||||
FinishParallel: () -> (),
|
||||
BeginParallelFrame: () -> (),
|
||||
GetParallelStats: () -> { [string]: number },
|
||||
GetParallelConfig: () -> ImGuiParallelConfig,
|
||||
[string]: any,
|
||||
}
|
||||
export type ImGuiModule = {
|
||||
ImGui: ImGuiAPI,
|
||||
ImGui_ImplRoblox: ImGuiImplRoblox,
|
||||
ImVec2: (x: number?, y: number?, z: number?, w: number?) -> ImVec2,
|
||||
ImVec4: (x: number?, y: number?, z: number?, w: number?) -> ImVec4,
|
||||
ImDrawFlags: ImDrawFlags,
|
||||
@@ -943,10 +1045,13 @@ export type ImGuiModule = {
|
||||
ImGuiItemFlags: ImGuiItemFlags,
|
||||
ImGuiItemStatusFlags: ImGuiItemStatusFlags,
|
||||
ImGuiKey: ImGuiKey,
|
||||
ImGuiListClipperFlags: ImGuiListClipperFlags,
|
||||
ImGuiMouseSource: ImGuiMouseSource,
|
||||
ImGuiMultiSelectFlags: ImGuiMultiSelectFlags,
|
||||
ImGuiNextItemDataFlags: ImGuiNextItemDataFlags,
|
||||
ImGuiPopupFlags: ImGuiPopupFlags,
|
||||
ImGuiSelectableFlags: ImGuiSelectableFlags,
|
||||
ImGuiSelectionRequestType: ImGuiSelectionRequestType,
|
||||
ImGuiSliderFlags: ImGuiSliderFlags,
|
||||
ImGuiStyleVar: ImGuiStyleVar,
|
||||
ImGuiTreeNodeFlags: ImGuiTreeNodeFlags,
|
||||
|
||||
Generated
+842
@@ -0,0 +1,842 @@
|
||||
--!optimize 2
|
||||
-- GENERATED by tools/bundle.py from backends/roblox/worker.luau + raster.lua - do not edit
|
||||
-- Parallel raster worker (Actor LocalScript). The build inlines raster.lua for the Raster line.
|
||||
local Actor = script:GetActor()
|
||||
if not Actor then
|
||||
return
|
||||
end
|
||||
|
||||
local Raster = (function()
|
||||
-- Software rasterizer: pure buffer code shared by the backend and the parallel worker (inlined into ImGuiWorker).
|
||||
-- Target: RGBA8 row-major (ImU32 is already R | G<<8 | B<<16 | A<<24), non-premultiplied "over" onto transparent.
|
||||
local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max
|
||||
local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
|
||||
local readf64 = buffer.readf64
|
||||
local band, rshift = bit32.band, bit32.rshift
|
||||
local readi32 = buffer.readi32
|
||||
|
||||
local M = {
|
||||
TILE = 128,
|
||||
-- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs.
|
||||
-- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2, 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 = 184, REC_A = 40, REC_C = 76, REC_B = 112, REC_D = 148, JOB = 32,
|
||||
}
|
||||
local TILE = M.TILE
|
||||
|
||||
local TargetBuffer: buffer, TargetWidth = buffer.create(0), 0
|
||||
local PrevRow = buffer.create(1024)
|
||||
|
||||
-- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else
|
||||
-- remembers this row. u32 loop, not readstring ==: that allocated a string per row.
|
||||
@native
|
||||
local function RowRepeats(o: number, len: number, has_prev: boolean): boolean
|
||||
if has_prev then
|
||||
local same = true
|
||||
for k = 0, len - 4, 4 do
|
||||
if readu32(TargetBuffer, o + k) ~= readu32(PrevRow, k) then
|
||||
same = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if same then return true end
|
||||
end
|
||||
if buffer.len(PrevRow) < len then PrevRow = buffer.create(len) end
|
||||
buffer.copy(PrevRow, 0, TargetBuffer, o, len)
|
||||
return false
|
||||
end
|
||||
local RectColumns = table.create(256, 0)
|
||||
|
||||
-- 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)
|
||||
if a >= 255 then
|
||||
writeu32(TargetBuffer, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080)
|
||||
return
|
||||
end
|
||||
if a <= 0 then return end
|
||||
local d = readu32(TargetBuffer, o)
|
||||
if d < 16777216 then
|
||||
writeu32(TargetBuffer, o,
|
||||
floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216)
|
||||
return
|
||||
end
|
||||
local sa = a / 255
|
||||
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
|
||||
if d >= 4278190080 then
|
||||
local ns = 1 - sa
|
||||
writeu32(TargetBuffer, o,
|
||||
floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256 + floor(b * sa + db * ns + 0.5) * 65536
|
||||
+ 4278190080)
|
||||
else
|
||||
local k = rshift(d, 24) * ((1 - sa) / 255)
|
||||
local oa = sa + k
|
||||
local inv = 1 / oa
|
||||
writeu32(TargetBuffer, o, floor((r * sa + dr * k) * inv + 0.5) + floor((g * sa + dg * k) * inv + 0.5) * 256
|
||||
+ floor((b * sa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
|
||||
end
|
||||
end
|
||||
|
||||
@native
|
||||
local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number,
|
||||
b: number, a: number)
|
||||
if a <= 0 then return end
|
||||
local w4 = (x1 - x0 - 1) * 4
|
||||
if 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
|
||||
local c1 = ns / 255
|
||||
local rs, gs, bs = r * sa, g * sa, b * sa
|
||||
local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination
|
||||
for y = y0, y1 - 1 do
|
||||
local o0 = (y * TargetWidth + x0) * 4
|
||||
for o = o0, o0 + w4, 4 do
|
||||
local d = readu32(TargetBuffer, o)
|
||||
if d == last_d then
|
||||
writeu32(TargetBuffer, o, last_v)
|
||||
elseif d < 16777216 then
|
||||
writeu32(TargetBuffer, o, packed0)
|
||||
else
|
||||
last_d = d
|
||||
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
|
||||
if d >= 4278190080 then
|
||||
last_v = floor(rs + dr * ns + 0.5) + floor(gs + dg * ns + 0.5) * 256
|
||||
+ floor(bs + db * ns + 0.5) * 65536 + 4278190080
|
||||
else
|
||||
local k = rshift(d, 24) * c1
|
||||
local oa = sa + k
|
||||
local inv = 1 / oa
|
||||
last_v = floor((rs + dr * k) * inv + 0.5) + floor((gs + dg * k) * inv + 0.5) * 256
|
||||
+ floor((bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
|
||||
end
|
||||
writeu32(TargetBuffer, o, last_v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@native
|
||||
local function UnpackColor(col: number)
|
||||
return col % 256, floor(col / 256) % 256, floor(col / 65536) % 256, floor(col / 16777216) % 256
|
||||
end
|
||||
|
||||
@native
|
||||
local function SampleTexture(t, u: number, v: number)
|
||||
local tw, th = t.Width, t.Height
|
||||
local tx, ty = floor(u * tw), floor(v * th)
|
||||
if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end
|
||||
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
|
||||
local o = (ty * tw + tx) * 4
|
||||
local tb = t.Buffer
|
||||
return readu8(tb, o), readu8(tb, o + 1), readu8(tb, o + 2), readu8(tb, o + 3)
|
||||
end
|
||||
|
||||
@native
|
||||
local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, u0: number, v0: number,
|
||||
u1: number, v1: number, col: number, t, cx0: number, cy0: number, cx1: number, cy1: number)
|
||||
local r, g, b, a = UnpackColor(col)
|
||||
if a == 0 then return end
|
||||
local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0)
|
||||
local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1)
|
||||
if px0 >= px1 or py0 >= py1 then return end
|
||||
|
||||
if not t or (u0 == u1 and v0 == v1) then
|
||||
if t then
|
||||
local tr, tg, tb, ta = SampleTexture(t, u0, v0)
|
||||
r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255
|
||||
end
|
||||
if a <= 0 then return end
|
||||
if a >= 255 or px1 - px0 < 32 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
|
||||
local o = (y * TargetWidth + px0) * 4
|
||||
if RowRepeats(o, len, y > py0) then
|
||||
buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len)
|
||||
else
|
||||
FillSpan(TargetBuffer, y, y + 1, px0, px1, r, g, b, a)
|
||||
end
|
||||
prev_o = o
|
||||
end
|
||||
return
|
||||
end
|
||||
|
||||
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
|
||||
cols[c] = tx * 4
|
||||
end
|
||||
for y = py0, py1 - 1 do
|
||||
local ty = floor((v0 + (y + 0.5 - y0) * dv) * th)
|
||||
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
|
||||
local trow4 = ty * tw * 4
|
||||
local o = (y * TargetWidth + px0) * 4
|
||||
for c = 1, ncol do
|
||||
local tv = readu32(tbuf, trow4 + cols[c])
|
||||
if tv < 16777216 then
|
||||
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
|
||||
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 += 4
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@native
|
||||
local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, vc: number, t, cx0: number, cy0: number,
|
||||
cx1: number, cy1: number, ox: number, oy: number)
|
||||
local x0, y0 = readf64(vbuf, va) - ox, readf64(vbuf, va + 8) - oy
|
||||
local x1, y1 = readf64(vbuf, vb) - ox, readf64(vbuf, vb + 8) - oy
|
||||
local x2, y2 = readf64(vbuf, vc) - ox, readf64(vbuf, vc + 8) - oy
|
||||
local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0)
|
||||
if area == 0 then return end
|
||||
if area < 0 then
|
||||
vb, vc = vc, vb
|
||||
x1, y1, x2, y2 = x2, y2, x1, y1
|
||||
area = -area
|
||||
end
|
||||
|
||||
local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1)
|
||||
local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1)
|
||||
if minx > maxx or miny > maxy then return end
|
||||
Shrink(minx, miny, maxx + 1, maxy + 1)
|
||||
|
||||
local A0, B0 = y1 - y2, x2 - x1
|
||||
local C0 = -(A0 * x1 + B0 * y1)
|
||||
local A1, B1 = y2 - y0, x0 - x2
|
||||
local C1 = -(A1 * x2 + B1 * y2)
|
||||
local A2, B2 = y0 - y1, x1 - x0
|
||||
local C2 = -(A2 * x0 + B2 * y0)
|
||||
local tl0 = A0 > 0 or (A0 == 0 and B0 > 0)
|
||||
local tl1 = A1 > 0 or (A1 == 0 and B1 > 0)
|
||||
local tl2 = A2 > 0 or (A2 == 0 and B2 > 0)
|
||||
|
||||
local inv = 1 / area
|
||||
local n0, n1, n2 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0
|
||||
local ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32))
|
||||
local rb, gb, bb, ab = UnpackColor(readu32(vbuf, vb + 32))
|
||||
local rc, gc, bc, ac = UnpackColor(readu32(vbuf, vc + 32))
|
||||
local ua, vva, ub, vvb, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vb + 16),
|
||||
readf64(vbuf, vb + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24)
|
||||
|
||||
local textured = t and not (ua == ub and ua == uc and vva == vvb and vva == vvc)
|
||||
if t and not textured then -- constant uv (atlas white pixel): fold the texel into the vertex colours
|
||||
local tr, tg, tb, ta = SampleTexture(t, ua, vva)
|
||||
ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255
|
||||
rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255
|
||||
rc, gc, bc, ac = rc * tr / 255, gc * tg / 255, bc * tb / 255, ac * ta / 255
|
||||
end
|
||||
local flat = not textured and ra == rb and ra == rc and ga == gb and ga == gc and ba == bb and ba == bc and aa == ab
|
||||
and aa == ac
|
||||
if flat and aa <= 0 then return end
|
||||
local f_opaque, f_packed, f_sa, f_ns, f_c1, f_rs, f_gs, f_bs = false, 0, 0, 0, 0, 0, 0, 0
|
||||
if flat then
|
||||
f_opaque = aa >= 255
|
||||
f_packed = floor(ra + 0.5) + floor(ga + 0.5) * 256 + floor(ba + 0.5) * 65536
|
||||
+ (f_opaque and 4278190080 or floor(aa + 0.5) * 16777216)
|
||||
f_sa = aa / 255
|
||||
f_ns = 1 - f_sa
|
||||
f_c1 = f_ns / 255
|
||||
f_rs, f_gs, f_bs = ra * f_sa, ga * f_sa, ba * f_sa
|
||||
end
|
||||
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
|
||||
local xl, xr = minx, maxx
|
||||
local e0, e1, e2 = B0 * py + C0, B1 * py + C1, B2 * py + C2
|
||||
-- (e * n is -e / A within an ulp; the 1e-6 margin covers that, and the exact tests below decide)
|
||||
if A0 > 0 then
|
||||
xl = max(xl, floor(e0 * n0 - 0.500001))
|
||||
elseif A0 < 0 then
|
||||
xr = min(xr, ceil(e0 * n0 - 0.499999))
|
||||
end
|
||||
if A1 > 0 then
|
||||
xl = max(xl, floor(e1 * n1 - 0.500001))
|
||||
elseif A1 < 0 then
|
||||
xr = min(xr, ceil(e1 * n1 - 0.499999))
|
||||
end
|
||||
if A2 > 0 then
|
||||
xl = max(xl, floor(e2 * n2 - 0.500001))
|
||||
elseif A2 < 0 then
|
||||
xr = min(xr, ceil(e2 * n2 - 0.499999))
|
||||
end
|
||||
|
||||
while xl <= xr do
|
||||
local px = xl + 0.5
|
||||
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2
|
||||
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
|
||||
break
|
||||
end
|
||||
xl += 1
|
||||
end
|
||||
while xr > xl do
|
||||
local px = xr + 0.5
|
||||
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2
|
||||
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
|
||||
break
|
||||
end
|
||||
xr -= 1
|
||||
end
|
||||
if xl > xr then continue end
|
||||
local o = (y * TargetWidth + xl) * 4
|
||||
if flat then
|
||||
local o1 = o + (xr - xl) * 4
|
||||
if f_opaque then
|
||||
for oo = o, o1, 4 do writeu32(dbuf, oo, f_packed) end
|
||||
continue
|
||||
end
|
||||
local last_d, last_v = -1, 0
|
||||
for oo = o, o1, 4 do
|
||||
local d = readu32(dbuf, oo)
|
||||
if d == last_d then
|
||||
writeu32(dbuf, oo, last_v)
|
||||
elseif d < 16777216 then
|
||||
writeu32(dbuf, oo, f_packed)
|
||||
else
|
||||
last_d = d
|
||||
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
|
||||
if d >= 4278190080 then
|
||||
last_v = floor(f_rs + dr * f_ns + 0.5) + floor(f_gs + dg * f_ns + 0.5) * 256
|
||||
+ floor(f_bs + db * f_ns + 0.5) * 65536 + 4278190080
|
||||
else
|
||||
local k = rshift(d, 24) * f_c1
|
||||
local oa = f_sa + k
|
||||
local inv = 1 / oa
|
||||
last_v = floor((f_rs + dr * k) * inv + 0.5) + floor((f_gs + dg * k) * inv + 0.5) * 256
|
||||
+ floor((f_bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
|
||||
end
|
||||
writeu32(dbuf, oo, last_v)
|
||||
end
|
||||
end
|
||||
continue
|
||||
end
|
||||
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
|
||||
local a = w0 * aa + w1 * ab + w2 * ac
|
||||
if textured then
|
||||
local r = w0 * ra + w1 * rb + w2 * rc
|
||||
local g = w0 * ga + w1 * gb + w2 * gc
|
||||
local b = w0 * ba + w1 * bb + w2 * bc
|
||||
local tr, tg, tb, ta = SampleTexture(t, w0 * ua + w1 * ub + w2 * uc, w0 * vva + w1 * vvb + w2 * vvc)
|
||||
BlendPixel(dbuf, o, r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255)
|
||||
elseif a > 0 then
|
||||
BlendPixel(dbuf, o, w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc,
|
||||
w0 * ba + w1 * bb + w2 * bc, a)
|
||||
end
|
||||
o += 4
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- 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,
|
||||
cb: number, kind: number, t, u: number, v: number, cx0: number, cy0: number, cx1: number, cy1: number)
|
||||
local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0)
|
||||
local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1)
|
||||
if px0 >= px1 or py0 >= py1 then return end
|
||||
Shrink(px0, py0, px1, py1)
|
||||
local ra, ga, ba, aa = UnpackColor(ca)
|
||||
local rb, gb, bb, ab = UnpackColor(cb)
|
||||
if t then
|
||||
local tr, tg, tb, ta = SampleTexture(t, u, v)
|
||||
ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255
|
||||
rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255
|
||||
end
|
||||
if kind == 1 then
|
||||
local inv = 1 / (y1 - y0)
|
||||
for y = py0, py1 - 1 do
|
||||
local f = (y + 0.5 - y0) * inv
|
||||
local nf = 1 - f
|
||||
FillSpan(TargetBuffer, y, y + 1, px0, px1, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f,
|
||||
aa * nf + ab * f)
|
||||
end
|
||||
else
|
||||
local inv = 1 / (x1 - x0)
|
||||
local len = (px1 - px0) * 4
|
||||
local opaque = aa >= 255 and ab >= 255
|
||||
local prev_o = 0
|
||||
for y = py0, py1 - 1 do
|
||||
local o = (y * TargetWidth + px0) * 4
|
||||
if y > py0 and (opaque or RowRepeats(o, len, true))
|
||||
or (y == py0 and not opaque and RowRepeats(o, len, false)) then
|
||||
buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len)
|
||||
else
|
||||
local oo = o
|
||||
for x = px0, px1 - 1 do
|
||||
local f = (x + 0.5 - x0) * inv
|
||||
local nf = 1 - f
|
||||
BlendPixel(TargetBuffer, oo, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f)
|
||||
oo = oo + 4
|
||||
end
|
||||
end
|
||||
prev_o = o
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function M.SetTarget(buf: buffer, width: number)
|
||||
TargetBuffer, TargetWidth = buf, width
|
||||
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
|
||||
for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4, 0, rw * 4) end
|
||||
end
|
||||
end
|
||||
|
||||
@native
|
||||
function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: number)
|
||||
for y = 0, rh - 1 do
|
||||
buffer.copy(dst, y * rw * 4, TargetBuffer, ((ry0 + y) * TargetWidth + rx0) * 4, rw * 4)
|
||||
end
|
||||
end
|
||||
|
||||
-- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2, 4 line quad (va vb vc vd)
|
||||
@native
|
||||
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
|
||||
if kind == 1 then
|
||||
DrawRect(TargetBuffer, ax, ay, cx, cy, readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16),
|
||||
readf64(vbuf, vc + 24), readu32(vbuf, va + 32), t, cx0, cy0, cx1, cy1)
|
||||
else
|
||||
DrawRectGradient(TargetBuffer, ax, ay, cx, cy, readu32(vbuf, va + 32), readu32(vbuf, vc + 32), kind - 1, t,
|
||||
readf64(vbuf, va + 16), readf64(vbuf, va + 24), cx0, cy0, cx1, cy1)
|
||||
end
|
||||
end
|
||||
M.DrawPrim = DrawPrim
|
||||
|
||||
-- Packed tile jobs -> one exact-size buffer per rect, in job order (worker + main-thread fallback)
|
||||
local Scratch = buffer.create(TILE * TILE * 4)
|
||||
@native
|
||||
function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
|
||||
local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect
|
||||
local REC_A, REC_B, REC_C, 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
|
||||
while o < tlen do
|
||||
local tox, toy = readf64(T, o), readf64(T, o + 8)
|
||||
local x0, y0, nr, count = readi32(T, o + 16), readi32(T, o + 20), readi32(T, o + 24), readi32(T, o + 28)
|
||||
local ro = o + 32
|
||||
local po = ro + nr * 16
|
||||
o = po + count * 4
|
||||
for r = 0, nr - 1 do
|
||||
local rx0, ry0, rx1, ry1 = readi32(T, ro + r * 16), readi32(T, ro + r * 16 + 4),
|
||||
readi32(T, ro + r * 16 + 8), readi32(T, ro + r * 16 + 12)
|
||||
ClearRect(rx0, ry0, rx1, ry1)
|
||||
for k = 0, count - 1 do
|
||||
local q = readi32(T, po + k * 4)
|
||||
local cx0, cy0 = max(readi32(P, q + 8) - x0, rx0), max(readi32(P, q + 12) - y0, ry0)
|
||||
local cx1, cy1 = min(readi32(P, q + 16) - x0, rx1), min(readi32(P, q + 20) - y0, ry1)
|
||||
if cx0 >= cx1 or cy0 >= cy1 or readi32(P, q + 24) - x0 >= rx1 or readi32(P, q + 28) - y0 >= ry1
|
||||
or readi32(P, q + 32) - x0 <= rx0 or readi32(P, q + 36) - y0 <= ry0 then
|
||||
continue
|
||||
end
|
||||
local tid, t = readi32(P, q + 4), nil
|
||||
if tid >= 0 then t = textures[tid] end
|
||||
DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, q + REC_D, tox, toy, cx0, cy0, cx1, cy1)
|
||||
end
|
||||
local rw, rh = rx1 - rx0, ry1 - ry0
|
||||
local sub = buffer.create(rw * rh * 4)
|
||||
CopySubRect(sub, rx0, ry0, rw, rh)
|
||||
no += 1
|
||||
out[no] = sub
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return M
|
||||
end)()
|
||||
local Done = Actor:WaitForChild("Done")
|
||||
local Textures = {}
|
||||
|
||||
Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength)
|
||||
for _, Texture in TexUpdates do
|
||||
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()
|
||||
Done:Fire(Id, Results)
|
||||
end)
|
||||
|
||||
Actor:SetAttribute("Ready", true)
|
||||
Generated
+1
-1
@@ -1 +1 @@
|
||||
[[149, "imgui.lua"], [18647, "imgui_demo.lua"], [25932, "imgui_draw.lua"], [31170, "imgui_h.lua"], [33368, "imgui_impl_love.lua"], [33908, "imgui_internal.lua"], [37084, "imgui_tables.lua"], [41431, "imgui_widgets.lua"], [51186, "imstb_rectpack.lua"], [51632, "imstb_textedit.lua"], [52873, "imstb_truetype.lua"], [55341, "imstd_minstdio.lua"]]
|
||||
[[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"]]
|
||||
Generated
+32312
-14457
File diff suppressed because it is too large.
Load diff
@@ -3,11 +3,15 @@
|
||||
"tree": {
|
||||
"$className": "DataModel",
|
||||
"ReplicatedStorage": {
|
||||
"ImGui": { "$path": "build/ImGuiTyped.luau", "Impl": { "$path": "build/ImGui.luau" } }
|
||||
"ImGui": {
|
||||
"$path": "build/ImGuiTyped.luau",
|
||||
"Impl": { "$path": "build/ImGui.luau" },
|
||||
"Worker": { "$path": "build/ImGuiWorker.client.luau" }
|
||||
}
|
||||
},
|
||||
"StarterPlayer": {
|
||||
"StarterPlayerScripts": {
|
||||
"ImGuiMain": { "$path": "examples/example_roblox/main.client.luau" }
|
||||
"ImGuiMain": { "$path": "examples/example_roblox_parallel/main.client.luau" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
-3
@@ -8,11 +8,16 @@ there, but keep this port's existing data structures and conventions. Read the s
|
||||
file shares one global namespace. Globals defined by one file are visible to the others at call time.
|
||||
- Layout mirrors upstream: library at the repo root (`imgui.lua` incl. docking, drag & drop and the debug tools,
|
||||
`imgui_widgets.lua` incl. tab bars, `imgui_draw.lua`, `imgui_tables.lua`, `imgui_internal.lua`, `imgui_h.lua`,
|
||||
`imstb_*.lua`), demo in `imgui_demo.lua` only, backend in `backends/`, fonts in `fonts/`, the example LocalScript in
|
||||
`imstb_*.lua`), demo in `imgui_demo.lua` only, backends in `backends/<target>/` (`bundle.py` bundles every `*.lua` of the
|
||||
target's folder: `roblox/` = `imgui_impl_roblox.lua` + its modules, `love/`), fonts in `fonts/`, the example LocalScript in
|
||||
`examples/example_roblox/`. The library must never call into `imgui_demo.lua` (`tools/bundle.py --no-demo`,
|
||||
`tools/test/undefined.py --no-demo`, `NO_DEMO=1 run.py --main tools/test/scripts/t_nodemo.luau`).
|
||||
- Each `.lua` file is a function body in the bundle. New files must be loaded with `IM_INCLUDE"file.lua"` from an
|
||||
existing file. Merged-in sections are wrapped in `do ... end` so their locals stay private.
|
||||
- Roblox backend modules (`backends/roblox/*.lua`) start with `local X = IM_INCLUDE("roblox/x.lua")` lines and end with
|
||||
`return M`; `bundle.py` inlines them into the `imgui_impl_roblox.lua` function (one `do ... end` each, in dependency
|
||||
order, `X` a local of that function). Use one name per module everywhere; no circular includes (late-bind a field on
|
||||
a shared table instead, e.g. `EditableImages.FreeTile`).
|
||||
- No `goto`, no `::labels::`, no `setfenv/getfenv`, no LuaJIT `bit`/`ffi`. Use `bit32`. For `continue` use
|
||||
`repeat ... until true` with `break`, and an explicit flag when the loop itself must break out of the wrapper.
|
||||
- Luau has a limit of 200 locals per function and 255 upvalues; split huge functions (like demo sections) into
|
||||
@@ -21,7 +26,7 @@ there, but keep this port's existing data structures and conventions. Read the s
|
||||
## Portability (LÖVE build)
|
||||
- Library code must stay valid **Lua 5.1/LuaJIT syntax** apart from `@native` lines (stripped for LÖVE): no `+=`, `//`,
|
||||
`continue`, type annotations, `if`-expressions or string interpolation. Luau library calls are fine only if
|
||||
the COMPAT section of `backends/imgui_impl_love.lua` shims them (`bit32`, `buffer`, `table.clear/find/move/unpack`, `utf8`).
|
||||
the COMPAT section of `backends/love/imgui_impl_love.lua` shims them (`bit32`, `buffer`, `table.clear/find/move/unpack`, `utf8`).
|
||||
- Check with `tools/test/love/run.sh` (LuaJIT draw checksums must equal the Luau ones).
|
||||
|
||||
## Conventions (follow what the port already does)
|
||||
@@ -65,5 +70,5 @@ there, but keep this port's existing data structures and conventions. Read the s
|
||||
|
||||
- **ImGuiAxis is 1-based in this port** (`None=0, X=1, Y=2`; upstream `None=-1, X=0, Y=1`). Use `v[axis]` to index an ImVec2 and `3 - axis` for the other axis. `ImGuiDir` keeps upstream values (`None=-1, Left=0, Right=1, Up=2, Down=3`).
|
||||
- Never write `cond and nil or x` in Lua: it always evaluates `x`. Use an `if`.
|
||||
- Port signature quirk: `AddRect(min, max, col, rounding, thickness, flags)` (thickness BEFORE flags; upstream has flags first). Check the port's signature before porting any draw call that takes both.\n
|
||||
- Draw calls taking both thickness and flags use upstream's 1.92.8+ order: thickness BEFORE flags, e.g. `AddRect(min, max, col, rounding, thickness, flags)`, `PathStroke(col, thickness, flags)`, `AddPolyline(points, count, col, thickness, flags)`.
|
||||
- C++ default arguments (e.g. `bool x = true`) must be reproduced with `if x == nil then x = true end`; a missing Lua argument is nil/falsy.
|
||||
File diff suppressed because it is too large.
Load diff
+19
-38
@@ -1,52 +1,33 @@
|
||||
Dear ImGui for Roblox - not yet ported / known gaps
|
||||
====================================================
|
||||
Upstream reference: tools/test/upstream/ (ocornut/imgui docking branch, 1.93 WIP).
|
||||
Re-check with: python3 tools/test/missing.py [imgui|widgets|tables|draw] and python3 tools/test/undefined.py --no-demo
|
||||
(missing.py also lists names the port defines differently, e.g. the *V printf variants and DragFloat2..4 / DragInt2..4,
|
||||
which exist as ImGui.DragFloat2 = DragFloatN(2) etc. Those are NOT gaps.)
|
||||
Re-check with: python3 tools/compare_upstream.py (writes docs/PORT_STATUS.txt: [ ] = not ported, [=] = replaced by a
|
||||
Lua equivalent, "missing:" = enum values / struct fields) and python3 tools/test/undefined.py --no-demo
|
||||
|
||||
|
||||
FEATURES NOT PORTED
|
||||
-------------------
|
||||
- Multi-select / box-select: BeginMultiSelect, EndMultiSelect, MultiSelectItemHeader/Footer, MultiSelectAddSetAll,
|
||||
MultiSelectAddSetRange, SetNextItemSelectionUserData, BeginBoxSelect/EndBoxSelect, DebugNodeMultiSelectState.
|
||||
(Selectable/TreeNode call sites are stubbed with TODOs; the demo "Selection State & Multi-Select" section is not ported.)
|
||||
- Typing-select (type to jump in lists): GetTypingSelectRequest, TypingSelectFind*, DebugNodeTypingSelectState.
|
||||
- Examples > Assets Browser (needs multi-select + box-select).
|
||||
- Metrics > Tools > Item Picker (UpdateDebugToolItemPicker).
|
||||
- DebugFlashStyleColor / UpdateDebugToolFlashStyleColor (Style Editor "?" flash button).
|
||||
- DebugNodeInputTextState (Metrics > Internal state > InputText).
|
||||
- BringWindowToDisplayBehind: stub, does nothing.
|
||||
- ColorEdit4 / ColorPicker4: drag & drop target (dropping a color onto a color widget).
|
||||
- ImFontAtlas:AddFontFromMemoryCompressedTTF: stub (binary_to_compressed_c fonts can't be loaded).
|
||||
- ImGuiSizeCallbackData: SetNextWindowSizeConstraints custom callbacks only partially supported
|
||||
(Examples > Constrained Resize).
|
||||
- LogSetNextTextDecoration (Selectable "[ ]" decoration in log/clipboard output).
|
||||
- stb_truetype: cmap high-byte mapping (some CJK fonts assert).
|
||||
- Context hooks removal (RemoveContextHook), SetContextName.
|
||||
- RegisterUserTexture / UnregisterUserTexture.
|
||||
- ErrorCheckNewFrameSanityChecks / ErrorCheckEndFrameSanityChecks (fewer usage-error asserts than upstream).
|
||||
- GetAllocatorFunctions (n/a in Luau).
|
||||
NOT PORTED / PARTIAL
|
||||
--------------------
|
||||
- ImFont::AddRemapCodepointToGlyphIndex / ImGui_ImplStbTrueType_FontSrcGetGlyphIndexFromCodepoint (the port's font
|
||||
loader still checks glyphs by codepoint; 1.93 split this into codepoint -> glyph index -> glyph).
|
||||
- ImGui_GetDefaultCompressedFontDataProggyClean/ProggyForever: AddFontFromMemoryCompressedTTF works, but the default
|
||||
fonts are loaded from fonts/ instead of embedded compressed data.
|
||||
- ImFontAtlasDebugLogTextureRequests, ImHashSkipUncontributingPrefix.
|
||||
- DebugLogSkippedErrors / DebugDrawIdConflicts* (error-recovery and ID-conflict debug tools).
|
||||
|
||||
LUA LIMITATIONS
|
||||
---------------
|
||||
- ImGuiDataType.S64/U64: values are Luau doubles, exact only within +-2^53 (LLONG_MAX/ULLONG_MAX round up).
|
||||
- ImDrawList::AddCallback(userdata_size > 0): the "copy" is a shallow copy of a table userdata (no raw bytes).
|
||||
|
||||
WON'T DO (platform)
|
||||
-------------------
|
||||
- Multi-viewports / platform windows: Roblox has one window. Viewport API exists for the main viewport only.
|
||||
- Multi-viewports / platform windows: Roblox has one window. The viewport API covers the main viewport only.
|
||||
- Gamepad navigation via a real gamepad backend (keyboard navigation works).
|
||||
- IME / non-ASCII keyboard text input (backend sends printable ASCII only).
|
||||
|
||||
NOT VERIFIED LINE BY LINE AGAINST UPSTREAM
|
||||
------------------------------------------
|
||||
- Demo: Layout & Scrolling, Popups & Modal windows, Inputs & Focus.
|
||||
|
||||
KNOWN ISSUES
|
||||
------------
|
||||
- Tables > "Columns flags": disabling every column asserts in TableUpdateLayout (upstream asserts too).
|
||||
- Style Editor > Colors uses a ListClipper (port-only change, upstream submits every row).
|
||||
|
||||
PERFORMANCE IDEAS (not done)
|
||||
----------------------------
|
||||
- Cheaper visible ColorEdit4 rows; cheaper Begin() for child windows.
|
||||
|
||||
PLANNED EXTENSIONS
|
||||
------------------
|
||||
- ImGuizmo, ImNodes, ImGuiColorTextEdit, ImPlot, ImPlot3D (as separate extensions/, built with a --with flag).
|
||||
- stb_truetype: cmap format 2 (high-byte mapping) asserts (same "@TODO" as upstream stb_truetype).
|
||||
- ImTriangulator differs from upstream (imgui_draw.lua, [Luau]): CCW input is reversed first and only strictly
|
||||
counter-clockwise corners are reflex, so CCW and duplicate-point polygons triangulate differently from upstream.
|
||||
@@ -1,5 +1,5 @@
|
||||
function love.conf(t)
|
||||
t.window.title = "Dear ImGui - shared example (LÖVE)"
|
||||
t.window.title = "Dear ImGui - LÖVE extensions example"
|
||||
t.window.width, t.window.height = 1280, 800
|
||||
t.window.resizable = true
|
||||
end
|
||||
@@ -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 <repo>/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
|
||||
@@ -17,7 +17,7 @@ setfenv(1, setmetatable({}, {
|
||||
|
||||
local MainScale = 1.0
|
||||
local RenderScale = 1.0
|
||||
local RenderRate = 60
|
||||
local RenderRate = 60 -- max tile redraws per second (0 = every frame, limited by the redraw budget instead)
|
||||
local ThumbnailSize = 420
|
||||
local FontSize = 13.0
|
||||
local FontNames = { "Cousine-Regular", "DroidSans", "Karla-Regular", "ProggyTiny", "Roboto-Medium" }
|
||||
@@ -83,6 +83,7 @@ local function StyleColorsCatppuccinMocha(Style)
|
||||
{ "ScrollbarGrabActive", Overlay0 },
|
||||
|
||||
{ "CheckMark", Mauve },
|
||||
{ "CheckboxSelectedBg", Surface0 },
|
||||
{ "SliderGrab", Mauve, 0.8 },
|
||||
{ "SliderGrabActive", Mauve },
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,234 @@
|
||||
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local RunService = game:GetService("RunService")
|
||||
|
||||
local ImGuiModule = ReplicatedStorage:WaitForChild("ImGui")
|
||||
local G = require(ImGuiModule)
|
||||
local ImGui, ImGui_ImplRoblox = G.ImGui, G.ImGui_ImplRoblox
|
||||
|
||||
ImGui.CreateContext()
|
||||
local IO = ImGui.GetIO()
|
||||
IO.ConfigFlags = bit32.bor(IO.ConfigFlags, G.ImGuiConfigFlags.NavEnableKeyboard, G.ImGuiConfigFlags.DockingEnable)
|
||||
|
||||
-- catppuccin mocha mauve https://catppuccin.com/palette
|
||||
local function StyleColorsCatppuccinMocha(Style)
|
||||
local function Hex(Value, Alpha)
|
||||
return G.ImVec4(
|
||||
bit32.extract(Value, 16, 8) / 255,
|
||||
bit32.extract(Value, 8, 8) / 255,
|
||||
bit32.extract(Value, 0, 8) / 255,
|
||||
Alpha or 1.0
|
||||
)
|
||||
end
|
||||
|
||||
local Crust, Mantle, Base = 0x11111b, 0x181825, 0x1e1e2e
|
||||
local Surface0, Surface1, Surface2 = 0x313244, 0x45475a, 0x585b70
|
||||
local Overlay0, Overlay2, Text = 0x6c7086, 0x9399b2, 0xcdd6f4
|
||||
local Mauve, Lavender = 0xcba6f7, 0xb4befe
|
||||
|
||||
local Entries = {
|
||||
{ "Text", Text },
|
||||
{ "TextDisabled", Overlay0 },
|
||||
|
||||
{ "WindowBg", Base },
|
||||
{ "ChildBg", Base, 0.0 },
|
||||
{ "PopupBg", Mantle, 0.98 },
|
||||
{ "Border", Surface1 },
|
||||
{ "BorderShadow", Crust, 0.0 },
|
||||
|
||||
{ "FrameBg", Surface0 },
|
||||
{ "FrameBgHovered", Surface1 },
|
||||
{ "FrameBgActive", Surface2 },
|
||||
|
||||
{ "TitleBg", Mantle },
|
||||
{ "TitleBgActive", Crust },
|
||||
{ "TitleBgCollapsed", Mantle, 0.75 },
|
||||
{ "MenuBarBg", Mantle },
|
||||
|
||||
{ "ScrollbarBg", Mantle },
|
||||
{ "ScrollbarGrab", Surface1 },
|
||||
{ "ScrollbarGrabHovered", Surface2 },
|
||||
{ "ScrollbarGrabActive", Overlay0 },
|
||||
|
||||
{ "CheckMark", Mauve },
|
||||
{ "CheckboxSelectedBg", Surface0 },
|
||||
{ "SliderGrab", Mauve, 0.8 },
|
||||
{ "SliderGrabActive", Mauve },
|
||||
|
||||
{ "Button", Surface0 },
|
||||
{ "ButtonHovered", Surface1 },
|
||||
{ "ButtonActive", Mauve, 0.6 },
|
||||
|
||||
{ "Header", Surface0 },
|
||||
{ "HeaderHovered", Surface1 },
|
||||
{ "HeaderActive", Mauve, 0.5 },
|
||||
|
||||
{ "Separator", Surface1 },
|
||||
{ "SeparatorHovered", Mauve, 0.7 },
|
||||
{ "SeparatorActive", Mauve },
|
||||
|
||||
{ "ResizeGrip", Mauve, 0.2 },
|
||||
{ "ResizeGripHovered", Mauve, 0.6 },
|
||||
{ "ResizeGripActive", Mauve, 0.9 },
|
||||
|
||||
{ "InputTextCursor", Text },
|
||||
|
||||
{ "Tab", Surface0 },
|
||||
{ "TabHovered", Surface2 },
|
||||
{ "TabSelected", Surface1 },
|
||||
{ "TabSelectedOverline", Mauve },
|
||||
{ "TabDimmed", Mantle },
|
||||
{ "TabDimmedSelected", Surface0 },
|
||||
{ "TabDimmedSelectedOverline", Overlay0 },
|
||||
|
||||
{ "DockingPreview", Mauve, 0.7 },
|
||||
{ "DockingEmptyBg", Crust },
|
||||
|
||||
{ "PlotLines", Overlay2 },
|
||||
{ "PlotLinesHovered", Mauve },
|
||||
{ "PlotHistogram", Mauve, 0.8 },
|
||||
{ "PlotHistogramHovered", Lavender },
|
||||
|
||||
{ "TableHeaderBg", Surface0 },
|
||||
{ "TableBorderStrong", Surface1 },
|
||||
{ "TableBorderLight", Surface0 },
|
||||
{ "TableRowBg", Base, 0.0 },
|
||||
{ "TableRowBgAlt", Surface0, 0.3 },
|
||||
|
||||
{ "TextLink", Mauve },
|
||||
{ "TextSelectedBg", Mauve, 0.35 },
|
||||
{ "TreeLines", Surface2 },
|
||||
{ "DragDropTarget", Mauve, 0.9 },
|
||||
|
||||
{ "NavCursor", Lavender },
|
||||
{ "NavWindowingHighlight", Lavender, 0.7 },
|
||||
{ "NavWindowingDimBg", Crust, 0.5 },
|
||||
{ "ModalWindowDimBg", Crust, 0.6 },
|
||||
}
|
||||
|
||||
for _, Entry in ipairs(Entries) do
|
||||
local Name, Color, Alpha = Entry[1], Entry[2], Entry[3]
|
||||
Style.Colors[G.ImGuiCol[Name]] = Hex(Color, Alpha)
|
||||
end
|
||||
end
|
||||
|
||||
StyleColorsCatppuccinMocha(ImGui.GetStyle())
|
||||
IO.Fonts:AddFontDefault()
|
||||
for _, Name in { "Cousine-Regular", "DroidSans", "Karla-Regular", "ProggyTiny", "Roboto-Medium" } do
|
||||
IO.Fonts:AddFontFromFileTTF("fonts/" .. Name .. ".ttf", 13.0)
|
||||
end
|
||||
|
||||
ImGui_ImplRoblox.Init()
|
||||
local RenderRate = 60 -- UI redraws per second (0 = every frame)
|
||||
ImGui_ImplRoblox.SetRenderRate(RenderRate)
|
||||
ImGui_ImplRoblox.EnableParallel({ Actors = 4 })
|
||||
|
||||
-- Game FPS and ImGui render FPS, sampled every 0.5 s
|
||||
local GameFps, RenderFps, Frames, Renders, Since = 0, 0, 0, nil, os.clock()
|
||||
RunService.RenderStepped:Connect(function()
|
||||
Frames += 1
|
||||
local Now = os.clock()
|
||||
local Dt = Now - Since
|
||||
if Dt >= 0.5 then
|
||||
GameFps = Frames / Dt
|
||||
local R = ImGui_ImplRoblox.GetStats().Renders
|
||||
RenderFps = (R and Renders) and (R - Renders) / Dt or 0
|
||||
Frames, Renders, Since = 0, R, Now
|
||||
end
|
||||
end)
|
||||
|
||||
local function Help(Desc)
|
||||
ImGui.SameLine()
|
||||
ImGui.TextDisabled("(?)")
|
||||
if ImGui.BeginItemTooltip() then
|
||||
ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0)
|
||||
ImGui.TextUnformatted(Desc)
|
||||
ImGui.PopTextWrapPos()
|
||||
ImGui.EndTooltip()
|
||||
end
|
||||
end
|
||||
|
||||
local Enabled, Timing = true, false
|
||||
local function ShowParallelWindow()
|
||||
local C, S = ImGui_ImplRoblox.GetParallelConfig(), ImGui_ImplRoblox.GetParallelStats()
|
||||
ImGui.Begin("Parallel")
|
||||
|
||||
local Fr = IO.Framerate
|
||||
ImGui.Text("Game %.1f FPS (%.2f ms)", GameFps, GameFps > 0 and 1000 / GameFps or 0)
|
||||
Help("Frames Roblox actually renders per second (counted from RenderStepped).")
|
||||
ImGui.Text("ImGui Logic %.1f FPS (%.2f ms)", Fr, Fr > 0 and 1000 / Fr or 0)
|
||||
Help("How often ImGui logic runs NewFrame..Render (io.Framerate, 60-frame average). Runs every game frame so input stays responsive.")
|
||||
ImGui.Text("ImGui Render %.1f FPS", RenderFps)
|
||||
Help("How often the backend actually redraws the UI (capped by Render rate). Frames in between reuse the last drawn UI.")
|
||||
local Rate, RateChanged = ImGui.SliderInt("Render rate", RenderRate, 0, 240, RenderRate == 0 and "every frame" or "%d Hz")
|
||||
Help("Max UI redraws per second (SetRenderRate). 0 = redraw every game frame.")
|
||||
if RateChanged then
|
||||
RenderRate = Rate
|
||||
ImGui_ImplRoblox.SetRenderRate(Rate)
|
||||
end
|
||||
|
||||
ImGui.Separator()
|
||||
local Changed
|
||||
Changed, Enabled = ImGui.Checkbox("Enabled", Enabled)
|
||||
Help("Rasterize dirty tiles on Actors (parallel Luau). Off = everything is rasterized on the main thread.")
|
||||
if Changed then
|
||||
if Enabled then
|
||||
ImGui_ImplRoblox.EnableParallel()
|
||||
else
|
||||
ImGui_ImplRoblox.DisableParallel()
|
||||
end
|
||||
end
|
||||
local Actors = C.Actors
|
||||
Actors, Changed = ImGui.SliderInt("Actors", Actors, 1, 16)
|
||||
Help("Number of worker Actors. Changing it finishes the pending frame and replaces the Actors. More than your CPU core count won't help.")
|
||||
if Changed then
|
||||
C.Actors = Actors
|
||||
if Enabled then
|
||||
ImGui_ImplRoblox.EnableParallel()
|
||||
end
|
||||
end
|
||||
C.MinTiles = ImGui.SliderInt("MinTiles", C.MinTiles, 0, 64)
|
||||
Help("A frame with fewer dirty tiles than this is rasterized on the main thread (dispatch overhead isn't worth it).")
|
||||
C.MinPixels = ImGui.SliderInt("MinPixels", C.MinPixels, 0, 262144)
|
||||
Help("A frame with fewer dirty pixels than this is rasterized on the main thread.")
|
||||
C.MaxBytesPerPixel = ImGui.SliderFloat("MaxBytesPerPixel", C.MaxBytesPerPixel, 0, 16)
|
||||
Help("If the packed data sent to Actors exceeds this many bytes per dirty pixel (e.g. lots of small text), the frame stays on the main thread, since copying would cost more than it saves. 0 = no limit.")
|
||||
|
||||
local B = ImGui_ImplRoblox.GetStats()
|
||||
ImGui.Separator()
|
||||
ImGui.Text("Flushes parallel %d serial %d", S.ParallelFlushes, S.SerialFlushes)
|
||||
Help("Frames whose dirty tiles went to Actors vs. were rasterized on the main thread (below thresholds, or ImGui ran too late in the frame).")
|
||||
ImGui.Text("Fallbacks %d Late %d", S.Fallbacks, S.Late)
|
||||
Help("Fallbacks: Actor batches not finished in time, rasterized on the main thread so the frame is never partial. Late: results that arrived after that and were discarded. Both should stay at 0.")
|
||||
ImGui.Text("Tiles %d EditableImage %.1f MB", B.Tiles, B.EditableImageBytes / 1048576)
|
||||
Help("Live 128x128 raster tiles and EditableImage memory used by the backend (hard-capped).")
|
||||
Changed, Timing = ImGui.Checkbox("Stage timing", Timing)
|
||||
Help("Per-stage main-thread time of the last rendered frame. With parallel on, Raster is only the packing for Actors.")
|
||||
if Changed then
|
||||
ImGui_ImplRoblox.SetStageTiming(Timing)
|
||||
end
|
||||
if Timing and B.Frame then
|
||||
for _, K in { "Compare", "Collect", "Hash", "Raster", "Upload", "Other", "Total" } do
|
||||
ImGui.Text("%-8s %.3f ms", K, (B.Frame[K] or 0) * 1000)
|
||||
end
|
||||
end
|
||||
|
||||
ImGui.End()
|
||||
end
|
||||
|
||||
-- PreSimulation, not RenderStepped: the parallel Finish runs in PostSimulation
|
||||
RunService.PreSimulation:Connect(function()
|
||||
ImGui_ImplRoblox.NewFrame()
|
||||
ImGui.NewFrame()
|
||||
ImGui.DockSpaceOverViewport(0, nil, G.ImGuiDockNodeFlags.PassthruCentralNode)
|
||||
ImGui.ShowDemoWindow()
|
||||
ShowParallelWindow()
|
||||
ImGui.Render()
|
||||
ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
end)
|
||||
|
||||
script.Destroying:Connect(function()
|
||||
ImGui_ImplRoblox.DisableParallel()
|
||||
ImGui_ImplRoblox.Shutdown()
|
||||
ImGui.DestroyContext()
|
||||
end)
|
||||
@@ -1,53 +0,0 @@
|
||||
-- One UI that runs unchanged on Roblox and LÖVE: only the Dear ImGui API is used, and the code is plain Lua 5.1
|
||||
-- (no Luau-only syntax), so both Luau and LuaJIT run it. The platform launchers are roblox.client.luau and main.lua.
|
||||
-- local App = require(app)(G) -- G = the table returned by the ImGui bundle
|
||||
-- every frame, between ImGui.NewFrame() and ImGui.Render(): App.Frame()
|
||||
return function(G)
|
||||
local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4
|
||||
local App = {
|
||||
Platform = "?", -- set by the launcher ("Roblox" / "LÖVE")
|
||||
ClearColor = ImVec4(0.45, 0.55, 0.60, 1.00), -- launchers may use it as the background colour
|
||||
}
|
||||
local show_demo, show_table = false, true
|
||||
local counter, speed = 0, 1.0
|
||||
local name = ImGui.NewTextBuffer("Player", 64)
|
||||
local samples, t = {}, 0.0
|
||||
local items = { { "Sword", 1, 120 }, { "Potion", 5, 15 }, { "Arrow", 64, 1 }, { "Shield", 1, 80 } }
|
||||
|
||||
function App.Frame()
|
||||
local io = ImGui.GetIO()
|
||||
t = t + io.DeltaTime * speed
|
||||
for i = 1, 90 do samples[i] = math.sin(i / 90 * math.pi * 4 + t * 3) end
|
||||
|
||||
ImGui.SetNextWindowPos(ImVec2(20, 20), G.ImGuiCond.FirstUseEver)
|
||||
ImGui.SetNextWindowSize(ImVec2(420, 360), G.ImGuiCond.FirstUseEver)
|
||||
ImGui.Begin("Shared Example")
|
||||
ImGui.Text("Running on %s (%.1f FPS)", App.Platform, io.Framerate)
|
||||
ImGui.Separator()
|
||||
ImGui.InputText("name", name, 64)
|
||||
if ImGui.Button("Click me") then counter = counter + 1 end
|
||||
ImGui.SameLine(); ImGui.Text("%s clicked %d times", ImGui.TextBufferToString(name), counter)
|
||||
speed = ImGui.SliderFloat("speed", speed, 0.0, 4.0)
|
||||
ImGui.ColorEdit3("background", App.ClearColor)
|
||||
ImGui.PlotLines("wave", samples, nil, #samples, 0, nil, -1.0, 1.0, ImVec2(0, 60))
|
||||
local _
|
||||
_, show_table = ImGui.Checkbox("Inventory table", show_table)
|
||||
ImGui.SameLine(); _, show_demo = ImGui.Checkbox("Demo window", show_demo)
|
||||
if show_table and ImGui.BeginTable("inv", 3, bit32.bor(G.ImGuiTableFlags.Borders, G.ImGuiTableFlags.RowBg, G.ImGuiTableFlags.Sortable)) then
|
||||
ImGui.TableSetupColumn("Item"); ImGui.TableSetupColumn("Count"); ImGui.TableSetupColumn("Value")
|
||||
ImGui.TableHeadersRow()
|
||||
for _, it in ipairs(items) do
|
||||
ImGui.TableNextRow()
|
||||
ImGui.TableNextColumn(); ImGui.Text(it[1])
|
||||
ImGui.TableNextColumn(); ImGui.Text("%d", it[2])
|
||||
ImGui.TableNextColumn(); ImGui.Text("%d", it[3])
|
||||
end
|
||||
ImGui.EndTable()
|
||||
end
|
||||
ImGui.End()
|
||||
|
||||
if show_demo and ImGui.ShowDemoWindow then show_demo = ImGui.ShowDemoWindow(show_demo) end
|
||||
end
|
||||
|
||||
return App
|
||||
end
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"name": "imgui-shared-example",
|
||||
"tree": {
|
||||
"$className": "DataModel",
|
||||
"ReplicatedStorage": {
|
||||
"ImGui": { "$path": "../../build/ImGuiTyped.luau", "Impl": { "$path": "../../build/ImGui.luau" } },
|
||||
"SharedApp": { "$path": "app.lua" }
|
||||
},
|
||||
"StarterPlayer": {
|
||||
"StarterPlayerScripts": {
|
||||
"SharedExample": { "$path": "roblox.client.luau" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
-- LÖVE launcher for app.lua: python3 tools/bundle.py --target love then love examples/example_shared
|
||||
local ROOT = love.filesystem.getSource() .. "/../../" -- repo root (build/, fonts/)
|
||||
local function load_bundle()
|
||||
local f = assert(io.open(ROOT .. "build/imgui_love.lua", "rb"), "run: python3 tools/bundle.py --target love")
|
||||
local src = f:read("*a"); f:close()
|
||||
return assert(loadstring(src, "@imgui_love.lua"))()
|
||||
end
|
||||
|
||||
local G, ImGui, App
|
||||
|
||||
function love.load()
|
||||
G = load_bundle()
|
||||
ImGui = G.ImGui
|
||||
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 })
|
||||
App = love.filesystem.load("app.lua")()(G)
|
||||
App.Platform = "LÖVE"
|
||||
end
|
||||
|
||||
function love.update(dt)
|
||||
G.ImGui_ImplLove.NewFrame()
|
||||
ImGui.NewFrame()
|
||||
App.Frame()
|
||||
ImGui.Render()
|
||||
end
|
||||
|
||||
function love.draw()
|
||||
local c = App.ClearColor
|
||||
love.graphics.clear(c.x, c.y, c.z, 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
|
||||
@@ -1,21 +0,0 @@
|
||||
-- Roblox launcher for app.lua (sync with examples/example_shared/default.project.json).
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local RunService = game:GetService("RunService")
|
||||
local G = require(ReplicatedStorage:WaitForChild("ImGui"))
|
||||
local ImGui = G.ImGui
|
||||
|
||||
ImGui.CreateContext()
|
||||
local io = ImGui.GetIO()
|
||||
io.ConfigFlags = bit32.bor(io.ConfigFlags, G.ImGuiConfigFlags.NavEnableKeyboard, G.ImGuiConfigFlags.DockingEnable)
|
||||
G.ImGui_ImplRoblox.Init()
|
||||
|
||||
local App = require(ReplicatedStorage:WaitForChild("SharedApp"))(G)
|
||||
App.Platform = "Roblox"
|
||||
|
||||
RunService.Stepped:Connect(function()
|
||||
G.ImGui_ImplRoblox.NewFrame()
|
||||
ImGui.NewFrame()
|
||||
App.Frame()
|
||||
ImGui.Render()
|
||||
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
end)
|
||||
Submodule
+1
Submodule extensions/imcurveedit-luau added at 9769fd0839.
Submodule
+1
Submodule extensions/imgradient-luau added at 21b3b2d287.
Submodule
+1
Submodule extensions/imgui-memory-editor-luau added at 3c9aca1a43.
Submodule
+1
Submodule extensions/imguicolortextedit-luau added at 9b8f9659f2.
Submodule
+1
Submodule extensions/imguizmo-luau added at ab98d60345.
Submodule
+1
Submodule extensions/imnodes-luau added at 363fd65d98.
Submodule
+1
Submodule extensions/implot-luau added at 7fa48b066b.
Submodule
+1
Submodule extensions/implot3d-luau added at 41c709c872.
Submodule
+1
Submodule extensions/imsequencer-luau added at a9110772e7.
+11035
-6463
File diff suppressed because it is too large.
Load diff
+4018
-905
File diff suppressed because it is too large.
Load diff
+1564
-761
File diff suppressed because it is too large.
Load diff
+1494
-702
File diff suppressed because it is too large.
Load diff
+984
-239
File diff suppressed because it is too large.
Load diff
+3151
-638
File diff suppressed because it is too large.
Load diff
+245
-14
@@ -1,8 +1,65 @@
|
||||
--- Dear ImGui
|
||||
-- This is a Lua port of original `imstb_rectpack.h`
|
||||
-- [Port] This is a Lua port of original `imstb_rectpack.h`
|
||||
|
||||
-- ALL TABLES IN THIS FILE ARE 1-BASED!
|
||||
-- Avoids table creation when possible
|
||||
-- [Port] ALL TABLES IN THIS FILE ARE 1-BASED!
|
||||
-- [Port] Avoids table creation when possible
|
||||
|
||||
-- [DEAR IMGUI]
|
||||
-- This is a slightly modified version of stb_rect_pack.h 1.01.
|
||||
-- Grep for [DEAR IMGUI] to find the changes.
|
||||
--
|
||||
-- stb_rect_pack.h - v1.01 - public domain - rectangle packing
|
||||
-- Sean Barrett 2014
|
||||
--
|
||||
-- Useful for e.g. packing rectangular textures into an atlas.
|
||||
-- Does not do rotation.
|
||||
--
|
||||
-- Not necessarily the awesomest packing method, but better than
|
||||
-- the totally naive one in stb_truetype (which is primarily what
|
||||
-- this is meant to replace).
|
||||
--
|
||||
-- Has only had a few tests run, may have issues.
|
||||
--
|
||||
-- More docs to come.
|
||||
--
|
||||
-- Uses table.sort and assert (STBRP_SORT and STBRP_ASSERT below).
|
||||
--
|
||||
-- This library currently uses the Skyline Bottom-Left algorithm.
|
||||
--
|
||||
-- Please note: better rectangle packers are welcome! Please
|
||||
-- implement them to the same API, but with a different init
|
||||
-- function.
|
||||
--
|
||||
-- Credits
|
||||
--
|
||||
-- Library
|
||||
-- Sean Barrett
|
||||
-- Minor features
|
||||
-- Martins Mozeiko
|
||||
-- github:IntellectualKitty
|
||||
--
|
||||
-- Bugfixes / warning fixes
|
||||
-- Jeremy Jaussaud
|
||||
-- Fabian Giesen
|
||||
--
|
||||
-- Version history:
|
||||
--
|
||||
-- 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section
|
||||
-- 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles
|
||||
-- 0.99 (2019-02-07) warning fixes
|
||||
-- 0.11 (2017-03-03) return packing success/fail result
|
||||
-- 0.10 (2016-10-25) remove cast-away-const to avoid warnings
|
||||
-- 0.09 (2016-08-27) fix compiler warnings
|
||||
-- 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
|
||||
-- 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
|
||||
-- 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
|
||||
-- 0.05: added STBRP_ASSERT to allow replacing assert
|
||||
-- 0.04: fixed minor bug in STBRP_LARGE_RECTS support
|
||||
-- 0.01: initial release
|
||||
--
|
||||
-- LICENSE
|
||||
--
|
||||
-- See end of file for license information.
|
||||
|
||||
--- The `prev_link` can be stbrp_context or stbrp_node
|
||||
--- @diagnostic disable
|
||||
@@ -13,7 +70,13 @@ local STBRP_SORT = table.sort
|
||||
local STBRP_ASSERT = assert
|
||||
local STBRP__NOTUSED = function(_) end
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
--
|
||||
-- INCLUDE SECTION
|
||||
--
|
||||
|
||||
local STBRP__MAXVAL = 0x7fffffff
|
||||
-- Mostly for internal use, but this is the maximum supported coordinate value.
|
||||
|
||||
--- @enum STBRP_HEURISTIC_Skyline
|
||||
local STBRP_HEURISTIC_Skyline = {
|
||||
@@ -42,14 +105,20 @@ local STBRP__PREV_LINK_TYPE = {
|
||||
|
||||
--- @return stbrp_rect
|
||||
--- @nodiscard
|
||||
@native
|
||||
local function stbrp_rect()
|
||||
return {
|
||||
-- reserved for your use:
|
||||
id = 0,
|
||||
|
||||
-- input:
|
||||
w = 0,
|
||||
h = 0,
|
||||
|
||||
-- output:
|
||||
x = 0,
|
||||
y = 0,
|
||||
was_packed = 0
|
||||
was_packed = 0 -- non-zero if valid packing
|
||||
}
|
||||
end
|
||||
|
||||
@@ -60,6 +129,7 @@ end
|
||||
|
||||
--- @return stbrp_node
|
||||
--- @nodiscard
|
||||
@native
|
||||
local function stbrp_node()
|
||||
return {
|
||||
x = 0,
|
||||
@@ -81,6 +151,7 @@ end
|
||||
|
||||
--- @return stbrp_context
|
||||
--- @nodiscard
|
||||
@native
|
||||
local function stbrp_context()
|
||||
return {
|
||||
width = 0,
|
||||
@@ -92,7 +163,7 @@ local function stbrp_context()
|
||||
|
||||
active_head = nil,
|
||||
free_head = nil,
|
||||
extra = {stbrp_node(), stbrp_node()}
|
||||
extra = {stbrp_node(), stbrp_node()} -- we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
|
||||
}
|
||||
end
|
||||
|
||||
@@ -103,6 +174,7 @@ end
|
||||
--- @field prev_link_type? int
|
||||
|
||||
--- @return stbrp__findresult
|
||||
@native
|
||||
local function stbrp__findresult()
|
||||
return {
|
||||
x = 0,
|
||||
@@ -113,15 +185,17 @@ local function stbrp__findresult()
|
||||
}
|
||||
end
|
||||
|
||||
--------------------------
|
||||
--------------------------
|
||||
---
|
||||
--- IMPLEMENTATION SECTION
|
||||
---
|
||||
---
|
||||
-------------------------------------------------------------------------------
|
||||
--
|
||||
-- IMPLEMENTATION SECTION
|
||||
--
|
||||
|
||||
-- Optionally select which packing heuristic the library should use. Different
|
||||
-- heuristics will produce better/worse results for different data sets.
|
||||
-- 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)
|
||||
@@ -131,21 +205,56 @@ local function stbrp_setup_heuristic(context, heuristic)
|
||||
end
|
||||
end
|
||||
|
||||
-- Optionally call this function after init but before doing any packing to
|
||||
-- change the handling of the out-of-temp-memory scenario, described above.
|
||||
-- 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;
|
||||
-- this gives better packing, but may fail due to OOM (even though
|
||||
-- the rectangles easily fit). @TODO a smarter approach would be to only
|
||||
-- quantize once we've hit OOM, then we could get rid of this parameter.
|
||||
context.align = 1
|
||||
else
|
||||
-- if it's not ok to run out of memory, then quantize the widths
|
||||
-- so that num_nodes is always enough nodes.
|
||||
--
|
||||
-- I.e. num_nodes * align >= width
|
||||
-- align >= width / num_nodes
|
||||
-- align = ceil(width/num_nodes)
|
||||
|
||||
context.align = (context.width + context.num_nodes - 1) / context.num_nodes
|
||||
end
|
||||
end
|
||||
|
||||
-- Initialize a rectangle packer to:
|
||||
-- pack a rectangle that is 'width' by 'height' in dimensions
|
||||
-- using temporary storage provided by the array 'nodes', which is 'num_nodes' long
|
||||
--
|
||||
-- You must call this function every time you start packing into a new target.
|
||||
--
|
||||
-- There is no "shutdown" function. The 'nodes' memory must stay valid for
|
||||
-- the following stbrp_pack_rects() call (or calls), but can be freed after
|
||||
-- the call (or calls) finish.
|
||||
--
|
||||
-- Note: to guarantee best results, either:
|
||||
-- 1. make sure 'num_nodes' >= 'width'
|
||||
-- or 2. call stbrp_setup_allow_out_of_mem() defined above with 'allow_out_of_mem = true'
|
||||
--
|
||||
-- If you don't do either of the above things, widths will be quantized to multiples
|
||||
-- of small integers to guarantee the algorithm doesn't run out of temporary storage.
|
||||
--
|
||||
-- If you do #2, then the non-quantized algorithm will be used, but the algorithm
|
||||
-- may run out of temporary storage and be unable to pack some rectangles.
|
||||
--- @param context stbrp_context
|
||||
--- @param width int
|
||||
--- @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]
|
||||
@@ -160,6 +269,7 @@ function stbrp_init_target(context, width, height, nodes, num_nodes)
|
||||
context.num_nodes = num_nodes
|
||||
stbrp_setup_allow_out_of_mem(context, false)
|
||||
|
||||
-- node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
|
||||
context.extra[1].x = 0
|
||||
context.extra[1].y = 0
|
||||
context.extra[1].next = context.extra[2]
|
||||
@@ -168,11 +278,14 @@ function stbrp_init_target(context, width, height, nodes, num_nodes)
|
||||
context.extra[2].next = nil
|
||||
end
|
||||
|
||||
-- find minimum y position if it starts at x1
|
||||
-- [Port] Returns (min_y, waste_area)
|
||||
--- @param c stbrp_context
|
||||
--- @param first stbrp_node
|
||||
--- @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
|
||||
@@ -181,7 +294,7 @@ local function stbrp__skyline_find_min_y(c, first, x0, width)
|
||||
|
||||
STBRP_ASSERT(first.x <= x0)
|
||||
|
||||
STBRP_ASSERT(node.next.x > x0)
|
||||
STBRP_ASSERT(node.next.x > x0) -- we ended up handling this in the caller for efficiency
|
||||
|
||||
STBRP_ASSERT(node.x <= x0)
|
||||
|
||||
@@ -190,14 +303,19 @@ local function stbrp__skyline_find_min_y(c, first, x0, width)
|
||||
local visited_width = 0
|
||||
while node.x < x1 do
|
||||
if node.y > min_y then
|
||||
-- raise min_y higher.
|
||||
-- we've accounted for all waste up to min_y,
|
||||
-- but we'll now add more waste for everything we've visited
|
||||
waste_area = waste_area + visited_width * (node.y - min_y)
|
||||
min_y = node.y
|
||||
-- the first time through, visited_width might be reduced
|
||||
if node.x < x0 then
|
||||
visited_width = visited_width + node.next.x - x0
|
||||
else
|
||||
visited_width = visited_width + node.next.x - node.x
|
||||
end
|
||||
else
|
||||
-- add waste area
|
||||
local under_width = node.next.x - node.x
|
||||
if under_width + visited_width > width then
|
||||
under_width = width - visited_width
|
||||
@@ -215,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
|
||||
@@ -223,10 +342,12 @@ local function stbrp__skyline_find_best_pos(c, width, height)
|
||||
local best_prev_link = nil
|
||||
local best_prev_link_type = nil
|
||||
|
||||
-- align to multiple of c.align
|
||||
width = width + c.align - 1
|
||||
width = width - width % c.align
|
||||
STBRP_ASSERT(width % c.align == 0)
|
||||
|
||||
-- if it can't possibly fit, bail immediately
|
||||
if width > c.width or height > c.height then
|
||||
fr.prev_link = nil
|
||||
fr.prev_link_type = nil
|
||||
@@ -242,7 +363,8 @@ local function stbrp__skyline_find_best_pos(c, width, height)
|
||||
while (node.x + width <= c.width) do
|
||||
local y, waste = stbrp__skyline_find_min_y(c, node, node.x, width)
|
||||
|
||||
if c.heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight then
|
||||
if c.heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight then -- actually just want to test BL
|
||||
-- bottom left
|
||||
if y < best_y then
|
||||
best_y = y
|
||||
best_prev_link = prev_link
|
||||
@@ -250,7 +372,9 @@ local function stbrp__skyline_find_best_pos(c, width, height)
|
||||
best_x = node.x
|
||||
end
|
||||
else
|
||||
-- best-fit
|
||||
if y + height <= c.height then
|
||||
-- can only use it if it first vertically
|
||||
if y < best_y or (y == best_y and waste < best_waste) then
|
||||
best_y = y
|
||||
best_waste = waste
|
||||
@@ -266,12 +390,30 @@ local function stbrp__skyline_find_best_pos(c, width, height)
|
||||
node = node.next
|
||||
end
|
||||
|
||||
-- if doing best-fit (BF), we also have to try aligning right edge to each node position
|
||||
--
|
||||
-- e.g, if fitting
|
||||
--
|
||||
-- ____________________
|
||||
-- |____________________|
|
||||
--
|
||||
-- into
|
||||
--
|
||||
-- | |
|
||||
-- | ____________|
|
||||
-- |____________|
|
||||
--
|
||||
-- then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
|
||||
--
|
||||
-- This makes BF take about 2x the time
|
||||
|
||||
if c.heuristic == STBRP_HEURISTIC_Skyline.BF_sortHeight then
|
||||
local tail = c.active_head
|
||||
local node_scan = c.active_head
|
||||
local prev_link_scan = c
|
||||
local prev_link_scan_type = STBRP__PREV_LINK_TYPE.ACTIVE_HEAD
|
||||
|
||||
-- find first node that's admissible
|
||||
while tail and tail.x < width do
|
||||
tail = tail.next
|
||||
end
|
||||
@@ -280,6 +422,7 @@ local function stbrp__skyline_find_best_pos(c, width, height)
|
||||
local xpos = tail.x - width
|
||||
STBRP_ASSERT(xpos >= 0)
|
||||
|
||||
-- find the left position that matches this
|
||||
while node_scan.next and node_scan.next.x <= xpos do
|
||||
prev_link_scan = node_scan
|
||||
prev_link_scan_type = STBRP__PREV_LINK_TYPE.NEXT
|
||||
@@ -295,6 +438,7 @@ local function stbrp__skyline_find_best_pos(c, width, height)
|
||||
if y <= best_y then
|
||||
if y < best_y or waste < best_waste or (waste == best_waste and xpos < best_x) then
|
||||
best_x = xpos
|
||||
-- STBRP_ASSERT(y <= best_y); [DEAR IMGUI]
|
||||
best_y = y
|
||||
best_waste = waste
|
||||
best_prev_link = prev_link_scan
|
||||
@@ -319,20 +463,31 @@ 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)
|
||||
|
||||
-- bail if:
|
||||
-- 1. it failed
|
||||
-- 2. the best node doesn't fit (we don't always check this)
|
||||
-- 3. we're out of memory
|
||||
if res.prev_link == nil or res.y + height > context.height or context.free_head == nil then
|
||||
res.prev_link = nil
|
||||
res.prev_link_type = nil
|
||||
return res
|
||||
end
|
||||
|
||||
-- on success, create new node
|
||||
local node = context.free_head
|
||||
node.x = res.x
|
||||
node.y = res.y + height
|
||||
context.free_head = node.next
|
||||
|
||||
-- insert the new node into the right starting point, and
|
||||
-- let 'cur' point to the remaining nodes needing to be
|
||||
-- stitched back in
|
||||
|
||||
local cur
|
||||
if res.prev_link_type == STBRP__PREV_LINK_TYPE.ACTIVE_HEAD then
|
||||
cur = res.prev_link.active_head
|
||||
@@ -341,6 +496,7 @@ local function stbrp__skyline_pack_rectangle(context, width, height)
|
||||
end
|
||||
|
||||
if cur.x < res.x then
|
||||
-- preserve the existing one, so start testing with the next one
|
||||
local next = cur.next
|
||||
cur.next = node
|
||||
cur = next
|
||||
@@ -352,13 +508,17 @@ local function stbrp__skyline_pack_rectangle(context, width, height)
|
||||
end
|
||||
end
|
||||
|
||||
-- from here, traverse cur and free the nodes, until we get to one
|
||||
-- that shouldn't be freed
|
||||
while cur.next and cur.next.x <= res.x + width do
|
||||
local next = cur.next
|
||||
-- move the current node to the free list
|
||||
cur.next = context.free_head
|
||||
context.free_head = cur
|
||||
cur = next
|
||||
end
|
||||
|
||||
-- stitch the list back in
|
||||
node.next = cur
|
||||
|
||||
if cur.x < res.x + width then
|
||||
@@ -372,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
|
||||
@@ -386,26 +547,53 @@ end
|
||||
--- @param b stbrp_rect
|
||||
--- @return bool
|
||||
--- @package
|
||||
@native
|
||||
local function rect_original_order(a, b)
|
||||
return a.was_packed < b.was_packed
|
||||
end
|
||||
|
||||
-- Assign packed locations to rectangles. The rectangles are of type
|
||||
-- 'stbrp_rect' defined above, stored in the array 'rects', and there
|
||||
-- are 'num_rects' many of them.
|
||||
--
|
||||
-- Rectangles which are successfully packed have the 'was_packed' flag
|
||||
-- set to a non-zero value and 'x' and 'y' store the minimum location
|
||||
-- on each axis (i.e. bottom-left in cartesian coordinates, top-left
|
||||
-- if you imagine y increasing downwards). Rectangles which do not fit
|
||||
-- have the 'was_packed' flag set to 0.
|
||||
--
|
||||
-- You should not try to access the 'rects' array from another thread
|
||||
-- while this function is running, as the function temporarily reorders
|
||||
-- the array while it executes.
|
||||
--
|
||||
-- To pack into another rectangle, you need to call stbrp_init_target
|
||||
-- again. To continue packing into the same rectangle, you can call
|
||||
-- this function again. Calling this multiple times with multiple rect
|
||||
-- arrays will probably produce worse packing results than calling it
|
||||
-- a single time with the full rectangle array, but the option is
|
||||
-- available.
|
||||
--
|
||||
-- The function returns 1 if all of the rectangles were successfully
|
||||
-- packed and 0 otherwise.
|
||||
--- @param context stbrp_context
|
||||
--- @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
|
||||
|
||||
-- we use the 'was_packed' field internally to allow sorting/unsorting
|
||||
for i = 1, num_rects do
|
||||
rects[i].was_packed = (i - 1)
|
||||
end
|
||||
|
||||
-- sort according to heuristic
|
||||
STBRP_SORT(rects, rect_height_compare)
|
||||
|
||||
for i = 1, num_rects do
|
||||
if rects[i].w == 0 or rects[i].h == 0 then
|
||||
rects[i].x = 0
|
||||
rects[i].x = 0 -- empty rect needs no space
|
||||
rects[i].y = 0
|
||||
else
|
||||
local fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h)
|
||||
@@ -419,8 +607,10 @@ local function stbrp_pack_rects(context, rects, num_rects)
|
||||
end
|
||||
end
|
||||
|
||||
-- unsort
|
||||
STBRP_SORT(rects, rect_original_order)
|
||||
|
||||
-- set was_packed flags and all_rects_packed status
|
||||
for i = 1, num_rects do
|
||||
rects[i].was_packed = (rects[i].x == STBRP__MAXVAL and rects[i].y == STBRP__MAXVAL) and 0 or 1
|
||||
if rects[i].was_packed == 0 then
|
||||
@@ -428,6 +618,7 @@ local function stbrp_pack_rects(context, rects, num_rects)
|
||||
end
|
||||
end
|
||||
|
||||
-- return the all_rects_packed status
|
||||
return all_rects_packed
|
||||
end
|
||||
|
||||
@@ -441,3 +632,43 @@ return {
|
||||
setup_allow_out_of_mem = stbrp_setup_allow_out_of_mem,
|
||||
setup_heuristic = stbrp_setup_heuristic
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------
|
||||
-- This software is available under 2 licenses -- choose whichever you prefer.
|
||||
-- ------------------------------------------------------------------------------
|
||||
-- ALTERNATIVE A - MIT License
|
||||
-- Copyright (c) 2017 Sean Barrett
|
||||
-- Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
-- this software and associated documentation files (the "Software"), to deal in
|
||||
-- the Software without restriction, including without limitation the rights to
|
||||
-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
-- of the Software, and to permit persons to whom the Software is furnished to do
|
||||
-- so, subject to the following conditions:
|
||||
-- The above copyright notice and this permission notice shall be included in all
|
||||
-- copies or substantial portions of the Software.
|
||||
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
-- SOFTWARE.
|
||||
-- ------------------------------------------------------------------------------
|
||||
-- ALTERNATIVE B - Public Domain (www.unlicense.org)
|
||||
-- This is free and unencumbered software released into the public domain.
|
||||
-- Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
|
||||
-- software, either in source code form or as a compiled binary, for any purpose,
|
||||
-- commercial or non-commercial, and by any means.
|
||||
-- In jurisdictions that recognize copyright laws, the author or authors of this
|
||||
-- software dedicate any and all copyright interest in the software to the public
|
||||
-- domain. We make this dedication for the benefit of the public at large and to
|
||||
-- the detriment of our heirs and successors. We intend this dedication to be an
|
||||
-- overt act of relinquishment in perpetuity of all present and future rights to
|
||||
-- this software under copyright law.
|
||||
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
-- AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
-- ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
-- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
-- ------------------------------------------------------------------------------
|
||||
+341
-40
@@ -1,7 +1,222 @@
|
||||
--- Dear ImGui
|
||||
-- This is a Lua port of original `imstb_textedit.h`
|
||||
-- [Port] This is a Lua port of original `imstb_textedit.h`
|
||||
|
||||
-- ALL TABLES IN THIS FILE ARE 1-BASED!
|
||||
-- [DEAR IMGUI]
|
||||
-- This is a slightly modified version of stb_textedit.h 1.14.
|
||||
-- Those changes would need to be pushed into nothings/stb:
|
||||
-- - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321)
|
||||
-- - Fix in stb_textedit_find_charpos to handle last line (see https://github.com/ocornut/imgui/issues/6000 + #6783)
|
||||
-- - Added name to struct or it may be forward declared in our code.
|
||||
-- - Added UTF-8 support (see https://github.com/nothings/stb/issues/188 + https://github.com/ocornut/imgui/pull/7925)
|
||||
-- - Changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion.
|
||||
-- Grep for [DEAR IMGUI] to find some changes.
|
||||
-- - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_*
|
||||
|
||||
-- stb_textedit.h - v1.14 - public domain - Sean Barrett
|
||||
-- Development of this library was sponsored by RAD Game Tools
|
||||
--
|
||||
-- This C header file implements the guts of a multi-line text-editing
|
||||
-- widget; you implement display, word-wrapping, and low-level string
|
||||
-- insertion/deletion, and stb_textedit will map user inputs into
|
||||
-- insertions & deletions, plus updates to the cursor position,
|
||||
-- selection state, and undo state.
|
||||
--
|
||||
-- It is intended for use in games and other systems that need to build
|
||||
-- their own custom widgets and which do not have heavy text-editing
|
||||
-- requirements (this library is not recommended for use for editing large
|
||||
-- texts, as its performance does not scale and it has limited undo).
|
||||
--
|
||||
-- Non-trivial behaviors are modelled after Windows text controls.
|
||||
--
|
||||
--
|
||||
-- LICENSE
|
||||
--
|
||||
-- See end of file for license information.
|
||||
--
|
||||
--
|
||||
-- DEPENDENCIES
|
||||
--
|
||||
-- Uses the C runtime function 'memmove', which you can override
|
||||
-- by defining IMSTB_TEXTEDIT_memmove before the implementation.
|
||||
-- [Port] (In this port: ImStb.TEXTEDIT_memmove.)
|
||||
--
|
||||
--
|
||||
-- VERSION HISTORY
|
||||
--
|
||||
-- !!!! (2025-10-23) changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion.
|
||||
-- 1.14 (2021-07-11) page up/down, various fixes
|
||||
-- 1.13 (2019-02-07) fix bug in undo size management
|
||||
-- 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash
|
||||
-- 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield
|
||||
-- 1.10 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
|
||||
-- 1.9 (2016-08-27) customizable move-by-word
|
||||
-- 1.8 (2016-04-02) better keyboard handling when mouse button is down
|
||||
-- 1.7 (2015-09-13) change y range handling in case baseline is non-0
|
||||
-- 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove
|
||||
-- 1.5 (2014-09-10) add support for secondary keys for OS X
|
||||
-- 1.4 (2014-08-17) fix signed/unsigned warnings
|
||||
-- 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary
|
||||
-- 1.2 (2014-05-27) fix some RAD types that had crept into the new code
|
||||
-- 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE )
|
||||
-- 1.0 (2012-07-26) improve documentation, initial public release
|
||||
-- 0.3 (2012-02-24) bugfixes, single-line mode; insert mode
|
||||
-- 0.2 (2011-11-28) fixes to undo/redo
|
||||
-- 0.1 (2010-07-08) initial version
|
||||
--
|
||||
-- ADDITIONAL CONTRIBUTORS
|
||||
--
|
||||
-- Ulf Winklemann: move-by-word in 1.1
|
||||
-- Fabian Giesen: secondary key inputs in 1.5
|
||||
-- Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6
|
||||
-- Louis Schnellbach: page up/down in 1.14
|
||||
--
|
||||
-- Bugfixes:
|
||||
-- Scott Graham
|
||||
-- Daniel Keller
|
||||
-- Omar Cornut
|
||||
-- Dan Thompson
|
||||
--
|
||||
-- USAGE
|
||||
--
|
||||
-- The basic concept is that you provide a "string" object which
|
||||
-- behaves like an array of characters. stb_textedit uses indices to
|
||||
-- refer to positions in the string, implicitly representing positions
|
||||
-- in the displayed textedit. This is true for both plain text and
|
||||
-- rich text; even with rich text stb_truetype interacts with your
|
||||
-- code as if there was an array of all the displayed characters.
|
||||
--
|
||||
-- Symbols you must define for implementation mode (in this port: fields of ImStb, see below):
|
||||
--
|
||||
-- STB_TEXTEDIT_STRING the type of object representing a string being edited,
|
||||
-- typically this is a wrapper object with other data you need
|
||||
--
|
||||
-- STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1))
|
||||
-- STB_TEXTEDIT_LAYOUTROW(r,obj,n) returns the results of laying out a line of characters
|
||||
-- starting from character #n (see discussion below)
|
||||
-- STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character
|
||||
-- to the xpos of the i+1'th char for a line of characters
|
||||
-- starting at character #n (i.e. accounts for kerning
|
||||
-- with previous char)
|
||||
-- STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 1-based in this port
|
||||
-- STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize
|
||||
-- as manually wordwrapping for end-of-line positioning
|
||||
--
|
||||
-- STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i
|
||||
-- STB_TEXTEDIT_INSERTCHARS(obj,i,c,c_offset,n) try to insert n characters at i (taken from array c starting at c_offset)
|
||||
-- returns number of characters actually inserted. [DEAR IMGUI]
|
||||
--
|
||||
-- STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key
|
||||
--
|
||||
-- STB_TEXTEDIT_K_LEFT keyboard input to move cursor left
|
||||
-- STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right
|
||||
-- STB_TEXTEDIT_K_UP keyboard input to move cursor up
|
||||
-- STB_TEXTEDIT_K_DOWN keyboard input to move cursor down
|
||||
-- STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page
|
||||
-- STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page
|
||||
-- STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line -- e.g. HOME
|
||||
-- STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line -- e.g. END
|
||||
-- STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text -- e.g. ctrl-HOME
|
||||
-- STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text -- e.g. ctrl-END
|
||||
-- STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor
|
||||
-- STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor
|
||||
-- STB_TEXTEDIT_K_UNDO keyboard input to perform undo
|
||||
-- STB_TEXTEDIT_K_REDO keyboard input to perform redo
|
||||
--
|
||||
-- STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to
|
||||
-- STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to
|
||||
-- STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word -- e.g. ctrl-LEFT
|
||||
-- STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word -- e.g. ctrl-RIGHT
|
||||
--
|
||||
-- To support UTF-8:
|
||||
--
|
||||
-- STB_TEXTEDIT_GETPREVCHARINDEX returns index of previous character
|
||||
-- STB_TEXTEDIT_GETNEXTCHARINDEX returns index of next character
|
||||
-- Do NOT define STB_TEXTEDIT_KEYTOTEXT.
|
||||
-- Instead, call stb_textedit_text() directly for text contents.
|
||||
--
|
||||
-- Keyboard input must be encoded as a single integer value; e.g. a character code
|
||||
-- and some bitflags that represent shift states. to simplify the interface, SHIFT must
|
||||
-- be a bitflag, so we can test the shifted state of cursor movements to allow selection,
|
||||
-- i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow.
|
||||
--
|
||||
-- STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed
|
||||
-- row of characters assuming they start on the i'th character--the width and
|
||||
-- the height and the number of characters consumed. This allows this library
|
||||
-- to traverse the entire layout incrementally. You need to compute word-wrapping
|
||||
-- here.
|
||||
--
|
||||
-- Each textfield keeps its own insert mode state, which is not how normal
|
||||
-- applications work. To keep an app-wide insert mode, update/copy the
|
||||
-- "insert_mode" field of STB_TexteditState before/after calling API functions.
|
||||
--
|
||||
-- API (in this port: fields of the table returned by this file)
|
||||
--
|
||||
-- initialize_state(state, is_single_line)
|
||||
--
|
||||
-- click(str, state, x, y)
|
||||
-- drag(str, state, x, y)
|
||||
-- cut(str, state) -> bool
|
||||
-- paste(str, state, text, len) -> bool
|
||||
-- key(str, state, key)
|
||||
-- text(str, state, text, text_len)
|
||||
--
|
||||
-- Each of these functions potentially updates the string and updates the
|
||||
-- state.
|
||||
--
|
||||
-- initialize_state:
|
||||
-- set the textedit state to a known good default state when initially
|
||||
-- constructing the textedit.
|
||||
--
|
||||
-- click:
|
||||
-- call this with the mouse x,y on a mouse down; it will update the cursor
|
||||
-- and reset the selection start/end to the cursor point. the x,y must
|
||||
-- be relative to the text widget, with (0,0) being the top left.
|
||||
--
|
||||
-- drag:
|
||||
-- call this with the mouse x,y on a mouse drag/up; it will update the
|
||||
-- cursor and the selection end point
|
||||
--
|
||||
-- cut:
|
||||
-- call this to delete the current selection; returns true if there was
|
||||
-- one. you should FIRST copy the current selection to the system paste buffer.
|
||||
-- (To copy, just copy the current selection out of the string yourself.)
|
||||
--
|
||||
-- paste:
|
||||
-- call this to paste text at the current cursor point or over the current
|
||||
-- selection if there is one.
|
||||
--
|
||||
-- key:
|
||||
-- call this for keyboard inputs sent to the textfield. you can use it
|
||||
-- for "key down" events or for "translated" key events.
|
||||
--
|
||||
-- text: (added 2025)
|
||||
-- call this to directly send text input the textfield, which is required
|
||||
-- for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT()
|
||||
-- cannot infer text length.
|
||||
--
|
||||
--
|
||||
-- When rendering, you can read the cursor position and selection state from
|
||||
-- the STB_TexteditState.
|
||||
--
|
||||
--
|
||||
-- Notes:
|
||||
--
|
||||
-- This is designed to be usable in IMGUI, so it allows for the possibility of
|
||||
-- running in an IMGUI that has NOT cached the multi-line layout. For this
|
||||
-- reason, it provides an interface that is compatible with computing the
|
||||
-- layout incrementally--we try to make sure we make as few passes through
|
||||
-- as possible. (For example, to locate the mouse pointer in the text, we
|
||||
-- could define functions that return the X and Y positions of characters
|
||||
-- and binary search Y and then X, but if we're doing dynamic layout this
|
||||
-- will run the layout algorithm many times, so instead we manually search
|
||||
-- forward in one pass. Similar logic applies to e.g. up-arrow and
|
||||
-- down-arrow movement.)
|
||||
--
|
||||
-- If it's run in a widget that *has* cached the layout, then this is less
|
||||
-- efficient, but it's not horrible on modern computers. But you wouldn't
|
||||
-- want to edit million-line files with it.
|
||||
|
||||
-- [Port] ALL TABLES IN THIS FILE ARE 1-BASED!
|
||||
-- Character Indexing:
|
||||
-- idx=n, the n'th char (1-based)
|
||||
-- Cursor Indexing:
|
||||
@@ -13,6 +228,10 @@ local STB_TEXTEDIT_STRINGLEN = ImStb.TEXTEDIT_STRINGLEN
|
||||
local STB_TEXTEDIT_GETCHAR = ImStb.TEXTEDIT_GETCHAR
|
||||
local STB_TEXTEDIT_GETWIDTH = ImStb.TEXTEDIT_GETWIDTH
|
||||
local STB_TEXTEDIT_LAYOUTROW = ImStb.TEXTEDIT_LAYOUTROW
|
||||
-- [DEAR IMGUI]
|
||||
-- Functions must be implemented for UTF8 support
|
||||
-- Code in this file that uses those functions is modified for [DEAR IMGUI] and deviates from the original stb_textedit.
|
||||
-- There is not necessarily a '[DEAR IMGUI]' at the usage sites.
|
||||
local IMSTB_TEXTEDIT_GETNEXTCHARINDEX = ImStb.TEXTEDIT_GETNEXTCHARINDEX
|
||||
local IMSTB_TEXTEDIT_GETPREVCHARINDEX = ImStb.TEXTEDIT_GETPREVCHARINDEX
|
||||
local STB_TEXTEDIT_MOVEWORDLEFT = ImStb.TEXTEDIT_MOVEWORDLEFT
|
||||
@@ -22,34 +241,35 @@ local STB_TEXTEDIT_MOVELINEEND = ImStb.TEXTEDIT_MOVELINEEND
|
||||
local STB_TEXTEDIT_DELETECHARS = ImStb.TEXTEDIT_DELETECHARS
|
||||
local STB_TEXTEDIT_INSERTCHARS = ImStb.TEXTEDIT_INSERTCHARS
|
||||
|
||||
STB_TEXTEDIT_NEWLINE = 10
|
||||
STB_TEXTEDIT_NEWLINE = 10 -- the character returned by _GETCHAR() we recognize as manually wordwrapping for end-of-line positioning
|
||||
STB_TEXTEDIT_K_LEFT = 0x200000 -- keyboard input to move cursor left
|
||||
STB_TEXTEDIT_K_RIGHT = 0x200001 -- keyboard input to move cursor right
|
||||
STB_TEXTEDIT_K_UP = 0x200002 -- keyboard input to move cursor up
|
||||
STB_TEXTEDIT_K_DOWN = 0x200003 -- keyboard input to move cursor down
|
||||
STB_TEXTEDIT_K_LINESTART = 0x200004 -- keyboard input to move cursor to start of line
|
||||
STB_TEXTEDIT_K_LINEEND = 0x200005 -- keyboard input to move cursor to end of line
|
||||
STB_TEXTEDIT_K_TEXTSTART = 0x200006 -- keyboard input to move cursor to start of text
|
||||
STB_TEXTEDIT_K_TEXTEND = 0x200007 -- keyboard input to move cursor to end of text
|
||||
STB_TEXTEDIT_K_LINESTART = 0x200004 -- keyboard input to move cursor to start of line -- e.g. HOME
|
||||
STB_TEXTEDIT_K_LINEEND = 0x200005 -- keyboard input to move cursor to end of line -- e.g. END
|
||||
STB_TEXTEDIT_K_TEXTSTART = 0x200006 -- keyboard input to move cursor to start of text -- e.g. ctrl-HOME
|
||||
STB_TEXTEDIT_K_TEXTEND = 0x200007 -- keyboard input to move cursor to end of text -- e.g. ctrl-END
|
||||
STB_TEXTEDIT_K_DELETE = 0x200008 -- keyboard input to delete selection or character under cursor
|
||||
STB_TEXTEDIT_K_BACKSPACE = 0x200009 -- keyboard input to delete selection or character left of cursor
|
||||
STB_TEXTEDIT_K_UNDO = 0x20000A -- keyboard input to perform undo
|
||||
STB_TEXTEDIT_K_REDO = 0x20000B -- keyboard input to perform redo
|
||||
STB_TEXTEDIT_K_WORDLEFT = 0x20000C -- keyboard input to move cursor left one word
|
||||
STB_TEXTEDIT_K_WORDRIGHT = 0x20000D -- keyboard input to move cursor right one word
|
||||
STB_TEXTEDIT_K_WORDLEFT = 0x20000C -- keyboard input to move cursor left one word -- e.g. ctrl-LEFT
|
||||
STB_TEXTEDIT_K_WORDRIGHT = 0x20000D -- keyboard input to move cursor right one word -- e.g. ctrl-RIGHT
|
||||
STB_TEXTEDIT_K_PGUP = 0x20000E -- keyboard input to move cursor up a page
|
||||
STB_TEXTEDIT_K_PGDOWN = 0x20000F -- keyboard input to move cursor down a page
|
||||
STB_TEXTEDIT_K_SHIFT = 0x400000
|
||||
STB_TEXTEDIT_K_SHIFT = 0x400000 -- a power of two that is or'd in to a keyboard input to represent the shift key
|
||||
|
||||
IMSTB_TEXTEDIT_UNDOSTATECOUNT = 99
|
||||
local IMSTB_TEXTEDIT_UNDOCHARCOUNT = 999
|
||||
IMSTB_TEXTEDIT_UNDOSTATECOUNT = 99 -- the number of undo states to allow
|
||||
local IMSTB_TEXTEDIT_UNDOCHARCOUNT = 999 -- the number of characters to store in the undo buffer
|
||||
local IMSTB_TEXTEDIT_memmove = ImStb.TEXTEDIT_memmove
|
||||
|
||||
-- forward declarations
|
||||
local stb_text_undo
|
||||
local stb_text_redo
|
||||
|
||||
----------------------------------------------------------------
|
||||
----------------------------------------------------------------
|
||||
-------------------------------------------------------------------------------
|
||||
-------------------------------------------------------------------------------
|
||||
---
|
||||
--- STB_TexteditState
|
||||
---
|
||||
@@ -72,6 +292,7 @@ local stb_text_redo
|
||||
--- @nodiscard
|
||||
local function StbUndoRecord()
|
||||
return {
|
||||
-- private data
|
||||
where = 1,
|
||||
insert_length = 0,
|
||||
delete_length = 0,
|
||||
@@ -101,6 +322,7 @@ local function StbUndoState()
|
||||
end
|
||||
|
||||
return {
|
||||
-- private data
|
||||
undo_rec = undo_rec,
|
||||
undo_char = undo_char,
|
||||
|
||||
@@ -131,16 +353,34 @@ end
|
||||
--- @nodiscard
|
||||
function STB_TexteditState()
|
||||
return {
|
||||
cursor = 0,
|
||||
---------------------
|
||||
--
|
||||
-- public data
|
||||
--
|
||||
|
||||
select_start = 0,
|
||||
cursor = 0,
|
||||
-- position of the text cursor within the string
|
||||
|
||||
select_start = 0, -- selection start point
|
||||
select_end = 0,
|
||||
-- selection start and end point in characters; if equal, no selection.
|
||||
-- note that start may be less than or greater than end (e.g. when
|
||||
-- dragging the mouse, start is where the initial click was, and you
|
||||
-- can drag in either direction)
|
||||
|
||||
insert_mode = false,
|
||||
-- each textfield keeps its own insert mode state. to keep an app-wide
|
||||
-- insert mode, copy this value in/out of the app state
|
||||
|
||||
row_count_per_page = 0,
|
||||
-- page size in number of row.
|
||||
-- this value MUST be set to >0 for pageup or pagedown in multilines documents.
|
||||
|
||||
cursor_at_end_of_line = false,
|
||||
---------------------
|
||||
--
|
||||
-- private data
|
||||
--
|
||||
cursor_at_end_of_line = false, -- not implemented yet
|
||||
initialized = false,
|
||||
has_preferred_x = false,
|
||||
single_line = false,
|
||||
@@ -148,7 +388,7 @@ function STB_TexteditState()
|
||||
padding2 = 0,
|
||||
padding3 = 0,
|
||||
|
||||
preferred_x = 0.0,
|
||||
preferred_x = 0.0, -- this determines where the cursor up/down tries to seek to along x
|
||||
|
||||
undostate = StbUndoState()
|
||||
}
|
||||
@@ -159,12 +399,20 @@ local function STB_TEXT_HAS_SELECTION(s)
|
||||
return s.select_start ~= s.select_end
|
||||
end
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
---
|
||||
--- StbTexteditRow
|
||||
---
|
||||
--- Result of layout query, used by stb_textedit to determine where
|
||||
--- the text in each row is.
|
||||
|
||||
-- result of layout query
|
||||
--- @class StbTexteditRow
|
||||
--- @field x0 float # starting x location
|
||||
--- @field x0 float # starting x location, end x location (allows for align=right, etc)
|
||||
--- @field x1 float # end x location
|
||||
--- @field baseline_y_delta float # position of baseline relative to previous row's baseline
|
||||
--- @field ymin float # height of row above baseline
|
||||
--- @field ymax float # height of row below baseline
|
||||
--- @field ymin float # height of row above and below baseline
|
||||
--- @field ymax float # height of row above and below baseline
|
||||
--- @field num_chars int
|
||||
|
||||
--- @return StbTexteditRow
|
||||
@@ -196,13 +444,18 @@ end
|
||||
----------------------------------------
|
||||
----------------------------------------
|
||||
---
|
||||
--- Implementation
|
||||
--- Implementation mode
|
||||
---
|
||||
---
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
---
|
||||
--- Mouse input handling
|
||||
---
|
||||
|
||||
local stb_text_locate_coord do
|
||||
|
||||
-- only create once, reuse later
|
||||
-- [Port] only create once, reuse later
|
||||
local r = StbTexteditRow()
|
||||
|
||||
--- traverse the layout to locate the nearest character to a display position
|
||||
@@ -351,6 +604,7 @@ end
|
||||
---
|
||||
---
|
||||
|
||||
-- forward declarations
|
||||
local stb_text_makeundo_insert
|
||||
local stb_text_makeundo_delete
|
||||
local stb_text_makeundo_replace
|
||||
@@ -399,8 +653,8 @@ function stb_textedit_find_charpos(find, str, n, single_line)
|
||||
local z = STB_TEXTEDIT_STRINGLEN(str)
|
||||
local first
|
||||
|
||||
-- special case if it's at the end (may not be needed?)
|
||||
if n == z + 1 and single_line then
|
||||
-- special case if it's at the end (may not be needed?)
|
||||
STB_TEXTEDIT_LAYOUTROW(r, str, 1)
|
||||
find.y = 0
|
||||
find.first_char = 1
|
||||
@@ -420,18 +674,18 @@ function stb_textedit_find_charpos(find, str, n, single_line)
|
||||
if n < i + r.num_chars - 1 then
|
||||
break
|
||||
end
|
||||
if str.LastMoveDirectionLR == ImGuiDir.Right and str.Stb.cursor > 1 and str.Stb.cursor == i + r.num_chars and STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) ~= STB_TEXTEDIT_NEWLINE then -- [IMGUI] Wrapping point handling
|
||||
if str.LastMoveDirectionLR == ImGuiDir.Right and str.Stb.cursor > 1 and str.Stb.cursor == i + r.num_chars and STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) ~= STB_TEXTEDIT_NEWLINE then -- [DEAR IMGUI] Wrapping point handling
|
||||
break
|
||||
end
|
||||
if (i - 1) + r.num_chars == z and z > 0 and STB_TEXTEDIT_GETCHAR(str, z) ~= STB_TEXTEDIT_NEWLINE then -- [IMGUI] special handling for last line
|
||||
break
|
||||
if (i - 1) + r.num_chars == z and z > 0 and STB_TEXTEDIT_GETCHAR(str, z) ~= STB_TEXTEDIT_NEWLINE then -- [DEAR IMGUI] special handling for last line
|
||||
break -- [DEAR IMGUI]
|
||||
end
|
||||
prev_start = i
|
||||
i = i + r.num_chars
|
||||
find.y = find.y + r.baseline_y_delta
|
||||
if i == z + 1 then -- [IMGUI]
|
||||
r.num_chars = 0
|
||||
break
|
||||
if i == z + 1 then -- [DEAR IMGUI]
|
||||
r.num_chars = 0 -- [DEAR IMGUI]
|
||||
break -- [DEAR IMGUI]
|
||||
end
|
||||
end
|
||||
|
||||
@@ -479,7 +733,7 @@ local function stb_textedit_delete(str, state, where, len)
|
||||
state.has_preferred_x = false
|
||||
end
|
||||
|
||||
-- delete the selection
|
||||
-- delete the section
|
||||
--- @param str IMSTB_TEXTEDIT_STRING
|
||||
--- @param state STB_TexteditState
|
||||
local function stb_textedit_delete_selection(str, state)
|
||||
@@ -498,7 +752,7 @@ local function stb_textedit_delete_selection(str, state)
|
||||
end
|
||||
end
|
||||
|
||||
-- canonicalize the selection so start <= end
|
||||
-- canoncialize the selection so start <= end
|
||||
--- @param state STB_TexteditState
|
||||
local function stb_textedit_sortselection(state)
|
||||
if state.select_end < state.select_start then
|
||||
@@ -579,7 +833,7 @@ local function stb_textedit_paste_internal(str, state, text, len)
|
||||
end
|
||||
|
||||
-- API key: process text input
|
||||
-- [IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility.
|
||||
-- [DEAR IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility.
|
||||
--- @param str IMSTB_TEXTEDIT_STRING
|
||||
--- @param state STB_TexteditState
|
||||
--- @param text IMSTB_TEXTEDIT_CHARTYPE[]
|
||||
@@ -710,7 +964,7 @@ function stb_textedit_key(str, state, key)
|
||||
if not is_page and state.single_line then
|
||||
-- on windows, up&down in single-line behave like left&right
|
||||
key = bit32.bor(STB_TEXTEDIT_K_RIGHT, bit32.band(key, STB_TEXTEDIT_K_SHIFT))
|
||||
return stb_textedit_key(str, state, key) -- was `goto retry`
|
||||
return stb_textedit_key(str, state, key) -- [Port] was `goto retry`
|
||||
end
|
||||
|
||||
if sel then
|
||||
@@ -732,7 +986,7 @@ function stb_textedit_key(str, state, key)
|
||||
break
|
||||
end
|
||||
|
||||
-- [IMGUI]
|
||||
-- [DEAR IMGUI]
|
||||
-- going down while being on the last line shouldn't bring us to that line end
|
||||
--if STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) ~= STB_TEXTEDIT_NEWLINE then
|
||||
-- break
|
||||
@@ -783,7 +1037,7 @@ function stb_textedit_key(str, state, key)
|
||||
if not is_page and state.single_line then
|
||||
-- on windows, up&down become left&right
|
||||
key = bit32.bor(STB_TEXTEDIT_K_LEFT, bit32.band(key, STB_TEXTEDIT_K_SHIFT))
|
||||
return stb_textedit_key(str, state, key) -- was `goto retry`
|
||||
return stb_textedit_key(str, state, key) -- [Port] was `goto retry`
|
||||
end
|
||||
|
||||
if sel then
|
||||
@@ -929,8 +1183,8 @@ end
|
||||
-----------------------------------------------------
|
||||
---
|
||||
--- Undo processing
|
||||
--- OPTIMIZE: the undo/redo buffer should be circular
|
||||
---
|
||||
--- @OPTIMIZE: the undo/redo buffer should be circular
|
||||
|
||||
--- @param state StbUndoState
|
||||
local function stb_textedit_flush_redo(state)
|
||||
@@ -950,7 +1204,7 @@ local function stb_textedit_discard_undo(state)
|
||||
IMSTB_TEXTEDIT_memmove(state.undo_char, 1, state.undo_char, n + 1, state.undo_char_point - 1)
|
||||
for i = 1, state.undo_point do
|
||||
if state.undo_rec[i].char_storage >= 0 then
|
||||
state.undo_rec[i].char_storage = state.undo_rec[i].char_storage - n -- OPTIMIZE: get rid of char_storage and infer it
|
||||
state.undo_rec[i].char_storage = state.undo_rec[i].char_storage - n -- @OPTIMIZE: get rid of char_storage and infer it
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -983,7 +1237,7 @@ local function stb_textedit_discard_redo(state)
|
||||
end
|
||||
|
||||
-- now move all the redo records towards the end of the buffer; the first one is at 'redo_point'
|
||||
-- [IMGUI]
|
||||
-- [DEAR IMGUI]
|
||||
local move_size = IMSTB_TEXTEDIT_UNDOSTATECOUNT - state.redo_point - 1
|
||||
IMSTB_TEXTEDIT_memmove(state.undo_rec, state.redo_point + 1, state.undo_rec, state.redo_point, move_size)
|
||||
|
||||
@@ -1129,6 +1383,9 @@ function stb_text_redo(str, state)
|
||||
local u = s.undo_rec[s.undo_point]
|
||||
local r = s.undo_rec[s.redo_point]
|
||||
|
||||
-- we KNOW there must be room for the undo record, because the redo record
|
||||
-- was derived from an undo record
|
||||
|
||||
u.delete_length = r.insert_length
|
||||
u.insert_length = r.delete_length
|
||||
u.where = r.where
|
||||
@@ -1137,6 +1394,7 @@ function stb_text_redo(str, state)
|
||||
if r.delete_length > 0 then
|
||||
-- the redo record requires us to delete characters, so the undo record
|
||||
-- needs to store the characters
|
||||
|
||||
if s.undo_char_point + u.insert_length > s.redo_char_point then
|
||||
u.insert_length = 0
|
||||
u.delete_length = 0
|
||||
@@ -1144,6 +1402,7 @@ function stb_text_redo(str, state)
|
||||
u.char_storage = s.undo_char_point
|
||||
s.undo_char_point = s.undo_char_point + u.insert_length
|
||||
|
||||
-- now save the characters
|
||||
for i = 0, u.insert_length - 1 do
|
||||
s.undo_char[u.char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i)
|
||||
end
|
||||
@@ -1153,6 +1412,7 @@ function stb_text_redo(str, state)
|
||||
end
|
||||
|
||||
if r.insert_length ~= 0 then
|
||||
-- easy case: need to insert n characters
|
||||
r.insert_length = STB_TEXTEDIT_INSERTCHARS(str, r.where, s.undo_char, r.char_storage, r.insert_length)
|
||||
s.redo_char_point = s.redo_char_point + r.insert_length
|
||||
end
|
||||
@@ -1199,6 +1459,7 @@ function stb_text_makeundo_replace(str, state, where, old_length, new_length)
|
||||
end
|
||||
end
|
||||
|
||||
-- reset the state to default
|
||||
--- @param state STB_TexteditState
|
||||
--- @param is_single_line bool
|
||||
local function stb_textedit_clear_state(state, is_single_line)
|
||||
@@ -1222,7 +1483,7 @@ return {
|
||||
click = stb_textedit_click,
|
||||
drag = stb_textedit_drag,
|
||||
createundo = stb_text_createundo,
|
||||
initialize_state = stb_textedit_clear_state,
|
||||
initialize_state = stb_textedit_clear_state, -- API initialize
|
||||
|
||||
text = stb_textedit_text,
|
||||
key = stb_textedit_key,
|
||||
@@ -1236,3 +1497,43 @@ return {
|
||||
|
||||
HAS_SELECTION = STB_TEXT_HAS_SELECTION
|
||||
}
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
-- This software is available under 2 licenses -- choose whichever you prefer.
|
||||
-------------------------------------------------------------------------------
|
||||
-- ALTERNATIVE A - MIT License
|
||||
-- Copyright (c) 2017 Sean Barrett
|
||||
-- Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
-- this software and associated documentation files (the "Software"), to deal in
|
||||
-- the Software without restriction, including without limitation the rights to
|
||||
-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
-- of the Software, and to permit persons to whom the Software is furnished to do
|
||||
-- so, subject to the following conditions:
|
||||
-- The above copyright notice and this permission notice shall be included in all
|
||||
-- copies or substantial portions of the Software.
|
||||
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
-- SOFTWARE.
|
||||
-------------------------------------------------------------------------------
|
||||
-- ALTERNATIVE B - Public Domain (www.unlicense.org)
|
||||
-- This is free and unencumbered software released into the public domain.
|
||||
-- Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
|
||||
-- software, either in source code form or as a compiled binary, for any purpose,
|
||||
-- commercial or non-commercial, and by any means.
|
||||
-- In jurisdictions that recognize copyright laws, the author or authors of this
|
||||
-- software dedicate any and all copyright interest in the software to the public
|
||||
-- domain. We make this dedication for the benefit of the public at large and to
|
||||
-- the detriment of our heirs and successors. We intend this dedication to be an
|
||||
-- overt act of relinquishment in perpetuity of all present and future rights to
|
||||
-- this software under copyright law.
|
||||
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
-- AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
-- ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
-- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
-------------------------------------------------------------------------------
|
||||
+551
-78
File diff suppressed because it is too large.
Load diff
+41
-25
@@ -1,12 +1,13 @@
|
||||
--- Dear ImGui
|
||||
-- This is a minimal Lua impl of C-like sscanf, sprintf sub-set
|
||||
-- [Port] This is a minimal Lua impl of C-like sscanf, sprintf sub-set
|
||||
|
||||
-- Supports:
|
||||
-- [Port] Supports:
|
||||
-- - %x, %X, %nx, %nX (where n is a number)
|
||||
-- - %d, %nd (where n is a number)
|
||||
-- - %d, %nd, %u, %nu (where n is a number)
|
||||
-- - length modifiers h, hh, l, ll, I64 on integers: ll/I64 = 64-bit range (doubles: exact only within +-2^53)
|
||||
-- - %f, %lf (very limited)
|
||||
--
|
||||
-- Returns items_matched instead of EOF on error
|
||||
-- [Port] Returns items_matched instead of EOF on error
|
||||
|
||||
local _byte = string.byte
|
||||
|
||||
@@ -17,6 +18,9 @@ local CHAR_0, CHAR_9 = _byte'0', _byte'9'
|
||||
local CHAR_a, CHAR_A = _byte'a', _byte'A'
|
||||
local CHAR_d = _byte'd'
|
||||
local CHAR_l = _byte'l'
|
||||
local CHAR_h = _byte'h'
|
||||
local CHAR_u = _byte'u'
|
||||
local CHAR_I = _byte'I'
|
||||
local CHAR_f, CHAR_F = _byte'f', _byte'F'
|
||||
local CHAR_x, CHAR_X = _byte'x', _byte'X'
|
||||
|
||||
@@ -36,11 +40,16 @@ local function hex_digit_to_int(c)
|
||||
if c >= CHAR_A and c <= CHAR_F then return c - CHAR_A + 10 end
|
||||
end
|
||||
|
||||
-- we force this behavior by default
|
||||
local function clamp_if_overflow(spec, val)
|
||||
-- [Port] we force this behavior by default
|
||||
local function clamp_if_overflow(spec, val, is_64)
|
||||
if spec == CHAR_d or spec == CHAR_x or spec == CHAR_X then
|
||||
if val > INT_MAX then return INT_MAX end
|
||||
if val < INT_MIN then return INT_MIN end
|
||||
local max = is_64 and 9223372036854775807 or INT_MAX
|
||||
local min = is_64 and -9223372036854775808 or INT_MIN
|
||||
if val > max then return max end
|
||||
if val < min then return min end
|
||||
elseif spec == CHAR_u then
|
||||
local max = is_64 and 18446744073709551615 or UINT_MAX
|
||||
if val > max then return max end
|
||||
end
|
||||
|
||||
return val
|
||||
@@ -52,7 +61,7 @@ end
|
||||
--- @param result table # table to store parsed values
|
||||
local function sscanf(buffer, buffer_begin, format, result)
|
||||
local p = buffer_begin
|
||||
local f = 1 -- format_begin
|
||||
local f = 1 -- [Port] format_begin
|
||||
local format_len = #format
|
||||
local assigned = 0
|
||||
local items_matched = 0
|
||||
@@ -79,10 +88,10 @@ local function sscanf(buffer, buffer_begin, format, result)
|
||||
break
|
||||
end
|
||||
|
||||
-- encountered % in fmt
|
||||
-- [Port] encountered % in fmt
|
||||
f = f + 1
|
||||
|
||||
-- %%
|
||||
-- [Port] %%
|
||||
if _byte(format, f, f) == CHAR_PERCENT then
|
||||
if buffer[p] == CHAR_PERCENT then
|
||||
p = p + 1
|
||||
@@ -94,7 +103,7 @@ local function sscanf(buffer, buffer_begin, format, result)
|
||||
break
|
||||
end
|
||||
|
||||
-- handle optional width
|
||||
-- [Port] handle optional width
|
||||
local width = 0
|
||||
while isdigit(_byte(format, f, f)) do
|
||||
width = width * 10 + _byte(format, f, f) - CHAR_0
|
||||
@@ -104,22 +113,27 @@ local function sscanf(buffer, buffer_begin, format, result)
|
||||
width = math.huge
|
||||
end
|
||||
|
||||
-- [Port] length modifiers
|
||||
local n_l = 0
|
||||
while _byte(format, f, f) == CHAR_l or _byte(format, f, f) == CHAR_h do
|
||||
if _byte(format, f, f) == CHAR_l then n_l = n_l + 1 end
|
||||
f = f + 1
|
||||
end
|
||||
if _byte(format, f, f) == CHAR_I and string.sub(format, f, f + 2) == "I64" then
|
||||
n_l = 2
|
||||
f = f + 3
|
||||
end
|
||||
local is_64 = n_l >= 2
|
||||
|
||||
local spec = _byte(format, f, f)
|
||||
local base
|
||||
local is_float = false
|
||||
if spec == CHAR_x or spec == CHAR_X then
|
||||
base = 16
|
||||
elseif spec == CHAR_d then
|
||||
elseif spec == CHAR_d or spec == CHAR_u then
|
||||
base = 10
|
||||
elseif spec == CHAR_f or spec == CHAR_F then
|
||||
is_float = true
|
||||
elseif spec == CHAR_l then
|
||||
f = f + 1
|
||||
if _byte(format, f, f) == CHAR_f then
|
||||
is_float = true -- TODO: distinguish from float?
|
||||
else
|
||||
return items_matched
|
||||
end
|
||||
is_float = true -- [Port] TODO: distinguish %lf from %f?
|
||||
else
|
||||
return items_matched
|
||||
end
|
||||
@@ -139,7 +153,7 @@ local function sscanf(buffer, buffer_begin, format, result)
|
||||
p = p + 1
|
||||
end
|
||||
|
||||
-- inf, nan are not handled
|
||||
-- [Port] inf, nan are not handled
|
||||
|
||||
local p_start = p
|
||||
local int_part = 0
|
||||
@@ -167,7 +181,7 @@ local function sscanf(buffer, buffer_begin, format, result)
|
||||
val = sign * (int_part + frac_part / frac_div)
|
||||
else
|
||||
local sign = 1
|
||||
-- optional sign
|
||||
-- [Port] optional sign
|
||||
if base == 10 then
|
||||
if buffer[p] == CHAR_PLUS then
|
||||
p = p + 1
|
||||
@@ -186,7 +200,6 @@ local function sscanf(buffer, buffer_begin, format, result)
|
||||
end
|
||||
|
||||
if p == p_start then
|
||||
-- failed to match
|
||||
return items_matched
|
||||
end
|
||||
|
||||
@@ -197,11 +210,14 @@ local function sscanf(buffer, buffer_begin, format, result)
|
||||
val = val * base + sign * hex_digit_to_int(c)
|
||||
|
||||
local old_val = val
|
||||
val = clamp_if_overflow(spec, val)
|
||||
val = clamp_if_overflow(spec, val, is_64)
|
||||
if old_val ~= val then
|
||||
break
|
||||
end
|
||||
end
|
||||
if spec == CHAR_u and val < 0 then
|
||||
val = val + (is_64 and 18446744073709551616 or 4294967296) -- [Port] unsigned wrap-around like strtoul()
|
||||
end
|
||||
end
|
||||
|
||||
result[assigned + 1] = val
|
||||
|
||||
+278
-23
@@ -1,52 +1,303 @@
|
||||
#!/usr/bin/env python3
|
||||
# Bundles the root *.lua (library + imgui_demo.lua), backends/ and fonts/ into ONE ModuleScript: build/ImGui.luau
|
||||
# Bundles the root *.lua (library + imgui_demo.lua), the target's backend folder (backends/roblox/*.lua, or
|
||||
# backends/love/*.lua) and fonts/ (Roblox) into ONE ModuleScript: build/ImGui.luau
|
||||
# --no-demo: library only (imgui_demo.lua left out, like not compiling imgui_demo.cpp)
|
||||
# --target love: build/imgui_love.lua for LÖVE/LuaJIT instead (LÖVE backend, shims from the LÖVE backend's COMPAT section, @native stripped).
|
||||
# The default (roblox) build is unaffected by it.
|
||||
# Why: ModuleScripts don't share globals, and the setfenv() alternative turns off Luau's fast paths / native codegen.
|
||||
# Each source file becomes a function in __FILES; IM_INCLUDE(name) runs it once and caches the result.
|
||||
# The module returns a table with every global the library defines (ImGui, ImVec2, ImGuiConfigFlags, ImGui_ImplRoblox, ...).
|
||||
# Roblox target also writes ImGuiTyped.luau (types + require(script.Impl), see tools/gen_types.py).
|
||||
import os, re
|
||||
# Roblox target also writes ImGuiTyped.luau (types + require(script.Impl), see tools/gen_types.py) and
|
||||
# ImGuiWorker.client.luau: the parallel raster Actor LocalScript (backends/roblox/worker.luau with its
|
||||
# `require(...Raster...)` line replaced by backends/roblox/raster.lua itself: self-contained, no require).
|
||||
# The Roblox backend's modules are inlined into one function (see "Backend modules" below).
|
||||
#
|
||||
# Build-time optimizations (token rewrites with minify.py's lexer: strings/comments are never touched, every source line
|
||||
# stays on its line so linemap.json still maps errors). IMGUI_BUNDLE_NOOPT=1 turns all off, IMGUI_BUNDLE_NO_<X>=1 one:
|
||||
# A hot library globals (most referenced names assigned at a file's top level) become bundle-level locals declared
|
||||
# before __FILES: every file's assignment/reference then hits an upvalue instead of GETGLOBAL. Fewer names for
|
||||
# LuaJIT (60 upvalues per function). Library globals can't be patched from outside (use the returned table).
|
||||
# B enum folding: the bundle is loaded once headless (Luau CLI) to dump enum-like tables (all values numbers, never
|
||||
# written inside a function) and numeric constants assigned once at top level; reads `ImGuiCol.Text` / `FLT_MAX`
|
||||
# inside function bodies become `0 --[[ImGuiCol.Text]]`. Load-time (top-level) code is left alone.
|
||||
# C `--@hoist` functions in the sources (pure numeric helpers: ImMin, ImMax, ImClamp, ...) are moved to the bundle top
|
||||
# as `local function`s (their source lines become blank) so Luau -O2 can inline them everywhere.
|
||||
# E statement-form `IM_ASSERT(...)` becomes `assert(...)` (fast builtin); expression uses are left alone.
|
||||
import os, re, sys, json, shutil, subprocess, tempfile
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(HERE)
|
||||
sys.path.insert(0, HERE)
|
||||
from minify import TOKEN
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
import sys
|
||||
NO_DEMO = "--no-demo" in sys.argv
|
||||
LOVE = False
|
||||
if "--target" in sys.argv:
|
||||
i = sys.argv.index("--target"); LOVE = sys.argv[i + 1] == "love"; del sys.argv[i:i + 2]
|
||||
sys.argv = [a for a in sys.argv if a != "--no-demo"]
|
||||
BACKEND = "imgui_impl_love.lua" if LOVE else "imgui_impl_roblox.lua"
|
||||
SKIP = {"imgui_impl_roblox.lua", "imgui_impl_roblox_fonts.lua"} if LOVE else {"imgui_impl_love.lua"}
|
||||
OPT = {x: os.environ.get("IMGUI_BUNDLE_NOOPT") != "1" and os.environ.get("IMGUI_BUNDLE_NO_" + x) != "1" for x in "ABCE"}
|
||||
# A limits: Luau 200 locals in the main chunk (+ helpers, __FILES, ...), 200 upvalues per function; LuaJIT 60 upvalues
|
||||
# per function (margin left for nested functions that also capture file locals)
|
||||
MAX_LOCALS, MAX_UPVALUES = 160, (45 if LOVE else 150)
|
||||
TARGET = "love" if LOVE else "roblox"
|
||||
BACKEND = "imgui_impl_%s.lua" % TARGET
|
||||
BACKEND_DIR = os.path.join(ROOT, "backends", TARGET) # every *.lua in it is bundled (*.luau, e.g. the worker, is not)
|
||||
FILES = {}
|
||||
for d in (ROOT, os.path.join(ROOT, "backends"), os.path.join(ROOT, "fonts")):
|
||||
for d in [ROOT, BACKEND_DIR] + ([] if LOVE else [os.path.join(ROOT, "fonts")]):
|
||||
for f in sorted(os.listdir(d)):
|
||||
if f.endswith(".lua") and not (NO_DEMO and f == "imgui_demo.lua") and f not in SKIP:
|
||||
if f.endswith(".lua") and not (NO_DEMO and f == "imgui_demo.lua"):
|
||||
src = open(os.path.join(d, f)).read()
|
||||
if LOVE: src = re.sub(r"^@native$", "", src, flags=re.M) # keep line numbers
|
||||
FILES[f] = src
|
||||
FILES[f if d != BACKEND_DIR or f == BACKEND else TARGET + "/" + f] = src
|
||||
|
||||
# Backend modules (backends/<target>/*.lua besides the main file, keyed "<target>/x.lua") are inlined into the main
|
||||
# file's __FILES function: `local X = IM_INCLUDE("<target>/x.lua")` lines become blank (X is declared once at the top of
|
||||
# the function), each module body goes in its own do ... end in dependency order, its final `return M` becomes `X = M`.
|
||||
# Cross-module access is then a local of the same function, no IM_INCLUDE at load time. In source, the same files work
|
||||
# with plain IM_INCLUDE (each a function returning its table).
|
||||
INCLUDE = re.compile(r'^local (\w+) = IM_INCLUDE\("(%s/\w+\.lua)"\)[ \t]*$' % TARGET, re.M)
|
||||
MODULES, EXPORT = [], {} # inline order, key -> local name
|
||||
def visit(f, stack=()):
|
||||
assert f not in stack, "backend modules: circular IM_INCLUDE %s" % " -> ".join(stack + (f,))
|
||||
for name, key in INCLUDE.findall(FILES[f]):
|
||||
assert EXPORT.setdefault(key, name) == name, "%s is included as both %s and %s" % (key, EXPORT[key], name)
|
||||
if key not in MODULES: visit(key, stack + (f,)); MODULES.append(key)
|
||||
visit(BACKEND)
|
||||
unused = [f for f in FILES if f.startswith(TARGET + "/") and f not in MODULES]
|
||||
assert not unused, "backend modules never included: %s" % unused
|
||||
GROUP = {f: BACKEND for f in MODULES} # file -> __FILES function it is emitted in
|
||||
|
||||
def inline_module(key, src):
|
||||
src = INCLUDE.sub("", src)
|
||||
m = re.search(r"^return (\w+)[ \t]*\n*\Z", src, re.M)
|
||||
assert m and m.group(1) != EXPORT[key], "%s must end with `return M` (a name other than %s)" % (key, EXPORT[key])
|
||||
return src[:m.start()] + "%s = %s\n" % (EXPORT[key], m.group(1))
|
||||
|
||||
ORIG = dict(FILES) # for gen_types
|
||||
ENTRY = ["imgui.lua", BACKEND] + ([] if NO_DEMO else ["imgui_demo.lua"]) # run order
|
||||
|
||||
names = set()
|
||||
for src in FILES.values():
|
||||
names.update(re.findall(r"^function ([A-Za-z_]\w*)\s*\(", src, re.M))
|
||||
names.update(re.findall(r"^([A-Za-z_]\w*)\s*=[^=]", src, re.M))
|
||||
assert not names & set(EXPORT.values()), "backend module names clash with globals: %s" % (names & set(EXPORT.values()))
|
||||
|
||||
# ---- lexer helpers ----
|
||||
KW = set("and break do else elseif end false for function goto if in local nil not or repeat return then true until while".split())
|
||||
|
||||
def lex(src):
|
||||
"""[(kind, text, start)] without whitespace/comments; kinds: name num str op."""
|
||||
toks, pos = [], 0
|
||||
while pos < len(src):
|
||||
m = TOKEN.match(src, pos)
|
||||
k = m.lastgroup
|
||||
if k in ("ceq", "seq"): k = "lcom" if m.group(0).startswith("--") else "lstr"
|
||||
if k not in ("ws", "lcom", "com"): toks.append(("str" if k == "lstr" else k, m.group(0), pos))
|
||||
pos = m.end()
|
||||
return toks
|
||||
|
||||
def fdepths(toks):
|
||||
"""function nesting depth of every token (0 = runs at load time)"""
|
||||
st, fd, out = [], 0, []
|
||||
for k, t, _ in toks:
|
||||
out.append(fd)
|
||||
if k == "name":
|
||||
if t == "function": st.append(1); fd += 1
|
||||
elif t in ("if", "do", "repeat"): st.append(0)
|
||||
elif t in ("end", "until"): fd -= st.pop()
|
||||
assert not st, "unbalanced blocks"
|
||||
return out
|
||||
|
||||
def declared(toks):
|
||||
"""names declared as locals / parameters / loop variables anywhere"""
|
||||
out, n = set(), len(toks)
|
||||
for i, (k, t, _) in enumerate(toks):
|
||||
j = None
|
||||
if t == "local": j = i + 2 if toks[i + 1][1] == "function" else i + 1
|
||||
elif t == "for": j = i + 1
|
||||
elif t == "function":
|
||||
j = i + 1
|
||||
while toks[j][1] != "(": j += 1
|
||||
j += 1
|
||||
while j is not None and j < n and toks[j][0] == "name" and toks[j][1] not in KW:
|
||||
out.add(toks[j][1])
|
||||
j += 1
|
||||
if j < n and toks[j][1] == ",": j += 1
|
||||
else: break
|
||||
return out
|
||||
|
||||
def apply(src, edits):
|
||||
for s, e, r in sorted(edits, reverse=True): src = src[:s] + r + src[e:]
|
||||
return src
|
||||
|
||||
def isref(toks, i):
|
||||
"""toks[i] is a variable read/write (not a field name)"""
|
||||
return toks[i][0] == "name" and (i == 0 or toks[i - 1][1] not in (".", ":"))
|
||||
|
||||
def nexttext(toks, i): return toks[i + 1][1] if i + 1 < len(toks) else ""
|
||||
|
||||
# ---- C: --@hoist helpers ----
|
||||
hoisted, hoisted_names = [], []
|
||||
if OPT["C"]:
|
||||
for f, src in FILES.items():
|
||||
while "--@hoist\n" in src:
|
||||
s = src.index("--@hoist\n") + len("--@hoist\n")
|
||||
toks = lex(src[s:])
|
||||
depth, i = 0, 0
|
||||
while True: # first `function` ... matching end
|
||||
t = toks[i][1]
|
||||
if t == "function" or t in ("if", "do", "repeat"): depth += 1
|
||||
elif t in ("end", "until"):
|
||||
depth -= 1
|
||||
if depth == 0: break
|
||||
i += 1
|
||||
e = s + toks[i][2] + 3
|
||||
text = src[s:e]
|
||||
m = re.search(r"^(local )?function ([A-Za-z_]\w*)", text, re.M)
|
||||
hoisted_names.append(m.group(2))
|
||||
hoisted.append(text[:m.start()] + "local function " + text[m.start() + len(m.group(0)) - len(m.group(2)):])
|
||||
src = src[:s - len("--@hoist\n")] + "\n" + re.sub(r"[^\n]", "", text) + src[e:]
|
||||
FILES[f] = src
|
||||
HOIST_DEPS = "local type, mathMin, mathMax, mathFloor, mathCeil, bitOr, bitLShift = type, math.min, math.max, math.floor, math.ceil, bit32.bor, bit32.lshift"
|
||||
|
||||
# ---- E: statement IM_ASSERT -> assert ----
|
||||
STMT_PREV_KW = {"end", "true", "false", "nil", "break", "then", "do", "else", "repeat"}
|
||||
def rewrite_assert(src):
|
||||
toks, edits = lex(src), []
|
||||
for i, (k, t, p) in enumerate(toks):
|
||||
if t == "IM_ASSERT" and isref(toks, i) and nexttext(toks, i) == "(":
|
||||
pk, pt = (toks[i - 1][0], toks[i - 1][1]) if i else ("op", ";")
|
||||
if (pk == "name" and (pt not in KW or pt in STMT_PREV_KW)) or pk in ("num", "str") or pt in (")", "]", "}", ";", "..."):
|
||||
edits.append((p, p + len(t), "assert"))
|
||||
return apply(src, edits)
|
||||
|
||||
if OPT["E"]:
|
||||
FILES = {f: rewrite_assert(s) for f, s in FILES.items()}
|
||||
hoisted = [rewrite_assert(s) for s in hoisted]
|
||||
|
||||
# ---- B: enum / constant folding ----
|
||||
LUAU = shutil.which("luau") or (sorted(__import__("glob").glob("/nix/store/*-luau-*/bin/luau")) or ["luau"])[-1]
|
||||
|
||||
def header():
|
||||
return ["local __FILES, __LOADED = {}, {}",
|
||||
"function IM_INCLUDE(name)",
|
||||
" local r = __LOADED[name]",
|
||||
" if r == nil then r = __FILES[name](); if r == nil then r = true end; __LOADED[name] = r end",
|
||||
" return r",
|
||||
"end", ""]
|
||||
|
||||
def numtext(s):
|
||||
v = float(s)
|
||||
if v != v or v in (float("inf"), float("-inf")) or (v == 0 and s.startswith("-")): return None
|
||||
r = str(int(v)) if v.is_integer() and abs(v) < 2 ** 53 else repr(v)
|
||||
return "(%s)" % r if v < 0 else r
|
||||
|
||||
def dump_values():
|
||||
"""{name: number} and {name: {key: number}} of the loaded library (imgui.lua and what it includes)"""
|
||||
src = ["--!optimize 1"] + ([HOIST_DEPS] + hoisted if hoisted else []) + header()
|
||||
for name, s in sorted(FILES.items()): src += ["__FILES[%r] = function()" % name, s, "end"]
|
||||
src += ['IM_INCLUDE("imgui.lua")',
|
||||
'local function D(n, v) if type(v) == "number" then print("C", n, string.format("%.17g", v)) elseif type(v) == "table" then',
|
||||
' for k, x in pairs(v) do print("T", n, type(k) == "string" and k or "?", type(x) == "number" and string.format("%.17g", x) or "?") end end end']
|
||||
src += ["D(%r, %s)" % (n, n) for n in sorted(names)]
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".luau", delete=False) as fp: fp.write("\n".join(src))
|
||||
try:
|
||||
p = subprocess.run([LUAU, fp.name], capture_output=True, text=True, timeout=60)
|
||||
finally:
|
||||
os.unlink(fp.name)
|
||||
if p.returncode: raise RuntimeError("enum dump failed:\n" + p.stdout[-2000:] + p.stderr[-2000:])
|
||||
consts, tables = {}, {}
|
||||
for line in p.stdout.splitlines():
|
||||
a = line.split("\t")
|
||||
if a[0] == "C": consts[a[1]] = a[2]
|
||||
elif a[0] == "T": tables.setdefault(a[1], {})[a[2]] = a[3]
|
||||
tables = {n: t for n, t in tables.items() if "?" not in t and "?" not in t.values()}
|
||||
return consts, tables
|
||||
|
||||
def fold(files):
|
||||
consts, tables = dump_values()
|
||||
lexed = {f: lex(s) for f, s in files.items()}
|
||||
depth = {f: fdepths(t) for f, t in lexed.items()}
|
||||
# tables written inside a function, constants assigned more than once or not at top level: not foldable
|
||||
assigns = {}
|
||||
for f, toks in lexed.items():
|
||||
for i, (k, t, _) in enumerate(toks):
|
||||
if not isref(toks, i): continue
|
||||
if t in tables and depth[f][i] > 0:
|
||||
j = i + 1
|
||||
if nexttext(toks, i) == ".": j = i + 3
|
||||
elif nexttext(toks, i) == "[":
|
||||
b = 0
|
||||
while True:
|
||||
b += {"[": 1, "]": -1}.get(toks[j][1], 0); j += 1
|
||||
if b == 0: break
|
||||
if j < len(toks) and toks[j][1] == "=": tables.pop(t, None)
|
||||
if t in consts and nexttext(toks, i) == "=":
|
||||
assigns[t] = assigns.get(t, 0) + (1 if depth[f][i] == 0 else 2)
|
||||
consts = {n: v for n, v in consts.items() if assigns.get(n) == 1 and numtext(v)}
|
||||
out = {}
|
||||
for f, toks in lexed.items():
|
||||
shadow = declared(toks)
|
||||
edits = []
|
||||
for i, (k, t, p) in enumerate(toks):
|
||||
if depth[f][i] == 0 or not isref(toks, i) or t in shadow: continue
|
||||
if t in tables and nexttext(toks, i) == "." and i + 2 < len(toks):
|
||||
key = toks[i + 2][1]
|
||||
if key in tables[t] and numtext(tables[t][key]) and nexttext(toks, i + 2) not in ("=", ".", ":", "[", "(", "{") and toks[i + 3][0] != "str":
|
||||
edits.append((p, toks[i + 2][2] + len(key), "%s --[[%s.%s]]" % (numtext(tables[t][key]), t, key)))
|
||||
elif t in consts and nexttext(toks, i) not in ("=", ".", ":", "[", "(", "{") and toks[i + 1][0] != "str":
|
||||
edits.append((p, p + len(t), "%s --[[%s]]" % (numtext(consts[t]), t)))
|
||||
out[f] = apply(files[f], edits)
|
||||
return out
|
||||
|
||||
if OPT["B"]:
|
||||
try:
|
||||
allf = dict(FILES); allf.update({"@hoist%d" % i: "local function __h()\n" + s + "\nend" for i, s in enumerate(hoisted)})
|
||||
allf = fold(allf)
|
||||
hoisted = [allf.pop("@hoist%d" % i)[len("local function __h()\n"):-len("\nend")] for i in range(len(hoisted))]
|
||||
FILES = allf
|
||||
except (OSError, RuntimeError) as e:
|
||||
if os.environ.get("IMGUI_BUNDLE_STRICT"): raise # CI: a release must not silently lose the folding
|
||||
print("bundle.py: enum folding skipped (%s)" % str(e).strip()[:300], file=sys.stderr)
|
||||
|
||||
# ---- A: hot globals -> bundle locals ----
|
||||
hot = []
|
||||
if OPT["A"]:
|
||||
count, used = {}, {}
|
||||
for f, src in FILES.items():
|
||||
toks = lex(src)
|
||||
used.setdefault(GROUP.get(f, f), set()).update(t for i, (k, t, _) in enumerate(toks) if isref(toks, i))
|
||||
for i, (k, t, _) in enumerate(toks):
|
||||
if t in names and isref(toks, i): count[t] = count.get(t, 0) + 1
|
||||
# greedy by reference count; each file function's upvalues (hoisted names it uses) stay <= MAX_UPVALUES
|
||||
used = list(used.values())
|
||||
taken = [len(u & set(hoisted_names + re.findall(r"\w+", HOIST_DEPS.split("=")[0]))) for u in used]
|
||||
for n in sorted((n for n in count if n not in hoisted_names), key=lambda n: (-count[n], n)):
|
||||
if len(hot) == MAX_LOCALS: break
|
||||
if all(taken[i] < MAX_UPVALUES for i, u in enumerate(used) if n in u):
|
||||
hot.append(n)
|
||||
taken = [c + (n in u) for c, u in zip(taken, used)]
|
||||
|
||||
out = ["--!optimize 2", "-- GENERATED by tools/bundle.py from *.lua, backends/, fonts/ - do not edit", ""]
|
||||
if LOVE:
|
||||
out = ["-- GENERATED by tools/bundle.py --target love - do not edit", re.search(r"--@compat-begin\n(.*?)--@compat-end", open(os.path.join(ROOT, "backends", "imgui_impl_love.lua")).read(), re.S).group(1), ""]
|
||||
out += [
|
||||
"local __FILES, __LOADED = {}, {}",
|
||||
"function IM_INCLUDE(name)",
|
||||
" local r = __LOADED[name]",
|
||||
" if r == nil then r = __FILES[name](); if r == nil then r = true end; __LOADED[name] = r end",
|
||||
" return r",
|
||||
"end", ""]
|
||||
out = ["-- GENERATED by tools/bundle.py --target love - do not edit", re.search(r"--@compat-begin\n(.*?)--@compat-end", open(os.path.join(BACKEND_DIR, BACKEND)).read(), re.S).group(1), ""]
|
||||
if hot: out.append("local " + ", ".join(hot))
|
||||
if hoisted: out += [HOIST_DEPS] + hoisted
|
||||
out += header()
|
||||
linemap = [] # (first bundle line, file) for error -> source mapping (tools/test/run.py)
|
||||
def nextline(): return sum(x.count("\n") + 1 for x in out) + 1
|
||||
for name, src in sorted(FILES.items()):
|
||||
if name in GROUP: continue
|
||||
out.append("__FILES[%r] = function()" % name)
|
||||
linemap.append((sum(x.count("\n") + 1 for x in out) + 1, name))
|
||||
if name == BACKEND and MODULES:
|
||||
out.append("local " + ", ".join(EXPORT[k] for k in MODULES))
|
||||
for k in MODULES:
|
||||
out.append("do")
|
||||
linemap.append((nextline(), k))
|
||||
out.append(inline_module(k, FILES[k]).rstrip("\n"))
|
||||
out.append("end")
|
||||
src = INCLUDE.sub("", src)
|
||||
linemap.append((nextline(), name))
|
||||
out.append(src.rstrip("\n"))
|
||||
out.append("end")
|
||||
out.append("")
|
||||
@@ -58,15 +309,19 @@ for n in sorted(names):
|
||||
out.append(" %s = %s," % (n, n))
|
||||
out.append("}")
|
||||
|
||||
import sys
|
||||
OUT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(ROOT, "build")
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
NAME = "imgui_love.lua" if LOVE else "ImGui.luau"
|
||||
open(os.path.join(OUT, NAME), "w").write("\n".join(out) + "\n")
|
||||
import json
|
||||
json.dump(linemap, open(os.path.join(OUT, NAME.rsplit(".", 1)[0] + ".linemap.json"), "w"))
|
||||
if not LOVE:
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from gen_types import wrapper
|
||||
open(os.path.join(OUT, "ImGuiTyped.luau"), "w").write(wrapper(FILES))
|
||||
open(os.path.join(OUT, "ImGuiTyped.luau"), "w").write(wrapper(ORIG))
|
||||
worker = open(os.path.join(BACKEND_DIR, "worker.luau")).read()
|
||||
req = re.search(r"^local Raster = require\(.*\)$", worker, re.M)
|
||||
assert req, "worker: no `local Raster = require(...)` line"
|
||||
raster = ORIG["roblox/raster.lua"].rstrip("\n")
|
||||
open(os.path.join(OUT, "ImGuiWorker.client.luau"), "w").write(
|
||||
"--!optimize 2\n-- GENERATED by tools/bundle.py from backends/roblox/worker.luau + raster.lua - do not edit\n"
|
||||
+ worker[:req.start()] + "local Raster = (function()\n" + raster + "\nend)()" + worker[req.end():])
|
||||
print("wrote build/%s (%d files, %d exports)" % (NAME, len(FILES), len(names)))
|
||||
@@ -0,0 +1,645 @@
|
||||
#!/usr/bin/env python3
|
||||
# Compares the port against upstream Dear ImGui (tools/test/upstream/*) and writes docs/PORT_STATUS.txt.
|
||||
# python3 tools/compare_upstream.py # print summary, write docs/PORT_STATUS.txt
|
||||
# Ported %: upstream functions (by qualified name, overloads merged) that have a port definition; enum values; struct fields;
|
||||
# public/internal API declarations in imgui.h / imgui_internal.h (namespace ImGui).
|
||||
# Similarity %: for each ported function, both bodies are normalized to a common token stream (comments/types/punctuation
|
||||
# dropped, C++ operators and names mapped to Lua: -> :: . ! && || _Flag) and compared with difflib ratio.
|
||||
# File figures are weighted by upstream body size. Matching is by name, so it's an estimate, not a proof.
|
||||
# Excluded from the %: C++-only (operators, destructors), #if 0, IMGUI_DISABLE_OBSOLETE_FUNCTIONS, OS-specific (#ifdef _WIN32...),
|
||||
# test engine. They're listed separately in the report.
|
||||
import os, re, sys
|
||||
from difflib import SequenceMatcher
|
||||
from fnmatch import fnmatchcase
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from minify import TOKEN as LUA_TOKEN
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
UP = os.path.join(ROOT, "tools", "test", "upstream")
|
||||
CPP_FILES = ["imgui.cpp", "imgui_widgets.cpp", "imgui_draw.cpp", "imgui_tables.cpp", "imgui_demo.cpp", "imgui.h", "imgui_internal.h"]
|
||||
PORT_FILES = sorted(f for f in os.listdir(ROOT) if f.endswith(".lua"))
|
||||
LUA_CLASS_ALIAS = {"IM_RECT": "ImRect", "IM_VECTOR": "ImVector", "IM_POOL": "ImPool", "IMGUI_VIEWPORT_P": "ImGuiViewportP",
|
||||
"ImGuiTextBufferMT": "ImGuiTextBuffer", "IMGUI_TEXT_INDEX": "ImGuiTextIndex", "IM_PAYLOAD": "ImGuiPayload",
|
||||
"DN": "ImGuiDockNode", "IM_VTXBUF": "ImVector"}
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
# Intentional Lua replacements: [=] rows, not counted as missing. (glob over the upstream key "Class::name" / "Struct::field",
|
||||
# reason, regex that must match the port sources - if the port's mechanism disappears, the entry falls back to [ ] / missing).
|
||||
# Only applies when no same-named port definition / field exists.
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
REPLACED = [
|
||||
# functions
|
||||
("ImGuiStorage::*", "Lua table keyed by ID (e.g. window.StateStorage = {})", r"StateStorage\s*=\s*\{\}"),
|
||||
("ImGuiStoragePair::*", "Lua table keyed by ID", r"StateStorage\s*=\s*\{\}"),
|
||||
("PairComparerByID", "table.sort over Lua table keys", r"table\.sort\("),
|
||||
("ImStr*", "Lua string library (string.find/sub/lower, immutable strings)", r"string\.find\("),
|
||||
("ImMemdup", "Lua strings/tables are values, no copy needed", r"string\.find\("),
|
||||
("ImFormatString*", "string.format", r"ImFormatString\s*=\s*string\.format"),
|
||||
("ImText*Utf8*", "strings stay UTF-8 bytes: ImStd.ImTextCharFromUtf8 decoder + utf8 library", r"function ImStd\.ImTextCharFromUtf8"),
|
||||
("MallocWrapper", "GC; IM_ALLOC = ImGui.MemAlloc", r"IM_ALLOC\s*=\s*ImGui\.MemAlloc"),
|
||||
("FreeWrapper", "GC; IM_ALLOC = ImGui.MemAlloc", r"IM_ALLOC\s*=\s*ImGui\.MemAlloc"),
|
||||
("ImGui::GetAllocatorFunctions", "GC, no allocator to query", r"IM_ALLOC\s*=\s*ImGui\.MemAlloc"),
|
||||
("ImFileWrite", "no filesystem on Roblox: SaveIniSettingsToDisk is a no-op, use SaveIniSettingsToMemory", r"Roblox: no disk"),
|
||||
("ImSwap", "Lua multiple assignment a, b = b, a", r"\b([\w.]+), ([\w.]+) = \2, \1\b"),
|
||||
("ImGui::DebugCheckVersionAndDataLayout", "C++ ABI / sizeof check", None),
|
||||
("TableSettingsCalcChunkSize", "sizeof; table settings are a plain ImVector", r"SettingsTables\s*=\s*ImVector\(\)"),
|
||||
("ImVector::size", "v.Size field", r"function IM_VECTOR:"),
|
||||
("ImVector::capacity", "v.Capacity field", r"function IM_VECTOR:"),
|
||||
("ImVector::front", "v.Data[1]", r"function IM_VECTOR:"),
|
||||
("ImVector::begin", "v.Data / v:iter()", r"function IM_VECTOR:iter\("),
|
||||
("ImVector::end", "v.Data / v:iter()", r"function IM_VECTOR:iter\("),
|
||||
("ImVector::size_in_bytes", "sizeof", None),
|
||||
("ImVector::max_size", "sizeof", None),
|
||||
("ImVector::clear_destruct", "GC: clear_delete / clear", r"function IM_VECTOR:clear_delete\("),
|
||||
("ImVector::find", "find_index (no element pointers)", r"function IM_VECTOR:find_index\("),
|
||||
("ImSpan::*", "plain Lua tables (e.g. table.Columns = {})", r"Columns = \{\}, ColumnsSize = 0"),
|
||||
("ImSpanAllocator::*", "plain Lua tables, no arena", r"Columns = \{\}, ColumnsSize = 0"),
|
||||
("ImStableVector::*", "ImVector (Lua references are stable)", r"BakedPool\s*=\s*ImVector\(\)"),
|
||||
("ImChunkStream::*", "plain ImVector of settings tables", r"SettingsTables\s*=\s*ImVector\(\)"),
|
||||
("ImPool::GetAliveCount", "pool.AliveCount field", r"\.AliveCount\)"),
|
||||
("ImPool::GetBufSize", "pool.BufSize field / GetMapSize()", r"function IM_POOL:GetMapSize\(\) return self\.BufSize"),
|
||||
("ImPool::TryGetMapData", "GetByIndex (removed slots hold false)", r"function IM_POOL:GetByIndex\("),
|
||||
("ImGuiTextBuffer::begin", "chunk-list string builder: c_str()", r"function ImGuiTextBufferMT:c_str\("),
|
||||
("ImGuiTextBuffer::end", "chunk-list string builder: c_str()", r"function ImGuiTextBufferMT:c_str\("),
|
||||
("ImGuiTextBuffer::resize", "chunk-list string builder, no byte buffer", r"function ImGuiTextBufferMT:c_str\("),
|
||||
("ImGuiTextBuffer::reserve", "chunk-list string builder, no byte buffer", r"function ImGuiTextBufferMT:c_str\("),
|
||||
("ImGuiTextBuffer::appendfv", "appendf(fmt, ...) (Lua varargs)", r"function ImGuiTextBufferMT:appendf\("),
|
||||
("ImGuiTextIndex::append", "debug log keeps a Lua line list (g.DebugLogLines)", r"g\.DebugLogLines\s*="),
|
||||
# struct fields (ImSpan*/ImStableVector/ImGuiStoragePair fields: covered by the globs above)
|
||||
("ImGuiTextBuffer::EmptyString", "c_str() of an empty chunk list", r"function ImGuiTextBufferMT:c_str\("),
|
||||
("ImGuiWindow::NameBufLen", "window.Name is an immutable Lua string", None),
|
||||
("ImGuiTextFilterItem::Begin", "item.Text substring", r"Text = string\.sub\(buf, b, e - 1\)"),
|
||||
("ImGuiTextFilterItem::Len", "item.Text substring", r"Text = string\.sub\(buf, b, e - 1\)"),
|
||||
("ImDrawVert::uv", "vertices packed into VtxBuffer.Buf (VTX_STRIDE bytes per vertex)", r"VTX_STRIDE\s*=\s*\d+"),
|
||||
("ImDrawVert::col", "vertices packed into VtxBuffer.Buf (VTX_STRIDE bytes per vertex)", r"VTX_STRIDE\s*=\s*\d+"),
|
||||
("ImGuiContext::DebugLogIndex", "Lua line list g.DebugLogLines", r"g\.DebugLogLines\s*="),
|
||||
("ImGuiContext::TempKeychordName", "GetKeyChordName returns a Lua string", r"\.\. \(\(key ~= ImGuiKey\.None"),
|
||||
("ImGuiContext::DragDropPayloadBuf*", "payload.Data holds the Lua value", r"payload\.Data = data"),
|
||||
("ImGuiTabBar::TabsNames", "names stored on the tab (tab.Name)", r"Tab names are stored on the tab itself"),
|
||||
]
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
# C++ side
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
CPP_TOKEN = re.compile(r"""
|
||||
(?P<nl>\n)
|
||||
| (?P<ws>[ \t\r\f\v]+|\\\n)
|
||||
| (?P<com>//[^\n]*|/\*.*?\*/)
|
||||
| (?P<pp>\#(?:[^\n\\]|\\.|\\\n)*)
|
||||
| (?P<str>(?:u8|u|U|L)?"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*')
|
||||
| (?P<num>0[xX][0-9a-fA-F']+[uUlL]*|(?:\d[\d']*\.?\d*|\.\d+)(?:[eE][+-]?\d+)?[fFuUlL]*)
|
||||
| (?P<name>[A-Za-z_]\w*)
|
||||
| (?P<op>->\*?|::|<<=|>>=|<<|>>|&&|\|\||==|!=|<=|>=|\+\+|--|[-+*/%&|^]=|\.\.\.|.)
|
||||
""", re.S | re.X)
|
||||
|
||||
EXCLUDE_PP = [("if0", re.compile(r"^\s*#\s*if\s+0\b")),
|
||||
("obsolete", re.compile(r"#\s*ifndef\s+IMGUI_DISABLE_OBSOLETE_FUNCTIONS|#\s*if\s+!defined\(IMGUI_DISABLE_OBSOLETE")),
|
||||
("os-specific", re.compile(r"_WIN32|__APPLE__|__linux__|_MSC_VER|__EMSCRIPTEN__|IMGUI_DISABLE_WIN32|__ANDROID__|_XBOX|__MINGW")),
|
||||
("test-engine", re.compile(r"IMGUI_ENABLE_TEST_ENGINE"))]
|
||||
|
||||
def cpp_tokens(src):
|
||||
"""[(kind, text, line, excl)] without whitespace/comments; excl = exclusion tag from enclosing #if, or None."""
|
||||
out, line, stack, sections = [], 1, [], []
|
||||
for m in CPP_TOKEN.finditer(src):
|
||||
kind, text = m.lastgroup, m.group(0)
|
||||
if kind == "nl": line += 1; continue
|
||||
if kind == "com":
|
||||
s = re.match(r"//\s*\[SECTION\]\s*(.+)", text)
|
||||
if s: sections.append((line, s.group(1).strip()))
|
||||
line += text.count("\n"); continue
|
||||
if kind == "ws": line += text.count("\n"); continue
|
||||
if kind == "pp":
|
||||
d = re.match(r"#\s*(\w+)", text); d = d.group(1) if d else ""
|
||||
if d in ("if", "ifdef", "ifndef"):
|
||||
stack.append(next((t for t, r in EXCLUDE_PP if r.search(text)), None))
|
||||
elif d in ("else", "elif") and stack:
|
||||
stack[-1] = None if stack[-1] in ("if0", "obsolete") else stack[-1] # #else of `#if 0` / obsolete is the live path
|
||||
elif d == "endif" and stack:
|
||||
stack.pop()
|
||||
line += text.count("\n"); continue
|
||||
out.append((kind, text, line, next((x for x in reversed(stack) if x), None)))
|
||||
return out, sections
|
||||
|
||||
CPP_MACROS = {"IM_MSVC_RUNTIME_CHECKS_OFF", "IM_MSVC_RUNTIME_CHECKS_RESTORE"} # argument-less macro lines, no trailing ';'
|
||||
CTRL = {"if", "for", "while", "switch", "catch", "sizeof", "return", "alignof", "decltype", "IM_ASSERT", "defined"}
|
||||
|
||||
def match_back(toks, i, close, open_):
|
||||
depth = 0
|
||||
while i >= 0:
|
||||
t = toks[i][1]
|
||||
if t == close: depth += 1
|
||||
elif t == open_:
|
||||
depth -= 1
|
||||
if depth == 0: return i
|
||||
i -= 1
|
||||
return -1
|
||||
|
||||
def match_fwd(toks, i):
|
||||
depth = 0
|
||||
pairs = {"{": "}", "(": ")", "[": "]"}
|
||||
open_ = toks[i][1]; close = pairs[open_]
|
||||
while i < len(toks):
|
||||
t = toks[i][1]
|
||||
if t == open_: depth += 1
|
||||
elif t == close:
|
||||
depth -= 1
|
||||
if depth == 0: return i
|
||||
i += 1
|
||||
return len(toks) - 1
|
||||
|
||||
def func_head(toks, i):
|
||||
"""toks[i] is '{'. If it opens a function body, return (class, name, name_tok_index, cpp_only) else None."""
|
||||
j = i - 1
|
||||
while j >= 0 and toks[j][1] in ("const", "noexcept", "override", "final", "IM_FMTARGS", "IM_FMTLIST"):
|
||||
j -= 1
|
||||
if j >= 0 and toks[j][1] == ")" and toks[match_back(toks, j, ")", "(") - 1][1] in ("IM_FMTARGS", "IM_FMTLIST"):
|
||||
j = match_back(toks, j, ")", "(") - 2
|
||||
# constructor initializer list: Foo::Foo(...) : a(1), b{2} {
|
||||
k = j
|
||||
while k >= 0 and toks[k][1] in (")", "}"):
|
||||
o = match_back(toks, k, toks[k][1], "(" if toks[k][1] == ")" else "{")
|
||||
if o <= 1: break
|
||||
if toks[o - 2][1] in (",",) or (toks[o - 2][1] == ":" ):
|
||||
if toks[o - 2][1] == ":": j = o - 3; break
|
||||
k = o - 3; continue
|
||||
break
|
||||
if j < 0 or toks[j][1] != ")": return None
|
||||
o = match_back(toks, j, ")", "(")
|
||||
if o <= 0: return None
|
||||
n = o - 1
|
||||
name = toks[n][1]
|
||||
cpp_only = False
|
||||
if toks[n - 1][1] == "operator" or (n >= 1 and toks[n][0] == "op" and toks[n - 1][1] == "operator"):
|
||||
return (None, "operator" + name, n, True)
|
||||
if toks[n][0] == "op" and n >= 2 and toks[n - 1][1] == "operator": return (None, "operator", n, True)
|
||||
if toks[n][0] != "name" or name in CTRL: return None
|
||||
if toks[n - 1][1] == "~": cpp_only = True; name = "~" + name
|
||||
cls = None
|
||||
if toks[n - 1][1] == "::" or (cpp_only and toks[n - 2][1] == "::"):
|
||||
q = n - 2 if not cpp_only else n - 3
|
||||
cls = toks[q][1]
|
||||
if toks[n - 1][1] == "operator": return (cls, "operator", n, True)
|
||||
return (cls, name, n, cpp_only)
|
||||
|
||||
class UpFunc:
|
||||
def __init__(s, file, cls, name, line, body, section, excl):
|
||||
s.file, s.cls, s.name, s.line, s.body, s.section, s.excl = file, cls, name, line, body, section, excl
|
||||
@property
|
||||
def key(s): return "%s::%s" % (s.cls, s.name) if s.cls else s.name
|
||||
|
||||
def parse_cpp(fname):
|
||||
src = open(os.path.join(UP, fname), encoding="utf-8", errors="replace").read()
|
||||
toks, sections = cpp_tokens(src)
|
||||
funcs, enums, structs, decls = [], {}, {}, {} # decls: namespace ImGui declarations (name -> line)
|
||||
|
||||
def section_at(line):
|
||||
cur = ""
|
||||
for l, s in sections:
|
||||
if l <= line and l > 120: cur = s # skip the index at the top of each file
|
||||
return cur
|
||||
|
||||
def scan(a, b, cls, ns):
|
||||
i = a
|
||||
stmt_start = a
|
||||
while i < b:
|
||||
k, t, line, excl = toks[i]
|
||||
if t == "{":
|
||||
head = func_head(toks, i)
|
||||
e = match_fwd(toks, i)
|
||||
pre = [x[1] for x in toks[stmt_start:i]]
|
||||
if head:
|
||||
hc, hn, ni, cpp_only = head
|
||||
c = hc or cls
|
||||
if cls and hn == cls: c = cls # inline ctor in struct
|
||||
ex = "c++-only" if cpp_only or hn.startswith("~") else toks[ni][3]
|
||||
if c and hn == c and fname.endswith(".h") and e - i < 4: ex = ex # trivial ctor kept
|
||||
funcs.append(UpFunc(fname, c, hn, toks[ni][2], toks[i + 1:e], section_at(toks[ni][2]), ex))
|
||||
elif "namespace" in pre:
|
||||
q = pre.index("namespace")
|
||||
scan(i + 1, e, cls, (pre[q + 1] if len(pre) > q + 1 else ""))
|
||||
elif "enum" in pre:
|
||||
nm = next((x for x in pre[pre.index("enum") + 1:] if re.match(r"[A-Za-z_]\w*$", x) and x not in ("class", "int")), None)
|
||||
vals, j, depth = [], i + 1, 0
|
||||
expect = True
|
||||
while j < e:
|
||||
tt = toks[j][1]
|
||||
if tt in "([{": depth += 1
|
||||
elif tt in ")]}": depth -= 1
|
||||
elif depth == 0 and tt == ",": expect = True
|
||||
elif expect and depth == 0 and toks[j][0] == "name":
|
||||
vals.append((tt, toks[j][2], toks[j][3])); expect = False
|
||||
j += 1
|
||||
if nm: enums[nm] = (vals, line, section_at(line))
|
||||
elif any(x in ("struct", "class", "union") for x in pre) and "=" not in pre:
|
||||
kw = max(q for q, x in enumerate(pre) if x in ("struct", "class", "union")) # skips macro lines / template<...> before it
|
||||
names = [x for x in pre[kw:] if re.match(r"[A-Za-z_]\w*$", x) and x not in ("struct", "class", "union", "IMGUI_API", "typedef", "final", "public", "private", "alignas")]
|
||||
nm = names[0] if names else cls
|
||||
if nm and "union" not in pre: structs.setdefault(nm, ([], line, section_at(line)))
|
||||
scan(i + 1, e, nm, ns)
|
||||
if nm and pre[:1] != ["union"] and toks[e + 1][1] != ";" and toks[e + 1][0] == "name" and cls:
|
||||
pass
|
||||
i = e + 1
|
||||
if i < b and toks[i][1] == ";": i += 1
|
||||
stmt_start = i
|
||||
continue
|
||||
if t == ";":
|
||||
st = toks[stmt_start:i]
|
||||
txt = [x[1] for x in st]
|
||||
if txt and txt[0] in ("public", "private", "protected") and len(txt) > 1 and txt[1] == ":": st, txt = st[2:], txt[2:]
|
||||
while txt and txt[0] in CPP_MACROS: st, txt = st[1:], txt[1:]
|
||||
if txt and ns == "ImGui" and cls is None and "(" in txt and txt[0] not in ("typedef", "struct", "enum", "using"):
|
||||
p = txt.index("(")
|
||||
if p > 0 and st[p - 1][0] == "name" and txt[p - 1] not in CTRL:
|
||||
decls.setdefault(txt[p - 1], (st[p - 1][2], st[p - 1][3], section_at(st[p - 1][2])))
|
||||
elif txt and cls and txt[0] not in ("typedef", "friend", "static", "using", "enum", "struct", "class", "template"):
|
||||
eq = txt.index("=") if "=" in txt else len(txt)
|
||||
pa = txt.index("(") if "(" in txt else len(txt)
|
||||
if pa >= eq: # not a method declaration
|
||||
depth = 0
|
||||
for j, x in enumerate(txt[:eq] + [";"]):
|
||||
if x in ("<", "(", "["): depth += 1
|
||||
elif x in (">", ")", "]"): depth -= 1
|
||||
elif depth == 0 and x in (",", ";", ":") or (depth == 0 and x == "[" ):
|
||||
if j > 0 and re.match(r"[A-Za-z_]\w*$", txt[j - 1]) and txt[j - 1] not in ("const", "unsigned", "int", "float"):
|
||||
structs.setdefault(cls, ([], 0, ""))[0].append((txt[j - 1], st[j - 1][2], st[j - 1][3]))
|
||||
if x == "[" and depth == 1 and j > 0 and re.match(r"[A-Za-z_]\w*$", txt[j - 1]):
|
||||
structs.setdefault(cls, ([], 0, ""))[0].append((txt[j - 1], st[j - 1][2], st[j - 1][3]))
|
||||
if eq < len(txt) and re.match(r"[A-Za-z_]\w*$", txt[eq - 1]):
|
||||
structs.setdefault(cls, ([], 0, ""))[0].append((txt[eq - 1], st[eq - 1][2], st[eq - 1][3]))
|
||||
stmt_start = i + 1
|
||||
i += 1
|
||||
scan(0, len(toks), None, "")
|
||||
for k in structs: # dedupe fields
|
||||
seen, out = set(), []
|
||||
for f in structs[k][0]:
|
||||
if f[0] not in seen: seen.add(f[0]); out.append(f)
|
||||
structs[k] = (out,) + structs[k][1:]
|
||||
return funcs, enums, structs, decls
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
# Lua side
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
def lua_tokens(src):
|
||||
out, line, pos = [], 1, 0
|
||||
while pos < len(src):
|
||||
m = LUA_TOKEN.match(src, pos)
|
||||
kind, text = m.lastgroup, m.group(0)
|
||||
if kind in ("ceq", "seq"): kind = "lcom" if text.startswith("--") else "lstr"
|
||||
if kind not in ("ws", "com", "lcom"):
|
||||
out.append(("str" if kind in ("str", "lstr") else kind, text, line))
|
||||
line += text.count("\n"); pos = m.end()
|
||||
return out
|
||||
|
||||
OPENERS = {"function", "if", "do", "repeat"}
|
||||
CLOSERS = {"end", "until"}
|
||||
|
||||
class PortFunc:
|
||||
alias = None
|
||||
def __init__(s, file, cls, name, line, body):
|
||||
s.file, s.cls, s.name, s.line, s.body = file, cls, name, line, body
|
||||
|
||||
def parse_lua():
|
||||
defs, enum_keys, globals_, fields = [], set(), set(), set()
|
||||
for f in PORT_FILES:
|
||||
toks = lua_tokens(open(os.path.join(ROOT, f), encoding="utf-8").read())
|
||||
n = len(toks)
|
||||
for i, (k, t, line) in enumerate(toks):
|
||||
chain, start = None, None
|
||||
if t == "function" and i + 1 < n and toks[i + 1][0] == "name":
|
||||
j = i + 1; chain = [toks[j][1]]
|
||||
while j + 2 < n and toks[j + 1][1] in (".", ":") and toks[j + 2][0] == "name":
|
||||
chain.append(toks[j + 2][1]); j += 2
|
||||
if j + 1 < n and toks[j + 1][1] == "(": start = j + 1
|
||||
else: chain = None
|
||||
elif k == "name" and i + 3 < n and toks[i + 1][1] == "=" and toks[i + 2][1] == "function" and toks[i + 3][1] == "(":
|
||||
j = i; chain = [t]
|
||||
while j >= 2 and toks[j - 1][1] == "." and toks[j - 2][0] == "name":
|
||||
chain.insert(0, toks[j - 2][1]); j -= 2
|
||||
start = i + 3; i0 = i + 2
|
||||
if chain is None: continue
|
||||
# body: from start's ')' to matching end
|
||||
j = start
|
||||
while toks[j][1] != ")": j += 1
|
||||
body_start, depth, j = j + 1, 1, j + 1
|
||||
while j < n and depth > 0:
|
||||
tt = toks[j][1]
|
||||
if tt in OPENERS and toks[j][0] == "name": depth += 1
|
||||
elif tt in CLOSERS and toks[j][0] == "name": depth -= 1
|
||||
j += 1
|
||||
name = chain[-1]
|
||||
cls = LUA_CLASS_ALIAS.get(chain[-2], chain[-2]) if len(chain) > 1 else None
|
||||
if cls and cls.endswith("MT") and len(cls) > 2: cls = cls[:-2] # method tables: function ExampleAppLogMT:AddLog()
|
||||
if cls is None and re.match(r"[A-Z]\w*_[A-Z]\w*$", name) and "__" not in name: # Class_Method globals (C++ static members)
|
||||
c, _, m = name.partition("_")
|
||||
defs.append(PortFunc(f, c, m, line, toks[body_start:j - 1]))
|
||||
pf = PortFunc(f, cls, name, line, toks[body_start:j - 1])
|
||||
bt = [x[1] for x in pf.body]
|
||||
if len(bt) >= 5 and bt[0] == "return" and bt[-3:] == ["(", "...", ")"] and all(x[0] == "name" or x[1] in (".", ":") for x in pf.body[1:-3]):
|
||||
pf.alias = " ".join(bt[1:-3]) + "(...)"; pf.body = pf.body[1:-3] # forwarder: function(...) return ImGui.X(...) end
|
||||
defs.append(pf)
|
||||
# aliases / factories: ImGui.DragFloat2 = DragFloatN(2) ImFormatString = string.format ImGui.LogTextV = ImGui.LogText
|
||||
for i, (k, t, line) in enumerate(toks):
|
||||
if k != "name" or (i and toks[i - 1][2] == line) or t == "local": continue
|
||||
j, chain = i, [t]
|
||||
while j + 2 < n and toks[j + 1][1] == "." and toks[j + 2][0] == "name":
|
||||
chain.append(toks[j + 2][1]); j += 2
|
||||
if j + 2 >= n or toks[j + 1][1] != "=" or toks[j + 2][0] != "name" or toks[j + 2][1] in ("function", "nil", "true", "false", "not"): continue
|
||||
if len(chain) == 1 and not re.match(r"(Im|STB|IMSTB|stb)", t): continue
|
||||
if len(chain) > 1 and chain[0] not in ("ImGui", "ImStd", "ImStb", "MT") and chain[-2] not in LUA_CLASS_ALIAS: continue
|
||||
rhs = [x for x in toks[j + 2:] if x[2] == toks[j + 2][2]]
|
||||
cls = LUA_CLASS_ALIAS.get(chain[-2], chain[-2]) if len(chain) > 1 else None
|
||||
pf = PortFunc(f, cls, chain[-1], line, rhs); pf.alias = " ".join(x[1] for x in rhs[:6])
|
||||
defs.append(pf)
|
||||
# enum tables / globals / fields
|
||||
depth_stack = []
|
||||
for i, (k, t, line) in enumerate(toks):
|
||||
if t == "{":
|
||||
owner = None
|
||||
if i >= 2 and toks[i - 1][1] == "=" and toks[i - 2][0] == "name": owner = toks[i - 2][1]
|
||||
depth_stack.append(owner)
|
||||
elif t == "}":
|
||||
if depth_stack: depth_stack.pop()
|
||||
elif k == "name" and i + 1 < n and toks[i + 1][1] == "=":
|
||||
prev = toks[i - 1][1] if i else ""
|
||||
if prev in ("{", ",", ";") or (prev == "." ) or (prev not in ("local", "for") and toks[i - 1][0] != "name" and prev not in ("]", ")")):
|
||||
fields.add(t)
|
||||
if prev in ("{", ",") and depth_stack and depth_stack[-1]: enum_keys.add((depth_stack[-1], t))
|
||||
if prev == "." and i >= 2: enum_keys.add((toks[i - 2][1], t))
|
||||
if prev not in (".", "local", ",") and not depth_stack: globals_.add(t)
|
||||
elif k == "str" and i >= 1 and toks[i - 1][1] == "[" and i + 2 < n and toks[i + 1][1] == "]" and toks[i + 2][1] == "=" and depth_stack and depth_stack[-1]:
|
||||
enum_keys.add((depth_stack[-1], toks[i][1].strip("\"'")))
|
||||
return defs, enum_keys, globals_, fields
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
# Normalization + similarity
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
CPP_DROP = {"const", "static", "float", "int", "unsigned", "signed", "bool", "char", "void", "auto", "double", "size_t", "short", "long",
|
||||
"ImU8", "ImU16", "ImU32", "ImU64", "ImS8", "ImS16", "ImS32", "ImS64", "ImWchar", "ImGuiID", "struct", "inline", "IMGUI_API",
|
||||
"constexpr", "template", "typename", "IM_UNUSED", "this", ";", "{", "}", "(", ")", "&", "*", "ImGuiContext", "ImGuiWindow", "ImGuiStyle",
|
||||
"ImGuiIO", "ImDrawList", "ImFont", "ImRect", "ImVec2", "ImVec4", "case", "break", "default", ":", "[", "]"}
|
||||
LUA_DROP = {"local", "then", "do", "end", "self", "(", ")", ";", "{", "}", "&", "*", "[", "]", ":", "bit32", "math", "string", "table"}
|
||||
LUA_MAP = {"~=": "!=", "not": "!", "and": "&&", "or": "||", "nil": "NULL", "elseif": "else if", "band": "&", "bor": "|", "bxor": "^",
|
||||
"bnot": "~", "lshift": "<<", "rshift": ">>", "btest": "&", "ImMax": "ImMax", "ImMin": "ImMin"}
|
||||
CPP_MAP = {"->": ".", "::": ".", "nullptr": "NULL", "++": "+=", "--": "-=", "IM_COUNTOF": "#", "IM_ARRAYSIZE": "#", "true": "true", "false": "false"}
|
||||
|
||||
def norm_num(t):
|
||||
try:
|
||||
if t.lower().startswith("0x"): return str(int(t.rstrip("uUlL").replace("'", ""), 16))
|
||||
return repr(float(t.rstrip("fFuUlL").replace("'", "")))
|
||||
except ValueError: return t
|
||||
|
||||
def split_enum(t):
|
||||
m = re.match(r"(Im[A-Za-z]+)_(\w+)$", t)
|
||||
return [m.group(1), ".", m.group(2)] if m and not t.endswith("_") else [t]
|
||||
|
||||
def norm_cpp(body):
|
||||
out = []
|
||||
for k, t, _, _ in body:
|
||||
if k == "num": out.append(norm_num(t)); continue
|
||||
if k == "str": out.append("S"); continue
|
||||
t = CPP_MAP.get(t, t)
|
||||
if t in CPP_DROP: continue
|
||||
out.extend(split_enum(t) if k == "name" else [t])
|
||||
o2 = []
|
||||
for i, t in enumerate(out): # drop the implicit ImGui:: qualifier (C++ calls inside the namespace omit it)
|
||||
if t == "ImGui" and i + 1 < len(out) and out[i + 1] == ".": continue
|
||||
if t == "." and o2 and o2[-1] in (".",): continue
|
||||
o2.append(t)
|
||||
return [t for i, t in enumerate(o2) if not (t == "." and (i == 0 or o2[i - 1] in ("(", ",", "=", "return")))]
|
||||
|
||||
def norm_lua(body):
|
||||
out = []
|
||||
for k, t, _ in body:
|
||||
if k == "num": out.append(norm_num(t)); continue
|
||||
if k == "str": out.append("S"); continue
|
||||
if t in LUA_DROP: continue
|
||||
t = LUA_MAP.get(t, t)
|
||||
out.extend(t.split(" ") if " " in t else [t])
|
||||
o2 = []
|
||||
for i, t in enumerate(out):
|
||||
if t == "ImGui" and i + 1 < len(out) and out[i + 1] == ".": continue
|
||||
if t == "." and (not o2 or o2[-1] in ("&", "|", "^", "~", "<<", ">>", "=", ",", "return", "if", "while", "!")): continue
|
||||
o2.append(t)
|
||||
return o2
|
||||
|
||||
def similarity(a, b):
|
||||
if not a and not b: return 1.0
|
||||
return SequenceMatcher(None, a, b, autojunk=False).ratio()
|
||||
|
||||
def is_stub(port_norm, up_norm):
|
||||
real = [t for t in port_norm if t not in ("return", "NULL", "false", "true", "0.0", "S", "IM_ASSERT", "!", ",", "=", "0")]
|
||||
return len(up_norm) > 12 and (len(real) < 3 or not any(re.match(r"[A-Za-z_]\w*$", t) for t in real))
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------
|
||||
def main():
|
||||
defs, enum_keys, lua_globals, lua_fields = parse_lua()
|
||||
by_name = {}
|
||||
for d in sorted(defs, key=lambda d: d.alias is not None): by_name.setdefault(d.name, []).append(d)
|
||||
port_classes = {d.cls for d in defs if d.cls}
|
||||
port_class_files = {}
|
||||
for d in defs:
|
||||
if d.cls: port_class_files.setdefault(d.cls, set()).add(d.file)
|
||||
|
||||
def find(u):
|
||||
m = re.match(r"I?M?STB_TEXTEDIT_(\w+?)(_IMPL)?$", u.name)
|
||||
if m: # STB_TEXTEDIT_INSERTCHARS / IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL -> ImStb.TEXTEDIT_*
|
||||
c = [d for d in by_name.get("TEXTEDIT_" + m.group(1), []) if d.cls == "ImStb"]
|
||||
return c[0] if c else None
|
||||
cands = by_name.get(u.name, [])
|
||||
if u.cls and u.cls not in ("ImGui",):
|
||||
exact = [d for d in cands if d.cls == u.cls]
|
||||
if exact: return exact[0]
|
||||
if u.name == u.cls: # constructor: function ImGuiStyle() / MT.X.new
|
||||
c = [d for d in cands if d.cls is None] or [d for d in by_name.get("new", []) if d.cls == u.cls]
|
||||
return c[0] if c else None
|
||||
if u.cls in port_classes: # only a classless helper in the class's own file (local function _grow_capacity)
|
||||
loose = [d for d in cands if d.cls is None and d.file in port_class_files[u.cls]] if len(cands) == 1 else []
|
||||
return loose[0] if loose else None
|
||||
loose = [d for d in cands if d.cls in (None, "ImGui")] if len(cands) == 1 else []
|
||||
return loose[0] if loose else None
|
||||
pref = [d for d in cands if d.cls == "ImGui"] + [d for d in cands if d.cls is None] + [d for d in cands if d.cls in ("ImStd", "ImStb")]
|
||||
return pref[0] if pref else None
|
||||
|
||||
up_names = set()
|
||||
for f in CPP_FILES:
|
||||
for u in parse_cpp(f)[0]: up_names.add(u.name)
|
||||
def expand(p, depth=0, seen=()):
|
||||
"""Port body with calls to port-only helpers in the same file inlined (the port splits some big functions)."""
|
||||
out, body = [], p.body
|
||||
for i, x in enumerate(body):
|
||||
out.append(x)
|
||||
if depth < 3 and x[0] == "name" and i + 1 < len(body) and body[i + 1][1] == "(" and x[1] not in up_names and (i == 0 or body[i - 1][1] not in (".", ":")):
|
||||
h = [d for d in by_name.get(x[1], []) if d.file == p.file and not d.alias and d is not p and d.name not in seen]
|
||||
if h: out.extend(expand(h[0], depth + 1, seen + (p.name,)))
|
||||
return out
|
||||
|
||||
report, summary = [], []
|
||||
all_up = {}
|
||||
enums_all, structs_all, decls_by_file = {}, {}, {}
|
||||
for f in CPP_FILES:
|
||||
funcs, enums, structs, decls = parse_cpp(f)
|
||||
merged = {}
|
||||
for u in funcs: # merge overloads (keep the largest body for similarity)
|
||||
if u.key not in merged or len(u.body) > len(merged[u.key].body):
|
||||
if u.key in merged and merged[u.key].excl is None: u.excl = None
|
||||
merged[u.key] = u
|
||||
elif u.excl is None: merged[u.key].excl = None
|
||||
all_up[f] = list(merged.values())
|
||||
for k, v in enums.items(): enums_all.setdefault(k, v)
|
||||
for k, v in structs.items():
|
||||
if k in structs_all: structs_all[k][0].extend(x for x in v[0] if x[0] not in {y[0] for y in structs_all[k][0]})
|
||||
else: structs_all[k] = v
|
||||
decls_by_file[f] = decls
|
||||
|
||||
port_src = "\n".join(open(os.path.join(ROOT, f), encoding="utf-8").read() for f in PORT_FILES)
|
||||
ev_ok = {ev: ev is None or re.search(ev, port_src) is not None for _, _, ev in REPLACED}
|
||||
def replaced(key):
|
||||
return next((why for pat, why, ev in REPLACED if ev_ok[ev] and fnmatchcase(key, pat)), None)
|
||||
|
||||
tot = {"n": 0, "have": 0, "stub": 0, "size": 0, "size_have": 0, "simw": 0.0, "size_sim": 0, "repl": 0}
|
||||
for f in CPP_FILES:
|
||||
rows = []
|
||||
st = {"n": 0, "have": 0, "stub": 0, "size": 0, "size_have": 0, "simw": 0.0, "size_sim": 0, "repl": 0}
|
||||
for u in sorted(all_up[f], key=lambda u: u.line):
|
||||
un = norm_cpp(u.body)
|
||||
if u.excl:
|
||||
rows.append((u.section, "[-]", "", u, None, u.excl)); continue
|
||||
p = find(u)
|
||||
why = replaced(u.key) if p is None else None
|
||||
if why:
|
||||
st["repl"] += 1; rows.append((u.section, "[=]", "", u, None, why)); continue
|
||||
st["n"] += 1; st["size"] += len(un)
|
||||
if p is None:
|
||||
rows.append((u.section, "[ ]", "", u, None, "")); continue
|
||||
body = p.body
|
||||
if p.alias: # ImGui.X = ImGui.Y / Factory(n): compare against the target's body when it is a plain reference
|
||||
tgt = [x[1] for x in p.body if x[0] == "name"]
|
||||
t = by_name.get(tgt[-1]) if tgt and all(x[1] == "." or x[0] == "name" for x in p.body) else None
|
||||
t = [d for d in (t or []) if not d.alias]
|
||||
body = t[0].body if t else None
|
||||
if body is None: # alias of a Lua builtin / factory: ported, but no body to compare
|
||||
st["have"] += 1; st["size_have"] += len(un)
|
||||
rows.append((u.section, "[x]", " n/a", u, p, "= " + p.alias)); continue
|
||||
pn = norm_lua(expand(p) if not p.alias else body)
|
||||
sim = similarity(un, pn)
|
||||
stub = is_stub(pn, un) and not p.alias
|
||||
st["have"] += 1; st["size_have"] += len(un); st["simw"] += sim * len(un); st["size_sim"] += len(un)
|
||||
if stub: st["stub"] += 1
|
||||
rows.append((u.section, "[~]" if stub else "[x]", "%3.0f%%" % (100 * sim), u, p, "stub" if stub else ("= " + p.alias if p.alias else "")))
|
||||
for k in tot: tot[k] += st[k]
|
||||
summary.append((f, st))
|
||||
report.append((f, rows))
|
||||
|
||||
def pct(a, b): return "%5.1f%%" % (100.0 * a / b) if b else " - "
|
||||
|
||||
# enums / fields / API declarations
|
||||
enum_rows, enum_n, enum_have = [], 0, 0
|
||||
for nm, (vals, line, sec) in sorted(enums_all.items(), key=lambda x: x[0]):
|
||||
base = re.sub(r"(Private)?_$", "", nm)
|
||||
missing, have, counted = [], 0, 0
|
||||
for v, vline, excl in vals:
|
||||
if excl or v.endswith("_COUNT") and False: continue
|
||||
pre, _, key = v.partition("_")
|
||||
ok = v in lua_globals or (pre, key) in enum_keys or (base, key) in enum_keys or (nm, v) in enum_keys or (base, v) in enum_keys
|
||||
if not ok and not key: ok = v in lua_globals
|
||||
enum_n += 1; counted += 1
|
||||
if ok: have += 1; enum_have += 1
|
||||
else: missing.append(v)
|
||||
enum_rows.append((nm, have, counted, missing))
|
||||
|
||||
field_rows, field_n, field_have, field_repl = [], 0, 0, 0
|
||||
for nm, (fl, line, sec) in sorted(structs_all.items()):
|
||||
fl = [x for x in fl if not x[2]]
|
||||
repl = [x[0] for x in fl if x[0] not in lua_fields and replaced("%s::%s" % (nm, x[0]))]
|
||||
fl = [x for x in fl if x[0] not in repl]
|
||||
if not fl and not repl: continue
|
||||
missing = [x[0] for x in fl if x[0] not in lua_fields]
|
||||
field_n += len(fl); field_have += len(fl) - len(missing); field_repl += len(repl)
|
||||
field_rows.append((nm, len(fl) - len(missing), len(fl), missing, repl))
|
||||
|
||||
api_rows, api_repl = [], 0
|
||||
port_names = set(by_name)
|
||||
for f, label in (("imgui.h", "Public API (imgui.h, namespace ImGui)"), ("imgui_internal.h", "Internal API (imgui_internal.h, namespace ImGui)")):
|
||||
d = {k: v for k, v in decls_by_file[f].items() if not v[1]}
|
||||
r = [k for k in d if k not in port_names and replaced("ImGui::" + k)]
|
||||
api_repl += len(r)
|
||||
for k in r: del d[k]
|
||||
have = [k for k in d if k in port_names]
|
||||
api_rows.append((label, len(have), len(d), sorted((k for k in d if k not in port_names), key=lambda k: d[k][0]), d))
|
||||
|
||||
# ------------------------------------------------------------------ summary (stdout + file)
|
||||
head = []
|
||||
head.append("%-22s %9s %9s %9s %11s %9s %9s" % ("upstream file", "funcs", "ported", "by size", "similarity", "stubs", "replaced"))
|
||||
for f, s in summary:
|
||||
head.append("%-22s %9d %9s %9s %11s %9d %9d" % (f, s["n"], pct(s["have"], s["n"]), pct(s["size_have"], s["size"]),
|
||||
pct(s["simw"], s["size_sim"]), s["stub"], s["repl"]))
|
||||
head.append("%-22s %9d %9s %9s %11s %9d %9d" % ("TOTAL", tot["n"], pct(tot["have"], tot["n"]), pct(tot["size_have"], tot["size"]),
|
||||
pct(tot["simw"], tot["size_sim"]), tot["stub"], tot["repl"]))
|
||||
head.append("")
|
||||
head.append("upstream code reproduced (similarity x ported size / all upstream size): %s" % pct(tot["simw"] / max(1, tot["size_sim"]) * tot["size_have"], tot["size"]))
|
||||
for label, h, n, _, _ in api_rows: head.append("%-52s %4d / %4d %s" % (label, h, n, pct(h, n)))
|
||||
head.append("%-52s %4d / %4d %s" % ("Enum values (imgui.h + imgui_internal.h)", enum_have, enum_n, pct(enum_have, enum_n)))
|
||||
head.append("%-52s %4d / %4d %s" % ("Struct fields (imgui.h + imgui_internal.h)", field_have, field_n, pct(field_have, field_n)))
|
||||
head.append("%d intentionally replaced by Lua equivalents [=] (%d functions, %d API declarations, %d struct fields), not counted above"
|
||||
% (tot["repl"] + api_repl + field_repl, tot["repl"], api_repl, field_repl))
|
||||
print("\n".join(head))
|
||||
|
||||
L = []
|
||||
L.append("PORT STATUS: imgui-luau vs upstream Dear ImGui (docking, %s)" % re.search(r'IMGUI_VERSION\s+"([^"]+)"', open(os.path.join(UP, "imgui.h")).read()).group(1))
|
||||
L.append("Generated by tools/compare_upstream.py - do not edit. Upstream sources: tools/test/upstream/.")
|
||||
L.append("")
|
||||
L.append("Columns: funcs = upstream function definitions (overloads merged), excluding [-] rows")
|
||||
L.append(" ported = share that has a port definition with the same name")
|
||||
L.append(" by size = same, weighted by upstream body size (tokens)")
|
||||
L.append(" similarity = normalized token similarity of the ported bodies (difflib ratio), weighted by size")
|
||||
L.append(" stubs = ported but (nearly) empty in the port")
|
||||
L.append(" replaced = [=] rows: intentionally replaced by a Lua mechanism (REPLACED table), excluded from funcs")
|
||||
L.append("Name-based matching: a renamed port function shows as [ ], a same-named one counts even if it differs. Treat as estimates.")
|
||||
L.append("Port-only helpers called from a ported function (same file) are inlined before comparing, since the port splits some big functions.")
|
||||
L.append("Known low scores that are not missing code: data-driven port code (e.g. DemoWindowTables' section table), the older 1.92")
|
||||
L.append("polyline stroker (AddPolyline), Lua-native replacements (ImGuiStorage, ImStr*, ImFormatString -> string.format).")
|
||||
L.append("")
|
||||
L += head
|
||||
L.append("")
|
||||
L.append("Legend: [x] ported (sim %) [~] stub [ ] not ported [=] replaced by Lua equivalent (reason) [-] excluded (c++-only / obsolete / os-specific / #if 0 / test-engine)")
|
||||
for f, rows in report:
|
||||
L.append("")
|
||||
L.append("=" * 100)
|
||||
L.append("%s" % f)
|
||||
L.append("=" * 100)
|
||||
cur = None
|
||||
for sec, mark, sim, u, p, note in rows:
|
||||
if sec != cur:
|
||||
cur = sec; L.append(""); L.append(" -- %s" % (sec or "(top)"))
|
||||
where = "%s:%d" % (p.file, p.line) if p else ""
|
||||
L.append(" %s %5s %-58s %-32s %s" % (mark, sim, u.key, where, note))
|
||||
L.append("")
|
||||
L.append("=" * 100)
|
||||
L.append("API declarations not ported (by upstream line; [=] replacements excluded)")
|
||||
L.append("=" * 100)
|
||||
for label, h, n, missing, d in api_rows:
|
||||
L.append(""); L.append(" %s: %d / %d" % (label, h, n))
|
||||
cur = None
|
||||
for k in missing:
|
||||
if d[k][2] != cur: cur = d[k][2]; L.append(" -- %s" % (cur or "(top)"))
|
||||
L.append(" [ ] ImGui::%s" % k)
|
||||
L.append("")
|
||||
L.append("=" * 100)
|
||||
L.append("Enums (values ported / total; missing listed)")
|
||||
L.append("=" * 100)
|
||||
for nm, h, n, missing in enum_rows:
|
||||
if not n: continue
|
||||
L.append(" %-40s %4d / %4d%s" % (nm, h, n, (" missing: " + ", ".join(missing)) if missing else ""))
|
||||
L.append("")
|
||||
L.append("=" * 100)
|
||||
L.append("Struct fields (name found in the port / total; missing listed; [=] replaced by Lua equivalent, excluded from total). Field names are matched globally, so common names may over-count.")
|
||||
L.append("=" * 100)
|
||||
for nm, h, n, missing, repl in field_rows:
|
||||
L.append(" %-40s %4d / %4d%s%s" % (nm, h, n, (" missing: " + ", ".join(missing)) if missing else "",
|
||||
(" [=] " + ", ".join("%s (%s)" % (x, replaced("%s::%s" % (nm, x))) for x in repl)) if repl else ""))
|
||||
out = os.path.join(ROOT, "docs", "PORT_STATUS.txt")
|
||||
open(out, "w").write("\n".join(L) + "\n")
|
||||
print("\nwrote docs/PORT_STATUS.txt")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+19
-2
@@ -113,15 +113,32 @@ def types_header(files):
|
||||
lines += [" [string]: any,", "}"]
|
||||
for name, keys in sorted(enums(files).items()):
|
||||
lines.append("export type %s = { %s, [string]: number }" % (name, ", ".join("%s: number" % k for k in keys)))
|
||||
return lines + module_type(set(enums(files)))
|
||||
return lines + impl_type(files) + module_type(set(enums(files)))
|
||||
|
||||
def wrapper(files):
|
||||
return "\n".join(["--!strict", "-- GENERATED by tools/gen_types.py - do not edit. The library is the child ModuleScript 'Impl'.", ""]
|
||||
+ types_header(files) + ["", "return (require(script:WaitForChild(\"Impl\")) :: any) :: ImGuiModule", ""])
|
||||
|
||||
IMPL_SIGS = { # backend functions with exact types; the rest of ImGui_ImplRoblox is loose
|
||||
"EnableParallel": "(opts: ImGuiParallelConfig?) -> ()",
|
||||
"DisableParallel": "() -> ()", "FinishParallel": "() -> ()", "BeginParallelFrame": "() -> ()",
|
||||
"GetParallelStats": "() -> { [string]: number }",
|
||||
"GetParallelConfig": "() -> ImGuiParallelConfig",
|
||||
}
|
||||
|
||||
def impl_type(files):
|
||||
"""ImGui_ImplRoblox: the keys of the backend's public table (ImGui_ImplRoblox = { Name = ..., })"""
|
||||
src = files.get("imgui_impl_roblox.lua", "")
|
||||
m = re.search(r"^ImGui_ImplRoblox = \{\n(.*?)^\}", src, re.M | re.S)
|
||||
keys = re.findall(r"^\s+(\w+)\s*=", m.group(1), re.M) if m else []
|
||||
return (["export type ImGuiParallelConfig = { Actors: number?, MinTiles: number?, MinPixels: number?,"
|
||||
" MaxBytesPerPixel: number?, Worker: any, Sync: boolean?, SyncDrop: boolean?, Inline: boolean?,"
|
||||
" [string]: any }", "export type ImGuiImplRoblox = {"]
|
||||
+ [" %s: %s," % (k, IMPL_SIGS.get(k, LOOSE)) for k in keys] + [" [string]: any,", "}"])
|
||||
|
||||
def module_type(enum_names):
|
||||
# the bundle is too large for Luau to infer, so its return value is cast to this explicit type
|
||||
lines = ["export type ImGuiModule = {", " ImGui: ImGuiAPI,"]
|
||||
lines = ["export type ImGuiModule = {", " ImGui: ImGuiAPI,", " ImGui_ImplRoblox: ImGuiImplRoblox,"]
|
||||
lines += [" %s: (x: number?, y: number?, z: number?, w: number?) -> %s," % (n, n) for n in ("ImVec2", "ImVec4")]
|
||||
lines += [" %s: %s," % (n, n) for n in sorted(enum_names)]
|
||||
return lines + [" [string]: any,", "}"]
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python3
|
||||
# Minifies a Lua/Luau file: drops comments, indentation, blank lines and spaces that don't separate tokens.
|
||||
# Kept: strings (verbatim), "--!" directive lines (--!optimize, --!native, ...), @native attributes, and one newline
|
||||
# wherever the source had one (so no ambiguous-call issues, and error line numbers stay roughly meaningful).
|
||||
# python3 tools/minify.py IN OUT # write minified IN to OUT
|
||||
# python3 tools/minify.py --same-code F.. # check F.. have the same code tokens as `git show HEAD:F` (comment-only edits)
|
||||
# python3 tools/minify.py --same-code-as OLD NEW # same check between two files
|
||||
# python3 tools/minify.py --test # self-check
|
||||
import re, subprocess, sys
|
||||
from functools import lru_cache
|
||||
|
||||
TOKEN = re.compile(r"""
|
||||
(?P<ws>[ \t\r\n\f\v]+)
|
||||
| (?P<lcom>--\[(?P<ceq>=*)\[.*?\](?P=ceq)\])
|
||||
| (?P<com>--[^\n]*)
|
||||
| (?P<lstr>\[(?P<seq>=*)\[.*?\](?P=seq)\])
|
||||
| (?P<str>"(?:\\.|\\\n|[^"\\\n])*"|'(?:\\.|\\\n|[^'\\\n])*'|`(?:\\.|\\\n|[^`\\])*`)
|
||||
| (?P<num>0[xX][0-9a-fA-F_]*(?:\.[0-9a-fA-F_]*)?(?:[pP][+-]?\d+)?[uUlLi]*|0[bB][01_]+|(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d+)?[uUlLi]*)
|
||||
| (?P<name>@?[A-Za-z_]\w*)
|
||||
| (?P<op>\.\.\.|\.\.=|//=|\.\.|==|~=|<=|>=|//|::|->|[-+*/%^]=|.)
|
||||
""", re.S | re.X)
|
||||
|
||||
def tokenize(src):
|
||||
"""[(kind, text, newline_before)]; comments/whitespace folded into newline_before ("--!" lines kept as 'dir')."""
|
||||
out, nl, pos = [], False, 0
|
||||
while pos < len(src):
|
||||
m = TOKEN.match(src, pos)
|
||||
kind, text = m.lastgroup, m.group(0)
|
||||
if kind in ("ceq", "seq"): kind = "lcom" if text.startswith("--") else "lstr"
|
||||
pos = m.end()
|
||||
if kind == "ws" or kind == "lcom" or (kind == "com" and not text.startswith("--!")):
|
||||
nl = nl or "\n" in text
|
||||
continue
|
||||
if kind == "com": kind = "dir"
|
||||
if kind == "lstr" or kind == "str": kind = "str"
|
||||
out.append((kind, text, nl))
|
||||
nl = False
|
||||
return out
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def glue_ok(a, b):
|
||||
"""True if `a..b` with no space still tokenizes as exactly a, b."""
|
||||
if re.match(r"\w", a[-1]) and re.match(r"\w", b[0]): return False # real lexers read `0then`/`x1` as one token
|
||||
return [t for _, t, _ in tokenize(a + b)] == [a, b]
|
||||
|
||||
def minify(src):
|
||||
toks, out = tokenize(src), []
|
||||
prev = None
|
||||
for kind, text, nl in toks:
|
||||
if prev is not None:
|
||||
if nl or prev[0] == "dir" or kind == "dir": out.append("\n")
|
||||
elif kind == "str" or prev[0] == "str": # strings are self-delimiting; only `[` + `[[` would fuse
|
||||
if kind == "str" and text[0] == "[" and prev[1].endswith("["): out.append(" ")
|
||||
elif not glue_ok(prev[1], text):
|
||||
out.append(" ")
|
||||
out.append(text)
|
||||
prev = (kind, text)
|
||||
return "".join(out) + "\n"
|
||||
|
||||
def code(src):
|
||||
return [(k, t) for k, t, _ in tokenize(src)]
|
||||
|
||||
def test():
|
||||
cases = {
|
||||
"local a = 1 -- c\nlocal b = a - -1\n": "local a=1\nlocal b=a- -1\n",
|
||||
"x = 1 .. 2": "x=1 ..2\n",
|
||||
"x = t[ [[s]] ]": "x=t[ [[s]]]\n",
|
||||
"x = t[ [==[s]==] ]": "x=t[ [==[s]==]]\n",
|
||||
"--!optimize 2\n--[[ long\ncomment ]] local s = 'a -- b' .. \"c\\\"d\"": "--!optimize 2\nlocal s='a -- b'..\"c\\\"d\"\n",
|
||||
"@native\nfunction f(...) return ... end": "@native\nfunction f(...)return...end\n",
|
||||
"a = b == c and d ~= e or f <= g": "a=b==c and d~=e or f<=g\n",
|
||||
"x = 0x10 + 1e-5 + .5": "x=0x10+1e-5+.5\n",
|
||||
"f(a)\n\n\n(g)(b)": "f(a)\n(g)(b)\n",
|
||||
"s = [[a\n-- not a comment\n]]": "s=[[a\n-- not a comment\n]]\n",
|
||||
"x = a / / b": "x=a/ /b\n",
|
||||
"x = a . . b": "x=a. .b\n",
|
||||
"if a == 0 then return 1 end": "if a==0 then return 1 end\n",
|
||||
"x = 1 .. y": "x=1 ..y\n",
|
||||
}
|
||||
for src, want in cases.items():
|
||||
got = minify(src)
|
||||
assert got == want, (src, got, want)
|
||||
assert code(minify(src)) == code(src), src
|
||||
print("minify OK")
|
||||
|
||||
if __name__ == "__main__":
|
||||
if sys.argv[1] == "--test":
|
||||
test()
|
||||
elif sys.argv[1] in ("--same-code", "--same-code-as"):
|
||||
bad = 0
|
||||
pairs = [(sys.argv[2], sys.argv[3])] if sys.argv[1] == "--same-code-as" else [(None, f) for f in sys.argv[2:]]
|
||||
for ref, f in pairs:
|
||||
old = open(ref).read() if ref else subprocess.run(["git", "show", "HEAD:" + f], capture_output=True, text=True, check=True).stdout
|
||||
a, b = code(old), code(open(f).read())
|
||||
if a != b:
|
||||
bad += 1
|
||||
i = next((i for i, (x, y) in enumerate(zip(a, b)) if x != y), min(len(a), len(b)))
|
||||
print("%s: CODE CHANGED at token %d: %r -> %r" % (f, i, a[i:i + 6], b[i:i + 6]))
|
||||
else:
|
||||
print("%s: same code" % f)
|
||||
sys.exit(1 if bad else 0)
|
||||
else:
|
||||
src = open(sys.argv[1], encoding="utf-8").read()
|
||||
dst = minify(src)
|
||||
assert code(dst) == code(src), "minify changed code tokens"
|
||||
open(sys.argv[2], "w", encoding="utf-8").write(dst)
|
||||
print("wrote %s (%d -> %d bytes, %.0f%%)" % (sys.argv[2], len(src.encode()), len(dst.encode()), 100.0 * len(dst) / len(src)))
|
||||
Executable
+61
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env bash
|
||||
# All local checks: CI's "Check" step (release.yml) + every scripted test + whole demo forced open + LÖVE.
|
||||
# Usage: tools/test/check_all.sh (prints PASS/FAIL per check, exit 1 if any failed)
|
||||
# HASHES=1 tools/test/check_all.sh (also prints the draw-data checksums, see hashes.sh)
|
||||
cd "$(dirname "$0")/../.."
|
||||
export PATH="$PATH:/nix/store/2m2ja613nndihc8qm10f2rhq6znp1nh4-luau-0.734/bin:/nix/store/4qxq4arv32ly13kl3g0m5q80gm3a35xr-luajit-2.1.1741730670/bin"
|
||||
command -v luau >/dev/null || { l=$(ls -d /nix/store/*-luau-*/bin 2>/dev/null | tail -1); [ -n "$l" ] && export PATH="$PATH:$l"; }
|
||||
command -v luajit >/dev/null || { l=$(ls -d /nix/store/*-luajit-2*/bin 2>/dev/null | grep -v -- -env | tail -1); [ -n "$l" ] && export PATH="$PATH:$l"; }
|
||||
T=$(mktemp -d /tmp/imgui_check.XXXX)
|
||||
R="python3 tools/test/run.py --quiet --roblox --timeout 600"
|
||||
|
||||
# name | expected output | command
|
||||
CHECKS=(
|
||||
"readme|README OK|$R --main tools/test/scripts/t_readme.luau --frames 30"
|
||||
"readme-min|README OK|MINIFY=1 $R --main tools/test/scripts/t_readme.luau --frames 30"
|
||||
"cached|CACHED OK|$R --main tools/test/scripts/t_cached_window.luau --frames 130"
|
||||
"fixes|FIXES OK|$R --main tools/test/scripts/t_fixes.luau --frames 55"
|
||||
"debugtools|DEBUGTOOLS OK|$R --main tools/test/scripts/t_debugtools.luau --frames 65"
|
||||
"helpers|HELPERS OK|$R --main tools/test/scripts/t_helpers.luau --frames 45"
|
||||
"multiselect|MULTISELECT OK|$R --main tools/test/scripts/t_multiselect.luau --frames 380"
|
||||
"nodemo|NODEMO OK|NO_DEMO=1 $R --main tools/test/scripts/t_nodemo.luau --frames 25"
|
||||
"widgets|OK|$R --main tools/test/scripts/t_widgets.luau --frames 80"
|
||||
"tables|OK|$R --main tools/test/scripts/t_tables.luau --frames 150"
|
||||
"tabs|scrollbtn.true|$R --main tools/test/scripts/t_tabs.luau --frames 60"
|
||||
"modal|round trip ok|$R --main tools/test/scripts/t_modal.luau --frames 40"
|
||||
"dock|DOCK OK|$R --main tools/test/scripts/t_dock.luau --frames 60"
|
||||
"dock_close|DOCK CLOSE OK|$R --main tools/test/scripts/t_dock_close.luau --frames 60"
|
||||
"dock_drag|OK|$R --main tools/test/scripts/t_dock_drag.luau --frames 80"
|
||||
"dock_ini|ROUNDTRIP OK|$R --main tools/test/scripts/t_dock_ini.luau --frames 60"
|
||||
"dock_move|OK|$R --main tools/test/scripts/t_dock_move.luau --frames 80"
|
||||
"passthru|PASSTHRU OK|$R --main tools/test/scripts/t_passthru.luau --frames 40"
|
||||
"fonts|FONTS OK|$R --main tools/test/scripts/t_fonts.luau --frames 8"
|
||||
"textproxy|PROXY OK|$R --main tools/test/scripts/t_textproxy.luau --frames 30"
|
||||
"textproxy_custom|CUSTOM PROXY OK|$R --main tools/test/scripts/t_textproxy_custom.luau --frames 15"
|
||||
"style_editor|SE OK|$R --main tools/test/scripts/t_style_editor.luau --frames 20"
|
||||
"style_leak|STYLE OK|$R --main tools/test/scripts/t_style_leak.luau --frames 60 --open"
|
||||
"apps|APPS OK|$R --main tools/test/scripts/t_apps.luau --frames 120 --open"
|
||||
"libhash|LIBHASH|NO_DEMO=1 $R --main tools/test/scripts/t_libhash.luau --frames 120"
|
||||
"demo_open|DRAWHASH|$R --main tools/test/scripts/t_drawhash.luau --frames 150 --open"
|
||||
"demo_random|^|python3 tools/test/run.py --roblox --timeout 600 --frames 400 --open"
|
||||
"pixels|PIXELS SAME|a=\$($R --main tools/test/scripts/t_pixels.luau --frames 600 | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_pixels.luau --frames 600 | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo PIXELS SAME"
|
||||
"rect_flip|RECTFLIP OK|$R --main tools/test/scripts/t_rect_flip.luau --frames 30"
|
||||
"tile_bound|TILEBOUND OK|$R --main tools/test/scripts/t_tile_bound.luau --frames 200"
|
||||
"parallel|PARALLEL OK|$R --main tools/test/scripts/t_parallel.luau --frames 500"
|
||||
"pool_ctx|POOLCTX OK|$R --main tools/test/scripts/t_pool_ctx.luau --frames 60"
|
||||
"assets_scroll|ASSETS OK|$R --main tools/test/scripts/t_assets_scroll.luau --frames 1010"
|
||||
"shot|wrote|python3 tools/test/shot.py /tmp/imgui_shot.png --app"
|
||||
"registers|REGS OK|mkdir -p $T/regs && python3 tools/bundle.py $T/regs >/dev/null && h=\"\$(printf 'local _h%d = {} ' \$(seq 20))\" && grep -q \"^__FILES\\['imgui_impl_roblox.lua'\\] = function()\$\" $T/regs/ImGui.luau && for f in $T/regs/*.luau; do { echo \"\$h\"; sed \"/^__FILES\\['imgui_impl_roblox.lua'\\] = function()\$/a \$h\" \$f; } > \$f.h && luau-compile -O0 --null \$f.h || exit 1; done && ! grep -q require $T/regs/ImGuiWorker.client.luau && echo REGS OK"
|
||||
"love|DRAWHASH|python3 tools/bundle.py --target love >/dev/null && luajit tools/test/love/t_drawhash.lua 60 Widgets,Basic && luajit tools/test/love/t_examples.lua"
|
||||
)
|
||||
|
||||
run() { # $1=name $2=expect $3=cmd
|
||||
bash -c "$3" > "$T/$1.txt" 2>&1; code=$?
|
||||
if [ $code -eq 0 ] && grep -q "$2" "$T/$1.txt" && ! grep -qiE "error|traceback|stack begin|FAIL" "$T/$1.txt"; then echo "PASS $1"
|
||||
else echo "FAIL $1 (exit $code, log $T/$1.txt)"; tail -5 "$T/$1.txt" | sed 's/^/ /'; fi
|
||||
}
|
||||
for c in "${CHECKS[@]}"; do IFS='|' read -r n e cmd <<< "$c"; run "$n" "$e" "$cmd" & done > "$T/summary.txt"
|
||||
wait
|
||||
sort "$T/summary.txt"
|
||||
[ -n "$HASHES" ] && tools/test/hashes.sh
|
||||
! grep -q "^FAIL" "$T/summary.txt"
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# Draw-data checksums of the working tree vs a git rev (default HEAD), to prove a change renders identically.
|
||||
# tools/test/hashes.sh [rev]
|
||||
# lib = t_libhash (library only, no demo): must stay equal unless rendering is meant to change
|
||||
# demo = t_drawhash with Widgets,Basic / whole demo open: changes with any demo edit
|
||||
cd "$(dirname "$0")/../.."
|
||||
export PATH="$PATH:/nix/store/2m2ja613nndihc8qm10f2rhq6znp1nh4-luau-0.734/bin:/nix/store/4qxq4arv32ly13kl3g0m5q80gm3a35xr-luajit-2.1.1741730670/bin"
|
||||
REV=${1:-HEAD}
|
||||
hashes() { # $1 = repo dir
|
||||
( cd "$1"
|
||||
R="python3 tools/test/run.py --quiet --roblox --timeout 600"
|
||||
echo "lib $(NO_DEMO=1 $R --main "$OLDPWD/tools/test/scripts/t_libhash.luau" --frames 120 | grep -o 'LIBHASH.*')" &
|
||||
echo "demo-basic $($R --main tools/test/scripts/t_drawhash.luau --frames 150 --open-only Widgets,Basic | grep -o 'DRAWHASH.*')" &
|
||||
echo "demo-all $($R --main tools/test/scripts/t_drawhash.luau --frames 150 --open | grep -o 'DRAWHASH.*')" &
|
||||
echo "love-basic $(python3 tools/bundle.py --target love >/dev/null; luajit tools/test/love/t_drawhash.lua 60 Widgets,Basic | grep -o 'DRAWHASH.*')" &
|
||||
wait ) | tr "\t" " " | sort
|
||||
}
|
||||
W=$(mktemp -d /tmp/imgui_rev.XXXX)
|
||||
git worktree add -q --detach "$W" "$REV"
|
||||
hashes "$W" > "$W.old" & hashes . > "$W.new"; wait
|
||||
git worktree remove --force "$W"
|
||||
echo "check $REV working tree"
|
||||
paste "$W.old" "$W.new" | awk -F'\t' '{split($1,a," "); split($2,b," "); printf "%-12s %-30s %-30s %s\n", a[1], a[3], b[3], (a[3]==b[3]?"same":"CHANGED")}'
|
||||
@@ -4,4 +4,4 @@ set -e
|
||||
cd "$(dirname "$0")/../../.."
|
||||
python3 tools/bundle.py --target love >/dev/null
|
||||
nix-shell -p luajit --run "luajit tools/test/love/t_drawhash.lua 150 Widgets,Basic && luajit tools/test/love/t_drawhash.lua 150 all && luajit tools/test/love/t_examples.lua"
|
||||
echo "expected (Luau, tools/test/scripts/t_drawhash.luau): 1385106188 / 1292122782"
|
||||
echo "expected (Luau, tools/test/scripts/t_drawhash.luau): 154977593 / 263656315"
|
||||
@@ -1,5 +1,5 @@
|
||||
-- Runs examples/example_love and examples/example_shared main.lua headless under LuaJIT (mock love) for some frames.
|
||||
for _, ex in ipairs({ "examples/example_love", "examples/example_shared" }) do
|
||||
-- Runs examples/example_love main.lua headless under LuaJIT (mock love) for some frames.
|
||||
for _, ex in ipairs({ "examples/example_love" }) do
|
||||
dofile("tools/test/love/mock_love.lua")
|
||||
love.filesystem.getSource = function() return ex end
|
||||
love.filesystem.load = function(p) return assert(loadfile(ex .. "/" .. p)) end
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ tmp = max(glob.glob("/tmp/imgui_test_*/ImGui.linemap.json"), key=os.path.getmtim
|
||||
lm = json.load(open(tmp))
|
||||
def loc(n):
|
||||
if not n.isdigit(): return "C"
|
||||
n = int(n) - 5 + 2; best = None
|
||||
n = int(n) - 5 + 1; best = None # run.luau header lines, 1 stripped --! line (see run.py)
|
||||
for start, name in lm:
|
||||
if start <= n: best = (start, name)
|
||||
return "%s:%d" % (best[1], n - best[0] + 1) if best else "?"
|
||||
|
||||
@@ -58,6 +58,8 @@ end })
|
||||
-- Instances
|
||||
local InstMethods = {}
|
||||
local InstMT = {}
|
||||
local MOCK = { Sets = 0, Parents = 0, News = 0, EIs = 0, Uploads = 0, UploadPx = 0 } -- engine call counters (global MOCK), for perf benches
|
||||
MOCK_STATS = MOCK
|
||||
InstMT.__index = function(t, k)
|
||||
if k == "Parent" then return rawget(t, "_parent") end
|
||||
local pv = rawget(t, "_props")[k]; if pv ~= nil then return pv end
|
||||
@@ -67,11 +69,13 @@ InstMT.__index = function(t, k)
|
||||
end
|
||||
InstMT.__newindex = function(t, k, v)
|
||||
if k == "Parent" then
|
||||
MOCK.Parents += 1
|
||||
local old = rawget(t, "_parent")
|
||||
if old then local ch = rawget(old, "_children"); for i, c in ipairs(ch) do if c == t then table.remove(ch, i) break end end end
|
||||
rawset(t, "_parent", v)
|
||||
if v then table.insert(rawget(v, "_children"), t) end
|
||||
else
|
||||
MOCK.Sets += 1
|
||||
local props = rawget(t, "_props")
|
||||
local old = props[k]
|
||||
props[k] = v
|
||||
@@ -96,6 +100,11 @@ end
|
||||
function InstMethods:WaitForChild(name) return assert(self:FindFirstChild(name), "WaitForChild would hang: " .. name) end
|
||||
function InstMethods:FindFirstChildOfClass(class) for _, c in ipairs(rawget(self, "_children")) do if c.ClassName == class then return c end end end
|
||||
function InstMethods:GetChildren() return table.clone(rawget(self, "_children")) end
|
||||
function InstMethods:GetDescendants()
|
||||
local out = {}
|
||||
for _, c in ipairs(rawget(self, "_children")) do table.insert(out, c); for _, d in ipairs(c:GetDescendants()) do table.insert(out, d) end end
|
||||
return out
|
||||
end
|
||||
function InstMethods:IsA(class)
|
||||
if class == "GuiObject" then return self.ClassName == "Frame" or self.ClassName == "ImageLabel" end
|
||||
return self.ClassName == class
|
||||
@@ -124,12 +133,14 @@ local RunService = { Heartbeat = Signal(), Stepped = Signal(), PreAnimation = Si
|
||||
local last_pixels -- last buffer written to an EditableImage
|
||||
local AssetService = {}
|
||||
function AssetService:CreateEditableImage(opts)
|
||||
MOCK.EIs += 1
|
||||
local img = { Size = opts.Size, Pixels = buffer.create(opts.Size.X * opts.Size.Y * 4) }
|
||||
UPLOADS = 0
|
||||
function img:WritePixelsBuffer(origin, size, buf)
|
||||
assert(buffer.len(buf) == size.X * size.Y * 4, "WritePixelsBuffer: buffer size mismatch")
|
||||
assert(origin.X >= 0 and origin.Y >= 0 and origin.X + size.X <= opts.Size.X and origin.Y + size.Y <= opts.Size.Y, "WritePixelsBuffer: out of bounds")
|
||||
for y = 0, size.Y - 1 do buffer.copy(img.Pixels, ((origin.Y + y) * opts.Size.X + origin.X) * 4, buf, y * size.X * 4, size.X * 4) end
|
||||
MOCK.Uploads += 1; MOCK.UploadPx += size.X * size.Y
|
||||
_G_UPLOADS = (_G_UPLOADS or 0) + 1; _G_UPLOAD_PX = (_G_UPLOAD_PX or 0) + size.X * size.Y
|
||||
end
|
||||
function img:Destroy() end
|
||||
@@ -168,7 +179,7 @@ end
|
||||
|
||||
ROBLOX = setmetatable({
|
||||
game = game, workspace = { CurrentCamera = { ViewportSize = v2(SCREEN_W, SCREEN_H) } }, require = rbxrequire, _G = fakeG,
|
||||
Instance = { new = function(class) return newInst(class) end },
|
||||
Instance = { new = function(class) MOCK.News += 1; return newInst(class) end },
|
||||
Enum = Enum, Vector2 = Vector2,
|
||||
Vector3 = { new = function(x, y, z) return { X = x, Y = y, Z = z } end },
|
||||
UDim2 = { new = function(...) return { ... } end, fromScale = function(...) return { ... } end, fromOffset = function(x, y) return { X = x, Y = y } end },
|
||||
@@ -181,6 +192,7 @@ ROBLOX = setmetatable({
|
||||
}, { __index = realG })
|
||||
|
||||
local mod = newInst("ModuleScript", "ImGui", ReplicatedStorage); rawset(mod, "_src", "ImGui.luau")
|
||||
for _, name in EXTRA_MODULES or {} do rawset(newInst("ModuleScript", name, ReplicatedStorage), "_src", name) end
|
||||
-- Run main.lua as a LocalScript
|
||||
local main = loadAsScript("main.client.luau", newInst("LocalScript", "main"))
|
||||
main()
|
||||
|
||||
+14
-6
@@ -11,20 +11,28 @@ TMP = tempfile.mkdtemp(prefix="imgui_test_") # per process: parallel runs must
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(os.path.dirname(HERE))
|
||||
LUAU = shutil.which("luau") or "/nix/store/2m2ja613nndihc8qm10f2rhq6znp1nh4-luau-0.734/bin/luau"
|
||||
LUAU = shutil.which("luau") or (sorted(__import__("glob").glob("/nix/store/*-luau-*/bin/luau")) or ["luau"])[-1]
|
||||
G = "game, workspace, Instance, Enum, Vector2, Vector3, UDim2, Color3, Content, UDim, CFrame, warn, require, script, os"
|
||||
|
||||
def build_run(args, flags):
|
||||
subprocess.run([sys.executable, os.path.join(ROOT, "tools", "bundle.py"), TMP] + (["--no-demo"] if os.environ.get("NO_DEMO") else []), check=True, stdout=subprocess.DEVNULL)
|
||||
if os.environ.get("MINIFY"): # test the minified bundle instead (error line numbers won't map back to sources)
|
||||
subprocess.run([sys.executable, os.path.join(ROOT, "tools", "minify.py"), os.path.join(TMP, "ImGui.luau"), os.path.join(TMP, "ImGui.luau")], check=True, stdout=subprocess.DEVNULL)
|
||||
out = ["--" if args.roblox else "--!native", "--!optimize 2", flags, "local SOURCE_FNS = {}"]
|
||||
def add(key, path):
|
||||
s = "\n".join(l for l in open(path).read().split("\n") if not l.startswith("--!"))
|
||||
out.append("SOURCE_FNS[%r] = function(%s)\n%s\nend" % (key, G, s))
|
||||
add("ImGui.luau", os.path.join(TMP, "ImGui.luau"))
|
||||
add("main.client.luau", args.main)
|
||||
for m in args.module: # [extensions] NAME=path -> ReplicatedStorage.NAME ModuleScript
|
||||
name, path = m.split("=", 1)
|
||||
add(name, path)
|
||||
out.append("EXTRA_MODULES = {%s}" % ",".join(repr(m.split("=", 1)[0]) for m in args.module))
|
||||
out.append(open(os.path.join(HERE, "roblox_mock.luau")).read())
|
||||
global OFFSET, LAST_LINE
|
||||
LAST_LINE = open(os.path.join(TMP, "ImGui.luau")).read().count("\n")
|
||||
global OFFSET, LAST_LINE, STRIPPED
|
||||
bundle = open(os.path.join(TMP, "ImGui.luau")).read()
|
||||
LAST_LINE = bundle.count("\n")
|
||||
STRIPPED = sum(l.startswith("--!") for l in bundle.split("\n")) # removed by add() (all at the top)
|
||||
OFFSET = 5 # lines before the ImGui function body in run.luau (flags/header lines + "function(...)" line)
|
||||
path = os.path.join(TMP, "run.luau")
|
||||
open(path, "w").write("\n".join(out))
|
||||
@@ -43,8 +51,7 @@ def remap(text):
|
||||
import json, re
|
||||
lm = json.load(open(os.path.join(TMP, "ImGui.linemap.json")))
|
||||
def sub(m):
|
||||
n = int(m.group(1)) - OFFSET # line inside build/ImGui.luau (minus its 2 stripped --! lines)
|
||||
n += 2
|
||||
n = int(m.group(1)) - OFFSET + STRIPPED # line inside build/ImGui.luau
|
||||
best = None
|
||||
if n > LAST_LINE: return "<harness>:%d" % n
|
||||
for start, name in lm:
|
||||
@@ -63,10 +70,11 @@ def main():
|
||||
ap.add_argument("--profile", action="store_true", help="sampling profile (no codegen) -> profile.out; see tools/test/prof.py")
|
||||
ap.add_argument("--open", action="store_true", help="force all CollapsingHeader/TreeNode open")
|
||||
ap.add_argument("--timeout", type=int, default=120)
|
||||
ap.add_argument("--module", action="append", default=[], help="NAME=path: extra ModuleScript in ReplicatedStorage (extension repos)")
|
||||
ap.add_argument("--quiet", action="store_true", help="no random input (scripted tests drive io themselves)")
|
||||
args = ap.parse_args()
|
||||
|
||||
code, out = run(args, "")
|
||||
code, out = run(args, os.environ.get("RUN_FLAGS", ""))
|
||||
print(out if os.environ.get("FULL_OUTPUT") else out[-4000:])
|
||||
sys.exit(code)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ io.ConfigFlags = bit32.bor(io.ConfigFlags, G.ImGuiConfigFlags.DockingEnable)
|
||||
G.ImGui_ImplRoblox.Init()
|
||||
local names = { "ShowExampleAppConsole", "ShowExampleAppLog", "ShowExampleAppLayout", "ShowExampleAppPropertyEditor", "ShowExampleAppLongText",
|
||||
"ShowExampleAppAutoResize", "ShowExampleAppConstrainedResize", "ShowExampleAppSimpleOverlay", "ShowExampleAppWindowTitles",
|
||||
"ShowExampleAppCustomRendering", "ShowExampleAppDocuments", "ShowExampleAppDockSpace", "ShowExampleAppFullscreen", "ShowExampleAppAssetsBrowser", "ShowExampleAppMainMenuBar" }
|
||||
"ShowExampleAppCustomRendering", "ShowExampleAppDocuments", "ShowExampleAppDockSpace", "ShowExampleAppFullscreen", "ShowExampleAppAssetsBrowser", "ShowExampleAppMainMenuBar", "ShowExampleAppImageViewer" }
|
||||
local tools = { "ShowMetricsWindow", "ShowDebugLogWindow", "ShowIDStackToolWindow", "ShowAboutWindow" }
|
||||
local open = {}
|
||||
local frame = 0
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
-- Demo Assets Browser (10000 items) scrolled continuously for ~1000 frames in raster mode: live tiles and
|
||||
-- EditableImage bytes must stay bounded by what is visible and flat (no growth trend between the 1st and 2nd half).
|
||||
-- Then (no input) the screen composited from those tiles (many recycled from the free list) must equal the one after
|
||||
-- rebuilding every tile from scratch: a recycled EditableImage never shows stale pixels.
|
||||
-- run: python3 tools/test/run.py --main tools/test/scripts/t_assets_scroll.luau --frames 1010 --quiet --roblox
|
||||
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2 = G.ImGui, G.ImVec2
|
||||
local Impl = G.ImGui_ImplRoblox
|
||||
ImGui.CreateContext()
|
||||
Impl.Init()
|
||||
Impl.SetRenderRate(0)
|
||||
local io = ImGui.GetIO()
|
||||
local N = 1000
|
||||
local frame, open = 0, true
|
||||
local peak = { { 0, 0, 0 }, { 0, 0, 0 } } -- per half: tiles, EI count, EI bytes
|
||||
local scroll_min, scroll_max = math.huge, 0
|
||||
local W, H = 1280, 760 -- (composite: copied from t_composite.luau)
|
||||
local function composite(gui)
|
||||
local screen = buffer.create(W * H * 3)
|
||||
local function walk(inst, ox, oy, kx0, ky0, kx1, ky1)
|
||||
local kids = inst:GetChildren()
|
||||
table.sort(kids, function(a, b) return (a.ZIndex or 1) < (b.ZIndex or 1) end) -- table.sort isn't stable, but siblings with equal ZIndex never overlap here
|
||||
for _, c in ipairs(kids) do
|
||||
if c.Visible ~= false then
|
||||
local x, y = ox + (c.Position and c.Position.X or 0), oy + (c.Position and c.Position.Y or 0)
|
||||
local cx0, cy0, cx1, cy1 = kx0, ky0, kx1, ky1
|
||||
if c.ClipsDescendants then
|
||||
cx0, cy0 = math.max(cx0, x), math.max(cy0, y)
|
||||
cx1, cy1 = math.min(cx1, x + c.Size.X), math.min(cy1, y + c.Size.Y)
|
||||
end
|
||||
if c.ClassName == "ImageLabel" then
|
||||
local img = c.ImageContent.Object
|
||||
local px, sz = img.Pixels, img.Size.X
|
||||
for ty = 0, sz - 1 do
|
||||
local sy = y + ty
|
||||
if sy >= ky0 and sy < ky1 then
|
||||
for tx = 0, sz - 1 do
|
||||
local sx = x + tx
|
||||
if sx >= kx0 and sx < kx1 then
|
||||
local o = (ty * sz + tx) * 4
|
||||
local a = buffer.readu8(px, o + 3)
|
||||
if a > 0 then
|
||||
local d = (sy * W + sx) * 3
|
||||
local fa = a / 255
|
||||
for ch = 0, 2 do
|
||||
local v = buffer.readu8(px, o + ch) * fa + buffer.readu8(screen, d + ch) * (1 - fa)
|
||||
buffer.writeu8(screen, d + ch, math.floor(v + 0.5))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(c, x, y, cx0, cy0, cx1, cy1)
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(gui, 0, 0, 0, 0, W, H)
|
||||
return screen
|
||||
end
|
||||
local before
|
||||
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
frame += 1
|
||||
if frame > N + 10 then return end
|
||||
Impl.NewFrame()
|
||||
io.DeltaTime = 1 / 60
|
||||
ImGui.NewFrame()
|
||||
ImGui.SetNextWindowPos(ImVec2(20, 20), G.ImGuiCond.Always)
|
||||
open = G.ShowExampleAppAssetsBrowser(open)
|
||||
local w = ImGui.FindWindowByName("Example: Assets Browser")
|
||||
if w and frame > 2 and frame <= N then
|
||||
io:AddMousePosEvent(w.Pos.x + w.Size.x / 2, w.Pos.y + w.Size.y / 2)
|
||||
io:AddMouseWheelEvent(0, (frame % 400 < 250) and -2 or 3) -- down, then back up: continuous, both directions
|
||||
end
|
||||
ImGui.Render()
|
||||
Impl.RenderDrawData(ImGui.GetDrawData())
|
||||
local s
|
||||
if Impl.GetStats then s = Impl.GetStats() else -- (older backends, for before/after numbers: 1 EditableImage per tile)
|
||||
local n = 0
|
||||
for _, d in ipairs(game:GetService("Players").LocalPlayer.PlayerGui:GetDescendants()) do if d.ClassName == "ImageLabel" and d.Name:sub(1, 4) == "Tile" then n += 1 end end
|
||||
s = { Tiles = n, EditableImages = n, EditableImageBytes = n * 65536, EditableImageCap = math.huge }
|
||||
end
|
||||
assert(s.EditableImageBytes <= s.EditableImageCap)
|
||||
for _, c in ipairs(w and w.DC.ChildWindows.Data or {}) do scroll_min = math.min(scroll_min, c.Scroll.y); scroll_max = math.max(scroll_max, c.Scroll.y) end
|
||||
if frame > 50 then
|
||||
local p = peak[frame <= 525 and 1 or 2]
|
||||
p[1], p[2], p[3] = math.max(p[1], s.Tiles), math.max(p[2], s.EditableImages), math.max(p[3], s.EditableImageBytes)
|
||||
end
|
||||
if frame == N then
|
||||
print(("ASSETS scrolled %d..%d px; peak tiles %d / %d, EditableImages %d / %d, EI bytes %d / %d (1st / 2nd half); now %d tiles"):format(
|
||||
scroll_min, scroll_max, peak[1][1], peak[2][1], peak[1][2], peak[2][2], peak[1][3], peak[2][3], s.Tiles))
|
||||
assert(scroll_max - scroll_min > 5000, "assets browser did not scroll")
|
||||
-- the whole demo-sized screen is ~ 10 x 6 tiles per layer; content + chrome + spares + free list stay well below 150
|
||||
assert(peak[1][1] <= 150 and peak[2][1] <= 150, "tile count not bounded by what is visible")
|
||||
assert(peak[2][2] <= peak[1][2] + 4 and peak[2][3] <= peak[1][3] + 4 * 128 * 128 * 4, "EditableImage use grows over time")
|
||||
end
|
||||
if frame == N + 8 then
|
||||
before = buffer.tostring(composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui")))
|
||||
Impl.SetRenderScale(2); Impl.SetRenderScale(1) -- (drops every tile: the next frame redraws all of them)
|
||||
elseif frame == N + 9 then
|
||||
local after = buffer.tostring(composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui")))
|
||||
assert(#before:gsub("%z", "") > 10000, "nothing composited")
|
||||
assert(before == after, "recycled tiles show different pixels than freshly drawn ones")
|
||||
print("ASSETS OK")
|
||||
end
|
||||
end)
|
||||
@@ -0,0 +1,92 @@
|
||||
-- Debug tools + misc imgui.cpp ports: item picker, DebugFlashStyleColor, DebugLocateItem, context hooks, AddInputCharactersUTF8, ImBezierCubicClosestPoint
|
||||
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2 = G.ImGui, G.ImVec2
|
||||
local ctx = ImGui.CreateContext(); G.ImGui_ImplRoblox.Init()
|
||||
local io = ImGui.GetIO()
|
||||
local failed = {}
|
||||
local function check(ok, msg) if not ok then table.insert(failed, msg); print("FAIL " .. msg) end end
|
||||
|
||||
-- ImBezierCubicClosestPoint: straight-line cubic (0,0)-(30,0)-(60,0)-(90,0): closest point to (45,10) is (45,0)
|
||||
local p1, p2, p3, p4 = ImVec2(0, 0), ImVec2(30, 0), ImVec2(60, 0), ImVec2(90, 0)
|
||||
local cp = G.ImBezierCubicClosestPoint(p1, p2, p3, p4, ImVec2(45, 10), 20)
|
||||
check(math.abs(cp.x - 45) < 1e-3 and math.abs(cp.y) < 1e-6, ("ImBezierCubicClosestPoint %g,%g"):format(cp.x, cp.y))
|
||||
-- Curved: result must lie on the curve (distance to a dense sampling of the curve ~0) and beat the endpoints
|
||||
local q1, q2, q3, q4 = ImVec2(0, 0), ImVec2(0, 100), ImVec2(100, 100), ImVec2(100, 0)
|
||||
local target = ImVec2(50, 120)
|
||||
for _, r in { G.ImBezierCubicClosestPoint(q1, q2, q3, q4, target, 64), G.ImBezierCubicClosestPointCasteljau(q1, q2, q3, q4, target, 0.25) } do
|
||||
check(math.abs(r.x - 50) < 0.5 and math.abs(r.y - 75) < 0.5, ("closest point on curve %g,%g (expected ~50,75)"):format(r.x, r.y))
|
||||
end
|
||||
|
||||
-- AddInputCharactersUTF8 queues one Text event per codepoint
|
||||
io:AddInputCharactersUTF8("a\u{e9}\u{20ac}\u{1F600}")
|
||||
local chars = {}
|
||||
for _, e in ctx.InputEventsQueue.Data do if e.Type == G.ImGuiInputEventType.Text then table.insert(chars, e.Text.Char) end end
|
||||
-- (this build has IM_UNICODE_CODEPOINT_MAX = 0xFFFF like upstream's default ImWchar16: U+1F600 becomes IM_UNICODE_CODEPOINT_INVALID)
|
||||
check(#chars == 4 and chars[1] == 0x61 and chars[2] == 0xE9 and chars[3] == 0x20AC and chars[4] == ((G.IM_UNICODE_CODEPOINT_MAX >= 0x1F600) and 0x1F600 or 0xFFFD), "AddInputCharactersUTF8 " .. table.concat(chars, ","))
|
||||
|
||||
-- Context hooks
|
||||
local log = {}
|
||||
local function hook(t, name)
|
||||
local h = G.ImGuiContextHook(); h.Type = t; h.Callback = function(c, hk) table.insert(log, name) end
|
||||
return ImGui.AddContextHook(ctx, h)
|
||||
end
|
||||
local T = G.ImGuiContextHookType
|
||||
hook(T.NewFramePre, "nfpre"); hook(T.NewFramePost, "nfpost"); hook(T.RenderPre, "rpre"); local rpost = hook(T.RenderPost, "rpost")
|
||||
|
||||
-- Context defaults (ImGuiContext()/ImGuiIO() constructors, upstream values)
|
||||
check(ctx.DebugFlashStyleColorIdx == G.ImGuiCol.COUNT and ctx.ActiveIdSource == G.ImGuiInputSource.None and io.MouseSource == G.ImGuiMouseSource.Mouse
|
||||
and ctx.DebugBreakKeyChord == G.ImGuiKey.Pause and ctx.DebugItemPickerActive == false and ctx.DebugLocateId == 0 and ctx.CurrentPixelDensity == 1.0, "context defaults")
|
||||
check(T.PendingRemoval_ == 7 and T.Shutdown == 6, "ImGuiContextHookType values")
|
||||
check(io.BackendPlatformName == "imgui_impl_roblox" and io.BackendRendererName == "imgui_impl_roblox", "BackendPlatformName/BackendRendererName")
|
||||
check((os.date == nil) == (ImGui.GetPlatformIO().Platform_SessionDate == 0), "Platform_SessionDate set from os.date() when available") -- (the test sandbox has no os.date)
|
||||
ImGui.GetPlatformIO().Platform_SessionDate = 20261015 -- exercise the metrics Settings section date code
|
||||
|
||||
-- Style color flash
|
||||
local col = ImGui.GetStyle().Colors[G.ImGuiCol.Button]
|
||||
local orig = { col.x, col.y, col.z, col.w }
|
||||
|
||||
local f, rect, picked, broke, button_id = 0, nil, nil, 0, 0
|
||||
ctx.DebugBreakCallback = function() broke += 1 end
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
f += 1
|
||||
G.ImGui_ImplRoblox.NewFrame()
|
||||
if rect and f == 5 then io:AddMousePosEvent((rect[1].x + rect[2].x) / 2, (rect[1].y + rect[2].y) / 2) end
|
||||
if f == 6 then ImGui.DebugStartItemPicker() end
|
||||
if f == 8 then io:AddMouseButtonEvent(0, true) elseif f == 9 then io:AddMouseButtonEvent(0, false) end
|
||||
ImGui.NewFrame()
|
||||
if f == 1 then check(table.concat(log, " ") == "nfpre nfpost", "hooks after NewFrame: " .. table.concat(log, " ")) end
|
||||
if f == 8 then picked = ctx.DebugItemPickerBreakId end
|
||||
if f == 3 then ImGui.DebugFlashStyleColor(G.ImGuiCol.Button) end
|
||||
ImGui.SetNextWindowPos(ImVec2(10, 10), G.ImGuiCond.Always)
|
||||
ImGui.Begin("DebugTools")
|
||||
ImGui.Button("Target")
|
||||
if f == 2 then local a, b = ImGui.GetItemRectMin(), ImGui.GetItemRectMax(); rect = { ImVec2(a.x, a.y), ImVec2(b.x, b.y) } end
|
||||
local target_id = ctx.LastItemData.ID
|
||||
button_id = target_id
|
||||
if f == 12 then ImGui.DebugLocateItem(target_id) end
|
||||
if f == 13 then check(ctx.DebugLocateId == 0, "DebugLocateItem resolved by ItemAdd()") end
|
||||
ImGui.DebugDrawItemRect(); ImGui.DebugDrawCursorPos(); ImGui.DebugDrawLineExtents()
|
||||
ImGui.DebugTextUnformattedWithLocateItem(("id 0x%08X here"):format(target_id))
|
||||
ImGui.End()
|
||||
if f == 3 then -- open the metrics Settings/InputText sections
|
||||
local mw = ImGui.FindWindowByName("Dear ImGui Metrics/Debugger")
|
||||
for _, lbl in { "Settings", "SettingsWindows", "SettingsTables", "InputText" } do mw.DC.StateStorage[mw:GetID(lbl)] = true end
|
||||
ctx.DebugMetricsConfig.SettingsHighlightOldEntries = true
|
||||
end
|
||||
ImGui.SetNextWindowPos(ImVec2(400, 10), G.ImGuiCond.Always); ImGui.ShowMetricsWindow()
|
||||
ImGui.SetNextWindowPos(ImVec2(400, 300), G.ImGuiCond.Always); ImGui.ShowDebugLogWindow()
|
||||
if f == 4 then
|
||||
local c = ImGui.GetStyle().Colors[G.ImGuiCol.Button]
|
||||
check(c.w == 1.0 and ctx.DebugFlashStyleColorIdx == G.ImGuiCol.Button, "flash active")
|
||||
end
|
||||
ImGui.Render(); G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
if f == 1 then check(table.concat(log, " ") == "nfpre nfpost rpre rpost", "hooks after Render: " .. table.concat(log, " ")); ImGui.RemoveContextHook(ctx, rpost) end
|
||||
if f == 2 then check(table.concat(log, " ") == "nfpre nfpost rpre rpost nfpre nfpost rpre", "RemoveContextHook: " .. table.concat(log, " ")) end
|
||||
if f == 60 then
|
||||
local c = ImGui.GetStyle().Colors[G.ImGuiCol.Button]
|
||||
check(c.x == orig[1] and c.y == orig[2] and c.z == orig[3] and c.w == orig[4] and ctx.DebugFlashStyleColorIdx == G.ImGuiCol.COUNT, "flash restored color exactly")
|
||||
check(picked ~= nil and picked ~= 0 and picked == button_id, ("item picker set DebugItemPickerBreakId (%s vs %s)"):format(tostring(picked), tostring(button_id)))
|
||||
check(not ctx.DebugItemPickerActive and broke >= 1, ("item picker break hook called (%d)"):format(broke))
|
||||
if #failed == 0 then print("DEBUGTOOLS OK") end
|
||||
end
|
||||
end)
|
||||
@@ -0,0 +1,142 @@
|
||||
-- Regressions vs upstream: clipboard paste filter (InputTextEx), ImParseFormatTrimDecorations (Ctrl+click temp input), ShrinkWidths tie order,
|
||||
-- CalcItemSize by value, PushClipRectFullScreen (drop target outside clip rect), long TextUnformatted, PushFont/PopFont, InputTextMultiline line index (render/scroll/edit), Shortcut() default
|
||||
-- args, IsWindowAppearing() on frame 1 (FrameCount starts at 0), ColorButton -> ColorEdit4 drag and drop
|
||||
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2 = G.ImGui, G.ImVec2
|
||||
ImGui.CreateContext()
|
||||
ImGui.GetIO().Fonts:AddFontDefault()
|
||||
local font2 = ImGui.GetIO().Fonts:AddFontDefault() -- second font for the PushFont/PopFont check
|
||||
G.ImGui_ImplRoblox.Init()
|
||||
local io = ImGui.GetIO()
|
||||
local failed = {}
|
||||
local function check(ok, msg) if not ok then table.insert(failed, msg); print("FAIL " .. msg) end end
|
||||
|
||||
-- ShrinkWidths: equal widths sort by Index descending (upstream ShrinkWidthItemComparer), so the rounding remainder goes to the highest Index first
|
||||
local items = {}
|
||||
for i = 1, 4 do local it = G.ImGuiShrinkWidthItem(); it.Index = i - 1; it.Width = 100; it.InitialWidth = 100; items[i] = it end
|
||||
ImGui.ShrinkWidths(items, 1, 4, 2.0, 10.0)
|
||||
local w = {}
|
||||
for _, it in items do w[it.Index] = it.Width end
|
||||
check(w[3] == 100 and w[2] == 100 and w[1] == 99 and w[0] == 99, ("ShrinkWidths widths %s %s %s %s"):format(w[0], w[1], w[2], w[3]))
|
||||
|
||||
check(G.ImFloor(-1.5) == -2 and G.ImFloor(-0.2) == -1 and G.ImFloor(2.7) == 2, "ImFloor negative")
|
||||
|
||||
local long_text = {}
|
||||
for i = 1, 300 do long_text[i] = string.format("line %04d", i) end
|
||||
long_text = table.concat(long_text, "\n") -- 2999 bytes
|
||||
|
||||
local function edit_text()
|
||||
local st = ImGui.GetCurrentContext().InputTextState
|
||||
return G.ImGui._ByteArrayToString(st.TextA.Data, 1, st.TextLen + 1)
|
||||
end
|
||||
local buf = ImGui.NewTextBuffer("", 64)
|
||||
local f, sf, di = 0, 45.0, 50
|
||||
local rects = {}
|
||||
local function rect() local a, b = ImGui.GetItemRectMin(), ImGui.GetItemRectMax(); return { ImVec2(a.x, a.y), ImVec2(b.x, b.y) } end -- copies: GetItemRectMin() returns the live LastItemData.Rect.Min
|
||||
local function click(name, ctrl)
|
||||
local r = rects[name]
|
||||
io:AddMousePosEvent((r[1].x + r[2].x) / 2, (r[1].y + r[2].y) / 2)
|
||||
if ctrl then io:AddKeyEvent(G.ImGuiMod_Ctrl, true) end
|
||||
io:AddMouseButtonEvent(0, true)
|
||||
end
|
||||
local function release() io:AddMouseButtonEvent(0, false); io:AddKeyEvent(G.ImGuiMod_Ctrl, false) end
|
||||
local function key(k) io:AddKeyEvent(k, true); io:AddKeyEvent(k, false) end
|
||||
local function center(name) local r = rects[name]; return (r[1].x + r[2].x) / 2, (r[1].y + r[2].y) / 2 end
|
||||
local ml_text = "line1\nline2\nline3\nline4\nline5\nline6"
|
||||
local mbuf = ImGui.NewTextBuffer(ml_text, 256)
|
||||
local wbuf = ImGui.NewTextBuffer("a long line that has to be word wrapped several times inside the narrow box\nsecond", 256)
|
||||
local shortcut_frames = {}
|
||||
local cb_col, ce_col = G.ImVec4(1, 0, 0, 1), { 0, 0, 0, 1 }
|
||||
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
f += 1
|
||||
G.ImGui_ImplRoblox.NewFrame()
|
||||
if f == 3 then click("t") elseif f == 4 then release() end
|
||||
-- clipboard: tab is filtered out (single line, no AllowTabInput), é is 2 bytes
|
||||
if f == 6 then ImGui.SetClipboardText("ab\tc\u{e9}"); io:AddKeyEvent(G.ImGuiMod_Ctrl, true); io:AddKeyEvent(G.ImGuiKey.V, true) end
|
||||
if f == 7 then io:AddKeyEvent(G.ImGuiKey.V, false); io:AddKeyEvent(G.ImGuiMod_Ctrl, false) end
|
||||
if f == 9 then key(G.ImGuiKey.Escape) end
|
||||
if f == 11 then click("s", true) elseif f == 12 then release() end
|
||||
if f == 14 then key(G.ImGuiKey.Escape) end
|
||||
if f == 16 then click("d", true) elseif f == 17 then release() end
|
||||
-- multi-line: click, Ctrl+End, type "x", Enter, "y"
|
||||
if f == 21 then click("m") elseif f == 22 then release() end
|
||||
if f == 23 then io:AddKeyEvent(G.ImGuiMod_Ctrl, true); io:AddKeyEvent(G.ImGuiKey.End, true) end
|
||||
if f == 24 then io:AddKeyEvent(G.ImGuiKey.End, false); io:AddKeyEvent(G.ImGuiMod_Ctrl, false) end
|
||||
if f == 25 then io:AddInputCharacter(string.byte("x")) end
|
||||
if f == 26 then key(G.ImGuiKey.Enter) end
|
||||
if f == 28 then io:AddInputCharacter(string.byte("y")) end
|
||||
if f == 29 then io:AddKeyEvent(G.ImGuiMod_Ctrl, true); io:AddKeyEvent(G.ImGuiKey.A, true) end -- select all: renders the multi-line selection
|
||||
if f == 30 then io:AddKeyEvent(G.ImGuiKey.A, false); io:AddKeyEvent(G.ImGuiMod_Ctrl, false) end
|
||||
if f == 31 then key(G.ImGuiKey.Escape) end
|
||||
-- Shortcut(chord) with default flags/owner
|
||||
if f == 33 then io:AddKeyEvent(G.ImGuiMod_Ctrl, true); io:AddKeyEvent(G.ImGuiKey.S, true) end
|
||||
if f == 34 then io:AddKeyEvent(G.ImGuiKey.S, false); io:AddKeyEvent(G.ImGuiMod_Ctrl, false) end
|
||||
-- drag the ColorButton onto the ColorEdit4
|
||||
if f == 36 then io:AddMousePosEvent(center("cb")) end
|
||||
if f == 37 then io:AddMouseButtonEvent(0, true) end
|
||||
if f == 38 then local x, y = center("cb"); io:AddMousePosEvent(x + 10, y + 5) end
|
||||
if f == 39 then io:AddMousePosEvent(center("ce")) end
|
||||
if f == 42 then io:AddMouseButtonEvent(0, false) end
|
||||
-- word-wrapped multi-line: click, Ctrl+End, type "z"
|
||||
if f == 45 then click("w") elseif f == 46 then release() end
|
||||
if f == 47 then io:AddKeyEvent(G.ImGuiMod_Ctrl, true); io:AddKeyEvent(G.ImGuiKey.End, true) end
|
||||
if f == 48 then io:AddKeyEvent(G.ImGuiKey.End, false); io:AddKeyEvent(G.ImGuiMod_Ctrl, false) end
|
||||
if f == 49 then io:AddInputCharacter(string.byte("z")) end
|
||||
ImGui.NewFrame()
|
||||
ImGui.SetNextWindowPos(ImVec2(10, 10)); ImGui.SetNextWindowSize(ImVec2(300, 200))
|
||||
ImGui.Begin("T")
|
||||
if f == 1 then check(ImGui.GetFrameCount() == 1 and ImGui.IsWindowAppearing(), "IsWindowAppearing() on frame 1") end
|
||||
if f == 2 then check(not ImGui.IsWindowAppearing(), "IsWindowAppearing() on frame 2") end
|
||||
ImGui.InputText("##t", buf, 64); rects.t = rect()
|
||||
sf = ImGui.SliderFloat("##s", sf, 0.0, 100.0, "%.0f deg"); rects.s = rect()
|
||||
di = ImGui.DragInt("##d", di, 1, 0, 100, "%d%%"); rects.d = rect()
|
||||
-- CalcItemSize takes 'size' by value: the caller's ImVec2 must not be written to
|
||||
local bsz, csz = ImVec2(0, 0), ImVec2(-1, 40)
|
||||
ImGui.Button("sz", bsz); check(bsz.x == 0 and bsz.y == 0, "Button wrote size_arg")
|
||||
ImGui.BeginChild("c", csz); ImGui.EndChild(); check(csz.x == -1 and csz.y == 40, "BeginChild wrote size_arg")
|
||||
-- drop target rect sticking out of the window clip rect pushes a full-screen clip rect
|
||||
ImGui.RenderDragDropTargetRectForItem(G.ImRect(-50, -50, 900, 900))
|
||||
ImGui.End()
|
||||
ImGui.SetNextWindowPos(ImVec2(320, 10)); ImGui.SetNextWindowSize(ImVec2(300, 200))
|
||||
ImGui.Begin("M")
|
||||
ImGui.InputTextMultiline("##m", mbuf, 256, ImVec2(200, ImGui.GetTextLineHeight() * 3)); rects.m = rect()
|
||||
if f == 30 then
|
||||
local st = ImGui.GetCurrentContext().InputTextState
|
||||
check(st.LineCount == 7, "multiline LineCount " .. tostring(st.LineCount))
|
||||
local cw -- the multi-line child window: cursor on the last line scrolled it
|
||||
for _, w in ImGui.GetCurrentContext().Windows.Data do if w.Name:find("^M/##m_") then cw = w end end
|
||||
check(cw ~= nil and cw.Scroll.y > 0, "multiline scroll " .. tostring(cw and cw.Scroll.y))
|
||||
end
|
||||
ImGui.InputTextMultiline("##w", wbuf, 256, ImVec2(120, 80), G.ImGuiInputTextFlags.WordWrap); rects.w = rect()
|
||||
if f == 30 then check(ImGui.GetCurrentContext().InputTextState:HasSelection(), "multiline select all") end
|
||||
if ImGui.Shortcut(bit32.bor(G.ImGuiMod_Ctrl, G.ImGuiKey.S)) then shortcut_frames[f] = true end
|
||||
ImGui.End()
|
||||
ImGui.SetNextWindowPos(ImVec2(10, 220)); ImGui.SetNextWindowSize(ImVec2(300, 150))
|
||||
ImGui.Begin("D")
|
||||
ImGui.ColorButton("cb", cb_col); rects.cb = rect()
|
||||
ImGui.ColorEdit4("##ce", ce_col); rects.ce = rect()
|
||||
ImGui.End()
|
||||
-- TextUnformatted() > 2000 bytes (coarse-clipped long text path): each visible line renders only up to its '\n'
|
||||
ImGui.SetNextWindowPos(ImVec2(320, 220)); ImGui.SetNextWindowSize(ImVec2(300, 150))
|
||||
ImGui.Begin("L")
|
||||
local dl = ImGui.GetWindowDrawList()
|
||||
local v0 = dl.VtxBuffer.Size
|
||||
ImGui.TextUnformatted(long_text)
|
||||
local nv = dl.VtxBuffer.Size - v0
|
||||
if f == 3 then check(nv > 0 and nv <= 14 * 9 * 4, "long TextUnformatted vertices " .. nv) end
|
||||
-- PushFont() saves the CURRENT font: PopFont() must restore it
|
||||
local font1 = ImGui.GetFont()
|
||||
check(font2 ~= font1, "font2 is the default font"); ImGui.PushFont(font2, 0.0); ImGui.PopFont()
|
||||
if f == 3 then check(ImGui.GetFont() == font1, "PopFont() did not restore the previous font") end
|
||||
ImGui.End()
|
||||
ImGui.Render(); G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
if f == 8 then check(edit_text() == "abc\u{e9}", "paste: '" .. edit_text() .. "'") end
|
||||
if f == 13 then check(edit_text() == "45", "SliderFloat temp input: '" .. edit_text() .. "'") end
|
||||
if f == 18 then check(edit_text() == "50", "DragInt temp input: '" .. edit_text() .. "'") end
|
||||
if f == 30 then check(ImGui.TextBufferToString(mbuf) == ml_text .. "x\ny", "multiline buffer: '" .. ImGui.TextBufferToString(mbuf) .. "'") end
|
||||
if f == 35 then check(shortcut_frames[33] and not shortcut_frames[32] and not shortcut_frames[34], "Shortcut(Ctrl+S) default args") end
|
||||
if f == 44 then check(ce_col[1] == 1 and ce_col[2] == 0 and ce_col[3] == 0 and ce_col[4] == 1, ("color drop: %s %s %s %s"):format(ce_col[1], ce_col[2], ce_col[3], ce_col[4])) end
|
||||
if f == 51 then check(ImGui.TextBufferToString(wbuf):sub(-7) == "secondz", "word-wrap buffer: '" .. ImGui.TextBufferToString(wbuf) .. "'") end
|
||||
if f == 52 and #failed == 0 then print("FIXES OK") end
|
||||
end)
|
||||
@@ -0,0 +1,174 @@
|
||||
-- Font pieces: ImFontGlyphRangesBuilder, ImFont:CalcWordWrapPosition() vs TextWrapped(), IsGlyphRangeUnused(),
|
||||
-- stb_decompress + Decode85 via AddFontFromMemoryCompressedBase85TTF() (same glyphs/metrics as the raw TTF).
|
||||
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2 = G.ImGui, G.ImVec2
|
||||
ImGui.CreateContext(); G.ImGui_ImplRoblox.Init()
|
||||
local io = ImGui.GetIO()
|
||||
local failed = {}
|
||||
local function check(ok, msg) if not ok then table.insert(failed, msg); print("FAIL " .. msg) end end
|
||||
|
||||
-- GlyphRangesBuilder
|
||||
local builder = G.ImFontGlyphRangesBuilder()
|
||||
builder:AddText("Hello \u{e9}")
|
||||
local ranges = G.ImVector()
|
||||
builder:BuildRanges(ranges)
|
||||
local got = table.concat(table.move(ranges.Data, 1, ranges.Size, 1, {}), ",")
|
||||
check(got == "32,32,72,72,101,101,108,108,111,111,233,233,0", "BuildRanges " .. got)
|
||||
builder:Clear()
|
||||
builder:AddRanges(io.Fonts:GetGlyphRangesDefault())
|
||||
builder:AddChar(0x41) -- already in range
|
||||
ranges = G.ImVector(); builder:BuildRanges(ranges)
|
||||
check(ranges.Size == 3 and ranges.Data[1] == 0x20 and ranges.Data[2] == 0xFF and ranges.Data[3] == 0, "AddRanges default")
|
||||
check(builder:GetBit(0x20) and not builder:GetBit(0x1F) and not builder:GetBit(0x100), "GetBit")
|
||||
|
||||
-- stb-compressed + base85 ProggyClean.ttf (generated with an stb_compress-format encoder + binary_to_compressed_c's base85)
|
||||
local B85 = ([==[
|
||||
7])#######hV0qs#####]h?>#/:jl&Ql#v#[Zre=N=K_o(-(##mQ%##B>A0F_%#g(g/'##r[(##PF6'I</,GM*BiC$v%###s,0%J*RB8O+d68%eKRrQ(.d<BW_*vCL%###E%###:d@UC%)BE#=.>>#'####<_[FH
|
||||
O97MKO->>#i6YY#i1JuB5eI`[VRUV$=.<T7oH[^ICAS5#T.>>#K####+>00FnH/5`S7g1TS->>#k%S+Hot3>MYJGiTLPUV$>eFVCUwS>#9G:;$n%###Sh(a1aA.;6BE-hAeI1=#au8eZ2D$CI[Mn20Gb?=iMPrIL
|
||||
DSGkFI5>##Q+`AMB%]`ac<%##CFgn*<WFX:&M'^#3@:B#`2B2#[0b30lOj)#-####.%*=Cvf./LVSiHdaT_n#X$###csu8.r:%)34Dk>$<,;.OOMDgEKnIS7EM9>ZoSAZ$*3)qMQv//L^MkA#wmCAMUnG<-7F>HM
|
||||
DHw>Pt*p+M[ul=Q<O]CPUoINNUm+p7S<oG76Mqr)twv9Mt0[0#=S&r;QDqk+SEqFR@0p--.iPDN+Y')$PP;vnQbxRMqJQ*OD:H-M#C]GQJ-jBPO&%^Qmus+M3@C58qNO&#sNk,%?$xu#Fle&,W6=G2,Hb;-;wcP$
|
||||
tPBuuE1V:vm3SML+x0B#/Dabh^KfW-j(.`&V8WQ-2$ZtQQpp5#l,$R#=`i['#l+S#Q*IX#6GMk#op/i#:n*x#tJV0$t#F=$X6iC$1/oh$TrKb$S/kt$&,)O%=q]E%o]n[%6dRd%lGTq%_#`C&$T1_&>Y^Y&2wbq&
|
||||
TB-K'@IZC'%]#V'Uv'n'[R%1(D6?c(OD1$)e>Lr(Z*24)C5Yb)R/uY)#PPj)uaFu)pEt**@7KY*j<MS*5Nki*SAC?+x/x5+ugwH+;f6w+**;8,V?'+,3Y6W,pGkM,sgEa,%5h7-QbL,-Z8sL-.[r<-r;tI-5hnl-
|
||||
Cnqc-CX86.QEKF.,hI9.1W`S%mQrV[C4s&#t3&KDU+DvZ)$SpA>O*dskh5??pb?^Y44[W7m@O9&/?o&YNgT?-'aPdsd(-qA0[9_#WMT9AcO#wm%e;e3?oWq/R1,XIghlWnL4mEX_v(R^+$4:A6.*x6Y+w_,ED)`,
|
||||
PIDRpbf::fN$F.N4Bv:/>80xm6wgLiuWsFXrv)AHt/sl19::#%T1?Ynm49;SFb8/N7n.a><s3T0OpXm(4@4sf)_W/WEcIZ70Ne5_QYMTBLMbT0%t4Tph<HT^;n@*>$P%O)]J/0j$)macqO]pg2V2u$&t@##5f1$#
|
||||
E@%%#Uqn%#fKb&#v&U'#0WH(#@2<)#Pc/*#a=#+#qnl+#+I`,#;$S-#KTF.#[/:/#l`-0#&;w0#6lj1#oiFJ('Moe2;4HZ$mgfX-b/g/HIt71#DRT<Lq8%dM$bLDNoaVV-Pm^dOJ@6##XaYx')_#&4Za=sQ-,7&4
|
||||
Oe)>Pn<<>P0]15/$[K<Lrhci9h&@2LaX:9$;$Ne?L*'?76@Vp.%XK<LdcPe6%l^>$?:b1#^QZ`*uqmV-8lt.ZRwbVRqjtH*PhBQ(-t]N-0*aYMiEVq7a=W4#`6_c)$/*JL(L-^(]$wIMlcs(UsvHv,,rbA#/2u]O
|
||||
hdcHMucWU-k^n:$VGR;oFHnq7e(Q&#uDdE&];bLcqC/^daSxFNtTGw.P3w.Ln1k,O7$22%r]<WS?OY)NJ[vI:DJNGokW_'6Q;I28n8X,Okie;)sJl_fawt-$II`;-sINN$tre+MLFg;-cG,-M<vp%N`tb48]_c6s
|
||||
:#^#$J?HC$,>2U%qS#n8as:jrQ=$##/)>uuN?Sq7^fV2ivEjJN-MT;-UJ;QMM=6##Cni&O1/Ut'7#[UN>+]K3M@2+8UkW1#k.WUN4DU;-j8(1$)[888aOHpgh<7r7#n8I?%R7p7tGF]u%OtlSE4$##6We'8SdfFI
|
||||
WVZ>nZ6c8MPhc(.i10p7x0'.=;lxb-4r'E>qC0%%?].e;I#72LclTAO0qD>$Vvnq2h^fW-LL4OiYW-mNFJuH&O(35&85c58@<iv%VwpGMX#$*&WFjp'jZCx$5N:q8/sgd4LhC^++re_8de;m8?37w%RICm8o4wd+
|
||||
*OhaW?_m.'3XYjM/gh.(xEe58>Y31#_Lx-[?u>q7:5i8K5(;mOM8#=Q'`+%&7'6i#BtxA?0KPM-1PHM&/esr7gC>B$1wGJ(>Q5t7]#:xT:tl.$Tvx;-%&26&`JT58^V_,FWN-c0F####HSI@1K<8FN&?bO'2[IfM
|
||||
j'YWN,<hn3bqwJN0:kC:(Yf>et`e;)LBf68(24gj1WXW'afQfFv7V.8R02?[LUlDN3cha'&]T&#b96$2*T5s7L5jv[&tsR%3dG2M0.(58=RK=`37;ENkWl9)Y7dp7v_k;fk&Z31P>5r'ZC$M&7&i)<U/5F%<bj/:
|
||||
b5vAmK4$##&J<j$&6G<QMA&D:Hbkxu.NTkM6ev.:XCF&#iR7S82tuF%k$IAOvjw:$ku0p7sTMBm9pUh$KAuu#5[,qpn%(.*;?>5SkFGm;i'72Ljb]1#+BcK:Fgs.F8`aBNT($28/7*.H1GrvqoTa2`b:EO-=sKj9
|
||||
crw0#.4D.M(s<A+,DPc=mTGQ:uaAL:Wjp#(R^uw9KvsDN781]&6tgA=_$Dc%.7vcMO>m;51/tW8Y@@S/#1jn8BZT/-Y,lJa-2Ht$i=(HMv'(P8Y>4AuNb6j9hP6(d?^OE23b<Q8)H*nkb$M#1kJAqgUJSk8kK'dk
|
||||
5#uk%xHA88V`;3;KicD%RE-RLwIsJ%#Et,krIK64v,N/Vn@^5+,(;eMs7jf%Pa64:0nhEYGlk%(I9x9Mk3AN9PV*1#m1OL;Y@0qb]2``]dhsp8HNDLPQ(C-M(NbS85^wek`P@'$fCAV8_hGWSE<?tO(=ZU*EK949
|
||||
9ux0#2nKA=dT'^#>sR&ZePWV&-=i>RM-']:uc%4;r>8R$tZgSN$fo1#8&n/;%G7@[Jf4x+.bjq7rlBEYk>h-%(X8j9VCxj2OM:/1_>qs7fEt-$n17tQE&9A.S+Ne+3]a:%$MLp7t]Wx'>3Ks7wtpDP.%L)$Q]BDN
|
||||
NOZf:iskA#j:8T@)BC[.<2N=8c4G`&EW<a&`aQd+s_Pp'a_&6(M@M.$:t1W?4@0#AKhL&OZr_G5Ndap''9nq&@EQkTL0>@$%,m/:PIh)P<e=K8`cI4;5/hu0$qVv[#aKm<Vh;BmVxk4%x3Kn9+Nkxu6Ro94fPQ:8
|
||||
P_)edQ/G0MPJKU11j?NWE?N(80m^&v+J?J:DRPx^YwdHMNf4-:K3<p^FSfo7kKtWSvQjN9)v[B739$^*i-It]VKVv/>Eq3:+x&'-t0sc;>[:</nIMS2He60Vdig`&6]Hj9QO_&RvTf'&mZ]mBRJ3SabaG'?hIi.$
|
||||
$./32CCP)NBxoO(9L(c%jxcp7a.-e4Y5n3-qg-a/9c639%wJ+G5X1e&?5V?-a?>Q-;4*88df9dk@]?Y'/ehS@A:R&m2_(:)QYJwTme-LEcuko$4B:T1=^J$&2(+@-]Ziu,ae_-tbUGDN`-Ra$;hhjW/v[lA3pKq^
|
||||
H<;&(8#DwP3c)/-SoDu7GaHQ:AX=W%+7k,4dQ,N11A>2Bv%03M_/wU&oNi5A)(&3MslOf-.brg=5SHx#7jg]O.F`c)6jK788At1#UfqV-`K<h=Vdb-8U,$90QK@I-E8o3%$grI;4HtdX.Qs$9nga.-c;@v><=ijV
|
||||
anS,,diDack,uG%(q-&>^Ep&?uTh&UIULu:N*DkDaoK>0T>R@@ho/P+uw<T8#pekXXLZ)GN?Hf,CHuU8>pTdx:O3h,p583DQa5frln2-eHrS`V[r7V<$+%Ej0HN,NbN&WQKP9p9qDP-L%r'r(Mj9P+3*GJ*2$/
|
||||
4_R;-22R2$*LKj:':c_-%4+X.)=a78Q<x0#JP;'PY?=(&BgGp8r;7F%@<PWJYRkH,+GX	ePr^o1%/8JE#QUU8jn'S=uPA$TS'J)G=@>^$r?%=FY%8=cFU_Kffo7m-u8NI/5'$NF81.taNq7)?Kq^T+DB)Wg>jV
|
||||
(ckS*I,1qAb-<p^7Mjf%NcuFNgX12)80EuK,1)g0jPmd;%aZp0ggZdM)j&Z$v>ZQS/U@)2.KDgU#Kk95sor>e@>(QYI<%Z*uB-x0*0K39$uQRX^T]M9_U?^?XD-:8t`MqM0pLP9BmS6(xp?e9dca,bq<3K*^w@T[
|
||||
bub7%Vu;S8/G5F%0'8rVUDCnNj9%dMllOf-B)(Wf2(73)oGHH;IoZp0Q1Gp7%Wc&#v6D39^P()HBs(2';aFq72v6b6P77'&h2da<TJ_pT`rE)-rf,78tAk)>6Rm3/Zt8#QHo4`)XmW7h'<>e+2NgM9dboLavtx$$
|
||||
KIK$>1fAoU4NP^0whIt7^iWx''x:Q:`PRB$lhV29)-.K<)dFu3^;mU8UO1S*KTJ/M$=Iw3qi6JN4AFoOalkGNhxNv'HM)?-0(Oh;0:aJsj[lT'5kWm83sdC%hHV7;LSb<S7du7IeKD'mS9JC9Jxr0$t8l>Pxwh9.
|
||||
L,hs7Elx2)+C30*5d'q7#L?T0W#H^Zths.L2*578H]]^-nO,X&2/Z&FM9%%B8&E#>OgR?RC5'T*;Xx9RhdA7(L01H;Pk1NV87(p7Qd41#fFQ;-xe=C$uf['$C+RPs51b-<8x.4rJ;pt-aA,q7Z6QYq]s/FN6PT[%
|
||||
gdf68Omx0#HA2s-tGPSIU*@w^dr,X/kJm;?T$dF#IwGP$hn1a*]p7,M.S?M9a$nx0;,Gp74,IpgKNdm'@Bt784N&:DUix*=bc^<Vh+&G[/;dFGR$=I$_Y##PPEV+8=uWd=5KWB%j&h'FPb84=_lDQ(Red/:KD/F.
|
||||
-o'^#nvkQ8'FjZSZ96Y/o(,,M[jxJjk)lWNSaX%(x11$8SF=[.P8k2B>_sR8w[gJj7*:6:5`)QLb:^i?lw%rMgu>q78aq5M?^w>%IVPp7M8td=/H+s7>&d:;k:&qK=?ex%a*sYPO[+<%&K2;8;fD.$Wk@vPTlC:R
|
||||
,9R>%-u#6AQ]m&6e32?%THYs%m-n58^<(0E=f2#$wonB$QB]m8R(7mMSpse*)jK29*O$90+$bk)VgB^m/i9R$)8LV4iPpdFBFX)-Q6s58&a3dX&TB59&@_[KAuJmSp13/%8Pp'5D2ZJ:j3:`f+5d+Nc2r.([59p7
|
||||
6A#'v>J6u'm[2Q8CS+5rbs14$nK%B>m%6Q:`%P1):BA*N1a-A)96D3#1TCt7#IgE#U/VR=`(qQ(U:c58:RRPDZ+,58@`EdtKP>[PQd/,M9u#>9d*-g)&%B@-j<1e(>ih29via.-S?5`8FO:;B&?ch'PMk8@YG@*n
|
||||
P@st7QGt-$,``wP[ZNC(uTEq70l)?[nS$i$FKgS8jJN9B<kU';c$/32mbBD$4;qeM?5R=MB:K'd@-K^&L.M'Oq4n2$SK%+dwY&(m7/HJ.emw-MLS]0)75,S32BtQ8f3;nqGb=<%Ckb69s#Z&Q^OVv-/vOp7:Mh,F
|
||||
s2K1:'.vhOt3QA%7rt:(?h+G%2V:<@?O#Qqkl2$;YqE#1:xK,M&%uW)DLo;oA^4e1cnV2([,HKDk)U/dN+dP8:N-Up5d1$1LNP^=EMv^ZR7cP8$Obx%xL>p'CUH-MgU,3D7)D_0'?D_=g>d&QMFJk*7&Pp7Gt3[T
|
||||
TwY+Y0v2o0DvI^#s-%g:26KE>o_`h*%L^VH1LbC=3;xji-O7r'Lf7KW4N+[&i7PW87O,i8DUjTBFRS?$UG1o*(VRd;4QG1#mpl%$>iraIcDKQ(d%g4([email protected]?^O&gCAr7t$.Ae*b8k&;1=6`d=_d'-05fD.D)E.
|
||||
uFxZ(d4vQ8.(J(8.%NX-X3RpK:'oLabx4I-1q.:)0.<q0/jF88;0ESCEE8SRN0]u:kpB+$eu*a*2XTe;?@)%IZ[./$HD]BfZ1jk9iCJ32e9R78a=)c<)]<T^'Kc'@lKLKE,LNn%%cl-MpehT$W2`l2b'nj959tT'
|
||||
1wv*$&9#[JNAC]&[mtvPGwA5;ckQdb`;]R$I&gjDXVfh<NTX1#a8T;-*F:`$qqu,MVqgZ$R(*@II4?uuW%QW@4LoKYVb%R8tks-$HG<f;^31ObK;lR(U@k+MLa'VIt)LE%IrM7)wU:EN&W[39ijMG%#w4g:,Xw0#
|
||||
w0[588iGJ$ps_>.,umo%x+B7$S)0p71m99pnERN93)9I$)#(IM_Yd>#6x;XCg]5<-3efW85,/n1#S]C'qqvcD2n4`8u9j<-E`Y%&`Qhg*tt2e$N$t49<#oW&^a*@,$^^dk7xK)$GJP/M>KO0&ND_j9>>P&#JuF.3
|
||||
S<r>I:OPE*XF>dOo#P-(I7Vj;vrlm968R,tB,cS(]FeW&&O`9$-L-5#aS-Ak*o#iSuvYmTPpq9&E*n&%lBap7aS=r7jnP7Ah-]pK>xo_N]mjvPjtJ.2/*'W$4BFQ8bN((&WpULN`$^3i'@+G%.[#.$_6>3)jr[PA
|
||||
&Wp5Uk_uk%Hk@bNH`(S%T)p/MdebV$4iQr7(QMG%k%8bRfU/L.bn/mSCf>SI$`G%h9JSpB%>xsF,^-Ehgn*Q8&j]K<l(Md8m/9MmPZ4j`a4K2`eI,H:m*Zeohdc,X+fTuYcjEE%M^5t7YsvK3FWHI9$lM4#0*joT
|
||||
?tM56R'Aq7$d95#n3nAI&'cm3Y(L-MnV#x'qj+l+liD.-8W;v>@wMQh=6)m$1_b-;I?Q5;7>`*6lg3G;sv&:`[JLN9w<gPqa/S/Mx@aJ%NNa,MG>gr'mKDKNrkdkasN/x0,l$q71^?Xh*X[8^PL*q%6cv58_S*1#
|
||||
bX`0MITc080x^@ilsnlf[L7I%(3mLC(BZE5+?,P@)$+1#DqsJaN-U:/-u?68)p<9j7E%>i?Ia;-kH/D,v(mn8=0'.$Nu49@Bm*1#XYs5CvbQa86j-bS`c5m8RiE1#4l^&#pCa$UOs068Z1-E5RhYl$Oh%TW*)LTA
|
||||
.#$]UnM;TK9(Dl%8`?6B<MiRWdaTl9'OGG.SAd[IOMvu>6E>WgZ3of$O1Up@XbS2L[OtL:aqtqK:M2j*_@-:)LF5F%sd40:3Fr_&]?'k9W@dF<A]r<J?&]lAL2j&-ntJ<(=skq7w^+Ls<q9et?<a^%+$Y98_&Zob
|
||||
vsUqpARc=<ROu7c=ebbOHwO/6Pm@*Ww0]%X*io?<8IQ<iLwrMg?r?eO%E:^-aB#KWu<7b'tRLdt#'-;?A1^FEMk82bPU#-MT>uw&hMM8Ia^vr'sj#j1>f:^OuVh29)g09Tq-.78(S%?7NCU29fbbgNaEJ)<jB'4r
|
||||
(OSP3WS698I9B.$?KS58QV`g$p=@`HW?U/5S&64;1n%:>7rU2`cGs_*,K)1#FCR(Q=Q7i8sDwUjLe.0M2('B$dwW88%vrv@bNOG%K8tMB`6XF-:/::;-:`6r0U=0$``Xp9Knp*-cUpeHl%w,;s+e<_3cs?-#s&r0
|
||||
1B^]02M(wYNshr00dW_ZG]0a;Gx4ND*&9;-HM%VqIL6GDsDZki/S0K)KF,:pgT4,%4K]dM*x8h8WVl6`g#gG$mhmF,,i2v*wBS1MFM0`&,:PP:[J'LPk%']h5(Wxd>i9UXuQk&18(&H;%Ug'hT6S</?xNx1fa5u7
|
||||
DW2QL',t`-Cx#okPutL<%cY'2pP)xPGHHiS^x6Z:R91ObU-iT9O(4m'+%2a*N9pP9(B.-bX%`XNve$U$Bht]=h6rJW<3VM%_j/'Q_7M3,ej5/-Ncf/sSl1]M(Q:['>v_Q93J04r7<,vNP%2d97xbEgJKQGVgB#r3
|
||||
FO4;89*^EfckAhDPC)c<6v690M?r&(GDc^$Ki+58v&LnF)iRTRpw<8Up^,(dPss3,0Z)kT#1i]$-KIZ7LI)3S`ig1(p^^URhRi*N,%$c4L4udO(jG9%[vg2V7I(e&NY<dX,WKw#_&Yj9>hMBQ4T:r2`e0l:lJB$h
|
||||
.`Pg+e]wY%jfNf$)']6K8lDKaC90I.p<3q7dQtA`Q`5?`(qQvc_6b,3O3)9gwixH-]$SR8vjMhdwMD$[V3xR&vCIpT$Vbk1f=RRblisvHe#Zq9Ske(9iR6XLQES29JsZIM-2>rDjiGr^89KO0-^'q718r_&61D58
|
||||
w+r_&.lCW/6iG<-`*wQ%8DQ^OmBjE%9X`E.1EDS@#j/q'J5x8-cxfJssL4($Uflq7hxad=4O:C4K9+hER0^F9G+UQc8W:uQ&/0<A7t3fWC[J90AEOn%&:+kCUYXjd*c-^O.<(d%&0)1#XrV'POoOS$AX+q8IZ4)6
|
||||
hxEFM,hSgN0aEW+x/;N3xJk0&j`S.;edM2i9D+*0GJlB$x:(29wPX&#?l%oS.cb&#`i[`*lQ/,MH@-##FEV6NTF6##$l84N1w?AO>'IAOl%4a*0Y^GM#RcGM9#ult_Ks$#B@`T.1rC$#`@`T.,Mc##T@`T.74i$#
|
||||
WrG<-N2:W.2`($#irG<-<q@u-?Wd`*eC;,M6WYdM6WYdM*?`T.HEX&#`YYdM6WYdM6WYdM%w@(#.E-(#cPc-NZxtk24Y($Jt1^oD0ZKKFg`]oD+,2eGc:@bHcFx.>@nuc<)0o6D]bdUCFdg+>?Wae3;BR12A::MB
|
||||
h]8;-?(DYGUq`uGNDw1B];8;-SHpw'r?Z.#K0f-#=ic+#E<x-#ZZO.#L)1/#wtu+#F:F&#;)1/#O<x-#YSq/#(ZO.#wc-2MVC/$$;^?w^Gm/aNs*p+M&fsD#*J(v#.c_V$2%@8%6=wo%:UWP&>n82'B0pi'FHPJ(
|
||||
Ja1,)N#ic)R;ID*VS*&+Zla]+_.B>,cF#v,_REmh1W@`$0u68%47no%8ONP&<h/2'@*gi'DBGJ(HZ(,)Ls_c)P5@D*TMw%+XfW]+](9>,a@pu,eXPV-iq18.m3io.qKIP/ud*20#'bi0'?BJ19if,=(N^o232;D3
|
||||
7Jr%4;cR]4?%4>5C=ku5GUKV6Kn,87O0do7SHDP8Wa%29[#]i9`;=J:dSt+;hlTc;l.6D<pFm%=t_M]=xw.>>&:fu>*RFV?.k'8@2-_o@6E?PA:^v1Bikur-m-VS.qE75/u^nl/#wNM0'90/1+Qgf1/jGG23,))3
|
||||
7D``3;]@A4?uwx4C7XY5GO9;6Khpr6O*QS7hPn:ZKe0GMgc>c`Mq&Sn8h?YPLS-JUrBB`WH+,AO,Wm+MTm6fqOR(>PCeG`NqHn@k_;LfUox3creaQ(st)7VZ`5Quc4R>MBmeu:QS(f7eQfi:di++PfiuIoe1#Don
|
||||
^w>igqOb1g:-r+DPn?VQ$(_.hbS8GDRI]1pm*m(EM(1DER=L`E2m(GVYq)>G['EYGbKAVHdW]rH0%]4ol2u4Jn>:PJsSUlJ(UFcVwl6MK%53JLTUxLpbwnWH#N#hF@0*K2,4IL2fCd<-gCd<-hCd<-iCd<-jCd<-
|
||||
kCd<-lCd<-mCd<-nCd<-@Dd<-ADd<-BDd<-CDd<-DDd<-EJ)X-v0P]'Gt.g2Gt.g2Gt.g2Gt.g2Gt.g2Gt.g2Gt.g2Gt.g2Gt.g2Gt.g2Gt.g2Gt.g2Gt.g2TmOh2Y#oTC$NXVCThmfGY4&>-K*IT-K*IT-K*IT-
|
||||
K*IT-K*IT-K*IT-K*IT-K*IT-K*IT-K*IT-K*IT-K*IT-K*IT-K*IT-18ZI'Et,gjm,(DPO/(DPO/(DPO/(DPO/(DPO/(DPO/(DPO/(DPO/(DPO/(DPO/(DPO/(DPO/(DPO/(DP+-XlC#m8Atkt>Ns
|
||||
]==]):gsub("\n", "")
|
||||
|
||||
local raw_data, raw_size = G.ImStd.ImFileLoadToMemory("fonts/ProggyClean.ttf", "rb")
|
||||
local raw = io.Fonts:AddFontFromMemoryTTF(raw_data, raw_size, 13.0)
|
||||
local comp = io.Fonts:AddFontFromMemoryCompressedBase85TTF(B85, 13.0)
|
||||
check(comp ~= nil, "AddFontFromMemoryCompressedBase85TTF returned nil")
|
||||
local comp_data = comp.Sources.Data[1].FontData
|
||||
local same = comp.Sources.Data[1].FontDataSize == raw_size
|
||||
for n = 1, raw_size do if not same then break end same = comp_data[n] == raw_data[n] end
|
||||
check(same, "decompressed bytes differ from fonts/ProggyClean.ttf")
|
||||
|
||||
local TEXT = "The quick brown fox jumps over the lazy dog again and again"
|
||||
local W = 100
|
||||
local f = 0
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
f += 1
|
||||
G.ImGui_ImplRoblox.NewFrame()
|
||||
ImGui.NewFrame()
|
||||
ImGui.SetNextWindowPos(ImVec2(10, 10)); ImGui.SetNextWindowSize(ImVec2(400, 300))
|
||||
ImGui.Begin("Fonts")
|
||||
ImGui.PushFont(raw, 13.0)
|
||||
ImGui.PushTextWrapPos(ImGui.GetCursorPosX() + W)
|
||||
ImGui.TextWrapped(TEXT)
|
||||
local wrapped_h = ImGui.GetItemRectSize().y
|
||||
ImGui.PopTextWrapPos()
|
||||
local line_h = ImGui.GetTextLineHeight()
|
||||
ImGui.PopFont()
|
||||
if f <= 3 then
|
||||
ImGui.PushFont(comp, 13.0)
|
||||
ImGui.Text("Hello \u{e9}")
|
||||
ImGui.PopFont()
|
||||
end
|
||||
ImGui.End()
|
||||
ImGui.Render(); G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
|
||||
if f == 3 then
|
||||
-- CalcWordWrapPosition(): same line breaks as TextWrapped(). ProggyClean 13px = 7px per char -> 14 chars per 100px line
|
||||
local te = #TEXT + 1
|
||||
local s, lines, breaks = 1, 0, {}
|
||||
while s < te do
|
||||
local e = raw:CalcWordWrapPosition(13.0, TEXT, s, te, W)
|
||||
lines += 1; table.insert(breaks, e)
|
||||
s = e
|
||||
while s < te and TEXT:sub(s, s) == " " do s += 1 end -- ImTextCalcWordWrapNextLineStart(): skip blanks
|
||||
end
|
||||
check(breaks[1] == 10, "first wrap after 'The quick': " .. tostring(breaks[1])) -- "The quick" | "brown fox" | ...
|
||||
check(TEXT:sub(11, breaks[2] - 1) == "brown fox", "second line '" .. TEXT:sub(11, breaks[2] - 1) .. "'")
|
||||
check(wrapped_h == lines * line_h, ("TextWrapped height %s vs %d lines * %s"):format(wrapped_h, lines, line_h))
|
||||
|
||||
-- Compressed font: same glyphs and metrics as the raw TTF
|
||||
local br, bc = raw:GetFontBaked(13.0), comp:GetFontBaked(13.0)
|
||||
check(br.Ascent == bc.Ascent and br.Descent == bc.Descent, "ascent/descent")
|
||||
for _, c in { 0x48, 0x65, 0x6C, 0xE9, 0x41, 0x7E } do
|
||||
local gr, gc = br:FindGlyph(c), bc:FindGlyph(c)
|
||||
check(gc.Visible and gc.X1 > gc.X0 and gc.Y1 > gc.Y0, "compressed glyph empty " .. c)
|
||||
check(gr.AdvanceX == gc.AdvanceX and gr.X0 == gc.X0 and gr.Y0 == gc.Y0 and gr.X1 == gc.X1 and gr.Y1 == gc.Y1, "glyph metrics " .. c)
|
||||
end
|
||||
local str = "Hello \u{e9}"
|
||||
local sr, sc = raw:CalcTextSizeA(13.0, 1e30, 0, str, 1, #str + 1), comp:CalcTextSizeA(13.0, 1e30, 0, str, 1, #str + 1)
|
||||
check(sr.x == sc.x and sr.y == sc.y and sc.x > 0, "CalcTextSizeA")
|
||||
check(not comp:IsGlyphRangeUnused(0, 255) and comp:IsGlyphRangeUnused(0x4E00, 0x9FFF), "IsGlyphRangeUnused")
|
||||
|
||||
-- AddRemapCodepoint(): '$' loads the 'A' glyph (applies to glyphs loaded afterwards: new 20px baked)
|
||||
comp:AddRemapCodepoint(0x24, 0x41)
|
||||
local b20 = comp:GetFontBaked(20.0)
|
||||
local gd, ga = b20:FindGlyph(0x24), raw:GetFontBaked(20.0):FindGlyph(0x41)
|
||||
check(gd.X0 == ga.X0 and gd.Y0 == ga.Y0 and gd.X1 == ga.X1 and gd.Y1 == ga.Y1, "AddRemapCodepoint")
|
||||
|
||||
-- RemoveCustomRect()
|
||||
local atlas = io.Fonts
|
||||
local id = atlas:AddCustomRect(8, 8)
|
||||
check(atlas:GetCustomRect(id, G.ImFontAtlasRect()) == true, "AddCustomRect")
|
||||
atlas:RemoveCustomRect(id)
|
||||
check(not atlas:GetCustomRect(id, G.ImFontAtlasRect()), "RemoveCustomRect")
|
||||
|
||||
-- RemoveFont()
|
||||
local nfonts, nsrc = atlas.Fonts.Size, atlas.Sources.Size
|
||||
atlas:RemoveFont(comp)
|
||||
check(atlas.Fonts.Size == nfonts - 1 and atlas.Sources.Size == nsrc - 1 and not atlas.Fonts:contains(comp), "RemoveFont")
|
||||
|
||||
-- ImFontAtlasTextureBlockFill(), ImTextureDataGetXXXName()
|
||||
local tex = G.ImTextureData(); tex:Create(G.ImTextureFormat.RGBA32, 4, 4)
|
||||
G.ImFontAtlasTextureBlockFill(tex, 1, 2, 2, 1, G.IM_COL32(1, 2, 3, 4))
|
||||
local px = table.concat(tex.Pixels, ",", 33, 48)
|
||||
check(px == "0,0,0,0,1,2,3,4,1,2,3,4,0,0,0,0" and tex.Pixels[29] == 0 and tex.Pixels[53] == 0, "TextureBlockFill " .. px)
|
||||
check(G.ImTextureDataGetStatusName(tex.Status) == "WantCreate" and G.ImTextureDataGetFormatName(tex.Format) == "RGBA32", "texture names")
|
||||
end
|
||||
if f == 5 and #failed == 0 then print("FONTS OK") end
|
||||
end)
|
||||
@@ -0,0 +1,301 @@
|
||||
-- Small upstream helpers: ImGuiInputTextState selection API + ReloadUserBuf*, ImGuiInputTextCallbackData:SetSelection, ImDrawList AddImageQuad/PrimQuadUV/
|
||||
-- CloneOutput, ImDrawData DeIndexAllBuffers/ScaleClipRects, ImBitVector/ImBitArray*, ImGuiPackedDate, ImParseFormatSanitizeForPrinting, drag cancel (ShortcutsForCancel),
|
||||
-- log decorations, ImGuiDataType.S64/U64, BringWindowToDisplayBehind, ImGuiSizeCallbackData
|
||||
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2 = G.ImGui, G.ImVec2
|
||||
ImGui.CreateContext(); G.ImGui_ImplRoblox.Init()
|
||||
local io = ImGui.GetIO()
|
||||
local failed = {}
|
||||
local function check(ok, msg) if not ok then table.insert(failed, msg); print("FAIL " .. msg) end end
|
||||
|
||||
-- Pure helpers
|
||||
check(G.ImParseFormatSanitizeForPrinting("%.3f%%", nil, 32) == "%.3f", "sanitize %.3f%%")
|
||||
check(G.ImParseFormatSanitizeForPrinting("%'_5.2f units", nil, 32) == "%5.2f", "sanitize stb flags: " .. G.ImParseFormatSanitizeForPrinting("%'_5.2f units", nil, 32))
|
||||
local d = G.ImGuiPackedDate(20260315)
|
||||
check(d:IsValid() and d:Unpack() == 20260315, "PackedDate round trip " .. d:Unpack())
|
||||
d:SubtractMonths(3)
|
||||
check(d:Unpack() == 20251215, "PackedDate SubtractMonths " .. d:Unpack())
|
||||
check(not G.ImGuiPackedDate():IsValid() and G.ImGuiPackedDate():Unpack() == 0, "PackedDate empty")
|
||||
local bv = G.ImBitVector()
|
||||
bv:Create(70)
|
||||
check(bv.Storage.Size == 3, "ImBitVector size")
|
||||
bv:SetBit(1); bv:SetBit(70); bv:SetBit(33)
|
||||
check(bv:TestBit(1) and bv:TestBit(70) and bv:TestBit(33) and not bv:TestBit(2) and not bv:TestBit(69), "ImBitVector SetBit/TestBit")
|
||||
bv:ClearBit(33)
|
||||
check(not bv:TestBit(33) and bv:TestBit(70), "ImBitVector ClearBit")
|
||||
local arr = {}
|
||||
G.ImBitArrayClearAllBits(arr, 96)
|
||||
G.ImBitArraySetBitRange(arr, 3, 70) -- [3..70)
|
||||
local ok_range = true
|
||||
for n = 1, 96 do if G.ImBitArrayTestBit(arr, n) ~= (n >= 3 and n < 70) then ok_range = false end end
|
||||
check(ok_range, "ImBitArraySetBitRange")
|
||||
check(G.ImBitArrayGetStorageSizeInBytes(70) == 12, "ImBitArrayGetStorageSizeInBytes")
|
||||
check(G.ImModPositive(-1, 5) == 4 and G.ImRoundSigned64(-1.5) == -2 and G.ImCharIsXdigitA(string.byte("F")), "math helpers")
|
||||
|
||||
local buf = ImGui.NewTextBuffer("hello world", 64)
|
||||
local cbuf = ImGui.NewTextBuffer("abcdef", 64)
|
||||
local cb_calls = 0
|
||||
local function cb(data)
|
||||
cb_calls += 1
|
||||
if cb_calls == 1 then data:SetSelection(1, 3) end
|
||||
return 0
|
||||
end
|
||||
local df, rect_df = 10.0, nil
|
||||
local s64_v = 2 ^ 40
|
||||
local f = 0
|
||||
local function center(r) return (r[1].x + r[2].x) / 2, (r[1].y + r[2].y) / 2 end
|
||||
|
||||
local function vtx(dl, i) -- 1-based vertex
|
||||
local b, o = dl.VtxBuffer.Buf, (i - 1) * G.VTX_STRIDE
|
||||
return buffer.readf64(b, o), buffer.readf64(b, o + 8), buffer.readf64(b, o + 16), buffer.readf64(b, o + 24), buffer.readu32(b, o + 32)
|
||||
end
|
||||
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
f += 1
|
||||
G.ImGui_ImplRoblox.NewFrame()
|
||||
-- drag + Escape cancels and reverts (ShortcutsForCancel)
|
||||
if f == 20 then io:AddMousePosEvent(center(rect_df)) end
|
||||
if f == 21 then io:AddMouseButtonEvent(0, true) end
|
||||
if f == 22 then local x, y = center(rect_df); io:AddMousePosEvent(x + 40, y) end
|
||||
if f == 24 then io:AddKeyEvent(G.ImGuiKey.Escape, true) end
|
||||
if f == 25 then io:AddKeyEvent(G.ImGuiKey.Escape, false) end
|
||||
if f == 26 then io:AddMouseButtonEvent(0, false) end
|
||||
ImGui.NewFrame()
|
||||
ImGui.SetNextWindowPos(ImVec2(10, 10)); ImGui.SetNextWindowSize(ImVec2(400, 300))
|
||||
ImGui.Begin("H")
|
||||
if f == 2 then ImGui.SetKeyboardFocusHere() end
|
||||
ImGui.InputText("##t", buf, 64)
|
||||
local id = ImGui.GetItemID()
|
||||
local st = ImGui.GetInputTextState(id)
|
||||
if f == 5 then
|
||||
check(st ~= nil, "InputText active")
|
||||
if st then
|
||||
st:SetSelection(3, 6)
|
||||
check(st:GetSelectionStart() == 3 and st:GetSelectionEnd() == 6 and st:GetCursorPos() == 6 and st:HasSelection(), "SetSelection/Get*")
|
||||
st:ClearSelection()
|
||||
check(st:GetSelectionStart() == 6 and st:GetSelectionEnd() == 6 and not st:HasSelection(), "ClearSelection")
|
||||
check(st:GetPreferredOffsetX() == -1, "GetPreferredOffsetX")
|
||||
-- modify the user buffer externally then reload
|
||||
local s = "bye"; for i = 1, #s do buf[i] = string.byte(s, i) end; buf[#s + 1] = 0
|
||||
st:ReloadUserBufAndSelectAll()
|
||||
end
|
||||
end
|
||||
if f == 7 and st then
|
||||
check(G.ImGui._ByteArrayToString(st:GetText(), 1, st.TextLen + 1) == "bye", "ReloadUserBufAndSelectAll text")
|
||||
check(st:GetSelectionStart() == 1 and st:GetSelectionEnd() == 4, ("ReloadUserBufAndSelectAll sel %d..%d"):format(st:GetSelectionStart(), st:GetSelectionEnd()))
|
||||
st:SetSelection(2, 3); st:ReloadUserBufAndKeepSelection()
|
||||
end
|
||||
if f == 9 and st then
|
||||
check(st:GetSelectionStart() == 2 and st:GetSelectionEnd() == 3, "ReloadUserBufAndKeepSelection")
|
||||
st:ReloadUserBufAndMoveToEnd()
|
||||
end
|
||||
if f == 11 and st then
|
||||
check(st:GetCursorPos() == 4 and not st:HasSelection(), "ReloadUserBufAndMoveToEnd " .. st:GetCursorPos())
|
||||
end
|
||||
-- callback SetSelection (0-based callback positions -> 1-based stb)
|
||||
if f == 12 then ImGui.SetKeyboardFocusHere() end
|
||||
ImGui.InputText("##c", cbuf, 64, G.ImGuiInputTextFlags.CallbackAlways, cb)
|
||||
if f == 15 then
|
||||
local cst = ImGui.GetInputTextState(ImGui.GetItemID())
|
||||
check(cst ~= nil and cb_calls > 0 and cst:GetSelectionStart() == 2 and cst:GetSelectionEnd() == 4, "callback SetSelection " .. (cst and (cst:GetSelectionStart() .. ".." .. cst:GetSelectionEnd()) or "nil"))
|
||||
end
|
||||
df = ImGui.DragFloat("##df", df, 1.0)
|
||||
local a, b = ImGui.GetItemRectMin(), ImGui.GetItemRectMax(); rect_df = { ImVec2(a.x, a.y), ImVec2(b.x, b.y) }
|
||||
if f == 23 then check(df ~= 10.0, "drag changed value " .. df) end
|
||||
if f == 25 then check(df == 10.0 and ImGui.GetActiveID() == 0, "Escape reverts drag " .. df) end
|
||||
|
||||
if f == 30 then
|
||||
local dl = ImGui.GetWindowDrawList()
|
||||
local v0, i0 = dl.VtxBuffer.Size, dl.IdxBuffer.Size
|
||||
local tex = G.ImTextureRef(1234)
|
||||
dl:AddImageQuad(tex, ImVec2(10, 10), ImVec2(50, 12), ImVec2(48, 60), ImVec2(8, 58), ImVec2(0, 0), ImVec2(1, 0), ImVec2(1, 1), ImVec2(0, 1), 0xFF00FF00)
|
||||
check(dl.VtxBuffer.Size == v0 + 4 and dl.IdxBuffer.Size == i0 + 6, "AddImageQuad counts")
|
||||
local x, y, u, v, col = vtx(dl, v0 + 3)
|
||||
check(x == 48 and y == 60 and u == 1 and v == 1 and col == 0xFF00FF00, ("PrimQuadUV vertex %s %s %s %s %x"):format(x, y, u, v, col))
|
||||
local idx = dl.IdxBuffer.Data
|
||||
check(idx[i0 + 1] == v0 + 1 and idx[i0 + 5] == v0 + 3 and idx[i0 + 6] == v0 + 4, "PrimQuadUV indices")
|
||||
local cmin, cmax = dl:GetClipRectMin(), dl:GetClipRectMax()
|
||||
check(cmax.x > cmin.x and cmax.y > cmin.y, "GetClipRectMin/Max")
|
||||
|
||||
local clone = dl:CloneOutput()
|
||||
check(clone.VtxBuffer.Size == dl.VtxBuffer.Size and clone.IdxBuffer.Size == dl.IdxBuffer.Size and clone.CmdBuffer.Size == dl.CmdBuffer.Size
|
||||
and clone.VtxBuffer.Buf ~= dl.VtxBuffer.Buf and clone.CmdBuffer.Data[1] ~= dl.CmdBuffer.Data[1], "CloneOutput copies buffers")
|
||||
local cx = vtx(clone, v0 + 3)
|
||||
check(cx == 48, "CloneOutput vertex data")
|
||||
|
||||
local dd = G.ImDrawData()
|
||||
dd.CmdLists:push_back(clone)
|
||||
local n_idx = clone.IdxBuffer.Size
|
||||
local ex, ey = vtx(clone, clone.IdxBuffer.Data[n_idx])
|
||||
dd:DeIndexAllBuffers()
|
||||
check(clone.IdxBuffer.Size == 0 and clone.VtxBuffer.Size == n_idx and dd.TotalVtxCount == n_idx and dd.TotalIdxCount == 0, "DeIndexAllBuffers counts")
|
||||
local lx, ly = vtx(clone, n_idx)
|
||||
check(lx == ex and ly == ey, "DeIndexAllBuffers vertex data")
|
||||
|
||||
local cr = clone.CmdBuffer.Data[1].ClipRect
|
||||
local x1, y1, z1, w1 = cr.x, cr.y, cr.z, cr.w
|
||||
dd:ScaleClipRects(ImVec2(2, 3))
|
||||
local cr2 = clone.CmdBuffer.Data[1].ClipRect
|
||||
check(cr2.x == x1 * 2 and cr2.y == y1 * 3 and cr2.z == z1 * 2 and cr2.w == w1 * 3 and dl.CmdBuffer.Data[1].ClipRect.z == z1, "ScaleClipRects")
|
||||
end
|
||||
|
||||
if f == 31 then
|
||||
local g = ImGui.GetCurrentContext()
|
||||
local style = ImGui.GetStyle()
|
||||
local window = ImGui.GetCurrentWindow()
|
||||
check(G.ImGuiKey["0"] == G.ImGuiKey.K0 and G.ImGuiKey["9"] == G.ImGuiKey.K9, "ImGuiKey digit aliases")
|
||||
|
||||
-- Style vars (enum values must match GStyleVarsInfo order)
|
||||
local sv = G.ImGuiStyleVar
|
||||
local b1, b2, b3 = style.SeparatorSize, style.SeparatorTextBorderSize, style.DockingSeparatorSize
|
||||
ImGui.PushStyleVar(sv.SeparatorSize, 5); ImGui.PushStyleVar(sv.SeparatorTextBorderSize, 6); ImGui.PushStyleVar(sv.DockingSeparatorSize, 7)
|
||||
check(style.SeparatorSize == 5 and style.SeparatorTextBorderSize == 6 and style.DockingSeparatorSize == 7, "PushStyleVar SeparatorSize/SeparatorTextBorderSize/DockingSeparatorSize")
|
||||
ImGui.PushStyleVar(sv.SeparatorTextPadding, ImVec2(3, 4))
|
||||
check(style.SeparatorTextPadding.x == 3 and style.SeparatorTextPadding.y == 4, "PushStyleVar SeparatorTextPadding")
|
||||
ImGui.PopStyleVar(4)
|
||||
check(style.SeparatorSize == b1 and style.SeparatorTextBorderSize == b2 and style.DockingSeparatorSize == b3, "PopStyleVar restores")
|
||||
|
||||
-- Log flags
|
||||
ImGui.LogToBuffer()
|
||||
check(g.LogEnabled and g.LogFlags == G.ImGuiLogFlags.OutputBuffer, "LogToBuffer sets ImGuiLogFlags.OutputBuffer")
|
||||
ImGui.Text("logged")
|
||||
check(string.find(g.LogBuffer:c_str(), "logged", 1, true) ~= nil, "LogToBuffer captures text")
|
||||
ImGui.LogFinish()
|
||||
check(g.LogFlags == G.ImGuiLogFlags.None and not g.LogEnabled, "LogFinish clears LogFlags")
|
||||
|
||||
-- Combo preview (no ImGuiComboFlags.CustomPreview needed since 1.93)
|
||||
if ImGui.BeginCombo("##cb", "") then ImGui.EndCombo() end
|
||||
local pd = g.ComboPreviewData
|
||||
local work_max_x, content_max_x = window.WorkRect.Max.x, window.ContentRegionRect.Max.x
|
||||
local opened = ImGui.BeginComboPreview()
|
||||
check(opened and pd.WithinPreview and window.WorkRect.Max.x == pd.PreviewRect.Max.x - style.FramePadding.x and window.ContentRegionRect.Max.x == window.WorkRect.Max.x, "BeginComboPreview sets WorkRect")
|
||||
if opened then
|
||||
ImGui.Text("preview")
|
||||
ImGui.EndComboPreview()
|
||||
end
|
||||
check(not pd.WithinPreview and window.WorkRect.Max.x == work_max_x and window.ContentRegionRect.Max.x == content_max_x, "EndComboPreview restores WorkRect")
|
||||
if ImGui.BeginCombo("##cb2", "x", G.ImGuiComboFlags.NoPreview) then ImGui.EndCombo() end
|
||||
check(not ImGui.BeginComboPreview(), "BeginComboPreview with NoPreview returns false")
|
||||
|
||||
-- ListClipper in a table: ImGuiListClipperFlags.NoSetTableRowCounters
|
||||
local rows = {}
|
||||
ImGui.SetNextWindowPos(ImVec2(500, 10)); ImGui.SetNextWindowSize(ImVec2(300, 400))
|
||||
ImGui.Begin("Clip")
|
||||
for pass = 1, 2 do
|
||||
if ImGui.BeginTable("##clip" .. pass, 1, G.ImGuiTableFlags.ScrollY, ImVec2(0, 60)) then
|
||||
local clipper = G.ImGuiListClipper()
|
||||
if pass == 2 then clipper.Flags = G.ImGuiListClipperFlags.NoSetTableRowCounters end
|
||||
clipper:Begin(1000)
|
||||
while clipper:Step() do
|
||||
for i = clipper.DisplayStart, clipper.DisplayEnd - 1 do ImGui.TableNextRow(); ImGui.TableNextColumn(); ImGui.Text("%d", i) end
|
||||
end
|
||||
clipper:End()
|
||||
rows[pass] = ImGui.GetCurrentTable().CurrentRow
|
||||
local tbl = ImGui.GetCurrentTable()
|
||||
ImGui.EndTable()
|
||||
if pass == 1 then ImGui.SetNextItemOpen(true); ImGui.DebugNodeTable(tbl) end -- DebugNodeTableGetSizingPolicyDesc()
|
||||
end
|
||||
end
|
||||
ImGui.End()
|
||||
check(rows[1] ~= nil and rows[2] ~= nil and rows[1] >= 990 and rows[2] < 100, ("clipper row counters %s / NoSetTableRowCounters %s"):format(tostring(rows[1]), tostring(rows[2])))
|
||||
|
||||
-- .ini LastUsed dates + CleanupIniSettings()
|
||||
local pio = ImGui.GetPlatformIO()
|
||||
pio.Platform_SessionDate = 20261015
|
||||
g.SessionDate = G.ImGuiPackedDate(pio.Platform_SessionDate) -- (normally done by NewFrame())
|
||||
io.ConfigIniSettingsAutoDiscardMonths = 6
|
||||
ImGui.LoadIniSettingsFromMemory("[Window][Old]\nPos=1,1\nLastUsed=20250101\n\n[Window][NoDate]\nPos=2,2\n\n[Window][Recent]\nPos=3,3\nLastUsed=20260901\n\n")
|
||||
io.ConfigIniSettingsAutoDiscardMonths = 0
|
||||
local function ws(name) for _, st in g.SettingsWindows.Data do if st.Name == name then return st end end; return nil end
|
||||
check(ws("Old").WantDelete and ws("NoDate").WantDelete and not ws("Recent").WantDelete and ws("Recent").LastUsedDate == 20260901, "ConfigIniSettingsAutoDiscardMonths discards old/undated entries")
|
||||
local args = G.ImGuiSettingsCleanupArgs()
|
||||
args.SetCurrentSessionDateToAll = true
|
||||
args.TypeHashFilter = G.ImHashStr("Window")
|
||||
ImGui.CleanupIniSettings(args)
|
||||
check(ws("Recent").LastUsedDate == 20261015, "CleanupIniSettings SetCurrentSessionDateToAll")
|
||||
local ini = ImGui.SaveIniSettingsToMemory()
|
||||
check(not string.find(ini, "[Window][Old]", 1, true) and string.find(ini, "[Window][Recent]\nPos=3,3\nCollapsed=0\nLastUsed=20261015\n", 1, true) ~= nil
|
||||
and string.find(ini, "[Window][H]\nPos=10,10\nSize=400,300\nCollapsed=0\nLastUsed=20261015\n", 1, true) ~= nil, "LastUsed written to .ini:\n" .. ini)
|
||||
io.ConfigIniSettingsSaveLastUsedDate = false
|
||||
check(not string.find(ImGui.SaveIniSettingsToMemory(), "LastUsed", 1, true), "ConfigIniSettingsSaveLastUsedDate = false")
|
||||
io.ConfigIniSettingsSaveLastUsedDate = true
|
||||
pio.Platform_SessionDate = 0
|
||||
|
||||
-- Log decorations: Selectable/Button/Checkbox/MenuItem shortcut
|
||||
ImGui.LogToBuffer()
|
||||
ImGui.Selectable("sel item")
|
||||
ImGui.Button("btn")
|
||||
ImGui.Checkbox("chk", true)
|
||||
ImGui.MenuItem("mi", "Ctrl+M")
|
||||
local log = g.LogBuffer:c_str()
|
||||
ImGui.LogFinish()
|
||||
check(string.find(log, "[sel item]", 1, true) == nil and string.find(log, "sel item", 1, true) ~= nil, "Selectable logs plain label: " .. log)
|
||||
check(string.find(log, "[ btn ]", 1, true) ~= nil and string.find(log, "[x]", 1, true) ~= nil and string.find(log, "mi ( Ctrl+M )", 1, true) ~= nil, "LogSetNextTextDecoration [ ]: " .. log)
|
||||
|
||||
-- DragScalar S64/U64 (doubles) + DataTypeFormatString
|
||||
local v64, ch = ImGui.DragScalar("##s64", G.ImGuiDataType.S64, 2 ^ 40, 1.0)
|
||||
check(v64 == 2 ^ 40 and ch == false, "DragScalar S64 idle")
|
||||
local b64 = {}
|
||||
local n = ImGui.DataTypeFormatString(b64, 64, G.ImGuiDataType.S64, -(2 ^ 40), "%lld")
|
||||
check(G.ImGui._ByteArrayToString(b64, 1, n + 1) == "-1099511627776", "DataTypeFormatString S64")
|
||||
n = ImGui.DataTypeFormatString(b64, 64, G.ImGuiDataType.U64, 18446744073709551615, "%llu")
|
||||
check(G.ImGui._ByteArrayToString(b64, 1, n + 1) == "18446744073709551615", "DataTypeFormatString U64 max")
|
||||
n = ImGui.DataTypeFormatString(b64, 64, G.ImGuiDataType.S32, -5, "%X")
|
||||
check(G.ImGui._ByteArrayToString(b64, 1, n + 1) == "FFFFFFFB", "DataTypeFormatString S32 hex")
|
||||
local tb = ImGui.NewTextBuffer("-123456789012", 64)
|
||||
local r64, c64 = ImGui.DataTypeApplyFromText(tb, G.ImGuiDataType.S64, 0, "%lld")
|
||||
check(r64 == -123456789012 and c64, "DataTypeApplyFromText S64 " .. tostring(r64))
|
||||
check(ImGui.DataTypeApplyOp(G.ImGuiDataType.S64, 43, 2 ^ 62, 2 ^ 62) == 9223372036854775807, "DataTypeApplyOp S64 clamp")
|
||||
check(G.ImGuiDataType.Float == 8 and G.ImGuiDataType.COUNT == 12 and ImGui.DataTypeGetInfo(G.ImGuiDataType.Float).Name == "float", "ImGuiDataType layout")
|
||||
end
|
||||
-- DragScalar S64: drag with the mouse
|
||||
local s64_rect
|
||||
s64_v = ImGui.DragScalar("##drag_s64", G.ImGuiDataType.S64, s64_v, 1.0)
|
||||
do local a, b = ImGui.GetItemRectMin(), ImGui.GetItemRectMax(); s64_rect = { ImVec2(a.x, a.y), ImVec2(b.x, b.y) } end
|
||||
if f == 33 then io:AddMousePosEvent(center(s64_rect)) end
|
||||
if f == 34 then io:AddMouseButtonEvent(0, true) end
|
||||
if f == 35 then local x, y = center(s64_rect); io:AddMousePosEvent(x + 30, y) end
|
||||
if f == 37 then io:AddMouseButtonEvent(0, false); check(s64_v > 2 ^ 40 and s64_v == math.floor(s64_v), "DragScalar S64 drag " .. s64_v) end
|
||||
ImGui.End()
|
||||
|
||||
-- BringWindowToDisplayBehind
|
||||
if f == 38 then
|
||||
local g = ImGui.GetCurrentContext()
|
||||
local wa, wb, wc = ImGui.FindWindowByName("WA"), ImGui.FindWindowByName("WB"), ImGui.FindWindowByName("WC")
|
||||
local function idx(w) return ImGui.FindWindowDisplayIndex(w) end
|
||||
ImGui.BringWindowToDisplayFront(wa); ImGui.BringWindowToDisplayFront(wb); ImGui.BringWindowToDisplayFront(wc)
|
||||
local n0 = g.Windows.Size
|
||||
ImGui.BringWindowToDisplayBehind(wc, wa) -- move forward-placed window behind: WC WA WB
|
||||
check(idx(wc) + 1 == idx(wa) and idx(wa) + 1 == idx(wb) and g.Windows.Size == n0, ("BringWindowToDisplayBehind back %d %d %d"):format(idx(wa), idx(wb), idx(wc)))
|
||||
ImGui.BringWindowToDisplayBehind(wa, wb) -- already directly behind: unchanged
|
||||
check(idx(wc) + 1 == idx(wa) and idx(wa) + 1 == idx(wb), "BringWindowToDisplayBehind no-op")
|
||||
ImGui.BringWindowToDisplayBehind(wc, wb) -- WA WC WB
|
||||
check(idx(wa) + 1 == idx(wc) and idx(wc) + 1 == idx(wb) and g.Windows.Size == n0, ("BringWindowToDisplayBehind fwd %d %d %d"):format(idx(wa), idx(wb), idx(wc)))
|
||||
end
|
||||
for _, name in { "WA", "WB", "WC" } do
|
||||
ImGui.SetNextWindowPos(ImVec2(820, 10)); ImGui.SetNextWindowSize(ImVec2(80, 60))
|
||||
ImGui.Begin(name); ImGui.End()
|
||||
end
|
||||
|
||||
-- Size callback (Step + AspectRatio)
|
||||
ImGui.SetNextWindowPos(ImVec2(10, 420))
|
||||
if f <= 3 then ImGui.SetNextWindowSize(ImVec2(237, 160)) end
|
||||
ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(G.FLT_MAX, G.FLT_MAX), function(data)
|
||||
local step = data.UserData
|
||||
check(data.Pos ~= nil and data.CurrentSize ~= nil and not rawequal(data.DesiredSize, data.CurrentSize), "ImGuiSizeCallbackData fields")
|
||||
data.DesiredSize = ImVec2(math.floor(data.DesiredSize.x / step + 0.5) * step, math.floor(data.DesiredSize.y / step + 0.5) * step)
|
||||
end, 100.0)
|
||||
ImGui.Begin("Step"); local step_size = ImGui.GetWindowSize(); ImGui.End()
|
||||
ImGui.SetNextWindowPos(ImVec2(300, 420))
|
||||
if f <= 3 then ImGui.SetNextWindowSize(ImVec2(320, 100)) end
|
||||
ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(G.FLT_MAX, G.FLT_MAX), function(data)
|
||||
data.DesiredSize.y = math.floor(data.DesiredSize.x / data.UserData)
|
||||
end, 16 / 9)
|
||||
ImGui.Begin("Aspect"); local asp_size = ImGui.GetWindowSize(); ImGui.End()
|
||||
if f == 5 then
|
||||
check(step_size.x == 200 and step_size.y == 200, ("size callback Step %gx%g"):format(step_size.x, step_size.y))
|
||||
check(asp_size.x == 320 and asp_size.y == 180, ("size callback AspectRatio %gx%g"):format(asp_size.x, asp_size.y))
|
||||
end
|
||||
ImGui.Render(); G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
if f == 40 and #failed == 0 then print("HELPERS OK") end
|
||||
end)
|
||||
@@ -0,0 +1,94 @@
|
||||
-- Library-only draw-data checksum (no demo, run with NO_DEMO=1): widgets + raw ImDrawList primitives with scripted input.
|
||||
-- Must stay identical across demo edits; changes only when library rendering changes. Prints "LIBHASH <n>".
|
||||
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4
|
||||
ImGui.CreateContext(); G.ImGui_ImplRoblox.Init(); G.ImGui_ImplRoblox.SetRenderRate(0)
|
||||
local io = ImGui.GetIO()
|
||||
local frame, h = 0, 0
|
||||
local function mix(v) h = (h * 31 + math.floor(v * 64 + 0.5)) % 2147483647 end
|
||||
local st = { b = false, f = 0.25, i = 42, c = ImVec4(0.2, 0.7, 0.4, 1.0), buf = ImGui.NewTextBuffer("hello", 64), r = 0, tab = 0, combo = 1, list = 2 }
|
||||
local plot = {}
|
||||
for i = 1, 40 do plot[i] = math.sin(i * 0.3) end
|
||||
local poly = { ImVec2(0, 0), ImVec2(60, 10), ImVec2(30, 30), ImVec2(70, 60), ImVec2(0, 50) }
|
||||
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
frame += 1
|
||||
G.ImGui_ImplRoblox.NewFrame()
|
||||
io.DeltaTime = 1 / 60
|
||||
io:AddMousePosEvent(20 + (frame * 37) % 560, 20 + (frame * 53) % 560)
|
||||
if frame % 7 == 0 then io:AddMouseButtonEvent(0, frame % 14 == 0) end
|
||||
if frame % 11 == 0 then io:AddMouseWheelEvent(0, -1) end
|
||||
ImGui.NewFrame()
|
||||
|
||||
ImGui.SetNextWindowPos(ImVec2(10, 10), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(320, 560), G.ImGuiCond.Always)
|
||||
ImGui.Begin("Widgets")
|
||||
ImGui.Text("Text %d", 123); ImGui.TextColored(ImVec4(1, 0.5, 0, 1), "Colored"); ImGui.TextWrapped("Wrapped text that is long enough to wrap around the window edge at least once.")
|
||||
ImGui.Button("Button"); ImGui.SameLine(); ImGui.SmallButton("Small"); ImGui.SameLine(); ImGui.ArrowButton("##a", G.ImGuiDir.Left)
|
||||
st.b = ImGui.Checkbox("Checkbox", st.b)
|
||||
st.r = ImGui.RadioButton("R0", st.r, 0); ImGui.SameLine(); st.r = ImGui.RadioButton("R1", st.r, 1)
|
||||
st.f = ImGui.SliderFloat("Slider", st.f, 0, 1); st.i = ImGui.DragInt("Drag", st.i, 1, 0, 100)
|
||||
ImGui.InputText("Input", st.buf, 64)
|
||||
ImGui.ColorEdit4("Color", st.c)
|
||||
st.combo = ImGui.Combo("Combo", st.combo, { "AAA", "BBB", "CCC" })
|
||||
st.list = ImGui.ListBox("List", st.list, { "one", "two", "three", "four" }, 4, 3)
|
||||
ImGui.ProgressBar(0.4, ImVec2(-1, 0)); ImGui.ProgressBar(-1.0 * frame / 60, ImVec2(-1, 0), "busy")
|
||||
ImGui.PlotLines("Lines", plot, nil, #plot); ImGui.PlotHistogram("Hist", plot, nil, #plot, 0, nil, -1, 1, ImVec2(0, 40))
|
||||
ImGui.Bullet(); ImGui.Text("bullet"); ImGui.Separator(); ImGui.SeparatorText("Sep")
|
||||
if ImGui.TreeNode("Tree") then ImGui.Text("inside"); ImGui.TreePop() end
|
||||
ImGui.SetNextItemOpen(true, G.ImGuiCond.Once)
|
||||
if ImGui.CollapsingHeader("Header") then
|
||||
if ImGui.BeginTabBar("tabs") then
|
||||
if ImGui.BeginTabItem("Tab A") then ImGui.Text("A"); ImGui.EndTabItem() end
|
||||
if ImGui.BeginTabItem("Tab B") then ImGui.Text("B"); ImGui.EndTabItem() end
|
||||
ImGui.EndTabBar()
|
||||
end
|
||||
if ImGui.BeginTable("t", 3, bit32.bor(G.ImGuiTableFlags.Borders, G.ImGuiTableFlags.RowBg, G.ImGuiTableFlags.Resizable)) then
|
||||
ImGui.TableSetupColumn("One"); ImGui.TableSetupColumn("Two"); ImGui.TableSetupColumn("Three"); ImGui.TableHeadersRow()
|
||||
for row = 0, 4 do ImGui.TableNextRow(); for col = 0, 2 do ImGui.TableSetColumnIndex(col); ImGui.Text("r%d c%d", row, col) end end
|
||||
ImGui.EndTable()
|
||||
end
|
||||
end
|
||||
ImGui.End()
|
||||
|
||||
ImGui.SetNextWindowPos(ImVec2(340, 10), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(300, 560), G.ImGuiCond.Always)
|
||||
ImGui.Begin("Draw")
|
||||
local dl, p = ImGui.GetWindowDrawList(), ImGui.GetCursorScreenPos()
|
||||
local x, y, col = p.x + 4, p.y + 4, 0xFF40C0FF
|
||||
for i, th in { 1.0, 2.5, 6.0 } do
|
||||
local yy = y + (i - 1) * 70
|
||||
dl:AddRect(ImVec2(x, yy), ImVec2(x + 50, yy + 50), col, 10.0, th)
|
||||
dl:AddRectFilled(ImVec2(x + 60, yy), ImVec2(x + 110, yy + 50), col, 10.0, G.ImDrawFlags.RoundTopLeft or G.ImDrawFlags.RoundCornersTopLeft) -- RoundCornersTopLeft: pre-1.93 revs (hashes.sh)
|
||||
dl:AddCircle(ImVec2(x + 145, yy + 25), 25, col, 0, th)
|
||||
dl:AddNgon(ImVec2(x + 200, yy + 25), 25, col, 6, th)
|
||||
dl:AddTriangle(ImVec2(x + 230, yy + 50), ImVec2(x + 255, yy), ImVec2(x + 280, yy + 50), col, th)
|
||||
dl:AddLine(ImVec2(x, yy + 60), ImVec2(x + 280, yy + 55), col, th)
|
||||
end
|
||||
y += 210
|
||||
dl:AddBezierCubic(ImVec2(x, y), ImVec2(x + 60, y - 30), ImVec2(x + 120, y + 60), ImVec2(x + 180, y), col, 3.0)
|
||||
dl:AddBezierQuadratic(ImVec2(x, y + 30), ImVec2(x + 90, y - 10), ImVec2(x + 180, y + 30), col, 2.0)
|
||||
dl:AddEllipse(ImVec2(x + 230, y + 15), ImVec2(40, 15), col, 0.5, 0, 2.0)
|
||||
y += 50
|
||||
local pts = {}
|
||||
for i, v in poly do pts[i] = ImVec2(x + v.x, y + v.y) end
|
||||
dl:AddConcavePolyFilled(pts, #pts, 0xFF8080FF)
|
||||
for i, v in poly do pts[i] = ImVec2(x + 100 + v.x, y + v.y) end
|
||||
dl:AddPolyline(pts, #pts, col, 4.0, G.ImDrawFlags.Closed)
|
||||
for i, v in poly do pts[i] = ImVec2(x + 200 + v.x, y + v.y) end
|
||||
dl:AddPolyline(pts, #pts, col, 1.0, 0)
|
||||
y += 80
|
||||
dl:AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x + 100, y + 40), 0xFF0000FF, 0xFF00FF00, 0xFFFF0000, 0xFFFFFFFF)
|
||||
dl:AddCircleFilled(ImVec2(x + 140, y + 20), 20, col)
|
||||
dl:AddEllipseFilled(ImVec2(x + 210, y + 20), ImVec2(30, 15), col, 0.3)
|
||||
dl:AddText(ImVec2(x, y + 50), 0xFFFFFFFF, "AddText")
|
||||
ImGui.End()
|
||||
|
||||
ImGui.Render()
|
||||
for _, dl in ImGui.GetDrawData().CmdLists:iter() do
|
||||
local vb, id = dl.VtxBuffer.Buf, dl.IdxBuffer.Data
|
||||
for i = 1, dl.VtxBuffer.Size do local o = (i - 1) * 36; mix(buffer.readf64(vb, o)); mix(buffer.readf64(vb, o + 8)); mix(buffer.readf64(vb, o + 16) * 4096); mix(buffer.readf64(vb, o + 24) * 4096); mix(buffer.readu32(vb, o + 32) / 64) end
|
||||
for i = 1, dl.IdxBuffer.Size do mix(id[i]) end
|
||||
for _, c in dl.CmdBuffer:iter() do mix(c.ClipRect.x); mix(c.ClipRect.y); mix(c.ClipRect.z); mix(c.ClipRect.w); mix(c.ElemCount) end
|
||||
end
|
||||
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
if frame == ARG_FRAMES - 1 then print("LIBHASH", h) end
|
||||
end)
|
||||
@@ -0,0 +1,265 @@
|
||||
-- Multi-select / box-select / typing-select: ImGuiSelectionBasicStorage + Selectable list (click, Ctrl+click, Shift+click, Ctrl+A,
|
||||
-- Escape, box-select drag, keyboard nav + Shift, typing-select), ImGuiListClipper + IncludeItemByIndex(RangeSrcItem),
|
||||
-- ImGuiSelectionExternalStorage on a bool array, checkboxes and tree nodes inside a multi-select scope.
|
||||
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2 = G.ImGui, G.ImVec2
|
||||
local MSF = G.ImGuiMultiSelectFlags
|
||||
ImGui.CreateContext(); G.ImGui_ImplRoblox.Init()
|
||||
local io = ImGui.GetIO()
|
||||
io.ConfigFlags = bit32.bor(io.ConfigFlags, G.ImGuiConfigFlags.NavEnableKeyboard)
|
||||
local failed = {}
|
||||
local function check(ok, msg) if not ok then table.insert(failed, msg); print("FAIL " .. msg) end end
|
||||
|
||||
local NAMES = { "Apple", "Apricot", "Banana", "Blueberry", "Cherry", "Coconut", "Date", "Durian", "Elderberry", "Fig",
|
||||
"Grape", "Guava", "Kiwi", "Lemon", "Lime", "Mango", "Melon", "Orange", "Papaya", "Peach" }
|
||||
local N = #NAMES
|
||||
|
||||
-- Iterate with GetNextSelectedItem() (sorted by key) -> "a,b,c"
|
||||
local function sel_str(sel)
|
||||
local out, it, id, has_more = {}, nil, 0, false
|
||||
while true do
|
||||
has_more, it, id = sel:GetNextSelectedItem(it)
|
||||
if not has_more then break end
|
||||
table.insert(out, tostring(id))
|
||||
end
|
||||
return table.concat(out, ",")
|
||||
end
|
||||
local function bools_str(t, n)
|
||||
local out = {}
|
||||
for i = 1, n do if t[i] then table.insert(out, tostring(i - 1)) end end
|
||||
return table.concat(out, ",")
|
||||
end
|
||||
|
||||
local sel_list = G.ImGuiSelectionBasicStorage()
|
||||
local sel_clip = G.ImGuiSelectionBasicStorage()
|
||||
local sel_tree = G.ImGuiSelectionBasicStorage()
|
||||
local ext_bools = {}
|
||||
local sel_ext = G.ImGuiSelectionExternalStorage()
|
||||
sel_ext.UserData = ext_bools
|
||||
sel_ext.AdapterSetItemSelected = function(self, idx, selected) self.UserData[idx + 1] = selected end
|
||||
local chk_bools = {}
|
||||
local sel_chk = G.ImGuiSelectionExternalStorage()
|
||||
sel_chk.UserData = chk_bools
|
||||
sel_chk.AdapterSetItemSelected = function(self, idx, selected) self.UserData[idx + 1] = selected end
|
||||
|
||||
local rects = {} -- [name] = { min, max } (copies)
|
||||
local ids = {} -- [name] = item id
|
||||
local function rect() local a, b = ImGui.GetItemRectMin(), ImGui.GetItemRectMax(); return { ImVec2(a.x, a.y), ImVec2(b.x, b.y) } end
|
||||
local function center(name) local r = rects[name]; return (r[1].x + r[2].x) / 2, (r[1].y + r[2].y) / 2 end
|
||||
local function key(k) io:AddKeyEvent(k, true); io:AddKeyEvent(k, false) end
|
||||
local function mods(ctrl, shift) io:AddKeyEvent(G.ImGuiMod_Ctrl, ctrl == true); io:AddKeyEvent(G.ImGuiMod_Shift, shift == true) end
|
||||
|
||||
-- Schedule: each step = { input = fn (before NewFrame), check = fn (after Render) }. Steps run on consecutive frames.
|
||||
local steps = {}
|
||||
local function step(input, chk) table.insert(steps, { input = input, check = chk }) end
|
||||
local function idle(n) for _ = 1, n or 1 do step(nil, nil) end end
|
||||
-- click: press (+mods) on frame A, release on frame B, then one idle frame for EndMultiSelect requests to be applied
|
||||
local function click(name, ctrl, shift)
|
||||
step(function() mods(ctrl, shift); io:AddMousePosEvent(center(name)); io:AddMouseButtonEvent(0, true) end)
|
||||
step(function() io:AddMouseButtonEvent(0, false) end)
|
||||
step(function() mods(false, false) end)
|
||||
end
|
||||
|
||||
local typed_focus_idx = -1
|
||||
local clip_scroll_request = false
|
||||
local f = 0
|
||||
|
||||
idle(3)
|
||||
-- 1. List: click selects one
|
||||
click("L2"); step(nil, function() check(sel_str(sel_list) == "2", "click: " .. sel_str(sel_list)) end)
|
||||
-- 2. Ctrl+click toggles
|
||||
click("L5", true); step(nil, function() check(sel_str(sel_list) == "2,5", "ctrl+click add: " .. sel_str(sel_list)) end)
|
||||
click("L2", true); step(nil, function() check(sel_str(sel_list) == "5", "ctrl+click remove: " .. sel_str(sel_list)) end)
|
||||
-- 3. Shift+click range (from RangeSrc = 2, the last Ctrl+clicked item)
|
||||
click("L8", false, true); step(nil, function() check(sel_str(sel_list) == "2,3,4,5,6,7,8", "shift+click range: " .. sel_str(sel_list)) end)
|
||||
-- 4. Ctrl+A
|
||||
step(function() io:AddKeyEvent(G.ImGuiMod_Ctrl, true); io:AddKeyEvent(G.ImGuiKey.A, true) end)
|
||||
step(function() io:AddKeyEvent(G.ImGuiKey.A, false); io:AddKeyEvent(G.ImGuiMod_Ctrl, false) end)
|
||||
step(nil, function() check(sel_list.Size == N, "ctrl+A size " .. sel_list.Size) end)
|
||||
-- 5. Escape clears (ClearOnEscape)
|
||||
step(function() key(G.ImGuiKey.Escape) end)
|
||||
step(nil, function() check(sel_list.Size == 0 and sel_str(sel_list) == "", "escape clear: " .. sel_str(sel_list)) end)
|
||||
-- 6. Box-select drag (BoxSelect1d) from item 2 to item 5
|
||||
step(function() io:AddMousePosEvent(center("L2")); io:AddMouseButtonEvent(0, true) end)
|
||||
step(function() local x, y = center("L2"); io:AddMousePosEvent(x + 2, y + 10) end)
|
||||
step(function() local x, y = center("L4"); io:AddMousePosEvent(x + 4, y) end)
|
||||
step(function() local x, y = center("L5"); io:AddMousePosEvent(x + 4, y) end,
|
||||
function() check(ImGui.GetCurrentContext().BoxSelectState.IsActive, "box-select active while dragging") end)
|
||||
step(nil)
|
||||
step(function() io:AddMouseButtonEvent(0, false) end)
|
||||
step(nil, function() check(sel_str(sel_list) == "2,3,4,5", "box-select: " .. sel_str(sel_list)); check(not ImGui.GetCurrentContext().BoxSelectState.IsActive, "box-select ended") end)
|
||||
-- 7. Keyboard nav: click 3, Down -> 4 (auto-select), Shift+Down x2 -> 4..6
|
||||
click("L3"); step(nil, function() check(sel_str(sel_list) == "3", "click before nav: " .. sel_str(sel_list)) end)
|
||||
step(function() key(G.ImGuiKey.DownArrow) end); idle(2)
|
||||
step(nil, function() check(sel_str(sel_list) == "4", "nav down auto-select: " .. sel_str(sel_list)) end)
|
||||
step(function() io:AddKeyEvent(G.ImGuiMod_Shift, true); key(G.ImGuiKey.DownArrow) end); idle(1)
|
||||
step(function() key(G.ImGuiKey.DownArrow) end); idle(1)
|
||||
step(function() io:AddKeyEvent(G.ImGuiMod_Shift, false) end); idle(1)
|
||||
step(nil, function() check(sel_str(sel_list) == "4,5,6", "shift+nav range: " .. sel_str(sel_list)) end)
|
||||
-- 8. Typing-select: "ch" -> Cherry (5), then single-char mode "b" "b" -> Banana (2) then Blueberry (3)
|
||||
step(function() io:AddInputCharacter(string.byte("c")); io:AddInputCharacter(string.byte("h")) end); idle(2)
|
||||
step(nil, function() check(ImGui.GetCurrentContext().NavId == ids.L4, "typing 'ch' -> Cherry"); check(sel_str(sel_list) == "4", "typing focus selects: " .. sel_str(sel_list)) end)
|
||||
idle(120) -- TYPING_SELECT_RESET_TIMER
|
||||
step(function() io:AddInputCharacter(string.byte("b")) end); idle(2)
|
||||
step(nil, function() check(ImGui.GetCurrentContext().NavId == ids.L2, "typing 'b' -> Banana") end)
|
||||
step(function() io:AddInputCharacter(string.byte("b")) end); idle(2)
|
||||
step(nil, function() check(ImGui.GetCurrentContext().NavId == ids.L3, "typing 'bb' -> Blueberry") end)
|
||||
idle(120)
|
||||
|
||||
-- 9. Clipper (1000 items): click 5, scroll down, Shift+click item 40 -> 5..40 (RangeSrcItem 5 kept submitted by IncludeItemByIndex)
|
||||
click("C5")
|
||||
-- move NavId away with Ctrl+Down (no selection change, RangeSrc stays 5) so the clipper doesn't keep item 5 alive as the nav item
|
||||
step(function() io:AddKeyEvent(G.ImGuiMod_Ctrl, true); key(G.ImGuiKey.DownArrow) end); idle(1)
|
||||
step(function() key(G.ImGuiKey.DownArrow) end); idle(1)
|
||||
step(function() key(G.ImGuiKey.DownArrow) end); idle(1)
|
||||
step(function() io:AddKeyEvent(G.ImGuiMod_Ctrl, false) end)
|
||||
step(nil, function() check(sel_str(sel_clip) == "5", "clipper ctrl+nav keeps selection: " .. sel_str(sel_clip)) end)
|
||||
step(function() clip_scroll_request = true end); idle(2)
|
||||
step(nil, function() check(rects.C40 ~= nil and rects.C5 == nil, "clipper scrolled (item 5 not visible)") end)
|
||||
click("C40", false, true)
|
||||
step(nil, function() check(sel_clip.Size == 36, "clipper shift+click range size " .. sel_clip.Size); check(sel_clip:Contains(5) and sel_clip:Contains(40) and not sel_clip:Contains(4) and not sel_clip:Contains(41), "clipper range bounds") end)
|
||||
|
||||
-- 10. External storage on bool array: click 1, Shift+click 3, Ctrl+click 2
|
||||
click("E1"); click("E3", false, true)
|
||||
step(nil, function() check(bools_str(ext_bools, 10) == "1,2,3", "external storage range: " .. bools_str(ext_bools, 10)) end)
|
||||
click("E2", true)
|
||||
step(nil, function() check(bools_str(ext_bools, 10) == "1,3", "external storage ctrl+click: " .. bools_str(ext_bools, 10)) end)
|
||||
|
||||
-- 11. Checkboxes (NoAutoSelect|NoAutoClear): click 1 toggles on, Shift+click 4 -> 1..4 on, click 2 toggles off
|
||||
click("K1"); step(nil, function() check(bools_str(chk_bools, 8) == "1", "checkbox click: " .. bools_str(chk_bools, 8)) end)
|
||||
click("K4", false, true); step(nil, function() check(bools_str(chk_bools, 8) == "1,2,3,4", "checkbox shift+click: " .. bools_str(chk_bools, 8)) end)
|
||||
click("K2"); step(nil, function() check(bools_str(chk_bools, 8) == "1,3,4", "checkbox toggle off: " .. bools_str(chk_bools, 8)) end)
|
||||
|
||||
-- 12. Tree nodes: click 0, Ctrl+click 2, Shift+click 4 (range from 2)
|
||||
click("T0"); click("T2", true)
|
||||
step(nil, function() check(sel_str(sel_tree) == "0,2", "tree ctrl+click: " .. sel_str(sel_tree)) end)
|
||||
click("T4", false, true)
|
||||
step(nil, function() check(sel_str(sel_tree) == "2,3,4", "tree shift+click: " .. sel_str(sel_tree)) end)
|
||||
|
||||
-- 13. Metrics window renders the TypingSelect / MultiSelect debug nodes
|
||||
local show_metrics = false
|
||||
step(function() show_metrics = true end); idle(3)
|
||||
step(nil, function() if #failed == 0 then print("MULTISELECT OK") end end)
|
||||
|
||||
local function list_window()
|
||||
ImGui.SetNextWindowPos(ImVec2(10, 10)); ImGui.SetNextWindowSize(ImVec2(200, 420))
|
||||
ImGui.Begin("L")
|
||||
local flags = bit32.bor(MSF.ClearOnEscape, MSF.BoxSelect1d)
|
||||
local ms_io = ImGui.BeginMultiSelect(flags, sel_list.Size, N)
|
||||
sel_list:ApplyRequests(ms_io)
|
||||
-- typing-select
|
||||
local focus_idx = -1
|
||||
if ImGui.IsWindowFocused() then
|
||||
local req = ImGui.GetTypingSelectRequest(G.ImGuiTypingSelectFlags.AllowSingleCharMode)
|
||||
local nav_idx = (type(ms_io.NavIdItem) == "number") and ms_io.NavIdItem or -1
|
||||
focus_idx = ImGui.TypingSelectFindMatch(req, N, function(_, idx) return NAMES[idx + 1] end, nil, nav_idx)
|
||||
end
|
||||
for n = 0, N - 1 do
|
||||
if n == focus_idx then ImGui.SetKeyboardFocusHere() end
|
||||
ImGui.SetNextItemSelectionUserData(n)
|
||||
ImGui.Selectable(NAMES[n + 1], sel_list:Contains(n))
|
||||
rects["L" .. n] = rect(); ids["L" .. n] = ImGui.GetItemID()
|
||||
end
|
||||
ms_io = ImGui.EndMultiSelect()
|
||||
sel_list:ApplyRequests(ms_io)
|
||||
ImGui.End()
|
||||
end
|
||||
|
||||
local function clipper_window()
|
||||
ImGui.SetNextWindowPos(ImVec2(220, 10)); ImGui.SetNextWindowSize(ImVec2(200, 300))
|
||||
ImGui.Begin("C")
|
||||
if clip_scroll_request then ImGui.SetScrollY(ImGui.GetTextLineHeightWithSpacing() * 30); clip_scroll_request = false end
|
||||
local COUNT = 1000
|
||||
local ms_io = ImGui.BeginMultiSelect(MSF.ClearOnEscape, sel_clip.Size, COUNT)
|
||||
sel_clip:ApplyRequests(ms_io)
|
||||
local clipper = G.ImGuiListClipper()
|
||||
clipper:Begin(COUNT)
|
||||
if ms_io.RangeSrcItem ~= -1 then clipper:IncludeItemByIndex(ms_io.RangeSrcItem) end -- Ensure RangeSrc item is not clipped.
|
||||
for k in rects do if string.sub(k, 1, 1) == "C" then rects[k] = nil end end
|
||||
while clipper:Step() do
|
||||
for n = clipper.DisplayStart, clipper.DisplayEnd - 1 do
|
||||
ImGui.SetNextItemSelectionUserData(n)
|
||||
ImGui.Selectable(("Object %04d"):format(n), sel_clip:Contains(n))
|
||||
if ImGui.IsItemVisible() then rects["C" .. n] = rect() end
|
||||
end
|
||||
end
|
||||
ms_io = ImGui.EndMultiSelect()
|
||||
sel_clip:ApplyRequests(ms_io)
|
||||
ImGui.End()
|
||||
end
|
||||
|
||||
local function external_window()
|
||||
ImGui.SetNextWindowPos(ImVec2(430, 10)); ImGui.SetNextWindowSize(ImVec2(180, 220))
|
||||
ImGui.Begin("E")
|
||||
local ms_io = ImGui.BeginMultiSelect(MSF.None, -1, 10)
|
||||
sel_ext:ApplyRequests(ms_io)
|
||||
for n = 0, 9 do
|
||||
ImGui.SetNextItemSelectionUserData(n)
|
||||
ImGui.Selectable("Ext " .. n, ext_bools[n + 1] == true)
|
||||
rects["E" .. n] = rect()
|
||||
end
|
||||
ms_io = ImGui.EndMultiSelect()
|
||||
sel_ext:ApplyRequests(ms_io)
|
||||
ImGui.End()
|
||||
end
|
||||
|
||||
local function checkbox_window()
|
||||
ImGui.SetNextWindowPos(ImVec2(430, 240)); ImGui.SetNextWindowSize(ImVec2(180, 200))
|
||||
ImGui.Begin("K")
|
||||
local ms_io = ImGui.BeginMultiSelect(bit32.bor(MSF.NoAutoSelect, MSF.NoAutoClear, MSF.ClearOnEscape), -1, 8)
|
||||
sel_chk:ApplyRequests(ms_io)
|
||||
for n = 0, 7 do
|
||||
ImGui.SetNextItemSelectionUserData(n)
|
||||
local _, v = ImGui.Checkbox("Check " .. n, chk_bools[n + 1] == true)
|
||||
rects["K" .. n] = rect()
|
||||
local _ = v -- the selection is updated through requests (ApplyRequests), like upstream's demo
|
||||
end
|
||||
ms_io = ImGui.EndMultiSelect()
|
||||
sel_chk:ApplyRequests(ms_io)
|
||||
ImGui.End()
|
||||
end
|
||||
|
||||
local function tree_window()
|
||||
ImGui.SetNextWindowPos(ImVec2(220, 320)); ImGui.SetNextWindowSize(ImVec2(200, 160))
|
||||
ImGui.Begin("T")
|
||||
local ms_io = ImGui.BeginMultiSelect(MSF.None, sel_tree.Size, 5)
|
||||
sel_tree:ApplyRequests(ms_io)
|
||||
for n = 0, 4 do
|
||||
local flags = bit32.bor(G.ImGuiTreeNodeFlags.Leaf, G.ImGuiTreeNodeFlags.NoTreePushOnOpen, G.ImGuiTreeNodeFlags.SpanAvailWidth)
|
||||
if sel_tree:Contains(n) then flags = bit32.bor(flags, G.ImGuiTreeNodeFlags.Selected) end
|
||||
ImGui.SetNextItemSelectionUserData(n)
|
||||
ImGui.TreeNodeEx("Node " .. n, flags)
|
||||
rects["T" .. n] = rect()
|
||||
end
|
||||
ms_io = ImGui.EndMultiSelect()
|
||||
sel_tree:ApplyRequests(ms_io)
|
||||
ImGui.End()
|
||||
end
|
||||
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
f += 1
|
||||
G.ImGui_ImplRoblox.NewFrame()
|
||||
local s = steps[f]
|
||||
if s and s.input then s.input() end
|
||||
ImGui.NewFrame()
|
||||
list_window()
|
||||
clipper_window()
|
||||
external_window()
|
||||
checkbox_window()
|
||||
tree_window()
|
||||
if show_metrics then
|
||||
ImGui.SetNextWindowPos(ImVec2(620, 10)); ImGui.SetNextWindowSize(ImVec2(400, 600))
|
||||
ImGui.ShowMetricsWindow()
|
||||
local ctx = ImGui.GetCurrentContext()
|
||||
ImGui.Begin("DebugNodes")
|
||||
ImGui.DebugNodeTypingSelectState(ctx.TypingSelectState)
|
||||
for n = 0, ctx.MultiSelectStorage:GetMapSize() - 1 do
|
||||
local st = ctx.MultiSelectStorage:GetByIndex(n)
|
||||
if st then ImGui.SetNextItemOpen(true); ImGui.DebugNodeMultiSelectState(st) end
|
||||
end
|
||||
ImGui.End()
|
||||
end
|
||||
ImGui.Render(); G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
if s and s.check then s.check() end
|
||||
end)
|
||||
print(("t_multiselect: %d steps"):format(#steps))
|
||||
@@ -0,0 +1,171 @@
|
||||
-- Parallel raster executor (ImGui_ImplRoblox.EnableParallel) vs the inline backend, pixel for pixel. Two contexts draw the same
|
||||
-- benchmark scenarios every frame: A inline (Config.Inline), B through the executor in Sync mode (the mock has no Actors: the "workers"
|
||||
-- run inline, same code). Frames cycle through: dispatch window open (batches pending until Finish, like
|
||||
-- PreSimulation -> PostSimulation), open with SyncDrop (half the worker results lost -> Finish falls back), and closed
|
||||
-- (late RenderDrawData: rasterized + uploaded at once). The composites of A and B must match at every checkpoint.
|
||||
-- Prints the executor's main-thread pack cost per frame next to A's inline raster + upload cost.
|
||||
-- run: python3 tools/test/run.py --main tools/test/scripts/t_parallel.luau --frames 900 --quiet --roblox
|
||||
local RS = game:GetService("ReplicatedStorage")
|
||||
local G = require(RS:WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2 = G.ImGui, G.ImVec2
|
||||
local Impl = G.ImGui_ImplRoblox
|
||||
local W, H = 1280, 760
|
||||
local N = ARG_N or 120 -- frames per scenario
|
||||
|
||||
local function composite(gui)
|
||||
local screen = buffer.create(W * H * 3)
|
||||
local function walk(inst, ox, oy, kx0, ky0, kx1, ky1)
|
||||
local kids = inst:GetChildren()
|
||||
table.sort(kids, function(a, b) return (a.ZIndex or 1) < (b.ZIndex or 1) end)
|
||||
for _, c in ipairs(kids) do
|
||||
if c.Visible ~= false then
|
||||
local x, y = ox + (c.Position and c.Position.X or 0), oy + (c.Position and c.Position.Y or 0)
|
||||
local cx0, cy0, cx1, cy1 = kx0, ky0, kx1, ky1
|
||||
if c.ClipsDescendants then
|
||||
cx0, cy0 = math.max(cx0, x), math.max(cy0, y)
|
||||
cx1, cy1 = math.min(cx1, x + c.Size.X), math.min(cy1, y + c.Size.Y)
|
||||
end
|
||||
if c.ClassName == "ImageLabel" then
|
||||
local px, sz = c.ImageContent.Object.Pixels, c.ImageContent.Object.Size.X
|
||||
for ty = math.max(0, cy0 - y), math.min(sz, cy1 - y) - 1 do
|
||||
local sy = y + ty
|
||||
for tx = math.max(0, cx0 - x), math.min(sz, cx1 - x) - 1 do
|
||||
local o = (ty * sz + tx) * 4
|
||||
local a = buffer.readu8(px, o + 3)
|
||||
if a > 0 then
|
||||
local d = (sy * W + x + tx) * 3
|
||||
local fa = a / 255
|
||||
for ch = 0, 2 do
|
||||
buffer.writeu8(screen, d + ch, math.floor(buffer.readu8(px, o + ch) * fa + buffer.readu8(screen, d + ch) * (1 - fa) + 0.5))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(c, x, y, cx0, cy0, cx1, cy1)
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(gui, 0, 0, 0, 0, W, H)
|
||||
local h = 0
|
||||
for i = 0, W * H * 3 - 4, 4 do h = (h * 31 + buffer.readu32(screen, i)) % 2147483647 end
|
||||
return h
|
||||
end
|
||||
|
||||
local plot = table.create(120, 0)
|
||||
local SCEN = {
|
||||
{ "resize", function(f)
|
||||
local s = 520 + ((f % 80) < 40 and (f % 40) * 7 or (40 - f % 40) * 7)
|
||||
ImGui.ShowDemoWindow()
|
||||
ImGui.SetWindowPos("Dear ImGui Demo", ImVec2(30, 20)); ImGui.SetWindowSize("Dear ImGui Demo", ImVec2(s, s * 0.8 + 60))
|
||||
end },
|
||||
{ "assets", function(f)
|
||||
ImGui.SetNextWindowPos(ImVec2(20, 20), G.ImGuiCond.Always)
|
||||
G.ShowExampleAppAssetsBrowser(true)
|
||||
local w = ImGui.FindWindowByName("Example: Assets Browser")
|
||||
if w and f > 2 then for _, c in ipairs(w.DC.ChildWindows.Data) do ImGui.SetScrollY(c, (f * 40) % 6000) end end
|
||||
end },
|
||||
{ "list", function(f)
|
||||
ImGui.SetNextWindowPos(ImVec2(40, 30), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(560, 680), G.ImGuiCond.Always)
|
||||
ImGui.Begin("Long list")
|
||||
ImGui.SetScrollY(13 * (f <= 60 and f or 120 - f))
|
||||
local clipper = G.ImGuiListClipper()
|
||||
clipper:Begin(10000)
|
||||
while clipper:Step() do
|
||||
for i = clipper.DisplayStart, clipper.DisplayEnd - 1 do ImGui.Text("%05d: The quick brown fox jumps over the lazy dog", i) end
|
||||
end
|
||||
ImGui.End()
|
||||
end },
|
||||
{ "plots", function(f)
|
||||
for i = 1, 120 do plot[i] = math.sin((i + f) * 0.15) + 0.3 * math.sin((i * 3 + f) * 0.4) end
|
||||
ImGui.SetNextWindowPos(ImVec2(40, 30), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(620, 520), G.ImGuiCond.Always)
|
||||
ImGui.Begin("Plots")
|
||||
ImGui.PlotLines("Lines", plot, nil, 120, 0, nil, -1.5, 1.5, ImVec2(0, 160))
|
||||
ImGui.PlotHistogram("Histogram", plot, nil, 120, 0, nil, -1.5, 1.5, ImVec2(0, 160))
|
||||
ImGui.Text("frame %d", f)
|
||||
ImGui.End()
|
||||
end },
|
||||
}
|
||||
|
||||
local ctx, gui = {}, {}
|
||||
for i = 1, 2 do
|
||||
ctx[i] = ImGui.CreateContext()
|
||||
ImGui.SetCurrentContext(ctx[i])
|
||||
local parent = Instance.new("Folder")
|
||||
Impl.Init(parent)
|
||||
Impl.SetRenderRate(0)
|
||||
Impl.SetStageTiming(true)
|
||||
gui[i] = parent:FindFirstChild("ImGui")
|
||||
end
|
||||
Impl.EnableParallel({ Sync = true, Actors = 4 })
|
||||
local C = Impl.GetParallelConfig()
|
||||
|
||||
local si, f, checks, bad = 1, 0, 0, 0
|
||||
local pack, inline, flushes = {}, {}, { open = 0, drop = 0, closed = 0 }
|
||||
local S = Impl.GetParallelStats()
|
||||
local s0 = table.clone(S)
|
||||
local kb = { 0, 0 } -- KB allocated in RenderDrawData (+ Finish for the executor context), per context
|
||||
local function k_add(i, k0) local d = collectgarbage("count") - k0; if f > 5 and d > 0 then kb[i] += d end end
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
local sc = SCEN[si]
|
||||
if not sc then return end
|
||||
f += 1
|
||||
local mode = f % 3 -- 0 closed, 1 open, 2 open + SyncDrop
|
||||
C.SyncDrop = mode == 2
|
||||
if mode ~= 0 then Impl.BeginParallelFrame() end
|
||||
flushes[mode == 0 and "closed" or mode == 1 and "open" or "drop"] += 1
|
||||
for i = 1, 2 do
|
||||
ImGui.SetCurrentContext(ctx[i])
|
||||
C.Inline = i == 1
|
||||
Impl.NewFrame()
|
||||
local io = ImGui.GetIO()
|
||||
io.DeltaTime = 1 / 60
|
||||
io:AddMousePosEvent(1270, 750)
|
||||
ImGui.NewFrame()
|
||||
sc[2](f)
|
||||
ImGui.Render()
|
||||
local fake = os.clock
|
||||
os.clock = os.realclock -- (mock: os.clock is frozen; real time for the stage / pack timers)
|
||||
local p0, k0 = S.Pack, collectgarbage("count")
|
||||
Impl.RenderDrawData(ImGui.GetDrawData())
|
||||
k_add(i, k0)
|
||||
os.clock = fake
|
||||
if f > 5 then
|
||||
if i == 1 then local st = Impl.GetStats().Frame; table.insert(inline, (st.Raster + st.Upload) * 1000)
|
||||
else table.insert(pack, (S.Pack - p0) * 1000) end
|
||||
end
|
||||
end
|
||||
local k0 = collectgarbage("count")
|
||||
Impl.FinishParallel()
|
||||
k_add(2, k0)
|
||||
if f % 10 == 0 or f == N then
|
||||
checks += 1
|
||||
local a, b = composite(gui[1]), composite(gui[2])
|
||||
if a ~= b then bad += 1; print("MISMATCH", sc[1], f, a, b) end
|
||||
end
|
||||
if f == N then
|
||||
local function stats(t)
|
||||
local s, m = 0, 0
|
||||
for _, v in t do s += v; m = math.max(m, v) end
|
||||
return s / math.max(#t, 1), m
|
||||
end
|
||||
local pm, px = stats(pack)
|
||||
local im, ix = stats(inline)
|
||||
print(string.format("PACK %-7s mean %.3f max %.3f ms/frame | inline raster+upload mean %.3f max %.3f ms/frame | tiles %.1f rects %.1f send %d KB/frame, tex resends %d (%d KB)",
|
||||
sc[1], pm, px, im, ix, (S.Tiles - s0.Tiles) / N, (S.Rects - s0.Rects) / N, (S.SendBytes - s0.SendBytes) / 1024 / N, S.TexSends - s0.TexSends, (S.TexBytes - s0.TexBytes) / 1024))
|
||||
print(string.format("ALLOC %-7s KB/frame inline %.1f executor %.1f (Sync: includes the inline worker raster)", sc[1], kb[1] / (N - 5), kb[2] / (N - 5)))
|
||||
kb = { 0, 0 }
|
||||
s0 = table.clone(S)
|
||||
pack, inline = {}, {}
|
||||
for i = 1, 2 do ImGui.SetCurrentContext(ctx[i]); Impl.SetRenderScale(2); Impl.SetRenderScale(1) end
|
||||
si += 1; f = 0
|
||||
Impl.EnableParallel({ Actors = si }) -- runtime re-Enable with a different actor count (pixels must still match)
|
||||
assert(C.Sync and Impl.GetParallelConfig() == C, "re-Enable kept Sync")
|
||||
if not SCEN[si] then
|
||||
print(string.format("STATS parallel flushes %d serial %d tiles %d fallbacks %d | frames open %d drop %d closed %d",
|
||||
S.ParallelFlushes, S.SerialFlushes, S.Tiles, S.Fallbacks, flushes.open, flushes.drop, flushes.closed))
|
||||
assert(S.ParallelFlushes > 0 and S.SerialFlushes > 0 and S.Fallbacks > 0, "a path was not exercised")
|
||||
if bad == 0 then print("PARALLEL OK " .. checks .. " checkpoints") else print("PARALLEL FAIL " .. bad .. "/" .. checks) end
|
||||
end
|
||||
end
|
||||
end)
|
||||
@@ -0,0 +1,133 @@
|
||||
-- Backend pixel oracle: composites the ScreenGui (like t_composite) at checkpoints and prints "PIX <frame> <hash>".
|
||||
-- Phases: resize (bottom-right, then top-left), move, scroll, hover, typing, new font sizes (glyph baking), colour drag.
|
||||
-- Each phase ends with a few still frames, then a checkpoint. Run with RUN_FLAGS="ARG_FORCE=true" for a full redraw
|
||||
-- every frame: incremental output must match it exactly (and match the previous backend version).
|
||||
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4
|
||||
ImGui.CreateContext()
|
||||
G.ImGui_ImplRoblox.Init()
|
||||
G.ImGui_ImplRoblox.SetRenderRate(0)
|
||||
if ARG_TILELIMIT then ImGui.GetIO().BackendPlatformUserData.TileLimit = ARG_TILELIMIT end
|
||||
local io = ImGui.GetIO()
|
||||
local W, H = 1280, 760
|
||||
local col = ImVec4(0.4, 0.7, 0.2, 0.5)
|
||||
local buf = ImGui.NewTextBuffer("type here", 128)
|
||||
local slider = 0.3
|
||||
|
||||
local function composite(gui)
|
||||
local screen = buffer.create(W * H * 3)
|
||||
local function walk(inst, ox, oy, kx0, ky0, kx1, ky1)
|
||||
local kids = inst:GetChildren()
|
||||
table.sort(kids, function(a, b) return (a.ZIndex or 1) < (b.ZIndex or 1) end)
|
||||
for _, c in ipairs(kids) do
|
||||
if c.Visible ~= false then
|
||||
local x, y = ox + (c.Position and c.Position.X or 0), oy + (c.Position and c.Position.Y or 0)
|
||||
local cx0, cy0, cx1, cy1 = kx0, ky0, kx1, ky1
|
||||
if c.ClipsDescendants then
|
||||
cx0, cy0 = math.max(cx0, x), math.max(cy0, y)
|
||||
cx1, cy1 = math.min(cx1, x + c.Size.X), math.min(cy1, y + c.Size.Y)
|
||||
end
|
||||
if c.ClassName == "ImageLabel" then
|
||||
local img = c.ImageContent.Object
|
||||
local px, sz = img.Pixels, img.Size.X
|
||||
for ty = 0, sz - 1 do
|
||||
local sy = y + ty
|
||||
if sy >= cy0 and sy < cy1 then
|
||||
for tx = 0, sz - 1 do
|
||||
local sx = x + tx
|
||||
if sx >= cx0 and sx < cx1 then
|
||||
local o = (ty * sz + tx) * 4
|
||||
local a = buffer.readu8(px, o + 3)
|
||||
if a > 0 then
|
||||
local d = (sy * W + sx) * 3
|
||||
local fa = a / 255
|
||||
for ch = 0, 2 do
|
||||
local v = buffer.readu8(px, o + ch) * fa + buffer.readu8(screen, d + ch) * (1 - fa)
|
||||
buffer.writeu8(screen, d + ch, math.floor(v + 0.5))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(c, x, y, cx0, cy0, cx1, cy1)
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(gui, 0, 0, 0, 0, W, H)
|
||||
local h = 0
|
||||
for i = 0, W * H * 3 - 4, 4 do h = (h * 31 + buffer.readu32(screen, i)) % 2147483647 end
|
||||
return h
|
||||
end
|
||||
|
||||
-- phase list: name, frames of action (then 6 still frames + checkpoint)
|
||||
local PHASES = { { "start", 4 }, { "resize_br", 24 }, { "resize_tl", 24 }, { "move", 24 }, { "scroll", 30 }, { "hover", 30 },
|
||||
{ "type", 24 }, { "fonts", 24 }, { "color", 20 } }
|
||||
local STILL = ARG_STILL or (ARG_TILELIMIT and 40 or 6) -- tile limit: deferred tiles need more frames to settle
|
||||
local PT = {}
|
||||
local pi, pf = 1, 0
|
||||
local pos, size, scroll, fsize = ImVec2(40, 40), ImVec2(460, 520), 0, 13
|
||||
local frame = 0
|
||||
local typing = "Hello, glyphs! 0123 xyz"
|
||||
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
local ph = PHASES[pi]
|
||||
if not ph then return end
|
||||
frame += 1; pf += 1
|
||||
local name, n = ph[1], ph[2]
|
||||
local act = pf <= n
|
||||
G.ImGui_ImplRoblox.NewFrame()
|
||||
io.DeltaTime = 1 / 60
|
||||
io:AddMousePosEvent(1200, 740)
|
||||
if act then
|
||||
if name == "resize_br" then size = ImVec2(460 + pf * 7, 520 + pf * 5)
|
||||
elseif name == "resize_tl" then pos = ImVec2(40 + pf * 3, 40 + pf * 2); size = ImVec2(size.x - 3, size.y - 2)
|
||||
elseif name == "move" then pos = ImVec2(pos.x + 5, pos.y + 3)
|
||||
elseif name == "scroll" then scroll += 9
|
||||
elseif name == "hover" then io:AddMousePosEvent(pos.x + 30 + (pf * 17) % 300, pos.y + 40 + (pf * 23) % 400)
|
||||
elseif name == "type" then
|
||||
if pf == 1 then io:AddMousePosEvent(pos.x + 120, pos.y + 37); io:AddMouseButtonEvent(0, true)
|
||||
elseif pf == 2 then io:AddMouseButtonEvent(0, false)
|
||||
else io:AddInputCharacter(string.byte(typing, (pf - 3) % #typing + 1)) end
|
||||
elseif name == "fonts" then fsize = 13 + pf * 0.75
|
||||
elseif name == "color" then
|
||||
local p = ImVec2(700 + pf * 4, 120 + pf * 3)
|
||||
io:AddMousePosEvent(p.x, p.y); io:AddMouseButtonEvent(0, pf < n)
|
||||
end
|
||||
end
|
||||
ImGui.NewFrame()
|
||||
ImGui.SetNextWindowPos(pos, G.ImGuiCond.Always); ImGui.SetNextWindowSize(size, G.ImGuiCond.Always)
|
||||
ImGui.Begin("Stress")
|
||||
ImGui.InputText("##in", buf, 128)
|
||||
if name == "scroll" or scroll > 0 then ImGui.SetScrollY(scroll) end
|
||||
for i = 1, 12 do ImGui.Button("Button " .. i); ImGui.SameLine(); slider = ImGui.SliderFloat("##s" .. i, slider, 0, 1) end
|
||||
if ImGui.BeginTable("tbl", 4, bit32.bor(G.ImGuiTableFlags.Borders, G.ImGuiTableFlags.RowBg)) then
|
||||
for r = 1, 30 do ImGui.TableNextRow(); for c = 1, 4 do ImGui.TableNextColumn(); ImGui.Text("r%d c%d", r, c) end end
|
||||
ImGui.EndTable()
|
||||
end
|
||||
ImGui.PushFont(nil, fsize); ImGui.Text("Font size %.2f AaBbCc", fsize); ImGui.PopFont()
|
||||
for i = 1, 30 do ImGui.TextWrapped("Line %d: the quick brown fox jumps over the lazy dog.", i) end
|
||||
ImGui.End()
|
||||
ImGui.SetNextWindowPos(ImVec2(660, 60), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(500, 620), G.ImGuiCond.Always)
|
||||
ImGui.Begin("Pickers")
|
||||
ImGui.ColorPicker4("bar", col, G.ImGuiColorEditFlags.PickerHueBar)
|
||||
ImGui.End()
|
||||
ImGui.Render()
|
||||
local clk = os.realclock or os.clock
|
||||
local t0 = clk()
|
||||
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
if act then PT[name] = (PT[name] or 0) + (clk() - t0) * 1000 end
|
||||
if pf == n then -- mid-action (not settled): only exact without a redraw budget
|
||||
print("PIXA", name, frame, composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui")))
|
||||
end
|
||||
if pf == n + STILL then
|
||||
local gui = game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui")
|
||||
print("PIX", name, frame, composite(gui))
|
||||
pi += 1; pf = 0
|
||||
if not PHASES[pi] then
|
||||
for _, q in PHASES do print(string.format("PIXT %-10s %7.2f ms/frame", q[1], PT[q[1]] / q[2])) end
|
||||
print("PIXELS DONE")
|
||||
end
|
||||
end
|
||||
end)
|
||||
@@ -0,0 +1,32 @@
|
||||
-- Two contexts sharing one font atlas (one backend module): new glyphs baked while B is current used to hit
|
||||
-- UpdateTexture's assert (per-context texture tables). Textures are now module-wide.
|
||||
-- run: python3 tools/test/run.py --main tools/test/scripts/t_pool_ctx.luau --frames 60 --quiet --roblox
|
||||
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2 = G.ImGui, G.ImVec2
|
||||
local Impl = G.ImGui_ImplRoblox
|
||||
local a = ImGui.CreateContext(); ImGui.SetCurrentContext(a); Impl.Init(); Impl.SetRenderRate(0)
|
||||
local b = ImGui.CreateContext(ImGui.GetIO().Fonts); ImGui.SetCurrentContext(b); Impl.Init(); Impl.SetRenderRate(0)
|
||||
|
||||
local function frame(ctx, body)
|
||||
ImGui.SetCurrentContext(ctx)
|
||||
Impl.NewFrame(); ImGui.GetIO().DeltaTime = 1 / 60
|
||||
ImGui.NewFrame()
|
||||
ImGui.SetNextWindowPos(ImVec2(10, 10), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(900, 700), G.ImGuiCond.Always)
|
||||
ImGui.Begin("W"); body(); ImGui.End()
|
||||
ImGui.Render(); Impl.RenderDrawData(ImGui.GetDrawData())
|
||||
end
|
||||
|
||||
local n = 0
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
n += 1
|
||||
if n > 60 then return end
|
||||
frame(a, function() ImGui.Text("context A"); if n == 20 then ImGui.PushFont(nil, 33); ImGui.Text("Glyphs baked under A"); ImGui.PopFont() end end)
|
||||
frame(b, function()
|
||||
if n == 5 then ImGui.PushFont(nil, 41); ImGui.Text("Big glyphs baked under B"); ImGui.PopFont() end
|
||||
ImGui.Text("context B")
|
||||
end)
|
||||
if n == 60 then
|
||||
assert(Impl.GetStats().Tiles > 0)
|
||||
print("POOLCTX OK")
|
||||
end
|
||||
end)
|
||||
@@ -0,0 +1,89 @@
|
||||
-- Reversed rects (min > max, e.g. box-select dragged up/left) must draw like upstream's GPU path:
|
||||
-- AddRectFilled + AddRect from each of the 4 drag directions composite to identical, non-blank pixels.
|
||||
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2 = G.ImGui, G.ImVec2
|
||||
ImGui.CreateContext()
|
||||
G.ImGui_ImplRoblox.Init()
|
||||
G.ImGui_ImplRoblox.SetRenderRate(0)
|
||||
local io = ImGui.GetIO()
|
||||
local W, H = 1280, 760
|
||||
local function composite(gui)
|
||||
local screen = buffer.create(W * H * 3)
|
||||
local function walk(inst, ox, oy, kx0, ky0, kx1, ky1)
|
||||
local kids = inst:GetChildren()
|
||||
table.sort(kids, function(a, b) return (a.ZIndex or 1) < (b.ZIndex or 1) end)
|
||||
for _, c in ipairs(kids) do
|
||||
if c.Visible ~= false then
|
||||
local x, y = ox + (c.Position and c.Position.X or 0), oy + (c.Position and c.Position.Y or 0)
|
||||
local cx0, cy0, cx1, cy1 = kx0, ky0, kx1, ky1
|
||||
if c.ClipsDescendants then
|
||||
cx0, cy0 = math.max(cx0, x), math.max(cy0, y)
|
||||
cx1, cy1 = math.min(cx1, x + c.Size.X), math.min(cy1, y + c.Size.Y)
|
||||
end
|
||||
if c.ClassName == "ImageLabel" then
|
||||
local img = c.ImageContent.Object
|
||||
local px, sz = img.Pixels, img.Size.X
|
||||
for ty = 0, sz - 1 do
|
||||
local sy = y + ty
|
||||
if sy >= cy0 and sy < cy1 then
|
||||
for tx = 0, sz - 1 do
|
||||
local sx = x + tx
|
||||
if sx >= cx0 and sx < cx1 then
|
||||
local o = (ty * sz + tx) * 4
|
||||
local a = buffer.readu8(px, o + 3)
|
||||
if a > 0 then
|
||||
local d = (sy * W + sx) * 3
|
||||
local fa = a / 255
|
||||
for ch = 0, 2 do
|
||||
local v = buffer.readu8(px, o + ch) * fa + buffer.readu8(screen, d + ch) * (1 - fa)
|
||||
buffer.writeu8(screen, d + ch, math.floor(v + 0.5))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(c, x, y, cx0, cy0, cx1, cy1)
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(gui, 0, 0, 0, 0, W, H)
|
||||
local h = 0
|
||||
for i = 0, W * H * 3 - 4, 4 do h = (h * 31 + buffer.readu32(screen, i)) % 2147483647 end
|
||||
return h
|
||||
end
|
||||
|
||||
local A, B = ImVec2(200, 150), ImVec2(520, 400) -- drag start/end, down-right
|
||||
local DIRS = { "none", "dr", "ul", "ur", "dl" }
|
||||
local CORNERS = {
|
||||
dr = { A, B }, ul = { B, A },
|
||||
ur = { ImVec2(A.x, B.y), ImVec2(B.x, A.y) }, dl = { ImVec2(B.x, A.y), ImVec2(A.x, B.y) },
|
||||
}
|
||||
local di, pf, res = 1, 0, {}
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
local d = DIRS[di]
|
||||
if not d then return end
|
||||
pf += 1
|
||||
G.ImGui_ImplRoblox.NewFrame()
|
||||
io.DeltaTime = 1 / 60
|
||||
ImGui.NewFrame()
|
||||
local c = CORNERS[d]
|
||||
if c then
|
||||
local dl = ImGui.GetForegroundDrawList()
|
||||
dl:AddRectFilled(c[1], c[2], 0x6496FF32)
|
||||
dl:AddRect(c[1], c[2], 0xFFFF9664, 0, 2)
|
||||
dl:AddRectFilled(c[1], c[2], 0xFF00FF00, 12) -- rounded too
|
||||
end
|
||||
ImGui.Render()
|
||||
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
if pf == 4 then
|
||||
res[d] = composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui"))
|
||||
print("RECT", d, res[d])
|
||||
di += 1; pf = 0
|
||||
if not DIRS[di] then
|
||||
local ok = res.dr ~= res.none and res.ul == res.dr and res.ur == res.dr and res.dl == res.dr
|
||||
print(ok and "RECTFLIP OK" or "RECTFLIP MISMATCH")
|
||||
end
|
||||
end
|
||||
end)
|
||||
@@ -0,0 +1,138 @@
|
||||
-- Screenshot of a fixed scene (t_libhash's widgets + primitives, optionally the Custom Rendering example):
|
||||
-- composites the ScreenGui like t_composite and prints "ROW y hex". tools/test/shot.py turns it into a PNG.
|
||||
-- RUN_FLAGS: ARG_APP=true also opens ShowExampleAppCustomRendering (needs the demo).
|
||||
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4
|
||||
ImGui.CreateContext(); G.ImGui_ImplRoblox.Init(); G.ImGui_ImplRoblox.SetRenderRate(0)
|
||||
local io = ImGui.GetIO()
|
||||
local W, H = 1280, 760
|
||||
local frame = 0
|
||||
local st = { b = false, f = 0.25, i = 42, c = ImVec4(0.2, 0.7, 0.4, 1.0), buf = ImGui.NewTextBuffer("hello", 64), r = 0, tab = 0, combo = 1, list = 2 }
|
||||
local plot = {}
|
||||
for i = 1, 40 do plot[i] = math.sin(i * 0.3) end
|
||||
local poly = { ImVec2(0, 0), ImVec2(60, 10), ImVec2(30, 30), ImVec2(70, 60), ImVec2(0, 50) }
|
||||
|
||||
local function composite(gui)
|
||||
local screen = buffer.create(W * H * 3)
|
||||
local function walk(inst, ox, oy, kx0, ky0, kx1, ky1)
|
||||
local kids = inst:GetChildren()
|
||||
table.sort(kids, function(a, b) return (a.ZIndex or 1) < (b.ZIndex or 1) end) -- table.sort isn't stable, but siblings with equal ZIndex never overlap here
|
||||
for _, c in ipairs(kids) do
|
||||
if c.Visible ~= false then
|
||||
local x, y = ox + (c.Position and c.Position.X or 0), oy + (c.Position and c.Position.Y or 0)
|
||||
local cx0, cy0, cx1, cy1 = kx0, ky0, kx1, ky1
|
||||
if c.ClipsDescendants then
|
||||
cx0, cy0 = math.max(cx0, x), math.max(cy0, y)
|
||||
cx1, cy1 = math.min(cx1, x + c.Size.X), math.min(cy1, y + c.Size.Y)
|
||||
end
|
||||
if c.ClassName == "ImageLabel" then
|
||||
local img = c.ImageContent.Object
|
||||
local px, sz = img.Pixels, img.Size.X
|
||||
for ty = 0, sz - 1 do
|
||||
local sy = y + ty
|
||||
if sy >= ky0 and sy < ky1 then
|
||||
for tx = 0, sz - 1 do
|
||||
local sx = x + tx
|
||||
if sx >= kx0 and sx < kx1 then
|
||||
local o = (ty * sz + tx) * 4
|
||||
local a = buffer.readu8(px, o + 3)
|
||||
if a > 0 then
|
||||
local d = (sy * W + sx) * 3
|
||||
local fa = a / 255
|
||||
for ch = 0, 2 do
|
||||
local v = buffer.readu8(px, o + ch) * fa + buffer.readu8(screen, d + ch) * (1 - fa)
|
||||
buffer.writeu8(screen, d + ch, math.floor(v + 0.5))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(c, x, y, cx0, cy0, cx1, cy1)
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(gui, 0, 0, 0, 0, W, H)
|
||||
return screen
|
||||
end
|
||||
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
frame += 1
|
||||
G.ImGui_ImplRoblox.NewFrame()
|
||||
io.DeltaTime = 1 / 60
|
||||
ImGui.NewFrame()
|
||||
ImGui.SetNextWindowPos(ImVec2(10, 10), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(320, 560), G.ImGuiCond.Always)
|
||||
ImGui.Begin("Widgets")
|
||||
ImGui.Text("Text %d", 123); ImGui.TextColored(ImVec4(1, 0.5, 0, 1), "Colored"); ImGui.TextWrapped("Wrapped text that is long enough to wrap around the window edge at least once.")
|
||||
ImGui.Button("Button"); ImGui.SameLine(); ImGui.SmallButton("Small"); ImGui.SameLine(); ImGui.ArrowButton("##a", G.ImGuiDir.Left)
|
||||
st.b = ImGui.Checkbox("Checkbox", st.b)
|
||||
st.r = ImGui.RadioButton("R0", st.r, 0); ImGui.SameLine(); st.r = ImGui.RadioButton("R1", st.r, 1)
|
||||
st.f = ImGui.SliderFloat("Slider", st.f, 0, 1); st.i = ImGui.DragInt("Drag", st.i, 1, 0, 100)
|
||||
ImGui.InputText("Input", st.buf, 64)
|
||||
ImGui.ColorEdit4("Color", st.c)
|
||||
st.combo = ImGui.Combo("Combo", st.combo, { "AAA", "BBB", "CCC" })
|
||||
st.list = ImGui.ListBox("List", st.list, { "one", "two", "three", "four" }, 4, 3)
|
||||
ImGui.ProgressBar(0.4, ImVec2(-1, 0)); ImGui.ProgressBar(-1.0 * frame / 60, ImVec2(-1, 0), "busy")
|
||||
ImGui.PlotLines("Lines", plot, nil, #plot); ImGui.PlotHistogram("Hist", plot, nil, #plot, 0, nil, -1, 1, ImVec2(0, 40))
|
||||
ImGui.Bullet(); ImGui.Text("bullet"); ImGui.Separator(); ImGui.SeparatorText("Sep")
|
||||
if ImGui.TreeNode("Tree") then ImGui.Text("inside"); ImGui.TreePop() end
|
||||
ImGui.SetNextItemOpen(true, G.ImGuiCond.Once)
|
||||
if ImGui.CollapsingHeader("Header") then
|
||||
if ImGui.BeginTabBar("tabs") then
|
||||
if ImGui.BeginTabItem("Tab A") then ImGui.Text("A"); ImGui.EndTabItem() end
|
||||
if ImGui.BeginTabItem("Tab B") then ImGui.Text("B"); ImGui.EndTabItem() end
|
||||
ImGui.EndTabBar()
|
||||
end
|
||||
if ImGui.BeginTable("t", 3, bit32.bor(G.ImGuiTableFlags.Borders, G.ImGuiTableFlags.RowBg, G.ImGuiTableFlags.Resizable)) then
|
||||
ImGui.TableSetupColumn("One"); ImGui.TableSetupColumn("Two"); ImGui.TableSetupColumn("Three"); ImGui.TableHeadersRow()
|
||||
for row = 0, 4 do ImGui.TableNextRow(); for col = 0, 2 do ImGui.TableSetColumnIndex(col); ImGui.Text("r%d c%d", row, col) end end
|
||||
ImGui.EndTable()
|
||||
end
|
||||
end
|
||||
ImGui.End()
|
||||
|
||||
ImGui.SetNextWindowPos(ImVec2(340, 10), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(300, 560), G.ImGuiCond.Always)
|
||||
ImGui.Begin("Draw")
|
||||
local dl, p = ImGui.GetWindowDrawList(), ImGui.GetCursorScreenPos()
|
||||
local x, y, col = p.x + 4, p.y + 4, 0xFF40C0FF
|
||||
for i, th in { 1.0, 2.5, 6.0 } do
|
||||
local yy = y + (i - 1) * 70
|
||||
dl:AddRect(ImVec2(x, yy), ImVec2(x + 50, yy + 50), col, 10.0, th)
|
||||
dl:AddRectFilled(ImVec2(x + 60, yy), ImVec2(x + 110, yy + 50), col, 10.0, G.ImDrawFlags.RoundTopLeft or G.ImDrawFlags.RoundCornersTopLeft) -- RoundCornersTopLeft: pre-1.93 revs (hashes.sh)
|
||||
dl:AddCircle(ImVec2(x + 145, yy + 25), 25, col, 0, th)
|
||||
dl:AddNgon(ImVec2(x + 200, yy + 25), 25, col, 6, th)
|
||||
dl:AddTriangle(ImVec2(x + 230, yy + 50), ImVec2(x + 255, yy), ImVec2(x + 280, yy + 50), col, th)
|
||||
dl:AddLine(ImVec2(x, yy + 60), ImVec2(x + 280, yy + 55), col, th)
|
||||
end
|
||||
y += 210
|
||||
dl:AddBezierCubic(ImVec2(x, y), ImVec2(x + 60, y - 30), ImVec2(x + 120, y + 60), ImVec2(x + 180, y), col, 3.0)
|
||||
dl:AddBezierQuadratic(ImVec2(x, y + 30), ImVec2(x + 90, y - 10), ImVec2(x + 180, y + 30), col, 2.0)
|
||||
dl:AddEllipse(ImVec2(x + 230, y + 15), ImVec2(40, 15), col, 0.5, 0, 2.0)
|
||||
y += 50
|
||||
local pts = {}
|
||||
for i, v in poly do pts[i] = ImVec2(x + v.x, y + v.y) end
|
||||
dl:AddConcavePolyFilled(pts, #pts, 0xFF8080FF)
|
||||
for i, v in poly do pts[i] = ImVec2(x + 100 + v.x, y + v.y) end
|
||||
dl:AddPolyline(pts, #pts, col, 4.0, G.ImDrawFlags.Closed)
|
||||
for i, v in poly do pts[i] = ImVec2(x + 200 + v.x, y + v.y) end
|
||||
dl:AddPolyline(pts, #pts, col, 1.0, 0)
|
||||
y += 80
|
||||
dl:AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x + 100, y + 40), 0xFF0000FF, 0xFF00FF00, 0xFFFF0000, 0xFFFFFFFF)
|
||||
dl:AddCircleFilled(ImVec2(x + 140, y + 20), 20, col)
|
||||
dl:AddEllipseFilled(ImVec2(x + 210, y + 20), ImVec2(30, 15), col, 0.3)
|
||||
dl:AddText(ImVec2(x, y + 50), 0xFFFFFFFF, "AddText")
|
||||
ImGui.End()
|
||||
|
||||
if ARG_APP then ImGui.SetNextWindowPos(ImVec2(650, 10), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(620, 740), G.ImGuiCond.Always); G.ShowExampleAppCustomRendering(true) end
|
||||
ImGui.Render()
|
||||
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
if frame == ARG_FRAMES - 1 then
|
||||
local screen = composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui"))
|
||||
for y = 0, H - 1 do
|
||||
local t = table.create(W * 3)
|
||||
for i = 0, W * 3 - 1 do t[i + 1] = string.format("%02x", buffer.readu8(screen, y * W * 3 + i)) end
|
||||
print("ROW", y, table.concat(t))
|
||||
end
|
||||
end
|
||||
end)
|
||||
@@ -64,7 +64,7 @@ game:GetService("RunService").Stepped:Connect(function()
|
||||
assert(st.TextLen == 0, "backspace should delete imgui's whole selection, len " .. st.TextLen)
|
||||
print("BACKSPACE OK")
|
||||
end
|
||||
if f == 27 then
|
||||
if f == 30 then -- (key-code fallback waits a few frames for the TextBox first)
|
||||
local st = ImGui.GetCurrentContext().InputTextState
|
||||
local got = G.ImGui._ByteArrayToString(st.TextA.Data, 1, st.TextLen + 1)
|
||||
assert(got:find("z"), "key fallback while proxy focused: " .. got)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
-- Text proxy for a custom widget (no ActiveId): it sets PlatformImeData.WantTextInput/SelectedText while its window is focused.
|
||||
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2 = G.ImGui, G.ImVec2
|
||||
local UIS = game:GetService("UserInputService")
|
||||
ImGui.CreateContext(); G.ImGui_ImplRoblox.Init(); G.ImGui_ImplRoblox.SetTextProxy(true)
|
||||
local io = ImGui.GetIO()
|
||||
local got, proxy, f = "", nil, 0
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
f += 1
|
||||
G.ImGui_ImplRoblox.NewFrame()
|
||||
proxy = proxy or game:GetService("Players").LocalPlayer.PlayerGui.ImGui.TextProxy
|
||||
if f == 3 then io:AddMousePosEvent(60, 45); io:AddMouseButtonEvent(0, true) end
|
||||
if f == 4 then io:AddMouseButtonEvent(0, false) end
|
||||
if f == 8 then assert(UIS:GetFocusedTextBox() == proxy, "proxy focused"); proxy.Text = "x" end
|
||||
ImGui.NewFrame()
|
||||
ImGui.SetNextWindowPos(ImVec2(10, 10)); ImGui.SetNextWindowSize(ImVec2(300, 100))
|
||||
ImGui.Begin("Editor")
|
||||
if ImGui.IsWindowFocused() then
|
||||
local ime = ImGui.GetCurrentContext().PlatformImeData
|
||||
ime.WantTextInput = true; ime.SelectedText = "abc"
|
||||
local q = io.InputQueueCharacters
|
||||
for i = 1, q.Size do got ..= utf8.char(q.Data[i]) end
|
||||
end
|
||||
ImGui.End()
|
||||
ImGui.Render(); G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
|
||||
if f == 12 then
|
||||
assert(got == "x", "widget got: " .. got)
|
||||
assert(proxy.Text == "abc", "mirror: " .. proxy.Text)
|
||||
print("CUSTOM PROXY OK")
|
||||
end
|
||||
end)
|
||||
@@ -0,0 +1,49 @@
|
||||
-- Scrolling a long child window must not leak tiles: scrolled-away tiles are freed (recycled), so the live tile count
|
||||
-- stays bounded by what is on screen. Then with a tiny EditableImage cap (SetEditableImageCap): tiles that don't fit
|
||||
-- are skipped (GetTile -> nil, no assert) and the budget is never exceeded.
|
||||
-- run: python3 tools/test/run.py --main tools/test/scripts/t_tile_bound.luau --frames 200 --quiet --roblox
|
||||
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
|
||||
local ImGui, ImVec2 = G.ImGui, G.ImVec2
|
||||
local Impl = G.ImGui_ImplRoblox
|
||||
ImGui.CreateContext()
|
||||
Impl.Init()
|
||||
Impl.SetRenderRate(0)
|
||||
local io = ImGui.GetIO()
|
||||
local P = 100 -- frames per phase
|
||||
local frame, peak = 0, 0
|
||||
local TILE_BYTES = 128 * 128 * 4
|
||||
|
||||
game:GetService("RunService").Stepped:Connect(function()
|
||||
frame += 1
|
||||
if frame > 2 * P then return end
|
||||
local t = (frame - 1) % P + 1
|
||||
if frame == P + 1 then Impl.SetEditableImageCap(10 * TILE_BYTES); Impl.SetRenderScale(2) end -- (rebuild: shown tiles are never evicted)
|
||||
Impl.NewFrame()
|
||||
io.DeltaTime = 1 / 60
|
||||
ImGui.NewFrame()
|
||||
ImGui.SetNextWindowPos(ImVec2(20, 20), G.ImGuiCond.Always)
|
||||
ImGui.SetNextWindowSize(ImVec2(400, 400), G.ImGuiCond.Always)
|
||||
ImGui.Begin("Scroll")
|
||||
ImGui.BeginChild("long", ImVec2(0, 0), G.ImGuiChildFlags.Borders)
|
||||
for i = 1, 3000 do ImGui.Text("row %d some text to fill the tile width ........", i) end
|
||||
ImGui.SetScrollY(t * 300) -- ~30k px per phase: hundreds of distinct tiles if never freed
|
||||
ImGui.EndChild()
|
||||
ImGui.End()
|
||||
ImGui.Render()
|
||||
Impl.RenderDrawData(ImGui.GetDrawData())
|
||||
local s = Impl.GetStats()
|
||||
if frame <= P or t > 1 then assert(s.EditableImageBytes <= s.EditableImageCap, "over the EditableImage budget") end -- (the free list drains on the next create)
|
||||
assert(s.EditableImages >= s.Tiles)
|
||||
if frame <= P and t > 20 then peak = math.max(peak, s.Tiles) end
|
||||
if frame == P then
|
||||
print(("raster: peak tiles %d, now %d tiles, %d EditableImages, %d Instances"):format(peak, s.Tiles, s.EditableImages, s.Instances))
|
||||
-- a 400x400 window covers ~4x4 tiles per layer (+1 row/col when unaligned) + a few spares
|
||||
assert(peak <= 60, "tile count not bounded by what is on screen")
|
||||
end
|
||||
if frame == 2 * P then
|
||||
print(("capped: %d tiles, %d EditableImages, %d / %d bytes"):format(s.Tiles, s.EditableImages, s.EditableImageBytes, s.EditableImageCap))
|
||||
assert(s.EditableImages <= 10)
|
||||
Impl.SetEditableImageCap(nil)
|
||||
print("TILEBOUND OK")
|
||||
end
|
||||
end)
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Headless screenshot: tools/test/shot.py out.png [--app] (runs scripts/t_shot.luau, writes a PNG; stdlib only)"""
|
||||
import os, subprocess, sys, struct, zlib
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
env = dict(os.environ, FULL_OUTPUT="1", RUN_FLAGS="ARG_APP=true" if "--app" in sys.argv else "")
|
||||
out = subprocess.run([sys.executable, os.path.join(HERE, "run.py"), "--quiet", "--roblox", "--frames", "30", "--timeout", "600",
|
||||
"--main", os.path.join(HERE, "scripts", "t_shot.luau")], env=env, capture_output=True, text=True).stdout
|
||||
rows = {int(l.split()[1]): bytes.fromhex(l.split()[2]) for l in out.splitlines() if l.startswith("ROW")}
|
||||
assert rows, out[-2000:]
|
||||
w, h = len(rows[0]) // 3, len(rows)
|
||||
raw = b"".join(b"\0" + rows[y] for y in range(h))
|
||||
chunk = lambda t, d: struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
|
||||
open(sys.argv[1], "wb").write(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b""))
|
||||
print("wrote", sys.argv[1], w, h)
|
||||
@@ -4,11 +4,12 @@
|
||||
"""
|
||||
import os, re, collections
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
SRC = ROOT # library *.lua at the root + backends/ (--no-demo: leave imgui_demo.lua out to check the library never needs it)
|
||||
SRC = ROOT # library *.lua at the root + backends/roblox, backends/love (--no-demo: leave imgui_demo.lua out to check the library never needs it)
|
||||
import sys
|
||||
NO_DEMO = "--no-demo" in sys.argv
|
||||
files = {}
|
||||
for dp, fn in ((ROOT, os.listdir(ROOT)), (os.path.join(ROOT, "backends"), os.listdir(os.path.join(ROOT, "backends")))):
|
||||
for dp in (ROOT, os.path.join(ROOT, "backends", "roblox"), os.path.join(ROOT, "backends", "love")):
|
||||
fn = os.listdir(dp)
|
||||
for f in fn:
|
||||
if f.endswith(".lua") and not (NO_DEMO and f == "imgui_demo.lua"):
|
||||
files[os.path.relpath(os.path.join(dp, f), SRC)] = open(os.path.join(dp, f)).read()
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "4dbug/imgui-luau"
|
||||
version = "0.1.3"
|
||||
version = "0.4.2"
|
||||
registry = "https://github.com/UpliftGames/wally-index"
|
||||
realm = "shared"
|
||||
license = "MIT"
|
||||
|
||||
Reference in new issue
Block a user