166 Commits
Author SHA1 Message Date
4DBug 6e9790bf2a extensions: submodule pointers -> the rewritten extension commits on their remotes (imcurveedit-luau 4998eaf, imgradient-luau 227f1a0, imgui-memory-editor-luau 8249fe2, imnodes-luau 357fc01, imsequencer-luau d09550e; same trees as the old 9769fd0 / 21b3b2d / 3c9aca1 / 363fd65 / a911077, which no longer exist upstream)
Build & Release / build (push) Canceled after 0s
2026-10-25 06:23:44 -05:00
4DBug d1818970b5 0.4.4
Build & Release / build (push) Canceled after 0s
Performance update (Roblox), no API changes; pixels identical to 0.4.3.
- Raster: solid spans 4-8 px per loop iteration, full-width rows copied in blocks, bit32 colour unpacking (colorpicker -19%, implot -13%, fonts -16%)
- Raster: axis-aligned edges tested once per row / column, AA fringe rows with alpha 0 skipped, triangle / line quad spans from per-side edge slots, narrow spans (vertical lines, histogram bars) without row bookkeeping (plots up to -25%)
- ImPlot rect fills (heatmaps, bars) drawn as one primitive instead of two triangles (implot -3.5%)
- DirtyRects: greedy diff of a tile's old and new primitive list, so scrolling no longer redraws everything after the first shifted row (scroll: 14.1k -> 4.3k pixels rasterized per frame)
- Hover recolors skip tile hashing and redraw only the affected tiles; unrolled per-primitive vertex hash; per-command primitive data (CollectPrims -10%)
- Library: @native table layout functions, trunc helpers, ImDrawListSplitter:Merge() via table.move (demo -2..4% instructions)
- stb_truetype: CFF-only / font-init functions no longer @native, -312 KB native code (more headroom under Studio's native code budget)
- Fix: clicking right after the Studio/game window regains focus (without moving the mouse first) did nothing
- Extensions: submodules point at the current implot-luau, imguicolortextedit-luau, implot3d-luau and imguizmo-luau commits
- tests: t_recolor_pixels, t_scroll_pixels, native_size.py (native code budget check)
2026-10-25 05:44:24 -05:00
4DBug b83d09de0c Roblox backend: forget the last mouse position when the window gains / loses focus (losing focus clears imgui's mouse to unavailable and NewFrame only resends a moved mouse, so a click on return without moving first landed nowhere); rebuilt build/ImGui.luau 2026-10-25 05:44:24 -05:00
4DBug 3bac70663f build: rebuild Roblox bundle + worker (span slots, ImPlot rect pairs, greedy dirty-rect diff, per-command primitive data, table natives, trunc helpers) 2026-10-24 06:09:18 -05:00
4DBug 132660be9a tools/test: t_scroll_pixels.luau (stress window with table + wrapped text scrolling down / up, resizing from the bottom-right and the top-left, composite every 3 frames: incremental must equal a forced full redraw; catches DirtyRects list-diff mistakes) + check_all.sh 'scroll_pixels' check 2026-10-24 06:06:32 -05:00
4DBug 7c21be04de Roblox backend: a primitive's texture, texture id, vertex buffer and clip rect are its draw command's (PrimCmd -> Cmd* arrays, numbered through the frame) instead of 7 per-primitive arrays: CollectPrims writes 11 instead of 17 values per primitive, HashTiles / RasterRect / PrimHash / Parallel.Tile read them through PrimCmd (headless instructions per frame: implot -0.23M, plots -0.1M, scroll -0.09M, fonts -0.08M, resize -0.03M; CollectPrims -10%; pixels identical) 2026-10-24 05:55:53 -05:00
4DBug 8e6abeede9 Roblox DirtyRects: a greedy diff of the tile's old and new primitive list (lookahead 8 entries for the one that resyncs both, so an inserted or removed run is skipped; same flat rect: strips) instead of pairing them only by position when the counts match: a row scrolled out of or into a tile, or an entry shifted by one, no longer redraws every primitive after it. Any order-preserving pairing is exact. Two unpaired entries without a resync: the positional pass as before (mostly changed lists: new font size, animated plots) (headless: scroll PixelsRasterized 14.1k -> 4.3k/frame, Raster -25%, resize_tl 106k -> 82k px, resize 82k -> 78k px; instructions scroll -0.4M/frame, resize_tl -0.2M, others within +-0.1M; pixels identical) 2026-10-24 05:35:18 -05:00
4DBug b119b07676 Roblox HashTiles: the per-primitive vertex hash unrolled (2 vertices for quads, 3 for triangles, 4 for line quads / triangle pairs; was a loop with a branch per vertex; same math, same order: hashes identical) (headless instructions: scroll -0.1M/frame, resize -0.06M; Hash stage -5..9% plots/implot) 2026-10-24 05:34:25 -05:00
4DBug 9ef8a623cc tools/test/native_size.py: native code size of the bundle per module / source file / function vs the Studio limit (one script's native code must fit one ~4 MB block or none of it is compiled; measured in Studio: native at 4,083,418 bytes, interpreted from 4,103,258; master 3,153,274 = 77%, ~900 KB headroom); check_all.sh 'native' check; PORTING.md note 2026-10-24 05:33:08 -05:00
4DBug ff7a04187c Tables: @native TableUpdateLayout(), TableSetupDrawChannels(), TableSetupColumnFlags() (once per table per frame, the largest interpreted cost of table-heavy windows: demo_all -2.5% instructions; +176 KB native code, paid for by the stb_truetype trim; draw data identical) 2026-10-24 04:54:21 -05:00
4DBug b87012f08f stb_truetype: no @native on CFF-only functions (charstring interpreter, CFF index/dict parsing, cubic tesselation) and font-init-only ones (InitFont, table directory): never run per frame for TrueType fonts, native code -312 KB (Studio shares one native code budget across scripts); per-frame cost unchanged (fonts scenario instructions identical), startup -3% instructions (less to compile) 2026-10-24 04:54:21 -05:00
4DBug ca621e1082 Trunc helpers: _Trunc/ImTrunc @native, ImTrunc64 its own hoisted function (was an alias of _Trunc: AddRect()/AddRectFilled() called a non-native function per rect), IM_TRUNC/IM_ROUND hoisted + @native; bundle.py: A's local budget counts the hoisted functions (main chunk stays under 200 locals) (demo_all -1.7% instructions; draw data identical) 2026-10-24 04:54:21 -05:00
4DBug f2658b755e ImDrawListSplitter:Merge(): copy each channel's indices with table.move() (upstream memcpy) instead of a per-index loop in interpreted code (stress hover -0.8% instructions; draw data identical) 2026-10-24 04:54:21 -05:00
4DBug 620660ccf9 Roblox backend: flat triangle pairs a b c + a b d (ImPlot PrimRectFill: heatmap cells, bars; one colour, one uv) are one primitive (kind 5): per row both triangles' spans exactly as DrawTriangle computes them, one fill where they touch (opaque: or overlap), else each in order; pairs DrawTriangle would walk by columns, or degenerate ones, still go to the two calls (tile hash kind field * 8; replay: implot -3.5%; randomized 800k cases vs the two DrawTriangle calls identical; pixels identical) 2026-10-24 04:30:29 -05:00
4DBug 5ae58c6b57 Roblox raster: narrow flat spans (opaque <= 8 px, translucent <= 4 px wide: vertical lines, histogram bars) skip the uniform-row bookkeeping and only mark pending damage; translucent ones blend per pixel (cached per destination value), one pixel wide in one loop down the column (replay: plots -13%, implot -3%, resize -2%; pixels identical) 2026-10-24 04:16:31 -05:00
4DBug 8520257086 Roblox raster: triangle / line quad spans from per-side edge slots (one estimate + short search per side, no per-edge branches per row; horizontal / vertical edges bound the row / column range once), line quad texels blended without the per-texel cache and opaque-texel branches (replay: implot -5%, plots -5%, colorpicker -2.5%; pixels identical) 2026-10-24 04:08:59 -05:00
4DBug 8611bfb4ed build: rebuild Roblox bundle + worker (recolor patch, unrolled span/row writes, axis-aligned edge and alpha-0 edge skips) 2026-10-23 23:52:00 -05:00
4DBug b3e9390653 extensions: submodule pointers -> the rewritten extension commits on their remotes (implot-luau 7199224, imguicolortextedit-luau a340940, implot3d-luau 6ff7fb1, imguizmo-luau a71a223; same trees as the old 2bc5700 / 0592ed6 / b30d2ff / 93f4569, which no longer exist upstream) 2026-10-23 23:51:47 -05:00
4DBug 752ae2e887 Roblox raster: vertex-colour triangles skip a row / column lying on an edge whose two vertices have alpha 0 (an AA fringe's outer edge sits on pixel centres; the interpolated alpha is exactly 0 there, so it drew nothing) (replay: plots -3%, resize -1.5%; pixels identical) 2026-10-23 23:41:50 -05:00
4DBug c0fc18177f Roblox raster: an axis-aligned edge (A = 0 for rows, B = 0 for columns) is tested once per row / column instead of per pixel by the span search: AA fringes and shaded fills next to a vertical / horizontal edge no longer scan empty rows / columns pixel by pixel (replay: implot -8%, plots -12%, resize -5%; pixels identical) 2026-10-23 23:39:02 -05:00
4DBug 5c076f65d5 Roblox raster: solid spans 4-8 pixels per loop iteration (FillRow; a native loop iteration costs more than a few writes), opaque column walks 4 rows per iteration, translucent black over opaque 4 pixels per iteration without the cache (colour picker SV square), full-width span rows copied in doubling blocks (CopyRows), bit32 colour unpacking instead of % / floor (replay in Studio: colorpicker -19%, implot -13%, fonts -16%; pixels identical) 2026-10-23 23:39:02 -05:00
4DBug d1db51dded Roblox backend: PatchDrawList skips primitives with no vertex in the listed vertices' offset range before the DriftSet lookups (hover recolor patch -25%, drift moves too) 2026-10-23 23:19:40 -05:00
4DBug cef7a1209e Roblox backend: recolored draw lists (same vertex positions, a few vertices' colour / uv changed, e.g. hover) skip HashTiles: CompareDrawList 4 lists them, PatchDrawList gives those primitives their real hashes (PrimHash / FlatTileHash) and redraws just their tiles, leaving the tiles exactly as the full path would; t_recolor_pixels (incremental vs forced, also parallel) in check_all 2026-10-23 23:19:40 -05:00
4DBug 951d18fda2 Roblox backend: HashTiles mixes the primitive kind into its bounds term instead of two extra % after the second vertex (gradient rects, ImPlot line quads; implot Hash -4%, same pixels) 2026-10-23 23:19:40 -05:00
4DBug 006c8c4a34 tools/test: prof.py finds run.py's linemap in $TMPDIR (tempfile.mkdtemp), not only /tmp 2026-10-23 22:32:53 -05:00
4DBug 23e31fcf3c 0.4.3
Build & Release / build (push) Canceled after 0s
Performance update (Roblox), no API changes; draw data and pixels identical to 0.4.2.
- Unchanged check: CompareDrawList reads vertices as f64 + col (3x fewer reads), moved lists shift their snapshot in place
- Collect/hash ~40% cheaper per changed draw list; DirtyRects without copies, skips unchanged prims at the same position
- Raster straight into the upload buffer (no CopySubRect; Upload -80..90%), uniform row intervals, faster glyph blits, pending damage rect, two-pixel span writes, inlined blends in gradient/interpolating triangles, tall flat triangles as spans
- Tiles: no 64 KB CPU buffer per tile, 4 prewarmed tiles in the free list; atlas record buffers reused on repack
- Fix: windows moved by whole pixels could keep stale pixels where trig-generated vertices drift by 1 ulp (t_move_pixels)
- Library: @native on hot helpers, fewer temporaries (Begin, widgets, tables, PlotEx, colour checkerboard), pooled ImDrawCmd / style / group stack entries (55 -> 31 KB/frame on the bench scene); faster glyph baking (repack O(n), vertical-edge fast path)
- backends/roblox/patches.lua: Luau-tuned RenderText/AddText/text-size cache hit (Roblox only)
- bundle.py optimization L: library-internal ImGui.Foo calls become locals (Roblox; hookable deny-list: Begin, End, TreeNode*, CollapsingHeader, ItemAdd, ItemHoverable, ItemSize, BeginTabItem, ShowDemoWindow; IMGUI_BUNDLE_NO_L=1 turns it off)
- Parallel: Actors free destroyed textures (leak), send only changed glyph rects
- Extensions: implot-luau (range renderers, tick reuse, @native per-point paths), imguicolortextedit-luau (widest line + selection cached), implot3d-luau, imguizmo-luau (@native math)
- LÖVE backend: RegisterCanvas()/UnregisterTexture(), ReadFile via love.filesystem root
- tests: t_move_pixels, t_scene_pixels, t_stress, t_stress2 + bench_scenes.luau
2026-10-21 04:04:31 -05:00
4DBug 694d56a78f LÖVE backend: ReadFile also tries the root as a love.filesystem path (works in .love/fused builds); RegisterCanvas()/UnregisterTexture() to show an existing Texture/Canvas without the backend owning it; rebuilt build/imgui_love.lua 2026-10-21 04:03:58 -05:00
4DBug 635cf6647b build: rebuild Roblox bundle + worker (round 3: rasterizer gradients/lines, library plots/colour pickers/Begin temporaries) 2026-10-21 03:50:40 -05:00
4DBug 90efb0c6e1 extensions: imguicolortextedit-luau -> 0592ed6 (TextEditor: widest line + selected text cached, @native glyph loops), implot3d-luau -> b30d2ff, imguizmo-luau -> 93f4569 (@native per-point/math paths) 2026-10-21 03:50:31 -05:00
4DBug 6eb91d17e4 extensions: implot-luau -> 2bc5700 (round 3 ImPlot performance: range renderers, @native per-point helpers, tick reuse) 2026-10-21 03:35:40 -05:00
4DBug dfdfea5ea7 Roblox backend: RasterRect tests a primitive's bounds against the rect before reading its clip (most of a tile's primitives miss a small dirty rect) 2026-10-21 03:35:32 -05:00
4DBug c85b2dbb96 Roblox raster: solid spans written two pixels per writef64 (the pixel twice as a normal double; per pixel otherwise), translucent black spans without the colour terms (colour picker SV square), triangle / line quad rows start past an estimate that is never in the span (replay: colorpicker -13%, plots -7%, implot -5%; pixels identical) 2026-10-21 03:35:32 -05:00
4DBug 12059f2646 Roblox backend: DirtyRects skips AddRect for a changed primitive inside the first dirty rect (where AddRect would merge it, unchanged) 2026-10-21 03:35:32 -05:00
4DBug d99864c315 Roblox raster: per-pixel blend/texel sample inlined in the interpolating triangle paths (rows and columns) and gradient kind 2 (a call per pixel cost more than the math), colours unpacked inline (shared when equal), white texels not folded, flat span constants only when translucent; line quads: bounds before edge setup, fixed texel row when v is constant; narrow solid spans written instead of copied per row (replay: colorpicker -14%, plots -14%, implot -3%; pixels identical) 2026-10-21 03:35:32 -05:00
4DBug b2c8ce7a00 tools/test: t_scene_pixels (bench scenes animated, composited every 8 frames: incremental == forced redraw), in check_all (ImPlot scene when extensions/implot-luau is checked out) 2026-10-21 03:35:32 -05:00
4DBug a2e19627fe tools/test: hashes.sh finds luau/luajit in the nix store when the pinned paths are gone (like check_all.sh) 2026-10-21 03:00:35 -05:00
4DBug 278f978d3e Library: fewer temporaries per window, child, input field, separator text and resizable table: Begin() skips CalcWindowAutoFitSize() when no axis auto-fits (result unused; still called when a size callback would see it), scalar scrollbar/auto-fit/avail/needed sizes, ScrollbarSizes updated in place, scratch viewport/visibility rects, OuterRectClipped and the previous-child overlap test without ImRects; RenderWindowOuterBorders() scratch corner; EndChild() scratch size/bb; InputTextEx() scalar label/frame/inner sizes, scratch total_bb and (single-line, until ItemAdd() accepts it) frame_bb, so clipped fields allocate nothing; SeparatorTextEx() scratch sizes/rect/positions; TableUpdateBorders() scratch hit rect
demo_all scene headless: 825 -> 553 KB/frame allocated (Begin 5.3 -> 1.4 KB per window, InputTextEx 0.8 KB -> 0 per
clipped field), user instructions/frame -1.3%. GC steps in that scene cost ~+1.5 ms on 2-4 frames per cycle, so
cycles get ~1/3 rarer. Draw data unchanged.
2026-10-21 03:00:23 -05:00
4DBug 30afa19ed1 Library: PlotEx() without per-point temporaries (scalar tp0/tp1 and ImLerp, two scratch corners only read by AddLine()/AddRectFilled(), scalar frame/inner/total rects) and @native; RenderColorRectWithAlphaCheckerboard() with scratch cell corners and @native; @native ShadeVertsLinearColorGradientKeepAlpha() and _PathArcToN() (color picker hue wheel)
plots scene headless --roblox (interleaved A/B): lib lowq ~0.35 -> ~0.27 ms/frame; colorpicker lib lowq ~0.43 ->
~0.38 ms/frame. Draw data unchanged (STRESS2HASH of all scenes, draw hashes).
2026-10-21 03:00:23 -05:00
4DBug 2ff5225f49 Library: @native on DebugNodeFontGlyphsForSrcMask() (the font atlas glyph grids: a 256-entry scan per codepoint block + 256 AddRect/RenderChar per open block) and on small helpers called from native code (IM_ASSERT, IM_ASSERT_USER_ERROR_RET, ImHashStr's memo, ImVector __index/push_back/pop_back/back/iter)
demo_all scene (whole demo open, headless --roblox, interleaved A/B): lib ~10.1 -> ~9.1 ms/frame, user
instructions/frame -5%; draw data unchanged.
2026-10-21 03:00:23 -05:00
4DBug 5fa9889a37 tools/test: bench_scenes.luau (plots, colorpicker, implot, demo_all scenes shared by the Studio bench and headless runs) and t_stress2.luau (library + backend time and draw checksum per scene) 2026-10-21 01:58:35 -05:00
4DBug 6f4ec3c2b7 build: rebuild Roblox bundle + worker (round 2: bundle-time ImGui.* localization, patches.lua, library allocations, backend raster/bookkeeping) 2026-10-21 01:29:48 -05:00
4DBug 701156b5cc Roblox backend: reuse the destroyed atlas texture record's buffer for the next one of the same size (repack)
buffer.create of a 512 KB atlas costs ~0.1-1.8 ms in Studio (spiky); a repack creates one every few frames
in the font size scenario.
2026-10-21 01:24:28 -05:00
4DBug 086e66cb3e Roblox backend: keep 4 prewarmed tiles in the free list (Heartbeat, one per call, never evicting)
A growing layer takes them instead of creating an EditableImage + ImageLabel mid-frame (~90 us per tile in
Studio vs ~7 us from the free list). GetTile: one path for new and recycled tiles (NewTile).
2026-10-21 01:24:28 -05:00
4DBug 162fa80075 Roblox raster: tall flat triangles (column walk) write spans like the row path (no BlendPixel call per pixel)
Opaque: direct writes; translucent: the row path's per-span constants + per-destination cache. Same math,
bit-identical (replay hash, t_pixels, t_composite, t_parallel). Replay: triangles ~13 -> ~9 ms, total -5%.
2026-10-21 01:24:28 -05:00
4DBug 31d09640bf Roblox backend: DirtyRects skips primitives unchanged at the same list position (paired lists)
Every pixel such a primitive covers is either inside a changed primitive's rect or drawn by the same
primitives in the same order. Headless: 7% fewer pixels rasterized on resize, raster+upload -6..-9%.
2026-10-21 01:24:28 -05:00
4DBug 53b3489f68 Roblox backend: moved draw lists with drifted vertices: redraw just what they touch (and always redraw it)
A window moved by whole pixels often has a few trig-generated vertices off the exact shift by an ulp (when a
coordinate crosses a power of two): CompareDrawList fell back to the full Collect + Hash (~1/4 of moving
frames), and the tile hashes don't see an ulp, so those primitives were never redrawn (stale pixels vs a
forced redraw, e.g. a moving Bullet). Now CompareDrawList lists the drifted vertices; if all their floor /
ceil (CollectPrims' bounds) shifted too it returns 3: PatchDrawList keeps the tile lists (same primitive
sequence, checked) and marks only the drifted primitives' entries changed (DriftMark, new each frame), so
their tiles redraw just those rects. Otherwise the full path marks them the same way.
2026-10-21 01:24:28 -05:00
4DBug 2fc6d75ef8 tools/test: t_move_pixels (moving window with circles / rounded rects / bullets: incremental == forced redraw), in check_all 2026-10-21 01:24:28 -05:00
4DBug f2648316e7 bundle.py: optimization L (Roblox): library-internal ImGui.Foo reads in function bodies become per-file locals ImGui_Foo (file function or a wrapper around it, within the 200 locals/upvalues limits), bound after every IM_INCLUDE; only names assigned once at load time, patchable deny-list (Begin/End/TreeNode*/CollapsingHeader/ItemAdd/ItemHoverable/ItemSize/BeginTabItem/ShowDemoWindow) stays a table lookup; IMGUI_BUNDLE_NO_L=1 turns it off
ImGui has ~1000 keys, so Luau's inline cache (hash slots < 256) missed most ImGui.Foo lookups. 722 names localized;
draw hashes identical, LÖVE bundle unchanged, IMGUI_BUNDLE_NO_L=1 reproduces the previous bundle byte for byte.
2026-10-21 01:20:39 -05:00
4DBug 328f13a3c4 Library: tables without per-instance temporaries in BeginTableEx()/TableUpdateLayout()/TableMergeDrawChannels() (scratch rects, scalar outer size); ImDrawListSplitter::Merge() keeps the command it merges away past Size for reuse (was 6 new ImDrawCmd per table per frame): 435 -> 247 tables/frame allocated for 10 small tables in a window
Draw data unchanged.
2026-10-21 01:14:31 -05:00
4DBug f3387cfe76 Library: no temporaries in Checkbox()'s check mark, Bullet(), Dummy(), NewLine(), ArrowButton[Ex](), InvisibleButton(), MenuItemEx() and InputScalar()'s step buttons
Per widget headless: MenuItem 658 -> 119 B, Bullet 611 -> 0 B, ArrowButton 634 -> 7 B, Checkbox 74 -> 7 B, NewLine 112 -> 0 B, Dummy/InvisibleButton 448/673 -> 112 B (the caller's own ImVec2). Draw data unchanged.
2026-10-21 01:14:31 -05:00
4DBug 2b5887d166 Library: no temporaries in Selectable(), RadioButton(), SeparatorEx(), LabelText(), BeginCombo(), SmallButton(), ProgressBar() and the single-line InputTextEx() path (scratch rects/vectors only read by callees, scalar text sizes, shared read-only defaults; the multi-line backup of LastItemData only built when multi-line)
Per widget headless (bytes allocated, time): Selectable 724 -> 7 B, -15%; RadioButton 857 -> 7 B, -15%; Separator 336 -> 0 B, -14%; LabelText 1555 -> 0 B, -33%; BeginCombo 1541 -> 6 B, -17%; InputFloat 3838 -> 1741 B, -15%; ProgressBar 986 -> 437 B, -10%. Draw data unchanged.
2026-10-21 01:14:31 -05:00
4DBug 9c965297ee Library: PushStyleColor()/PushStyleVar*()/BeginGroup() reuse the stack entry left past Size by the matching pop (C++ copies them into the vector's storage), EndGroup() without temporaries: no garbage per push/group (was 288/193/1952 bytes), per widget headless: PushStyleColor -14%, PushStyleVar -12%, BeginGroup+EndGroup -34%, DragFloat3 -11%
Draw data unchanged.
2026-10-21 01:14:31 -05:00
4DBug de8e2fef08 Library: fewer temporaries per window in Begin() (scalar TitleBarRect()/CollapseButton() rects, viewport clip and contains tests, visibility rect, CalcWindowSizeAfterConstraint() writes its own copy, title bar rect only built for a hovered window): 21.4 -> 18.8 KB/frame allocated for one window of buttons/sliders, 46.6 -> 42.5 KB/frame in the Studio bench scene
Draw data unchanged.
2026-10-21 01:14:31 -05:00
4DBug 015cd40172 Library: ImDrawList reuses its ImDrawCmd objects (AddDrawCmd() takes the command left past Size by last frame's resize(0)/pop_back(), Merge() swaps instead of clearing channel slots), _CmdHeader reset in place: ~9 KB/frame less garbage in the Studio bench scene
Draw data unchanged.
2026-10-21 01:14:31 -05:00
4DBug c740729106 Roblox backend: patches.lua, Luau-tuned replacements of hot library internals (text rendering, text size cache hit)
New backend module installed when the backend loads (the library sources stay the 1:1 port): MT.ImFont.RenderText and
MT.ImDrawList.AddText share one native core (clip rect as numbers, PrimReserve inlined, no CPU fine clip branches,
AddText without the clip rect copy and extra call); ImFontCalcTextSizeXY checks its cache hit first. Uncommon cases
(byte-table text, CPU fine clip, > 10k bytes unwrapped, texture change mid-text) go to the originals. One switch per
patch (Enabled), M.Set() for in-process A/B. Draw hashes, composite pixels identical; imgui time -3..-4% (Studio
in-process A/B and headless).
2026-10-21 01:04:21 -05:00
4DBug 76cfcf6e12 build: rebuild Roblox bundle + worker (backend and library performance work since 0.4.2) 2026-10-20 20:52:38 -05:00
4DBug 90363f4a6e Library: @native on small, frequently called helpers (style color stack, tree push/pop, indent, item size, draw list clip/cmd, glyph lookup, table column helpers)
Picked from a per-function call census of the whole demo opened (hundreds of calls/frame each); +~100 KB of native
code. Whole demo open (headless --roblox) 10.35 -> 9.84 ms/frame together with the previous commits; draw data unchanged.
2026-10-20 15:19:28 -05:00
4DBug b05d2535c0 tools/test: t_stress.luau, headless copy of the Studio bench scene (library CPU per frame + draw checksum) 2026-10-20 15:19:28 -05:00
4DBug 70df13d409 Library: drop @native from once-per-window/frame giants, fewer slow lookups in text helpers
- Begin/End/NewFrame/UpdateMouseInputs back to interpreted: ~520 KB of native code (Begin alone 369 KB, +30% of the
  bundle's native code) for ~5 us/frame; native code is a game-wide budget in Roblox
- GetCurrentWindow(): read g.CurrentWindow once (the key sits in a hash slot >= 256 of the ~300-field context, which
  Luau's inline cache can't predict, so every read is a slow lookup)
- FindRenderedTextEnd(): strings use string.find/string.len directly (no ImMemchr() call, no `#` on a string)
- CalcTextSize(): calls CalcTextSizeXY() directly (one wrapper level less); TextEx(): string.len() for strings

Draw data unchanged.
2026-10-20 15:19:28 -05:00
4DBug 46551df26b Library: fewer calls/lookups per text item, table cell and frame
- Text(): TextV() inlined (one vararg call less per formatted Text); TextEx(): CalcTextSize() inlined
- ImFontCalcTextSizeXY / RenderText / CalcWordWrapPosition: GetFontBaked() fast path inlined (LastBaked check)
- TableBeginCell(): SetWindowClipRectBeforeSetChannel() inlined; SetCurrentChannel(): skip the TexRef field reads
  when both commands share the same TexRef (as ImDrawCmd_HeaderCompare already does)
- UpdateKeyboardInputs / UpdateKeyRoutingTable: loop-invariant field reads hoisted
- `#` on strings replaced by string.len() in ImFontCalcTextSizeXY (`#` is not a native fast path)

Headless --roblox: stress+demo 0.98 -> 0.89 ms/frame, empty frame 0.085 -> 0.067 ms; draw data unchanged.
2026-10-20 15:19:28 -05:00
4DBug 713cd3c22a Library: @native on hot interpreted paths (Begin/End, NewFrame key loops, table rows, sliders, buttons, wrapped text, GetFontBaked)
Fewer native<->interpreter transitions on the per-item call chains. Stress+demo headless (--roblox) 0.98 -> 0.93 ms/frame,
draw data unchanged.
2026-10-20 15:19:28 -05:00
4DBug b75f183ecf Roblox backend: tiles no longer allocate a 64 KB CPU pixel buffer each (unused since dirty rects are rasterized straight into upload buffers) 2026-10-20 15:12:11 -05:00
4DBug 5f23d260fd Roblox backend raster: damage to the uniform rows collected in one pending rect (applied when a span needs them); spans process runs of rows with the same uniform piece at once 2026-10-20 15:11:51 -05:00
4DBug a20b7fcacf Roblox backend raster: uniform rows are only valid inside the last ClearRect (no reset passes) 2026-10-20 15:11:51 -05:00
4DBug efe16cc1e8 Roblox backend raster: glyph blits read consecutive texels without the column table, cache white-texel blends per alpha 2026-10-20 15:11:51 -05:00
4DBug 7a453fd8b7 Roblox backend raster: uniform region tracked per row instead of one rect (translucent spans over uniform rows fill instead of blending per pixel) 2026-10-20 15:11:51 -05:00
4DBug ad32fa4bd1 Roblox backend: rasterize dirty rects straight into the upload buffer (no CopySubRect, no cold 64 KB tile buffer) 2026-10-20 15:11:51 -05:00
4DBug 360e7b70bc Font atlas: ImTextureData:Create() reuses the pixel table of the last atlas texture removed after the backend destroyed it (same byte size, zero-filled with table.move doubling) instead of a new 512K-entry table per repack (texadd 92 -> 44 ms, bake bench -8% run side by side; atlas/glyph checksums and draw hashes unchanged) 2026-10-20 14:47:54 -05:00
4DBug 08953d4270 Parallel: Actors free destroyed textures (each atlas grow/repack left a full copy in every Actor), atlas patches send the updated glyph rects instead of whole row spans and are built once per version for all Actors (fonts tex sends 151 -> 91 KB/frame in Studio, TexBytes 35.6 -> 22.2 MB headless); Actor texture handling moved to Raster.ApplyTextures, which Sync mode now runs on per-Actor copies so t_parallel checks it; t_parallel fonts scenario (new size per frame), check_all runs 620 frames 2026-10-20 14:47:54 -05:00
4DBug 19083b757d Faster glyph baking: atlas repack finds RectsIndex entries by the loop index (index_from_ptr was O(n^2) per repack), stb_truetype vertical edges (all of ProggyClean's) without stbtt__handle_clipped_edge calls, FlattenCurves with locals + inlined add_point, @native trunc (sorted-edges 215 -> 107 ms, repack 330 -> 184 ms on bake bench; glyph bitmaps, atlas and draw hashes unchanged) 2026-10-20 14:47:54 -05:00
4DBug c3119740e4 Textures: typed, unrolled RGBA/Alpha8 row conversion (no zero-skip branch): new 512x256 atlas record 0.54 -> 0.30 ms headless, pixels unchanged 2026-10-20 14:47:54 -05:00
4DBug 2ffc355ffe Roblox render: hot loop locals, native DrawLayer, DirtyRects without copies
- CollectPrims / HashTiles / DirtyRects: the Prim* / slot tables as locals (upvalue access per element was
  measurable: Collect -13%, Hash -8%)
- CollectPrims notes flat rects (PrimFlat): HashTiles no longer re-reads uvs, gradient and texture per quad
- HashTiles: one loop over a primitive's tiles instead of nested for loops (most touch one tile)
- DrawLayer, SweepTiles @native (per-tile bookkeeping -33%)
- DirtyRects: clipped bounds computed once (content bounds from them); the tile's Drawn* hash/flat lists are
  swapped with the layer's lists and the bounds with a scratch set instead of copied per entry
Headless full re-collect of the demo vs 0.4.2: Collect -24%, Hash -48%, bookkeeping -32%. Pixels identical
(t_pixels, t_composite, t_parallel, TileLimit run).
2026-10-20 14:47:19 -05:00
4DBug ba9d529935 Roblox render: cheaper CollectPrims + HashTiles (per changed draw list)
HashTiles: a touched tile's count/hashes/lists live in slot arrays for the call (one KeySlot lookup per tile
switch instead of ~7 hash-table reads/writes; consecutive primitives alternate tiles ~40% of the time), the
vertex hash is inlined (HashVertex calls weren't inlined and cost more than the hashing), tile ranges come
from the already-relative bounds. Hash values are unchanged.
CollectPrims: the axis aligned rect test runs before the textured line-quad test (mutually exclusive, so the
result is the same; glyphs no longer read their colours/uvs twice), clipped/limit/extent checks per command
from the command's bounds instead of per primitive, and primitives go to their layer lists while collecting
(no PrimKind pass in DrawLists).
Headless full re-collect of the demo (1500 prims): Collect -10%, Hash -35%.
2026-10-20 14:47:19 -05:00
4DBug b62997f2c3 Roblox backend: faster unchanged check: CompareDrawList compares vertices as 4 f64 + col (3x fewer reads), indices 4 per step; a moved list's snapshot is shifted in place (ShiftSnapshot) instead of re-snapshotted from another list's Cmd* data 2026-10-20 13:56:21 -05:00
4DBug dd9a5ef219 0.4.2
Build & Release / build (push) Canceled after 0s
- Less garbage per frame: scalar text/label sizes, scratch rects/points, reused clip-stack ImVec4 and window stack entries (160 -> 56 KB/frame on demo+stress, draw hashes unchanged)
- Faster glyph baking: @native rasterizer/rect packer/pixel loops, glyph shape cache, comparator-free edge sort, inline scanline conversion, table.create zero-fill; fix leaked global 'step'
- Textures: new atlases convert only the packed corner, flat row conversion skipping zero pixels
- Raster: uniform-region tracking, direct opaque glyph texels, inlined BlendPixel with per-texel cache
- Raster: textured line quads drawn as one quad, u32 texel reads for constant-colour triangles, column walk for tall narrow triangles (plot bench Raster 4.16 -> 3.21 ms, HashVertex 0.64 -> 0.55 ms, pixels unchanged)
- Parallel: send Actors only changed atlas rows / rows above FillRow (full-copy 1283 -> 619 MB on fontbench x4 Actors); dispatch small and text-heavy frames (MinTiles 1, MinPixels 2048, MaxBytesPerPixel 0)
- Stage timing: Textures and Flush stages; parallel stats explain serial flushes
- extensions/: submodules for imcurveedit-luau, imgradient-luau, imgui-memory-editor-luau, imsequencer-luau; all 9 submodule URLs and README links now on GitHub
- new examples: example_love_extensions, example_roblox_extensions
2026-10-17 13:18:53 -05:00
4DBug 9b1052beed 0.4.1
Build & Release / build (push) Canceled after 0s
- TextProxy works for any widget that sets PlatformImeData.WantTextInput (+ SelectedText)
- TextProxy: key-code fallback waits for the TextBox (fixes doubled typing); no stuck Ctrl after paste
- Raster: reversed rects (min > max) draw like upstream (fixes ImNodes/ImPlot box select)
- test harness: --module NAME=path loads extra ModuleScripts
- new tests: t_textproxy_custom, t_rect_flip
- extensions/: submodules for imguicolortextedit-luau, imguizmo-luau, implot-luau, implot3d-luau, imnodes-luau
2026-10-17 07:31:40 -05:00
4DBug b4458195b9 0.4.0
Build & Release / build (push) Canceled after 0s
2026-10-16 22:53:18 -05:00
4DBug 9b735db59c 0.3.0
Build & Release / build (push) Canceled after 0s
2026-10-15 11:04:45 -05:00
4DBug 6fc870a519 CI/releases: drop the nodemo bundles (--no-demo build flag kept); remove examples/example_shared; Roblox backend RenderRate defaults to 60 (0 = every frame); README + TODO.txt updated 2026-10-15 10:57:00 -05:00
4DBug 8f4e07c94a Fix: long TextUnformatted (>2000 bytes) rendered each visible line to the end of the text (RenderText end was nil, upstream passes line_end); PushFont() saved the new font instead of the current one, so PopFont() never restored it (font preview leaked into all later text); t_fixes covers both 2026-10-15 10:54:56 -05:00
4DBug 056c414112 Port leftovers: BringWindowToDisplayBehind, ImGuiSizeCallbackData + CalcWindowSizeAfterConstraint, ErrorCheckUsingSetCursorPosToExtendParentBoundaries, PopFocusScope user error (+ SetCurrentWindow stack sizes fix), log text decorations (Button/Menu/TreeNode/Drag/Slider/InputText/Checkbox/Radio), DataTypeFormatString display, ImGuiDataType S64/U64 (upstream enum layout; doubles), sscanf %u/length modifiers, mouse arrays sized ImGuiMouseButton.COUNT, AddCallback userdata copy; TODO.txt refreshed 2026-10-15 10:51:20 -05:00
4DBug 15485b7aa4 Integration: debug/context fields in ImGuiContext ctor, ImGuiContextHookType, DebugFlashStyleColorIdx=COUNT, CurrentPixelDensity, clipper range/data helpers, full Shutdown cleanup, settings dates (ImGuiSettingsCleanupArgs, CleanupIniSettings, LastUsed=, Platform_SessionDate) + metrics Settings section, ImGuiStyleVar SeparatorSize/DockingSeparatorSize (fixes off-by-one style var table), LogRenderedText restored in RenderText*, combo preview 1.93, InputScalar ValidatedThisFrame, ImGuiListClipperFlags/LogFlags/OldColumnFlags, ImGuiKey digit aliases, backend names 2026-10-15 09:39:17 -05:00
4DBug cdb183da59 compare_upstream: skip IM_MSVC_RUNTIME_CHECKS_*/template<> when naming structs; [=] status for intentional Lua replacements (ImGuiStorage, ImStr*/ImFormatString*, allocators, C++ container internals, sizeof/ABI helpers...) with evidence regexes, reported separately 2026-10-15 09:39:17 -05:00
4DBug df641ad622 Port debug tools (item picker, flash style color, debug locate, DebugDraw*, keyboard preview, debug break, DrawCmd mesh view), context hooks, SetContextName, AddInputCharactersUTF8, sanity checks, window resize ids, Register/UnregisterUserTexture, SetPixelDensity, TestShortcutRouting, DemoMarker; InputTextState selection API (fixes undo crash, callbacks get 0-based positions), ShortcutsForCancel (Esc/right-click reverts drags/sliders), ImParseFormatSanitizeForPrinting, ImDrawList CloneOutput/PrimQuadUV/AddImageQuad, ImDrawData DeIndexAllBuffers/ScaleClipRects, internal helpers (ImBitVector, ImGuiPackedDate, inline ImGui getters...); t_debugtools, t_helpers 2026-10-15 08:52:30 -05:00
4DBug 91931a482b Fonts: ImFontGlyphRangesBuilder + GetGlyphRangesDefault, ImFont:CalcWordWrapPosition, stb_decompress + Decode85 + AddFontFromMemoryCompressed(Base85)TTF, atlas helpers (RemoveFont, RemoveCustomRect, AddRemapCodepoint (remap never triggered before), IsGlyphRangeUnused, texture status/format names...); t_fonts 2026-10-15 08:05:51 -05:00
4DBug c94f62a1e4 Port ImTriangulator + upstream AddConcavePolyFilled (AA fringe, no per-triangle seams); [Luau] handles CCW winding and duplicate/collinear points that upstream mis-triangulates 2026-10-15 07:43:21 -05:00
4DBug 25001b0c8f Library draw call sites match 1.93: AddLineH/AddLineV + StrokeCenterBiased/StrokeInside (window/menu borders, separators, text cursor), tab border PathStroke, check mark AALineEnds, CloseButton/TreeNode lines/ColorButton/alpha checkerboard 1.93, Ctrl+Tab highlight AddRect arg order, metrics AA push/pop 2026-10-15 07:24:13 -05:00
4DBug f875e2b5f7 Draw list 1.93: baked round corners in the font atlas (ImFontAtlasBuildUpdateTexDataCorners, fill radii 1..16 + 3 stroke thicknesses) used by AddRect/AddRectFilled when pixel-aligned (_AddRectBaked/_AddRectFilledBaked) 2026-10-15 06:55:57 -05:00
4DBug 923e6cdafb Draw list 1.93 strokes: _AddPolyline ported (texture AA lines, joins/miter/bevel, CapSquare, AALineEnds, Stroke Inside/Center/CenterBiased/Outside/Legacy), AddConvexPolyFilled AAFill, all primitives with 1.93 signatures/flags, PathRect/PathArcTo 1.93, baked line textures; Custom Rendering demo flags UI restored. check_all: t_pixels incremental==full redraw, headless screenshot (tools/test/shot.py) 2026-10-15 06:37:49 -05:00
4DBug 720daa80d7 Draw list 1.93 foundation (no output change): ImDrawFlags 1.93 values (Round*/Stroke*/AA*/JoinMiter/CapSquare/TextNoPixelSnap/UseTexForRoundCorners...; RoundCorners* kept as obsolete aliases), ImDrawList.Flags + PushDrawFlag/PopDrawFlag/_SetPixelDensity, SetupDrawListSharedData 1.93, style.CurveTessellationMaxError/AntiAliasedLineEnds, _AddPolyline entry point 2026-10-15 05:13:58 -05:00
4DBug 1b618f7230 compare_upstream: match XxxMT:Method and Class_Method globals to C++ class members (demo 100% ported by name) 2026-10-15 04:35:23 -05:00
4DBug ddbfd8fb66 Demo: Selection State & Multi-Select section (ExampleSelectionWithDeletion, ExampleDualListBox, all 11 sub-demos) and Assets Browser ported; fix ImFloor() for negative non-integers (was floor-1) 2026-10-15 04:13:40 -05:00
4DBug 25bc437635 Port multi-select, box-select and typing-select (BeginMultiSelect/EndMultiSelect, SetNextItemSelectionUserData, MultiSelectItemHeader/Footer, BeginBoxSelect/EndBoxSelect, GetTypingSelectRequest/TypingSelectFind*, ImGuiSelectionBasicStorage/ExternalStorage, Metrics nodes); wired into Selectable/Checkbox/TreeNode/clipper/tables; t_multiselect 2026-10-15 03:49:53 -05:00
4DBug d6bdedee85 Fix: InputTextMultiline crashed when drawn (InputTextLineIndexBuild/line offsets 0-based like upstream, inverted buf_display_end), InputText LiveEdit flag check; Shortcut()/IsKeyChordPressed() upstream defaults; FrameCount starts at 0 (IsWindowAppearing on first frame); missing ImGuiIO config fields with upstream defaults (+ ConfigDebugBeginReturnValueOnce/Loop); ColorButton drag source + ColorEdit4 drop target, IMGUI_PAYLOAD_TYPE_COLOR_3F/4F; t_fixes covers them 2026-10-15 03:03:10 -05:00
4DBug 966da7fbcf Demo: re-ported imgui_demo.cpp line by line in upstream order (one function per upstream function, same labels/HelpMarkers/comments, 176/186 IMGUI_DEMO_MARKERs; port table driver/Sub()/Demo* helpers removed, statics in S.<Function>). New: DemoWindowInputs (Inputs & Focus), Image Viewer, ShowExampleAppDockSpaceBasic. Selection/Assets Browser stubbed until multi-select is ported. ImColor helper (imgui_h.lua). PORT_STATUS demo similarity 29% -> 51% 2026-10-15 02:32:58 -05:00
4DBug bc13bc50b8 Fix: ImDrawList:PushClipRectFullScreen() was missing (drop target outside the window clip rect crashed); CalcItemSize() no longer writes to the caller's size (by value like upstream; fixes BeginTable UserOuterSize), scalar _CalcItemSizeXY for internal callers; t_fixes covers both 2026-10-15 02:05:43 -05:00
4DBug ce0f51d9d5 tools/test: check_all.sh (CI mirror + all scripted tests + demo forced open + LÖVE), hashes.sh (draw checksums vs a git rev), t_libhash (library-only draw checksum); regenerate PORT_STATUS 2026-10-15 02:03:40 -05:00
4DBug 7ca140665d 0.2.0
Build & Release / build (push) Canceled after 0s
2026-10-15 01:06:11 -05:00
4DBug 3b28ba362b Roblox backend: redraw budget is opt-in (SetRedrawBudget default 0 = every changed tile drawn the same frame) 2026-10-15 00:55:43 -05:00
4DBug b15bdcd8b6 bundle.py: build-time Luau optimizations (draw-data identical; IMGUI_BUNDLE_NOOPT=1 disables): hot library globals as bundle locals, enum/constant folding (values dumped by the luau CLI; IMGUI_BUNDLE_STRICT=1 in CI), --@hoist pure helpers to inlinable bundle-level local functions, statement IM_ASSERT -> assert; builtin type instead of ImGui._GetTypeFunc() alias (GETGLOBAL 15903 -> 540) 2026-10-15 00:23:20 -05:00
4DBug a0a9799efd Library perf (draw-data identical): layout core (no ImVec2 __index in ItemSize, inlined ID/style/clip stacks, scalar ItemAdd/IsClippedEx/CalcItemSize/GetColorU32), text + widgets (scalar TextEx/ButtonEx/Checkbox/Slider/Drag/Selectable/TreeNode, word-wrap memo), tables (in-place clip rects, no per-row/cell temporaries, @native cell functions, scalar ClipWith), draw list (PrimRectXY, scalar AddRect/AddRectFilled/AddLine/PathRect/arcs) 2026-10-14 23:27:23 -05:00
4DBug 01978e76ad Roblox backend perf (pixel-identical): redraw budget (SetRedrawBudget, default 1.5 ms; RenderRate default 0), exact in-place draw list compare + whole-pixel move fast path, partial tile redraws, flat rects hashed by in-tile rect, quads hashed by TL/BR, no full redraw on texture updates, @native CopyTexturePixels, reused partial upload buffers; imgui_draw: @native word wrap, ImStrByte/classifier inlined, text size cache covers wrapped text; t_pixels pixel oracle; run.py RUN_FLAGS 2026-10-14 22:26:38 -05:00
4DBug 1f4ae93a2e tools/compare_upstream.py: port coverage + code similarity vs upstream, writes docs/PORT_STATUS.txt 2026-10-14 22:26:38 -05:00
4DBug 67dc6d3e18 0.1.4
Build & Release / build (push) Canceled after 0s
2026-10-14 10:32:10 -05:00
4DBug 43410ad035 InputText: fix clipboard paste (filter was inverted, then off-by-one in the filtered buffer); ImParseFormatTrimDecorations: return [start, end) like upstream (Ctrl+click temp input showed decorations / crashed on "%d%%"); ShrinkWidths: tie order by Index descending like upstream; t_fixes test 2026-10-14 10:32:10 -05:00
4DBug 0d01aaddf3 Comments: mirror upstream imgui.cpp/.h, imgui_internal.h, widgets/draw/tables/demo and imstb_* comments (comment-only, code tokens unchanged) 2026-10-14 10:23:55 -05:00
4DBug 0091e0e879 CI: minified builds (ImGui.min.luau, ImGui-nodemo.min.luau, imgui_love.min.lua, imgui_love-nodemo.min.lua) via tools/minify.py; checks + release assets; run.py MINIFY=1 2026-10-14 10:23:55 -05:00
4DBug 65d8510f29 0.1.3
Build & Release / build (push) Canceled after 0s
2026-10-14 06:26:28 -05:00
4DBug 7beab8da57 Docking: set node.LastBgColor (closing dock hosts drew white bodies), host skips own bg, fix SetNextWindowBgAlpha; Roblox backend: frames skipped by the render rate cap are drawn later (UI could freeze when the app stopped rendering); t_dock_close test 2026-10-14 06:26:28 -05:00
4DBug 3bebc88ffc 0.1.2
Build & Release / build (push) Canceled after 0s
2026-10-09 02:24:21 -05:00
4DBug 5db1490647 Roblox backend: text proxy is opt-in (SetTextProxy), remove SetTextProxyDebug; new example main.client.luau 2026-10-09 02:22:30 -05:00
4DBug 51399d29d2 README: move 'How it works' below Getting Started 2026-10-08 20:57:31 -05:00
4DBug ce90ebf139 README: Wally package link; 0.1.1
Build & Release / build (push) Canceled after 0s
2026-10-08 20:54:31 -05:00
4DBug cc6cf48cd1 Wally: scope 4dbug (must match the GitHub account) 2026-10-08 20:52:52 -05:00
4DBug 303b626938 SetNextWindowCached(key): opt-in cached windows on top of the refresh policy (skip contents while idle), t_cached_window test, README snippet
Build & Release / build (push) Canceled after 0s
2026-10-08 20:43:56 -05:00
4DBug 7eb87c94e9 Luau types: generated typed entry module build/ImGuiTyped.luau (requires the bundle as child Impl); Rojo/Wally use it 2026-10-08 20:36:27 -05:00
4DBug d9a2371d5f Wally package (bug/imgui-luau), published by CI on v* tags 2026-10-08 20:30:22 -05:00
4DBug 9ffc76de06 README: AI disclosure wording; .gitignore 2026-10-08 20:29:29 -05:00
4DBug acbe92bd12 README: AI disclosure 2026-10-08 19:43:06 -05:00
4DBug ac54986e6f GitHub-only mirror notice (.github/README.md, synced from README.md), 'latest' is a full release 2026-10-08 19:40:49 -05:00
4DBug 42c84ad947 GitHub Actions: build Roblox/LÖVE bundles (with and without demo), check, publish to Releases (latest + v* tags) 2026-10-08 19:34:40 -05:00
4DBug c3f8ebe21e README: 'Dear ImGui for Roblox (and more)', Backends section/table, multi-backend wording 2026-10-08 19:31:22 -05:00
4DBug 54f7a79abd README: in-depth Roblox backend explanation; FAQ: why this exists, vs Iris, trade-offs 2026-10-08 19:31:22 -05:00
4DBug a36033598c Move LuaJIT compat shims into backends/imgui_impl_love.lua (COMPAT section); remove compat/ 2026-10-08 19:31:22 -05:00
4DBug 8ce6ee6ca1 LÖVE backend + build target (compat/luajit.lua shims, Roblox build unchanged), examples/example_love, examples/example_shared (same app on Roblox and LÖVE), LuaJIT checksum tests 2026-10-08 19:31:22 -05:00
4DBug 6493450bbc Roblox backend: hidden TextBox proxy for text input
A single off-screen TextBox holds focus while an imgui text field is active, so the OS
delivers typing (any layout/unicode), paste and copy/cut. Its text mirrors imgui selection
(fully selected) so Ctrl+C/X copy exactly that; deletions apply as an imgui Backspace;
Ctrl is released around pasted characters. Focus is captured after the click is released,
kept on clicks inside imgui, ends on clicks outside. KeyCode text kept as fallback.
SetTextProxyDebug for logging.
2026-10-08 19:31:22 -05:00
4DBug abe1004af3 Decal Viewer: try thumbnail pixels, fall back to an ImageLabel thumbnail when the asset's pixels can't be read 2026-10-08 17:42:15 -05:00
4DBug 6d07691237 Decal Viewer example (decal/image id -> imgui texture, demo image viewer with grid); backend CreateTexture/DestroyTexture 2026-10-08 17:38:33 -05:00
4DBug 3007126135 Embed widget example (Instances inside imgui windows, one Frame per id, hidden when not submitted, EmbedFlags) + backend SetOverlay 2026-10-08 17:28:13 -05:00
4DBug 9fbfd8a18d README: credit GrayWolf64/imgui-lua 2026-10-08 17:17:46 -05:00
4DBug cc3aef0e03 README modelled on upstream with rendered screenshots/GIF, docs/TODO.txt, screenshot tooling, t_readme snippet test, ImGui.NewTextBuffer helpers 2026-10-08 17:15:54 -05:00
4DBug 98bb23ef9a Rename 'ImGui Sincerely' to 'Dear ImGui' 2026-10-08 17:00:00 -05:00
4DBug 9be30c5bfa Reorganize like upstream: library at root (docking/dragdrop/debug tools merged into imgui.lua, tabs into imgui_widgets.lua), single imgui_demo.lua, backends/, fonts/, examples/, docs/; --no-demo build 2026-10-08 16:47:42 -05:00
4DBug 99b79a9977 Style Editor Colors tab: ListClipper so only visible rows are submitted 2026-10-08 13:18:29 -05:00
4DBug 17b0a27534 Perf: ColorEdit4 layout-only fast path for fully clipped rows, cached drag/slider value text, @native on color/group widgets; t_widget_cost + t_colors_hash 2026-10-08 12:31:10 -05:00
4DBug 0779b88618 Perf: ImDrawList vertices in a flat buffer (f64 pos/uv + u32 col); backend reads it directly and skips draw lists identical to last frame 2026-10-08 12:11:36 -05:00
4DBug 683fd5c3d4 Roblox backend: window content in its own clipped layer at the scroll origin (scrolling moves pixels instead of redrawing), 128px tiles 2026-10-08 11:52:42 -05:00
4DBug 01b5c3c6c2 Roblox backend: optional SetBusyRenderRate (lower redraw rate while scrolling/resizing/moving) 2026-10-08 11:43:31 -05:00
4DBug fdca7fd10a Roblox backend: clear/upload only each tile's dirty region; scroll benchmark in t_drag, scrolling in t_composite 2026-10-08 11:33:28 -05:00
4DBug 9acd130e4d Roblox backend: one layer (Frame + tiles) per draw list so moving windows costs no redraw; gradient rect fast path; t_drag/t_composite checks 2026-10-08 11:10:53 -05:00
4DBug 1b35900bba Perf: allocation-free ItemSize/ItemAdd/IsMouseHoveringRect/GetColorU32/RenderArrow, @native on hot UI paths; t_drawhash output-equivalence check 2026-10-08 10:41:15 -05:00
4DBug eb18082bf1 Fix StyleCopy for named-field vectors (Style Editor assert) 2026-10-08 10:33:05 -05:00
4DBug d7cb04d86d Perf: memoize ImHashStr per seed, inline glyph lookup in ImFont:RenderText 2026-10-08 10:21:16 -05:00
4DBug a3bb7530c5 Perf: ImVec2/ImVec4/ImRect store named fields (no metamethod per .x/.Min), bench flags --roblox/--open-only 2026-10-08 10:16:40 -05:00
4DBug fe33536b3f Perf: cache text sizes per baked font, AddRect fast path as 4 rects; run.py --profile + prof.py 2026-10-08 10:03:18 -05:00
4DBug afe7fe0f32 Roblox backend: 60 Hz render cap (SetRenderRate) and MicroProfiler labels (SetProfiling) 2026-10-08 09:49:18 -05:00
4DBug 00bdd2f0fd Embed upstream misc/fonts; Catppuccin Mocha theme in main.client.luau 2026-10-08 09:40:04 -05:00
4DBug 7b41ae468c Fix PushStyleVar aliasing the caller's ImVec2 into the style; fix DebugNodeFontGlyph crash 2026-10-08 09:27:57 -05:00
4DBug 1d293c8cbe Port window hit-test hole so PassthruCentralNode doesn't capture the mouse 2026-10-08 09:15:32 -05:00
4DBug a4612ce2ea Revert "Roblox backend: block game input with a 1x1 frame under the mouse instead of Active tiles"
This reverts commit 9bbd6671f1.
2026-10-08 09:14:51 -05:00
4DBug b6a0d8ae1e Roblox backend: block game input with a 1x1 frame under the mouse instead of Active tiles 2026-10-08 09:13:01 -05:00
4DBug 24ce5eef25 tools: full Metrics/Debugger window (windows, drawlists, viewports, fonts, popups, tab bars, tables, docking, settings, inputs, internal state, rect overlays) 2026-10-08 08:40:30 -05:00
4DBug e52fb60452 tools: About, Debug Log, ID Stack Tool, ShowFontAtlas/DebugNodeFont/Texture, ShowFontSelector; debug log macros route to DebugLog; GetID hooks 2026-10-08 08:33:57 -05:00
4DBug 1be2a77f0e demo: dockspace + documents example apps 2026-10-08 08:28:23 -05:00
4DBug 14b4626f36 draw: Ngon/Ellipse/Bezier/concave fill; demo: custom rendering app 2026-10-08 08:27:05 -05:00
4DBug b6f814c331 demo: example apps (console, log, layout, property editor, long text, auto/constrained resize, overlay, fullscreen, window titles) 2026-10-08 08:24:43 -05:00
4DBug 05d956fe52 roblox backend: render scale for high-DPI displays; make tiles Active while imgui wants the mouse so input doesn't reach the game 2026-10-08 08:21:54 -05:00
4DBug dab36caef9 demo: port all Widgets sections, ShowStyleEditor/ShowStyleSelector, menus; fix crashes found by click fuzzer (color/scalar default args, InputTextWithHint string hint, AddText overload, splitter reset, CollapsingHeader close button, callback data methods, SetKeyboardFocusHere & misc getters) 2026-10-08 08:06:00 -05:00
4DBug bc117e42da tables: full port of imgui_tables.cpp (layout, borders, draw channel merge, sorting, headers, angled headers, context menu, .ini settings, reconcile, GC) + legacy Columns API; demo: ShowUserGuide, DemoWindowColumns; misc widget aliases 2026-10-08 06:53:00 -05:00
4DBug 8c1703e703 core: ListClipper, TextFilter, error recovery + error tooltip, NavEndFrame; widgets: Combo, ListBox, TreeNodeEx/TreePush, MainMenuBar, ViewportSideBar; tree node fixes 2026-10-08 06:35:35 -05:00
4DBug b271646367 docking: fix docked bg + dock-host moving; per-function @native to fit Roblox codegen limit 2026-10-08 05:51:40 -05:00
4DBug c7fe06ceb0 docking: runs end to end (dock/undock by drag, builder, ini round trip), test scripts 2026-10-08 05:43:00 -05:00
4DBug eff97a2b74 WIP: tabs, docking, dragdrop, settings, logging, harness 2026-10-08 05:35:25 -05:00
4DBug 86c42f2225 optimize 2026-10-07 15:12:59 -05:00
4DBug 6a25eddef1 roblox 2026-10-07 14:47:12 -05:00
4DBug 79c8eee906 Initial commit 2026-10-07 13:03:05 -05:00
73 changed files with 25005 additions and 11751 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
build/** linguist-generated=true -diff
+63 -8
View File
@@ -25,7 +25,7 @@ This port brings that to Roblox (and LÖVE): debug overlays, admin panels, in-ga
### Usage ### 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. 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) ### Getting Started & Integration (Roblox)
With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/imgui-luau@0.3.0"` under `[dependencies]` in your `wally.toml`, run `wally install`, then `require(ReplicatedStorage.Packages.ImGui)`. Or from source: With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/imgui-luau@0.4.4"` 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. 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`. 2. Sync with [Rojo](https://rojo.space): [`default.project.json`](/default.project.json) puts the module in `ReplicatedStorage.ImGui` and the example LocalScript in `StarterPlayerScripts`.
@@ -155,6 +155,8 @@ Backend options:
| `ImGui_ImplRoblox.SetRedrawBudget(ms)` | Max milliseconds per frame spent redrawing changed tiles (opt-in; default `0` = no limit, every change is drawn the same frame). With a budget, tiles over it keep their old pixels for a few frames, so big changes are spread over frames instead of one long frame (parts of the UI may update a frame or two apart). | | `ImGui_ImplRoblox.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.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.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. | | `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/): Fonts: ProggyClean (default), ProggyTiny, ProggyForever, Cousine, DroidSans, Karla and Roboto are embedded from [fonts/](/fonts/):
@@ -164,9 +166,46 @@ io.Fonts:AddFontDefault()
io.Fonts:AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0) 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) ### 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: **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. - *One GUI Instance per widget/shape* (what most Roblox UI libraries do) means re-creating, re-parenting or diffing thousands of Instances every frame, can't express anti-aliased curves, per-vertex gradients or font-atlas glyphs, and would no longer be Dear ImGui's renderer output.
@@ -189,21 +228,21 @@ The cost is CPU time in Luau, so the backend is built around **not drawing**:
| Backend | File | Build | Renderer | Example | | 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) | | 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/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) | | 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 #### 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) python3 tools/bundle.py --target love # -> build/imgui_love.lua (LÖVE backend + shims from the LÖVE backend)
love examples/example_love love examples/example_love
``` ```
Roblox stays the primary target: the Roblox build is untouched by this (no shims, `@native` kept); the LÖVE build strips `@native` and adds small `bit32`/`buffer`/`utf8`/`table` shims (the COMPAT section of [backends/imgui_impl_love.lua](/backends/imgui_impl_love.lua)). `tools/test/love/run.sh` checks that LuaJIT produces exactly the same draw data as Luau. Roblox stays the primary target: the Roblox build is untouched by this (no shims, `@native` kept); the LÖVE build strips `@native` and adds small `bit32`/`buffer`/`utf8`/`table` shims (the COMPAT section of [backends/love/imgui_impl_love.lua](/backends/love/imgui_impl_love.lua)). `tools/test/love/run.sh` checks that LuaJIT produces exactly the same draw data as Luau.
#### Prebuilt releases #### Prebuilt releases
@@ -273,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. 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 ### 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). 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).
+9 -5
View File
@@ -34,7 +34,7 @@ jobs:
IMGUI_BUNDLE_STRICT: "1" # fail if enum folding (needs the luau CLI above) can't run IMGUI_BUNDLE_STRICT: "1" # fail if enum folding (needs the luau CLI above) can't run
run: | run: |
mkdir -p dist mkdir -p dist
python3 tools/bundle.py dist/roblox # ImGui.luau (library + demo) python3 tools/bundle.py dist/roblox # ImGui.luau (library + demo), ImGuiTyped.luau, ImGuiWorker.client.luau
python3 tools/bundle.py --target love dist/love # imgui_love.lua (library + demo) python3 tools/bundle.py --target love dist/love # imgui_love.lua (library + demo)
# minified variants (comments/whitespace stripped, same code): tools/minify.py # 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/roblox/ImGui.luau dist/ImGui.min.luau
@@ -44,6 +44,8 @@ jobs:
run: | run: |
python3 tools/sync_github_readme.py --check python3 tools/sync_github_readme.py --check
luau-compile --null dist/roblox/ImGui.luau luau-compile --null dist/roblox/ImGui.luau
luau-compile --null dist/roblox/ImGuiWorker.client.luau
! grep -n "require" dist/roblox/ImGuiWorker.client.luau # parallel worker: self-contained (worker.luau + raster.lua inlined)
sed 's|require(script:WaitForChild("Impl"))|nil|' dist/roblox/ImGuiTyped.luau > /tmp/ImGuiTyped.luau && luau-analyze /tmp/ImGuiTyped.luau 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/imgui_love.lua > /dev/null
python3 tools/minify.py --test python3 tools/minify.py --test
@@ -71,9 +73,10 @@ jobs:
cd dist cd dist
cp roblox/ImGui.luau ImGui.luau cp roblox/ImGui.luau ImGui.luau
cp love/imgui_love.lua imgui_love.lua cp love/imgui_love.lua imgui_love.lua
cp roblox/ImGuiWorker.client.luau ImGuiWorker.client.luau
# Roblox: module + example LocalScript + Rojo project # 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/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 pkg-roblox/examples/ 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 .) (cd pkg-roblox && zip -qr ../imgui-luau-roblox-$V.zip .)
# LÖVE: bundle + fonts + examples (run: love examples/example_love) # 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/build && cp imgui_love.lua pkg-love/build/ && cp -r ../fonts pkg-love/ && rm -f pkg-love/fonts/*.lua
@@ -87,6 +90,7 @@ jobs:
with: with:
files: | files: |
dist/ImGui.luau dist/ImGui.luau
dist/ImGuiWorker.client.luau
dist/imgui_love.lua dist/imgui_love.lua
dist/*.min.luau dist/*.min.luau
dist/*.min.lua dist/*.min.lua
@@ -102,7 +106,7 @@ jobs:
grep -q "^version = \"${GITHUB_REF_NAME#v}\"" wally.toml || { echo "wally.toml version != tag"; exit 1; } 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 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 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 echo '{"name":"imgui-luau","tree":{"$path":"src"}}' > dist/wally/default.project.json
wallybin/wally login --token "$WALLY_TOKEN" wallybin/wally login --token "$WALLY_TOKEN"
wallybin/wally publish --project-path dist/wally wallybin/wally publish --project-path dist/wally
@@ -115,4 +119,4 @@ jobs:
gh release delete latest --yes --cleanup-tag || true gh release delete latest --yes --cleanup-tag || true
gh release create latest --latest --title "Latest build (${GITHUB_SHA::7})" \ 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." \ --notes "Automatic build of ${GITHUB_SHA} on ${GITHUB_REF_NAME}. Tag a commit v* for a versioned release." \
dist/ImGui.luau dist/imgui_love.lua dist/*.min.luau dist/*.min.lua dist/*.zip dist/ImGui.luau dist/ImGuiWorker.client.luau dist/imgui_love.lua dist/*.min.luau dist/*.min.lua dist/*.zip
+27
View File
@@ -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
+63 -8
View File
@@ -22,7 +22,7 @@ This port brings that to Roblox (and LÖVE): debug overlays, admin panels, in-ga
### Usage ### 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. 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) ### Getting Started & Integration (Roblox)
With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/imgui-luau@0.3.0"` under `[dependencies]` in your `wally.toml`, run `wally install`, then `require(ReplicatedStorage.Packages.ImGui)`. Or from source: With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/imgui-luau@0.4.4"` 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. 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`. 2. Sync with [Rojo](https://rojo.space): [`default.project.json`](default.project.json) puts the module in `ReplicatedStorage.ImGui` and the example LocalScript in `StarterPlayerScripts`.
@@ -152,6 +152,8 @@ Backend options:
| `ImGui_ImplRoblox.SetRedrawBudget(ms)` | Max milliseconds per frame spent redrawing changed tiles (opt-in; default `0` = no limit, every change is drawn the same frame). With a budget, tiles over it keep their old pixels for a few frames, so big changes are spread over frames instead of one long frame (parts of the UI may update a frame or two apart). | | `ImGui_ImplRoblox.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.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.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. | | `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/): Fonts: ProggyClean (default), ProggyTiny, ProggyForever, Cousine, DroidSans, Karla and Roboto are embedded from [fonts/](fonts/):
@@ -161,9 +163,46 @@ io.Fonts:AddFontDefault()
io.Fonts:AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0) 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) ### 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: **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. - *One GUI Instance per widget/shape* (what most Roblox UI libraries do) means re-creating, re-parenting or diffing thousands of Instances every frame, can't express anti-aliased curves, per-vertex gradients or font-atlas glyphs, and would no longer be Dear ImGui's renderer output.
@@ -186,21 +225,21 @@ The cost is CPU time in Luau, so the backend is built around **not drawing**:
| Backend | File | Build | Renderer | Example | | 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) | | 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/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) | | 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 #### 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) python3 tools/bundle.py --target love # -> build/imgui_love.lua (LÖVE backend + shims from the LÖVE backend)
love examples/example_love love examples/example_love
``` ```
Roblox stays the primary target: the Roblox build is untouched by this (no shims, `@native` kept); the LÖVE build strips `@native` and adds small `bit32`/`buffer`/`utf8`/`table` shims (the COMPAT section of [backends/imgui_impl_love.lua](backends/imgui_impl_love.lua)). `tools/test/love/run.sh` checks that LuaJIT produces exactly the same draw data as Luau. Roblox stays the primary target: the Roblox build is untouched by this (no shims, `@native` kept); the LÖVE build strips `@native` and adds small `bit32`/`buffer`/`utf8`/`table` shims (the COMPAT section of [backends/love/imgui_impl_love.lua](backends/love/imgui_impl_love.lua)). `tools/test/love/run.sh` checks that LuaJIT produces exactly the same draw data as Luau.
#### Prebuilt releases #### Prebuilt releases
@@ -270,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. 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 ### 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). 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
@@ -231,6 +231,9 @@ local function ReadFile(filename)
local data = love.filesystem.getInfo(filename) and love.filesystem.read(filename) local data = love.filesystem.getInfo(filename) and love.filesystem.read(filename)
if data then return data end if data then return data end
local bd = ImGui_ImplLOVE_GetBackendData() local bd = ImGui_ImplLOVE_GetBackendData()
local lf = bd and bd.Root ~= "" and bd.Root .. filename -- root may also be a love.filesystem path (works in .love/fused)
data = lf and love.filesystem.getInfo(lf) and love.filesystem.read(lf)
if data then return data end
local f = io.open(((bd and bd.Root) or "") .. filename, "rb") local f = io.open(((bd and bd.Root) or "") .. filename, "rb")
if not f then return nil end if not f then return nil end
data = f:read("*a"); f:close() data = f:read("*a"); f:close()
@@ -328,6 +331,19 @@ function ImGui_ImplLOVE_DestroyTexture(tex_ref)
if image then image:release(); bd.Textures[tex_ref._TexID] = nil end if image then image:release(); bd.Textures[tex_ref._TexID] = nil end
end end
--- Register an existing LÖVE Texture/Canvas (not owned: never released by the backend). Returns an ImTextureRef.
function ImGui_ImplLOVE_RegisterCanvas(drawable)
local bd = ImGui_ImplLOVE_GetBackendData()
bd.TextureCount = bd.TextureCount + 1
bd.Textures[bd.TextureCount] = drawable
return ImTextureRef(bd.TextureCount)
end
--- Forget a registered texture without releasing it.
function ImGui_ImplLOVE_UnregisterTexture(tex_ref)
ImGui_ImplLOVE_GetBackendData().Textures[tex_ref._TexID] = nil
end
--------------------------------------------------------- ---------------------------------------------------------
-- RENDERING: one streamed Mesh per draw list; vertices converted from the port's flat VtxBuffer (f64 x, y, u, v, -- RENDERING: one streamed Mesh per draw list; vertices converted from the port's flat VtxBuffer (f64 x, y, u, v,
-- u32 col; 36 bytes) to LÖVE's float x, y, u, v + byte rgba (20 bytes); indices -> 0-based uint32 vertex map. -- u32 col; 36 bytes) to LÖVE's float x, y, u, v + byte rgba (20 bytes); indices -> 0-based uint32 vertex map.
@@ -526,6 +542,8 @@ ImGui_ImplLove = {
RenderDrawData = ImGui_ImplLOVE_RenderDrawData, RenderDrawData = ImGui_ImplLOVE_RenderDrawData,
CreateTexture = ImGui_ImplLOVE_CreateTexture, CreateTexture = ImGui_ImplLOVE_CreateTexture,
DestroyTexture = ImGui_ImplLOVE_DestroyTexture, DestroyTexture = ImGui_ImplLOVE_DestroyTexture,
RegisterCanvas = ImGui_ImplLOVE_RegisterCanvas,
UnregisterTexture = ImGui_ImplLOVE_UnregisterTexture,
MouseMoved = MouseMoved, MouseMoved = MouseMoved,
MousePressed = MousePressed, MousePressed = MousePressed,
MouseReleased = MouseReleased, MouseReleased = MouseReleased,
+509
View File
@@ -0,0 +1,509 @@
-- 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")
-- Luau-tuned replacements of hot library internals, installed when this file loads (see patches.lua)
local Patches = IM_INCLUDE("roblox/patches.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, LastCmdCount = 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
Layers.Prewarm()
BackendData.HeartbeatCount += 1
end)
-- (losing focus clears imgui's mouse to "unavailable"; NewFrame only resends a moved mouse, so on return forget the
-- last position: a click on a field without moving the mouse first would otherwise land nowhere)
connect(UserInputService.WindowFocused, function()
ImGui.GetIO():AddFocusEvent(true)
BackendData.MouseX, BackendData.MouseY = nil, nil
end)
connect(UserInputService.WindowFocusReleased, function()
ImGui.GetIO():AddFocusEvent(false)
BackendData.MouseX, BackendData.MouseY = nil, nil
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
+420
View File
@@ -0,0 +1,420 @@
-- 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, ceil, max = math.floor, math.ceil, 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
-- A new tile (transparent image, hidden unparented label), nil over the EditableImage budget
local function NewTile()
local img = EditableImages.Create(TILE, TILE)
if not img then return nil end
local 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
return {
Image = img, Label = label,
Hash1 = -1, Hash2 = -1, Visible = false, Used = 0,
ContentX0 = TILE, ContentY0 = TILE, ContentX1 = 0, ContentY1 = 0,
ValidX0 = 0, ValidY0 = 0, ValidX1 = TILE, ValidY1 = TILE,
Scale = false, Active = nil, Parent = nil,
DrawnCount = -1, DrawnHash1 = {}, DrawnHash2 = {}, DrawnFlat = {},
DrawnX0 = {}, DrawnY0 = {}, DrawnX1 = {}, DrawnY1 = {},
}
end
-- Keeps PREWARM tiles in the free list (Heartbeat, one per call, never evicting): a layer that grows takes them instead
-- of creating EditableImages + labels mid-frame (~90 us per tile in Studio, ~7 us from the free list)
local PREWARM = 4
function M.Prewarm()
local pool = EditableImages.Pool
if #pool < PREWARM and EditableImages.Bytes + TILE * TILE * 4 <= EditableImages.Cap then
local tile = NewTile()
if tile then table.insert(pool, 1, tile) end -- (at the bottom: recycled tiles keep their parent, used first)
end
end
function M.GetTile(BackendData, layer, key, tx, ty)
local tile = layer.Tiles[key]
if tile then return tile end
local scale = BackendData.Scale
-- Content*: content bounds; Valid*: where the image pixels are current. 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.
tile = table.remove(EditableImages.Pool) or NewTile()
if not tile then return nil end -- over the budget even after eviction: the caller skips this tile this frame
local label = tile.Label
if tile.Scale ~= scale then label.Size = UDim2.fromOffset(TILE / scale, TILE / scale) end
label.Position = UDim2.fromOffset(tx * TILE / scale, ty * TILE / scale)
if tile.Active ~= BackendData.TilesActive then label.Active = BackendData.TilesActive end
if tile.Parent ~= layer.Frame then label.Parent = layer.Frame end
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
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), 3 = moved with drifted vertices, 4 = same positions, a few vertices' uv / colour changed
-- (both list those in Drift), 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
-- The snapshot of a list CompareDrawList found moved by (dx, dy): only its vertices, clip rects, content clip,
-- scroll origin, primitive bounds and extents move (counts, indices, kinds are equal; Cmd* describe another list now)
@native
function M.ShiftSnapshot(set, draw_list, dx, dy)
buffer.copy(set.SnapVtx, 0, draw_list.VtxBuffer.Buf, 0, set.SnapVtxBytes)
local sc, o = set.SnapCmds, 0
for _, pcmd in draw_list.CmdBuffer:iter() do
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)
if buffer.readu8(sc, o + 53) ~= 0 then
buffer.writei32(sc, o + 54, buffer.readi32(sc, o + 54) + dx)
buffer.writei32(sc, o + 58, buffer.readi32(sc, o + 58) + dy)
buffer.writei32(sc, o + 62, buffer.readi32(sc, o + 62) + dx)
buffer.writei32(sc, o + 66, buffer.readi32(sc, o + 66) + dy)
end
o += CMD_STRIDE
end
if set.SnapHasContent then
set.SnapContentX0, set.SnapContentY0, set.SnapContentX1, set.SnapContentY1 = draw_list._ContentClipX0,
draw_list._ContentClipY0, draw_list._ContentClipX1, draw_list._ContentClipY1
set.SnapScrollX, set.SnapScrollY = draw_list._ScrollOriginX, draw_list._ScrollOriginY
end
set.SnapExtentX0 += dx
set.SnapExtentY0 += dy
set.SnapExtentX1 += dx
set.SnapExtentY1 += dy
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
-- vertex byte offsets of the last CompareDrawList's drifted vertices (moved by about an ulp off the exact shift)
local MAX_DRIFT = 256
local Drift = table.create(MAX_DRIFT, 0)
M.Drift, M.DriftCount = Drift, 0
@native
function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
M.DriftCount = 0
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
local nd = 0
if dx == 0 and dy == 0 then
-- per vertex: x y u v as f64s + col, not readstring == (that allocated 2 vertex-buffer strings per list per
-- frame: GC spikes) or 9 u32s (3x slower). Equal f64s have equal bits except +-0: their sign words decide.
-- Same position, other uv / colour (hover, a changed colour): listed ("recolored"), up to MAX_DRIFT.
for v = 0, nv - VTX_STRIDE, VTX_STRIDE do
local x, y, u, w = readf64(vb, v), readf64(vb, v + 8), readf64(vb, v + 16), readf64(vb, v + 24)
if x ~= readf64(sv, v) or y ~= readf64(sv, v + 8) then return 0 end
if (x == 0 or y == 0)
and (readu32(vb, v + 4) ~= readu32(sv, v + 4) or readu32(vb, v + 12) ~= readu32(sv, v + 12)) then
return 0
end
if u ~= readf64(sv, v + 16) or w ~= readf64(sv, v + 24) or readu32(vb, v + 32) ~= readu32(sv, v + 32)
or ((u == 0 or w == 0)
and (readu32(vb, v + 20) ~= readu32(sv, v + 20) or readu32(vb, v + 28) ~= readu32(sv, v + 28))) then
if nd >= MAX_DRIFT then return 0 end
nd += 1
Drift[nd] = v
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
local n4 = ni - ni % 4
for i = 1, n4, 4 do
if idx[i] ~= si[i] or idx[i + 1] ~= si[i + 1] or idx[i + 2] ~= si[i + 2] or idx[i + 3] ~= si[i + 3] then
return 0
end
end
for i = n4 + 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
if nd == 0 then return 1 end
M.DriftCount = nd
return 4, 0, 0
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
-- vertices off the exact shift ("drift": trig-generated ones round differently, often when a coordinate crosses a
-- power of two) are listed. All their floor / ceil / ceil(- 0.5) (CollectPrims' bounds) shifted: 3, only the tiles
-- of their primitives change; else 0 (the full path still gets the list: tile hashes don't see an ulp)
local consistent = true
for v = 0, nv - VTX_STRIDE, VTX_STRIDE do
if 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
local ax, ay, bx, by = readf64(sv, v), readf64(sv, v + 8), readf64(vb, v), readf64(vb, v + 8)
if not ShiftedExact(ax, dx, bx) or not ShiftedExact(ay, dy, by) then
if nd >= MAX_DRIFT then return 0 end
nd += 1
Drift[nd] = v
if floor(bx) ~= floor(ax) + dx or ceil(bx) ~= ceil(ax) + dx or ceil(bx - 0.5) ~= ceil(ax - 0.5) + dx
or floor(by) ~= floor(ay) + dy or ceil(by) ~= ceil(ay) + dy or ceil(by - 0.5) ~= ceil(ay - 0.5) + dy then
consistent = false
end
end
end
M.DriftCount = nd
if nd == 0 then return 2, dx, dy end
return consistent and 3 or 0, 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
+79
View File
@@ -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
+530
View File
@@ -0,0 +1,530 @@
-- 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, PrimGradient = Render.PrimA, Render.PrimB, Render.PrimC, Render.PrimD,
Render.PrimGradient
local PrimCmd, CmdTexture, CmdTexId, CmdVtxBuffer = Render.PrimCmd, Render.CmdTexture, Render.CmdTexId,
Render.CmdVtxBuffer
local CmdClipX0, CmdClipY0, CmdClipX1, CmdClipY1 = Render.CmdClipX0, Render.CmdClipY0, Render.CmdClipX1,
Render.CmdClipY1
local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = Render.PrimBoundsX0, Render.PrimBoundsY0,
Render.PrimBoundsX1, Render.PrimBoundsY1
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 = {}
-- ids of destroyed textures each Actor holds a copy of, sent with its next job (the Actor drops them)
local drops = {}
local NO_DROPS = {}
local sync_tex = {} -- Sync mode: the "Actors'" texture copies
EditableImages.TextureDropped = function(id, rec)
if not rec then
return
end
for a = 1, NA do
local s = sent[a]
if s and s[rec] ~= nil then
s[rec] = nil
local d = drops[a]
d[#d + 1] = id
end
end
end
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 cmd = PrimCmd[p]
local d, t = PrimD[p], CmdTexture[cmd]
local gk = PrimGradient[p]
writei32(P, pn, d and (gk and gk + 1 or 1) or 0)
writei32(P, pn + 4, t and CmdTexId[cmd] or -1)
if t then
u[t] = CmdTexId[cmd]
end
writei32(P, pn + 8, CmdClipX0[cmd])
writei32(P, pn + 12, CmdClipY0[cmd])
writei32(P, pn + 16, CmdClipX1[cmd])
writei32(P, pn + 20, CmdClipY1[cmd])
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 = CmdVtxBuffer[cmd]
copy(P, pn + REC_A, vb, PrimA[p], VTX)
copy(P, pn + REC_C, vb, PrimC[p], VTX)
if not d or gk == 3 or gk == 4 then
copy(P, pn + REC_B, vb, PrimB[p], VTX)
end
if gk == 3 or gk == 4 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
-- The pixels changed between versions had and v (rows y0..y1 of rec): the updated rects (rect list -> worker copies
-- each rect's rows), or the whole rows when they are smaller. Built once per (had, v), shared by every Actor.
local function patchCopy(rec, had: number, v: number, y0: number, y1: number): (buffer, any)
if rec.PatchHad == had and rec.PatchV == v then
return rec.Patch, rec.PatchAt
end
local row, src = rec.Width * 4, rec.Buffer
local log, area = rec.Log, 0
for k = had + 1, v do
local r = log[k][3]
if r then
for i = 1, #r, 4 do area += r[i + 2] * r[i + 3] end
end
end
local patch, at
if area * 4 < (y1 - y0) * row then
patch, at = buffer.create(area * 4), {}
local o, n = 0, 0
for k = had + 1, v do
local r = log[k][3]
if r then
for i = 1, #r, 4 do
local x, y, w, h = r[i], r[i + 1], r[i + 2], r[i + 3]
at[n + 1], at[n + 2], at[n + 3], at[n + 4] = x, y, w, h
n += 4
for yy = y, y + h - 1 do
copy(patch, o, src, (yy * rec.Width + x) * 4, w * 4)
o += w * 4
end
end
end
end
else
patch, at = buffer.create((y1 - y0) * row), y0 * row
copy(patch, 0, src, y0 * row, (y1 - y0) * row)
end
rec.PatchHad, rec.PatchV, rec.Patch, rec.PatchAt = had, v, patch, at
return patch, at
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 patch, at = patchCopy(rec, had, v, y0, y1)
tex[#tex + 1] = { id, false, rec.Width, rec.Height, at, patch }
Stats.TexBytes += buffer.len(patch)
end
Stats.TexSends += 1
end
end
Stats.SendBytes += Pn[a] + tl
local d = drops[a]
if #d > 0 then
drops[a] = {}
else
d = NO_DROPS
end
if cfg.Sync then
-- like an Actor: own texture copies, kept by the same messages (SendMessage copies: clone the buffers)
local st = sync_tex[a]
if not st then
st = {}
sync_tex[a] = st
end
local msg = table.create(#tex)
for i, u in tex do
local c = table.clone(u)
for k, x in c do
if type(x) == "buffer" then
local nb = buffer.create(buffer.len(x))
copy(nb, 0, x)
c[k] = nb
end
end
msg[i] = c
end
Raster.ApplyTextures(st, msg, d)
if not (cfg.SyncDrop and a % 2 == 0) then
b.Res[a] = RasterJobs(P, T, tl, st)
end
else
actors[a]:SendMessage("job", batch_no, P, T, tex, tl, d)
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" })
drops[a] = {}
sync_tex[a] = nil
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
+284
View File
@@ -0,0 +1,284 @@
-- Patches: Luau/Roblox-tuned replacements of hot library internals, installed when the backend loads.
-- The library sources stay a 1:1 port (and run on LÖVE); these versions use buffers, typed natives and specialized fast
-- paths instead. Every patch must be exactly equivalent (same draw data, IDs, pixels): uncommon cases are handed back to
-- the original function. Only method tables / globals the callers look up at call time are replaced (MT.*), never a
-- library local. Enabled holds one switch per patch (bisecting: set one to false and rebuild; M.Set() switches at run
-- time for A/B timing).
local M = {}
M.Enabled = {
RenderText = true, -- MT.ImFont.RenderText: Lua string, no CPU fine clip
AddText = true, -- MT.ImDrawList.AddText: same, calling the RenderText core directly
CalcTextSize = true, -- ImFontCalcTextSizeXY: cache hit of an unwrapped whole string, checked first
}
local MT = ImGui.GetMetatables()
local byte, floor = string.byte, math.floor
local band, bor = bit32.band, bit32.bor
local writef64, writeu32 = buffer.writef64, buffer.writeu32
local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -- same values as imgui_draw.lua's locals
local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE
------------------------------------------------------------------------------------------------------------------------
-- Text: ImFont:RenderText() for a Lua string without CPU fine clip (and < 10k bytes unless wrapped) as one function
-- taking the clip rect as numbers, PrimReserve() inlined, no fine clip branches in the glyph loop. Same vertex/index
-- writes in the same order. ImDrawList:AddText() calls it directly (no clip rect copy, one call less).
------------------------------------------------------------------------------------------------------------------------
local RenderText_Orig = MT.ImFont.RenderText
local AddText_Orig = MT.ImDrawList.AddText
local text_clip_rect = ImVec4() -- only for the texture-change fallback
-- imgui_draw.lua's local ImTextCalcWordWrapNextLineStart() for a Lua string: trim trailing blanks, skip one '\n'
local function WordWrapNextLineStart(text: string, pos: number, text_end: number, flags: number): number
if band(flags, ImDrawTextFlags.WrapKeepBlanks) == 0 then
while pos < text_end do
local c = byte(text, pos)
if c ~= 32 and c ~= 9 then break end
pos += 1
end
end
if pos < text_end and byte(text, pos) == 10 then
pos += 1
end
return pos
end
-- Returns false (nothing done) when the original must handle it: CPU fine clip, or unloaded glyphs changed the texture
@native
local function RenderTextCore(font, draw_list, size: number, x: number, y: number, col: number, clip_x1: number, clip_y1: number, clip_x2: number, clip_y2: number, text: string, s: number, text_end: number, wrap_width: number, flags: number): boolean
if y > clip_y2 then
return true
end
flags = bor(flags, draw_list.Flags)
if band(flags, ImDrawTextFlags.CpuFineClip) ~= 0 then
return false
end
if band(flags, ImDrawFlags.TextNoPixelSnap) == 0 then
x = floor(x)
y = floor(y)
end
local baked = font.LastBaked
if not (baked and baked.Size == floor(size + 0.5) and baked.RasterizerDensity == font.CurrentRasterizerDensity) then
baked = font:GetFontBaked(size)
end
local scale: number = size / baked.Size
local origin_x = x
local line_height = size
local word_wrap_enabled = wrap_width > 0.0
-- Fast-forward to first visible line
if y + line_height < clip_y1 then
while y + line_height < clip_y1 and s < text_end do
local line_end = ImMemchr(text, '\n', s)
if word_wrap_enabled then
s = ImFontCalcWordWrapPositionEx(font, size, text, s, (line_end ~= nil) and line_end or text_end, wrap_width, flags)
s = WordWrapNextLineStart(text, s, text_end, flags)
else
s = (line_end ~= nil) and (line_end + 1) or text_end
end
y = y + line_height
end
end
if s == text_end then
return true
end
local vtx_count_max = (text_end - s) * 4
local idx_count_max = (text_end - s) * 6
-- PrimReserve(idx_count_max, vtx_count_max) inlined
if (draw_list._VtxCurrentIdx + vtx_count_max >= 65536) and (band(draw_list.Flags, ImDrawFlags.UseVtxOffset) ~= 0) then
draw_list._CmdHeader.VtxOffset = draw_list.VtxBuffer.Size + 1
draw_list:_OnChangedVtxOffset()
end
local cmd_buffer = draw_list.CmdBuffer
local cmd_count = cmd_buffer.Size
local draw_cmd = cmd_buffer.Data[cmd_count]
local elem_count = draw_cmd.ElemCount + idx_count_max
draw_cmd.ElemCount = elem_count
local vtx_buffer = draw_list.VtxBuffer
local vtx_write: number = vtx_buffer.Size + 1
local vtx_new_size = vtx_write - 1 + vtx_count_max
if vtx_new_size > vtx_buffer.Capacity then vtx_buffer:resize(vtx_new_size) else vtx_buffer.Size = vtx_new_size end
local idx_buffer = draw_list.IdxBuffer
local idx_write: number = idx_buffer.Size + 1
local idx_new_size = idx_write - 1 + idx_count_max
if idx_new_size > idx_buffer.Capacity then idx_buffer:resize(idx_new_size) else idx_buffer.Size = idx_new_size end
local idx_begin = idx_write
local vtx_index: number = draw_list._VtxCurrentIdx
local idx_data = idx_buffer.Data
local vtx_data: buffer = vtx_buffer.Buf
local color_untinted = bor(col, 0x00FFFFFF)
local lookup, lookup_n, glyphs = baked.IndexLookup.Data, baked.IndexLookup.Size, baked.Glyphs.Data
local word_wrap_eol: number? = nil
while s < text_end do
if word_wrap_enabled then
if not word_wrap_eol then
word_wrap_eol = ImFontCalcWordWrapPositionEx(font, size, text, s, text_end, wrap_width - (x - origin_x), flags)
lookup, lookup_n, glyphs = baked.IndexLookup.Data, baked.IndexLookup.Size, baked.Glyphs.Data
end
if s >= word_wrap_eol then
x = origin_x
y += line_height
if y > clip_y2 then
break
end
word_wrap_eol = nil
s = WordWrapNextLineStart(text, s, text_end, flags) -- Wrapping skips upcoming blanks
continue
end
end
local c: number = byte(text, s)
if c < 0x80 then
s += 1
else
local wanted, out_char = ImStd.ImTextCharFromUtf8(text, s, text_end)
c = out_char
s += wanted
end
if c < 32 then
if c == 10 then
x = origin_x
y += line_height
if y > clip_y2 then
break
end
continue
end
if c == 13 then
continue
end
end
local glyph
local gi = (c < lookup_n) and lookup[c + 1] or nil
if gi ~= nil and gi ~= IM_FONTGLYPH_INDEX_NOT_FOUND and gi ~= IM_FONTGLYPH_INDEX_UNUSED then
glyph = glyphs[gi]
else
glyph = baked:FindGlyph(c)
lookup, lookup_n, glyphs = baked.IndexLookup.Data, baked.IndexLookup.Size, baked.Glyphs.Data
end
local char_width: number = glyph.AdvanceX * scale
if glyph.Visible then
local x1: number = x + glyph.X0 * scale
local x2: number = x + glyph.X1 * scale
if x1 <= clip_x2 and x2 >= clip_x1 then
local y1: number = y + glyph.Y0 * scale
local y2: number = y + glyph.Y1 * scale
local u1: number, v1: number, u2: number, v2: number = glyph.U0, glyph.V0, glyph.U1, glyph.V1
local glyph_col = glyph.Colored and color_untinted or col
local o = (vtx_write - 1) * 36
writef64(vtx_data, o, x1); writef64(vtx_data, o + 8, y1); writef64(vtx_data, o + 16, u1); writef64(vtx_data, o + 24, v1); writeu32(vtx_data, o + 32, glyph_col)
writef64(vtx_data, o + 36, x2); writef64(vtx_data, o + 44, y1); writef64(vtx_data, o + 52, u2); writef64(vtx_data, o + 60, v1); writeu32(vtx_data, o + 68, glyph_col)
writef64(vtx_data, o + 72, x2); writef64(vtx_data, o + 80, y2); writef64(vtx_data, o + 88, u2); writef64(vtx_data, o + 96, v2); writeu32(vtx_data, o + 104, glyph_col)
writef64(vtx_data, o + 108, x1); writef64(vtx_data, o + 116, y2); writef64(vtx_data, o + 124, u1); writef64(vtx_data, o + 132, v2); writeu32(vtx_data, o + 140, glyph_col)
idx_data[idx_write] = vtx_index; idx_data[idx_write + 1] = vtx_index + 1; idx_data[idx_write + 2] = vtx_index + 2
idx_data[idx_write + 3] = vtx_index; idx_data[idx_write + 4] = vtx_index + 2; idx_data[idx_write + 5] = vtx_index + 3
vtx_write += 4
vtx_index += 4
idx_write += 6
end
end
x += char_width
end
if cmd_count ~= cmd_buffer.Size then
-- Unloaded glyphs changed the texture: undo (like the original's edge case), the caller redoes it with the original
IM_ASSERT(cmd_buffer.Data[cmd_buffer.Size].ElemCount == 0)
cmd_buffer:pop_back()
draw_list:PrimUnreserve(idx_count_max, vtx_count_max)
draw_list:AddDrawCmd()
return false
end
-- Give back unused vertices (clipped ones, blanks)
vtx_buffer.Size = vtx_write - 1
idx_buffer.Size = idx_write - 1
draw_cmd.ElemCount = elem_count - (idx_count_max - (idx_write - idx_begin))
draw_list._VtxWritePtr = vtx_write
draw_list._IdxWritePtr = idx_write
draw_list._VtxCurrentIdx = vtx_index
return true
end
@native
local function RenderText(self, draw_list, size: number, pos, col: number, clip_rect, text, text_begin: number, text_end: number, wrap_width: number?, flags: number?)
if type(text) ~= "string" or (text_end - text_begin > 1e4 and not (wrap_width ~= nil and wrap_width > 0.0))
or not RenderTextCore(self, draw_list, size, pos.x, pos.y, col, clip_rect.x, clip_rect.y, clip_rect.z, clip_rect.w, text, text_begin, text_end, wrap_width or 0.0, flags or 0) then
return RenderText_Orig(self, draw_list, size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, flags)
end
end
@native
local function AddText(self, font, font_size, pos, col, text, text_begin, text_end, wrap_width, cpu_fine_clip_rect)
if cpu_fine_clip_rect ~= nil or type(text) ~= "string" or text_end == nil
or (type(font) == "table" and type(font[1]) == "number") then
return AddText_Orig(self, font, font_size, pos, col, text, text_begin, text_end, wrap_width, cpu_fine_clip_rect)
end
if text_begin == nil then text_begin = 1 end
if band(col, 0xFF000000) == 0 or text_begin == text_end then
return
end
if font == nil then
font = self._Data.Font
end
if font_size == 0.0 then
font_size = self._Data.FontSize
end
local cr = self._CmdHeader.ClipRect
if (text_end - text_begin > 1e4 and not (wrap_width ~= nil and wrap_width > 0.0))
or not RenderTextCore(font, self, font_size, pos.x, pos.y, col, cr.x, cr.y, cr.z, cr.w, text, text_begin, text_end, wrap_width or 0.0, 0) then
local clip_rect = text_clip_rect
clip_rect.x = cr.x; clip_rect.y = cr.y; clip_rect.z = cr.z; clip_rect.w = cr.w
RenderText_Orig(font, self, font_size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, 0)
end
end
------------------------------------------------------------------------------------------------------------------------
-- CalcTextSize: ImFontCalcTextSizeXY() answers most calls from its per baked font cache (whole string, no wrap/limit);
-- check that case first, with the same conditions, and hand everything else to the original.
------------------------------------------------------------------------------------------------------------------------
local CalcTextSizeXY_Orig = ImFontCalcTextSizeXY
local TEXT_SIZE_CACHE_MAX = 4096 -- imgui_draw.lua's local: a full cache is reset by the original before looking up
@native
local function CalcTextSizeXY(font, size: number, max_width: number, wrap_width: number, text, text_begin, text_end_display, text_end, out_offset, flags)
if wrap_width <= 0.0 and text_begin == 1 and type(text) == "string" and out_offset == nil and max_width >= FLT_MAX
and (flags == nil or band(flags, ImDrawTextFlags.StopOnNewLine) == 0) then
local baked = font.LastBaked
if baked and baked.Size == floor(size + 0.5) and baked.RasterizerDensity == font.CurrentRasterizerDensity then
local cache = baked._TextSizeCache
if cache ~= nil and baked._TextSizeCacheN < TEXT_SIZE_CACHE_MAX then
local e = cache[text]
if e then
local text_len1 = string.len(text) + 1
if (text_end == nil or text_end == text_len1) and (text_end_display == nil or text_end_display == text_len1) then
return e[1] * (size / baked.Size), e[2] * size, text_len1
end
end
end
end
end
return CalcTextSizeXY_Orig(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags)
end
------------------------------------------------------------------------------------------------------------------------
-- name -> function(on) installing the patch or restoring the original
local Install = {
RenderText = function(on) MT.ImFont.RenderText = on and RenderText or RenderText_Orig end,
AddText = function(on) MT.ImDrawList.AddText = on and AddText or AddText_Orig end,
CalcTextSize = function(on) ImFontCalcTextSizeXY = on and CalcTextSizeXY or CalcTextSizeXY_Orig end,
}
-- Switches a patch at run time (tests time both versions in one process)
function M.Set(name: string, on: boolean)
Install[name](on)
end
for name in Install do
M.Set(name, M.Enabled[name])
end
return M
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+249
View File
@@ -0,0 +1,249 @@
-- 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),
-- TextureDropped(id, record) by parallel.lua (Actors free their copies).
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
-- n pixels from the byte table src (1-based index s) to dst (byte offset d). Typed + unrolled by 4: the native code
-- skips the generic table/buffer checks (~40% faster than the plain loop).
@native
local function CopyRGBA(src: { number }, s: number, dst: buffer, d: number, n: number)
for _ = 1, n // 4 do
writeu32(dst, d, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216)
writeu32(dst, d + 4, src[s + 4] + src[s + 5] * 256 + src[s + 6] * 65536 + src[s + 7] * 16777216)
writeu32(dst, d + 8, src[s + 8] + src[s + 9] * 256 + src[s + 10] * 65536 + src[s + 11] * 16777216)
writeu32(dst, d + 12, src[s + 12] + src[s + 13] * 256 + src[s + 14] * 65536 + src[s + 15] * 16777216)
s += 16
d += 16
end
for _ = 1, n % 4 do
writeu32(dst, d, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216)
s += 4
d += 4
end
end
@native
local function CopyAlpha8(src: { number }, s: number, dst: buffer, d: number, n: number) -- white with alpha
for _ = 1, n do
writeu32(dst, d, 16777215 + src[s] * 16777216)
s += 1
d += 4
end
end
local function CopyTexturePixels(tex, dst, x, y, w, h)
local tex_w = tex.Width
local copy = tex.BytesPerPixel == 4 and CopyRGBA or CopyAlpha8
if x == 0 and w == tex_w then -- whole rows: one flat run
local src, s = tex:GetPixelsAt(0, y)
copy(src, s, dst, y * tex_w * 4, w * h)
return
end
for row = 0, h - 1 do
local src, s = tex:GetPixelsAt(x, y + row)
copy(src, s, dst, ((y + row) * tex_w + x) * 4, w)
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
-- The buffer of the last destroyed atlas texture record: the next one of the same size (an atlas repack: same size
-- every time) reuses it. buffer.create of an atlas is slow in Studio (~0.2-1.8 ms for 512 KB, spiky).
local SpareBuffer: buffer? = nil
local function CreateTextureRecord(tex)
local w, h = tex.Width, tex.Height
local b, reused = SpareBuffer, false
if b and buffer.len(b) == w * h * 4 then
SpareBuffer, reused = nil, true
else
b = buffer.create(w * h * 4)
end
-- 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
if reused then buffer.fill(b, 0, 0) end
else -- 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)
else
CopyTexturePixels(tex, b, 0, 0, w, h)
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
local rects, n = {}, 0
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
rects[n + 1], rects[n + 2], rects[n + 3], rects[n + 4] = r.x, r.y, r.w, r.h
n += 4
end
-- parallel workers hold copies, patched when this changes: Log[V] = changed rows + the rects (x, y, w, h
-- quadruples) (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, rects } or { 0, 0 }
t.Log[v - 16] = nil
tex:SetStatus(ImTextureStatus.OK)
elseif tex.Status == ImTextureStatus.WantDestroy then
if tex.BackendUserData then
local id = tex.BackendUserData
local rec = Records[id]
if EditableImages.TextureDropped then EditableImages.TextureDropped(id, rec) end
if rec and rec.FillRow then SpareBuffer = rec.Buffer end -- (FillRow: a buffer CreateTextureRecord made)
Records[id] = 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)
local id = tex_ref._TexID
if EditableImages.TextureDropped then EditableImages.TextureDropped(id, Records[id]) end
Records[id] = 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
+19
View File
@@ -0,0 +1,19 @@
-- 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, Dropped)
-- this Actor's texture copies: destroyed ids dropped, changed rows/rects patched (parallel.lua Flush)
Raster.ApplyTextures(Textures, TexUpdates, Dropped)
local Results = Raster.RasterJobs(Prims, Tiles, TileLength, Textures)
task.synchronize()
Done:Fire(Id, Results)
end)
Actor:SetAttribute("Ready", true)
+1 -1
View File
@@ -1 +1 @@
[[46, "imgui.lua"], [22675, "imgui_demo.lua"], [34533, "imgui_draw.lua"], [42860, "imgui_h.lua"], [45857, "imgui_impl_roblox.lua"], [47509, "imgui_impl_roblox_fonts.lua"], [53912, "imgui_internal.lua"], [57884, "imgui_tables.lua"], [62976, "imgui_widgets.lua"], [75210, "imstb_rectpack.lua"], [75874, "imstb_textedit.lua"], [77416, "imstb_truetype.lua"], [80204, "imstd_minstdio.lua"]] [[57, "imgui.lua"], [22812, "imgui_demo.lua"], [34672, "imgui_draw.lua"], [43097, "imgui_h.lua"], [46107, "roblox/raster.lua"], [47714, "roblox/textures.lua"], [47965, "roblox/layers.lua"], [48387, "roblox/overlays.lua"], [48468, "roblox/render.lua"], [49763, "roblox/parallel.lua"], [50295, "roblox/patches.lua"], [50580, "imgui_impl_roblox.lua"], [51092, "imgui_impl_roblox_fonts.lua"], [57497, "imgui_internal.lua"], [61482, "imgui_tables.lua"], [66610, "imgui_widgets.lua"], [78998, "imstb_rectpack.lua"], [79675, "imstb_textedit.lua"], [81217, "imstb_truetype.lua"], [84151, "imstd_minstdio.lua"]]
+12390 -8438
View File
File diff suppressed because it is too large. Load diff
+31
View File
@@ -70,6 +70,7 @@ export type ImGuiAPI = {
CalcRoundingFlagsForRectInRect: (...any) -> ...any, CalcRoundingFlagsForRectInRect: (...any) -> ...any,
CalcTextSize: (text: string, text_end: string?, hide_text_after_double_hash: boolean?, wrap_width: number?) -> ImVec2, CalcTextSize: (text: string, text_end: string?, hide_text_after_double_hash: boolean?, wrap_width: number?) -> ImVec2,
CalcTextSizeEx: (...any) -> ...any, CalcTextSizeEx: (...any) -> ...any,
CalcTextSizeXY: (...any) -> ...any,
CalcTypematicRepeatAmount: (...any) -> ...any, CalcTypematicRepeatAmount: (...any) -> ...any,
CalcWindowNextAutoFitSize: (...any) -> ...any, CalcWindowNextAutoFitSize: (...any) -> ...any,
CalcWrapWidthForPos: (...any) -> ...any, CalcWrapWidthForPos: (...any) -> ...any,
@@ -991,8 +992,38 @@ export type ImGuiStyleVar = { Alpha: number, DisabledAlpha: number, WindowPaddin
export type ImGuiTreeNodeFlags = { None: number, Selected: number, Framed: number, AllowOverlap: number, NoTreePushOnOpen: number, NoAutoOpenOnLog: number, DefaultOpen: number, OpenOnDoubleClick: number, OpenOnArrow: number, Leaf: number, Bullet: number, FramePadding: number, SpanAvailWidth: number, SpanFullWidth: number, SpanLabelWidth: number, SpanAllColumns: number, LabelSpanAllColumns: number, NavLeftJumpsToParent: number, DrawLinesNone: number, DrawLinesFull: number, DrawLinesToNodes: number, NoNavFocus: number, ClipLabelForTrailingButton: number, UpsideDownArrow: number, CollapsingHeader: number, OpenOnMask_: number, DrawLinesMask_: number, [string]: number } export type 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 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 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 = { export type ImGuiModule = {
ImGui: ImGuiAPI, ImGui: ImGuiAPI,
ImGui_ImplRoblox: ImGuiImplRoblox,
ImVec2: (x: number?, y: number?, z: number?, w: number?) -> ImVec2, ImVec2: (x: number?, y: number?, z: number?, w: number?) -> ImVec2,
ImVec4: (x: number?, y: number?, z: number?, w: number?) -> ImVec4, ImVec4: (x: number?, y: number?, z: number?, w: number?) -> ImVec4,
ImDrawFlags: ImDrawFlags, ImDrawFlags: ImDrawFlags,
+1627
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1 +1 @@
[[183, "imgui.lua"], [22812, "imgui_demo.lua"], [34670, "imgui_draw.lua"], [42997, "imgui_h.lua"], [45994, "imgui_impl_love.lua"], [46538, "imgui_internal.lua"], [50510, "imgui_tables.lua"], [55602, "imgui_widgets.lua"], [67836, "imstb_rectpack.lua"], [68500, "imstb_textedit.lua"], [70042, "imstb_truetype.lua"], [72830, "imstd_minstdio.lua"]] [[183, "imgui.lua"], [22933, "imgui_demo.lua"], [34790, "imgui_draw.lua"], [43214, "imgui_h.lua"], [46222, "imgui_impl_love.lua"], [46784, "imgui_internal.lua"], [50756, "imgui_tables.lua"], [55878, "imgui_widgets.lua"], [68266, "imstb_rectpack.lua"], [68943, "imstb_textedit.lua"], [70485, "imstb_truetype.lua"], [73446, "imstd_minstdio.lua"]]
+1415 -796
View File
File diff suppressed because it is too large. Load diff
+6 -2
View File
@@ -3,11 +3,15 @@
"tree": { "tree": {
"$className": "DataModel", "$className": "DataModel",
"ReplicatedStorage": { "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": { "StarterPlayer": {
"StarterPlayerScripts": { "StarterPlayerScripts": {
"ImGuiMain": { "$path": "examples/example_roblox/main.client.luau" } "ImGuiMain": { "$path": "examples/example_roblox_parallel/main.client.luau" }
} }
} }
} }
+14 -2
View File
@@ -8,20 +8,32 @@ 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. 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, - 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`, `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`, `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`). `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 - 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. 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`).
- Roblox/Luau-specific replacements of hot library internals go in `backends/roblox/patches.lua` (installed when the
backend loads, one switch per patch in `Enabled`), never in the library sources. They must stay exactly equivalent
(draw hashes, pixels) and hand uncommon cases back to the original; patch `MT.*` methods or globals looked up at
call time. When changing a patched library function, update or disable its patch.
- No `goto`, no `::labels::`, no `setfenv/getfenv`, no LuaJIT `bit`/`ffi`. Use `bit32`. For `continue` use - 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. `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 - Luau has a limit of 200 locals per function and 255 upvalues; split huge functions (like demo sections) into
several local/global functions. several local/global functions.
- `@native` has a budget: all native code of one script must fit in one ~4 MB block, or Roblox compiles none of it
(every function of the bundle runs interpreted, silently). `tools/test/native_size.py --top 30` shows the bundle's
size and headroom (part of check_all.sh); put `@native` only on functions that run every frame.
## Portability (LÖVE build) ## Portability (LÖVE build)
- Library code must stay valid **Lua 5.1/LuaJIT syntax** apart from `@native` lines (stripped for LÖVE): no `+=`, `//`, - 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 `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). - Check with `tools/test/love/run.sh` (LuaJIT draw checksums must equal the Luau ones).
## Conventions (follow what the port already does) ## Conventions (follow what the port already does)
@@ -0,0 +1,5 @@
function love.conf(t)
t.window.title = "Dear ImGui - LÖVE extensions example"
t.window.width, t.window.height = 1280, 800
t.window.resizable = true
end
+619
View File
@@ -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
+1
View File
@@ -83,6 +83,7 @@ local function StyleColorsCatppuccinMocha(Style)
{ "ScrollbarGrabActive", Overlay0 }, { "ScrollbarGrabActive", Overlay0 },
{ "CheckMark", Mauve }, { "CheckMark", Mauve },
{ "CheckboxSelectedBg", Surface0 },
{ "SliderGrab", Mauve, 0.8 }, { "SliderGrab", Mauve, 0.8 },
{ "SliderGrabActive", Mauve }, { "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)
+363 -242
View File
File diff suppressed because it is too large. Load diff
+54 -55
View File
@@ -1191,7 +1191,7 @@ S.DemoWindowWidgetsColorAndPickers = {
color = ImVec4(114.0 / 255.0, 144.0 / 255.0, 154.0 / 255.0, 200.0 / 255.0), color = ImVec4(114.0 / 255.0, 144.0 / 255.0, 154.0 / 255.0, 200.0 / 255.0),
base_flags = ImGuiColorEditFlags.None, base_flags = ImGuiColorEditFlags.None,
saved_palette_init = true, saved_palette_init = true,
saved_palette = {}, -- 32 x ImVec4, 1-based saved_palette = {}, -- [Port] 32 x ImVec4, 1-based
backup_color = ImVec4(), backup_color = ImVec4(),
no_border = false, no_border = false,
ref_color = false, ref_color = false,
@@ -1401,7 +1401,7 @@ end
S.DemoWindowWidgetsComboBoxes = { S.DemoWindowWidgetsComboBoxes = {
flags = 0, flags = 0,
item_selected_idx = 0, -- Here we store our selection data as an index. item_selected_idx = 0, -- Here we store our selection data as an index.
filter = nil, -- ImGuiTextFilter, created lazily filter = nil, -- [Port] ImGuiTextFilter, created lazily
item_current_2 = 0, item_current_2 = 0,
item_current_3 = -1, -- If the selection isn't within 0..count, Combo won't display a preview item_current_3 = -1, -- If the selection isn't within 0..count, Combo won't display a preview
item_current_4 = 0, item_current_4 = 0,
@@ -1519,7 +1519,7 @@ S.DemoWindowWidgetsDataTypes = {
s16_v = 32767, s16_v = 32767,
u16_v = 65535, u16_v = 65535,
s32_v = -1, s32_v = -1,
u32_v = 4294967295, -- (ImU32)-1 u32_v = 4294967295, -- [Port] (ImU32)-1
s64_v = -1, s64_v = -1,
u64_v = 18446744073709551615, -- (ImU64)-1 [Port] Lua numbers are doubles: 64-bit values are exact only within +-2^53 u64_v = 18446744073709551615, -- (ImU64)-1 [Port] Lua numbers are doubles: 64-bit values are exact only within +-2^53
f32_v = 0.123, f32_v = 0.123,
@@ -1557,15 +1557,15 @@ function DemoWindowWidgetsDataTypes()
local u8_zero, u8_one, u8_fifty, u8_min, u8_max = 0, 1, 50, 0, 255 local u8_zero, u8_one, u8_fifty, u8_min, u8_max = 0, 1, 50, 0, 255
local s16_zero, s16_one, s16_fifty, s16_min, s16_max = 0, 1, 50, -32768, 32767 local s16_zero, s16_one, s16_fifty, s16_min, s16_max = 0, 1, 50, -32768, 32767
local u16_zero, u16_one, u16_fifty, u16_min, u16_max = 0, 1, 50, 0, 65535 local u16_zero, u16_one, u16_fifty, u16_min, u16_max = 0, 1, 50, 0, 65535
local s32_zero, s32_one, s32_fifty, s32_min, s32_max, s32_hi_a, s32_hi_b = 0, 1, 50, -1073741824, 1073741823, 1073741823 - 100, 1073741823 -- INT_MIN/2, INT_MAX/2 local s32_zero, s32_one, s32_fifty, s32_min, s32_max, s32_hi_a, s32_hi_b = 0, 1, 50, -1073741824, 1073741823, 1073741823 - 100, 1073741823 -- [Port] INT_MIN/2, INT_MAX/2
local u32_zero, u32_one, u32_fifty, u32_min, u32_max, u32_hi_a, u32_hi_b = 0, 1, 50, 0, 2147483647, 2147483647 - 100, 2147483647 -- UINT_MAX/2 local u32_zero, u32_one, u32_fifty, u32_min, u32_max, u32_hi_a, u32_hi_b = 0, 1, 50, 0, 2147483647, 2147483647 - 100, 2147483647 -- [Port] UINT_MAX/2
local s64_zero, s64_one, s64_fifty, s64_min, s64_max, s64_hi_a, s64_hi_b = 0, 1, 50, LLONG_MIN / 2, LLONG_MAX / 2, LLONG_MAX / 2 - 100, LLONG_MAX / 2 local s64_zero, s64_one, s64_fifty, s64_min, s64_max, s64_hi_a, s64_hi_b = 0, 1, 50, LLONG_MIN / 2, LLONG_MAX / 2, LLONG_MAX / 2 - 100, LLONG_MAX / 2
local u64_zero, u64_one, u64_fifty, u64_min, u64_max, u64_hi_a, u64_hi_b = 0, 1, 50, 0, ULLONG_MAX / 2, ULLONG_MAX / 2 - 100, ULLONG_MAX / 2 local u64_zero, u64_one, u64_fifty, u64_min, u64_max, u64_hi_a, u64_hi_b = 0, 1, 50, 0, ULLONG_MAX / 2, ULLONG_MAX / 2 - 100, ULLONG_MAX / 2
local f32_zero, f32_one, f32_lo_a, f32_hi_a = 0.0, 1.0, -10000000000.0, 10000000000.0 local f32_zero, f32_one, f32_lo_a, f32_hi_a = 0.0, 1.0, -10000000000.0, 10000000000.0
local f64_zero, f64_one, f64_lo_a, f64_hi_a = 0.0, 1.0, -1000000000000000.0, 1000000000000000.0 local f64_zero, f64_one, f64_lo_a, f64_hi_a = 0.0, 1.0, -1000000000000000.0, 1000000000000000.0
-- State -- State
-- (see S.DemoWindowWidgetsDataTypes) -- [Port] (see S.DemoWindowWidgetsDataTypes)
local drag_speed = 0.2 local drag_speed = 0.2
IMGUI_DEMO_MARKER("Widgets/Data Types/Drags") IMGUI_DEMO_MARKER("Widgets/Data Types/Drags")
@@ -1784,7 +1784,6 @@ function DemoWindowWidgetsDragAndDrop()
local drop_target_flags = bit32.bor(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoPreviewTooltip) local drop_target_flags = bit32.bor(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoPreviewTooltip)
local payload = ImGui.AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, drop_target_flags) local payload = ImGui.AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, drop_target_flags)
if payload then if payload then
-- IM_UNUSED(payload)
ImGui.SetMouseCursor(ImGuiMouseCursor.NotAllowed) ImGui.SetMouseCursor(ImGuiMouseCursor.NotAllowed)
ImGui.SetTooltip("Cannot drop here!") ImGui.SetTooltip("Cannot drop here!")
end end
@@ -2200,7 +2199,7 @@ end
S.DemoWindowWidgetsPlotting = { S.DemoWindowWidgetsPlotting = {
animate = true, animate = true,
arr = { 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2 }, arr = { 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2 },
values = {}, -- 90 zeros, filled below values = {}, -- [Port] 90 zeros, filled below
values_offset = 0, values_offset = 0,
refresh_time = 0.0, refresh_time = 0.0,
phase = 0.0, phase = 0.0,
@@ -3124,7 +3123,7 @@ S.DemoWindowWidgetsSelectionAndMultiSelect = {
show_in_table = false, show_in_table = false,
show_color_button = true, show_color_button = true,
flags = bit32.bor(ImGuiMultiSelectFlags.ClearOnEscape, ImGuiMultiSelectFlags.BoxSelect1d), flags = bit32.bor(ImGuiMultiSelectFlags.ClearOnEscape, ImGuiMultiSelectFlags.BoxSelect1d),
widget_type = 0, -- WidgetType_Selectable widget_type = 0, -- [Port] WidgetType_Selectable
items = ImVector(), items = ImVector(),
items_next_id = 0, items_next_id = 0,
selection = ExampleSelectionWithDeletion(), selection = ExampleSelectionWithDeletion(),
@@ -3516,7 +3515,7 @@ function DemoWindowWidgetsSelectionAndMultiSelect(demo_data)
if ImGui.TreeNode("Multi-Select (advanced)") then if ImGui.TreeNode("Multi-Select (advanced)") then
IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (advanced)") IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (advanced)")
-- Options -- Options
local WidgetType_Selectable, WidgetType_TreeNode = 0, 1 -- enum WidgetType local WidgetType_Selectable, WidgetType_TreeNode = 0, 1 -- [Port] enum WidgetType
local st = s.advanced local st = s.advanced
if ImGui.TreeNode("Options") then if ImGui.TreeNode("Options") then
@@ -4113,22 +4112,22 @@ S.DemoWindowWidgetsTextInput = {
"\tlock cmpxchg8b eax\n", 1024 * 16), "\tlock cmpxchg8b eax\n", 1024 * 16),
flags = ImGuiInputTextFlags.AllowTabInput, flags = ImGuiInputTextFlags.AllowTabInput,
}, },
-- "Filtered Text Input" -- [Port] "Filtered Text Input"
filtered = { filtered = {
buf1 = ImGui.NewTextBuffer("", 32), buf2 = ImGui.NewTextBuffer("", 32), buf3 = ImGui.NewTextBuffer("", 32), buf1 = ImGui.NewTextBuffer("", 32), buf2 = ImGui.NewTextBuffer("", 32), buf3 = ImGui.NewTextBuffer("", 32),
buf4 = ImGui.NewTextBuffer("", 32), buf5 = ImGui.NewTextBuffer("", 32), buf6 = ImGui.NewTextBuffer("", 32), buf4 = ImGui.NewTextBuffer("", 32), buf5 = ImGui.NewTextBuffer("", 32), buf6 = ImGui.NewTextBuffer("", 32),
buf7 = ImGui.NewTextBuffer("", 32), buf7 = ImGui.NewTextBuffer("", 32),
}, },
-- "Password Input" -- [Port] "Password Input"
password = { password = ImGui.NewTextBuffer("password123", 64) }, password = { password = ImGui.NewTextBuffer("password123", 64) },
-- "Completion, History, Edit Callbacks" -- [Port] "Completion, History, Edit Callbacks"
callbacks = { callbacks = {
buf1 = ImGui.NewTextBuffer("", 64), buf2 = ImGui.NewTextBuffer("", 64), buf3 = ImGui.NewTextBuffer("", 64), buf1 = ImGui.NewTextBuffer("", 64), buf2 = ImGui.NewTextBuffer("", 64), buf3 = ImGui.NewTextBuffer("", 64),
edit_count = 0, edit_count = 0,
}, },
-- "Resize Callback" -- "Resize Callback"
resize = { flags = ImGuiInputTextFlags.None, my_str = ImVector() }, resize = { flags = ImGuiInputTextFlags.None, my_str = ImVector() },
-- "Eliding, Alignment" -- [Port] "Eliding, Alignment"
eliding = { buf1 = ImGui.NewTextBuffer("/path/to/some/folder/with/long/filename.cpp", 128), flags = ImGuiInputTextFlags.ElideLeft }, eliding = { buf1 = ImGui.NewTextBuffer("/path/to/some/folder/with/long/filename.cpp", 128), flags = ImGuiInputTextFlags.ElideLeft },
-- "Miscellaneous" -- "Miscellaneous"
misc = { buf1 = ImGui.NewTextBuffer("", 16), flags = ImGuiInputTextFlags.EscapeClearsAll }, misc = { buf1 = ImGui.NewTextBuffer("", 16), flags = ImGuiInputTextFlags.EscapeClearsAll },
@@ -4418,7 +4417,7 @@ end
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
S.DemoWindowWidgetsTreeNodes = { S.DemoWindowWidgetsTreeNodes = {
base_flags = bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DefaultOpen), -- "Hierarchy Lines" base_flags = bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DefaultOpen), -- [Port] "Hierarchy Lines"
selection_mask = 0x00, selection_mask = 0x00,
base_flags_2 = bit32.bor(ImGuiTreeNodeFlags.OpenOnArrow, ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.SpanAvailWidth), -- "Advanced" base_flags_2 = bit32.bor(ImGuiTreeNodeFlags.OpenOnArrow, ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.SpanAvailWidth), -- "Advanced"
align_label_with_current_x_position = false, align_label_with_current_x_position = false,
@@ -4751,7 +4750,7 @@ S.DemoWindowLayout = {
-- Widgets Width -- Widgets Width
f = 0.0, f = 0.0,
show_indented_items = true, show_indented_items = true,
-- Basic Horizontal Layout -- [Port] Basic Horizontal Layout
c1 = false, c2 = false, c3 = false, c4 = false, c1 = false, c2 = false, c3 = false, c4 = false,
f0 = 1.0, f1 = 2.0, f2 = 3.0, f0 = 1.0, f1 = 2.0, f2 = 3.0,
item = -1, item = -1,
@@ -4776,7 +4775,7 @@ S.DemoWindowLayout = {
-- Text Clipping -- Text Clipping
size = ImVec2(100.0, 100.0), size = ImVec2(100.0, 100.0),
offset = ImVec2(30.0, 30.0), offset = ImVec2(30.0, 30.0),
-- Overlap Mode -- [Port] Overlap Mode
enable_allow_overlap = true, enable_allow_overlap = true,
} }
@@ -5615,14 +5614,14 @@ end
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
S.DemoWindowPopups = { S.DemoWindowPopups = {
selected_fish = -1, -- static int selected_fish = -1; selected_fish = -1, -- [Port] static int selected_fish = -1;
toggles = { true, false, false, false, false }, -- static bool toggles[] = { true, false, false, false, false }; toggles = { true, false, false, false, false }, -- [Port] static bool toggles[] = { true, false, false, false, false };
selected = -1, -- static int selected = -1; selected = -1, -- [Port] static int selected = -1;
value = 0.5, -- static float value = 0.5f; value = 0.5, -- [Port] static float value = 0.5f;
name = ImGui.NewTextBuffer("Label1", 32), -- static char name[32] = "Label1"; name = ImGui.NewTextBuffer("Label1", 32), -- [Port] static char name[32] = "Label1";
dont_ask_me_next_time = false, -- static bool dont_ask_me_next_time = false; dont_ask_me_next_time = false, -- [Port] static bool dont_ask_me_next_time = false;
item = 1, -- static int item = 1; item = 1, -- [Port] static int item = 1;
color = { 0.4, 0.7, 0.0, 0.5 }, -- static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; color = { 0.4, 0.7, 0.0, 0.5 }, -- [Port] static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f };
} }
function DemoWindowPopups() function DemoWindowPopups()
local s = S.DemoWindowPopups local s = S.DemoWindowPopups
@@ -5919,7 +5918,7 @@ end
-- This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID. -- This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID.
-- But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex) -- But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex)
-- If you don't use sorting, you will generally never care about giving column an ID! -- If you don't use sorting, you will generally never care about giving column an ID!
-- enum MyItemColumnID -- [Port] enum MyItemColumnID
MyItemColumnID_ID = 0 MyItemColumnID_ID = 0
MyItemColumnID_Name = 1 MyItemColumnID_Name = 1
MyItemColumnID_Action = 2 MyItemColumnID_Action = 2
@@ -6001,7 +6000,7 @@ S.EditTableSizingFlags = { policies = nil }
-- [Port] p_flags -> takes flags, returns the new flags. -- [Port] p_flags -> takes flags, returns the new flags.
function EditTableSizingFlags(p_flags) function EditTableSizingFlags(p_flags)
local s = S.EditTableSizingFlags local s = S.EditTableSizingFlags
-- struct EnumDesc { ImGuiTableFlags Value; const char* Name; const char* Tooltip; }; -- [Port] struct EnumDesc { ImGuiTableFlags Value; const char* Name; const char* Tooltip; };
if s.policies == nil then if s.policies == nil then
s.policies = s.policies =
{ {
@@ -6092,7 +6091,7 @@ end
-- [SECTION] DemoWindowTables() -- [SECTION] DemoWindowTables()
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
S.DemoWindowTables = { -- statics of DemoWindowTables(), one sub-table per TreeNode S.DemoWindowTables = { -- [Port] statics of DemoWindowTables(), one sub-table per TreeNode
disable_indent = false, disable_indent = false,
BordersBackground = { BordersBackground = {
flags = bit32.bor(ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg), flags = bit32.bor(ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg),
@@ -6117,14 +6116,14 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su
flags2 = bit32.bor(ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg), flags2 = bit32.bor(ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg),
cell_padding = ImVec2(0.0, 0.0), cell_padding = ImVec2(0.0, 0.0),
show_widget_frame_bg = true, show_widget_frame_bg = true,
text_bufs = {}, -- 1-based, cell + 1 text_bufs = {}, -- [Port] 1-based, cell + 1
init = true, init = true,
}, },
SizingPolicies = { SizingPolicies = {
flags1 = bit32.bor(ImGuiTableFlags.BordersV, ImGuiTableFlags.BordersOuterH, ImGuiTableFlags.RowBg, ImGuiTableFlags.ContextMenuInBody), flags1 = bit32.bor(ImGuiTableFlags.BordersV, ImGuiTableFlags.BordersOuterH, ImGuiTableFlags.RowBg, ImGuiTableFlags.ContextMenuInBody),
sizing_policy_flags = { ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.SizingFixedSame, ImGuiTableFlags.SizingStretchProp, ImGuiTableFlags.SizingStretchSame }, sizing_policy_flags = { ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.SizingFixedSame, ImGuiTableFlags.SizingStretchProp, ImGuiTableFlags.SizingStretchSame },
flags = bit32.bor(ImGuiTableFlags.ScrollY, ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg, ImGuiTableFlags.Resizable), flags = bit32.bor(ImGuiTableFlags.ScrollY, ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg, ImGuiTableFlags.Resizable),
contents_type = 0, -- CT_ShowWidth contents_type = 0, -- [Port] CT_ShowWidth
column_count = 3, column_count = 3,
text_buf = ImGui.NewTextBuffer("", 32), text_buf = ImGui.NewTextBuffer("", 32),
}, },
@@ -6159,7 +6158,7 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su
table_flags = bit32.bor(ImGuiTableFlags.BordersV, ImGuiTableFlags.BordersOuterH, ImGuiTableFlags.Resizable, ImGuiTableFlags.RowBg, ImGuiTableFlags.NoBordersInBody), table_flags = bit32.bor(ImGuiTableFlags.BordersV, ImGuiTableFlags.BordersOuterH, ImGuiTableFlags.Resizable, ImGuiTableFlags.RowBg, ImGuiTableFlags.NoBordersInBody),
tree_node_flags_base = bit32.bor(ImGuiTreeNodeFlags.SpanAllColumns, ImGuiTreeNodeFlags.DefaultOpen, ImGuiTreeNodeFlags.DrawLinesFull), tree_node_flags_base = bit32.bor(ImGuiTreeNodeFlags.SpanAllColumns, ImGuiTreeNodeFlags.DefaultOpen, ImGuiTreeNodeFlags.DrawLinesFull),
MyTreeNode = nil, -- [Port] local struct, created once on first use MyTreeNode = nil, -- [Port] local struct, created once on first use
nodes = { -- 1-based; ChildIdx stays 0-based like upstream nodes = { -- [Port] 1-based; ChildIdx stays 0-based like upstream
{ Name = "Root with Long Name", Type = "Folder", Size = -1, ChildIdx = 1, ChildCount = 3 }, -- 0 { Name = "Root with Long Name", Type = "Folder", Size = -1, ChildIdx = 1, ChildCount = 3 }, -- 0
{ Name = "Music", Type = "Folder", Size = -1, ChildIdx = 4, ChildCount = 2 }, -- 1 { Name = "Music", Type = "Folder", Size = -1, ChildIdx = 4, ChildCount = 2 }, -- 1
{ Name = "Textures", Type = "Folder", Size = -1, ChildIdx = 6, ChildCount = 3 }, -- 2 { Name = "Textures", Type = "Folder", Size = -1, ChildIdx = 6, ChildCount = 3 }, -- 2
@@ -6180,7 +6179,7 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su
AngledHeaders = { AngledHeaders = {
table_flags = bit32.bor(ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY, ImGuiTableFlags.BordersOuter, ImGuiTableFlags.BordersInnerH, ImGuiTableFlags.Hideable, ImGuiTableFlags.Resizable, ImGuiTableFlags.Reorderable, ImGuiTableFlags.HighlightHoveredColumn), table_flags = bit32.bor(ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY, ImGuiTableFlags.BordersOuter, ImGuiTableFlags.BordersInnerH, ImGuiTableFlags.Hideable, ImGuiTableFlags.Resizable, ImGuiTableFlags.Reorderable, ImGuiTableFlags.HighlightHoveredColumn),
column_flags = bit32.bor(ImGuiTableColumnFlags.AngledHeader, ImGuiTableColumnFlags.WidthFixed), column_flags = bit32.bor(ImGuiTableColumnFlags.AngledHeader, ImGuiTableColumnFlags.WidthFixed),
bools = {}, -- 1-based, filled with false on first use bools = {}, -- [Port] 1-based, filled with false on first use
frozen_cols = 1, frozen_cols = 1,
frozen_rows = 2, frozen_rows = 2,
}, },
@@ -6209,11 +6208,11 @@ S.DemoWindowTables = { -- statics of DemoWindowTables(), one su
ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY, ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY,
ImGuiTableFlags.SizingFixedFit), ImGuiTableFlags.SizingFixedFit),
columns_base_flags = ImGuiTableColumnFlags.None, columns_base_flags = ImGuiTableColumnFlags.None,
contents_type = 5, -- CT_SelectableSpanRow contents_type = 5, -- [Port] CT_SelectableSpanRow
freeze_cols = 1, freeze_cols = 1,
freeze_rows = 1, freeze_rows = 1,
items_count = 0, -- IM_COUNTOF(template_items_names) * 2, set below items_count = 0, -- [Port] IM_COUNTOF(template_items_names) * 2, set below
outer_size_value = nil, -- ImVec2(0.0f, TEXT_BASE_HEIGHT * 12), set lazily (needs font) outer_size_value = nil, -- [Port] ImVec2(0.0f, TEXT_BASE_HEIGHT * 12), set lazily (needs font)
row_min_height = 0.0, -- Auto row_min_height = 0.0, -- Auto
inner_width_with_scroll = 0.0, -- Auto-extend inner_width_with_scroll = 0.0, -- Auto-extend
outer_size_enabled = true, outer_size_enabled = true,
@@ -6333,7 +6332,7 @@ function DemoWindowTables()
if ImGui.TreeNode("Borders, background") then if ImGui.TreeNode("Borders, background") then
IMGUI_DEMO_MARKER("Tables/Borders, background") IMGUI_DEMO_MARKER("Tables/Borders, background")
-- Expose a few Borders related flags interactively -- Expose a few Borders related flags interactively
local CT_Text, CT_FillButton = 0, 1 -- enum ContentsType local CT_Text, CT_FillButton = 0, 1 -- [Port] enum ContentsType
local s = s.BordersBackground local s = s.BordersBackground
PushStyleCompact() PushStyleCompact()
@@ -6696,7 +6695,7 @@ function DemoWindowTables()
"This section allows you to interact and see the effect of various sizing policies " .. "This section allows you to interact and see the effect of various sizing policies " ..
"depending on whether Scroll is enabled and the contents of your columns.") "depending on whether Scroll is enabled and the contents of your columns.")
local CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText = 0, 1, 2, 3, 4, 5 -- enum ContentsType local CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText = 0, 1, 2, 3, 4, 5 -- [Port] enum ContentsType
PushStyleCompact() PushStyleCompact()
ImGui.PushID("Advanced") ImGui.PushID("Advanced")
@@ -7239,7 +7238,7 @@ function DemoWindowTables()
ImGui.TableHeadersRow() ImGui.TableHeadersRow()
-- Simple storage to output a dummy file-system. -- Simple storage to output a dummy file-system.
-- struct MyTreeNode { Name, Type, Size, ChildIdx, ChildCount } (see s.nodes) -- [Port] struct MyTreeNode { Name, Type, Size, ChildIdx, ChildCount } (see s.nodes)
local MyTreeNode = s.MyTreeNode local MyTreeNode = s.MyTreeNode
if MyTreeNode == nil then -- [Port] local struct with a static method, created once and kept in statics if MyTreeNode == nil then -- [Port] local struct with a static method, created once and kept in statics
MyTreeNode = {} MyTreeNode = {}
@@ -7675,7 +7674,7 @@ function DemoWindowTables()
IMGUI_DEMO_MARKER("Tables/Advanced") IMGUI_DEMO_MARKER("Tables/Advanced")
local s = s.Advanced local s = s.Advanced
local CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow = 0, 1, 2, 3, 4, 5 -- enum ContentsType local CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow = 0, 1, 2, 3, 4, 5 -- [Port] enum ContentsType
local contents_type_names = { "Text", "Button", "SmallButton", "FillButton", "Selectable", "Selectable (span row)" } local contents_type_names = { "Text", "Button", "SmallButton", "FillButton", "Selectable", "Selectable (span row)" }
if s.outer_size_value == nil then s.outer_size_value = ImVec2(0.0, TEXT_BASE_HEIGHT * 12) end if s.outer_size_value == nil then s.outer_size_value = ImVec2(0.0, TEXT_BASE_HEIGHT * 12) end
-- static float row_min_height = 0.0f -- Auto -- static float row_min_height = 0.0f -- Auto
@@ -8195,7 +8194,7 @@ function DemoWindowInputs()
end end
ImGui.Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y) ImGui.Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y)
ImGui.Text("Mouse down:") ImGui.Text("Mouse down:")
for i = 0, ImGuiMouseButton.COUNT - 1 do if ImGui.IsMouseDown(i) then ImGui.SameLine(); ImGui.Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]) end end -- IM_COUNTOF(io.MouseDown), 0-based for i = 0, ImGuiMouseButton.COUNT - 1 do if ImGui.IsMouseDown(i) then ImGui.SameLine(); ImGui.Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]) end end -- [Port] IM_COUNTOF(io.MouseDown), 0-based
ImGui.Text("Mouse wheel: %.1f", io.MouseWheel) ImGui.Text("Mouse wheel: %.1f", io.MouseWheel)
ImGui.Text("Mouse clicked count:") ImGui.Text("Mouse clicked count:")
for i = 0, ImGuiMouseButton.COUNT - 1 do if io.MouseClickedCount[i] > 0 then ImGui.SameLine(); ImGui.Text("b%d: %d", i, io.MouseClickedCount[i]) end end for i = 0, ImGuiMouseButton.COUNT - 1 do if io.MouseClickedCount[i] > 0 then ImGui.SameLine(); ImGui.Text("b%d: %d", i, io.MouseClickedCount[i]) end end
@@ -8669,12 +8668,12 @@ function GetTreeLinesFlagsName(flags)
end end
S.ShowStyleEditor = { S.ShowStyleEditor = {
ref_saved_style = nil, -- static ImGuiStyle ref_saved_style; (created lazily) ref_saved_style = nil, -- [Port] static ImGuiStyle ref_saved_style; (created lazily)
init = true, init = true,
output_dest = 0, output_dest = 0,
output_only_modified = true, output_only_modified = true,
alpha_flags = 0, alpha_flags = 0,
filter = nil, -- static ImGuiTextFilter filter; (created lazily) filter = nil, -- [Port] static ImGuiTextFilter filter; (created lazily)
} }
-- We omit the ImGui:: prefix in this function, as we don't expect user to be copy and pasting this code. -- We omit the ImGui:: prefix in this function, as we don't expect user to be copy and pasting this code.
-- [Port] Lua has no `using namespace`: calls keep the ImGui. prefix -- [Port] Lua has no `using namespace`: calls keep the ImGui. prefix
@@ -9203,17 +9202,17 @@ ExampleAppConsoleMT = {}
ExampleAppConsoleMT.__index = ExampleAppConsoleMT ExampleAppConsoleMT.__index = ExampleAppConsoleMT
function ExampleAppConsole() function ExampleAppConsole()
local self = setmetatable({}, ExampleAppConsoleMT) local self = setmetatable({}, ExampleAppConsoleMT)
self.InputBuf = nil -- char InputBuf[256] self.InputBuf = nil -- [Port] char InputBuf[256]
self.Items = ImVector() -- ImVector<char*> self.Items = ImVector() -- [Port] ImVector<char*>
self.Commands = ImVector() -- ImVector<const char*> self.Commands = ImVector() -- [Port] ImVector<const char*>
self.History = ImVector() -- ImVector<char*> self.History = ImVector() -- [Port] ImVector<char*>
self.HistoryPos = 0 -- -1: new line, 0..History.Size-1 browsing history. self.HistoryPos = 0 -- -1: new line, 0..History.Size-1 browsing history.
self.Filter = ImGuiTextFilter() self.Filter = ImGuiTextFilter()
self.AutoScroll = false self.AutoScroll = false
self.ScrollToBottom = false self.ScrollToBottom = false
self:ClearLog() self:ClearLog()
self.InputBuf = ImGui.NewTextBuffer("", 256) -- memset(InputBuf, 0, sizeof(InputBuf)) self.InputBuf = ImGui.NewTextBuffer("", 256) -- [Port] memset(InputBuf, 0, sizeof(InputBuf))
self.HistoryPos = -1 self.HistoryPos = -1
-- "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches. -- "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches.
@@ -9454,7 +9453,7 @@ function ExampleAppConsoleMT:TextEditCallback(data)
local word_end = data.CursorPos local word_end = data.CursorPos
local word_start = word_end local word_start = word_end
while word_start > 0 do while word_start > 0 do
local c = data.Buf[word_start] -- word_start[-1] local c = data.Buf[word_start] -- [Port] word_start[-1]
if c == 32 or c == 9 or c == 44 or c == 59 then -- ' ', '\t', ',', ';' if c == 32 or c == 9 or c == 44 or c == 59 then -- ' ', '\t', ',', ';'
break break
end end
@@ -9542,7 +9541,7 @@ function ExampleAppConsoleMT:TextEditCallback(data)
end end
S.ShowExampleAppConsole = { S.ShowExampleAppConsole = {
console = nil, -- ExampleAppConsole, created on first use console = nil, -- [Port] ExampleAppConsole, created on first use
} }
function ShowExampleAppConsole(p_open) function ShowExampleAppConsole(p_open)
local s = S.ShowExampleAppConsole local s = S.ShowExampleAppConsole
@@ -9555,7 +9554,7 @@ end
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
S.ShowExampleAppImageViewer = { S.ShowExampleAppImageViewer = {
image_viewer = nil, -- ExampleImageViewerData, created on first use image_viewer = nil, -- [Port] ExampleImageViewerData, created on first use
} }
function ShowExampleAppImageViewer(p_open) function ShowExampleAppImageViewer(p_open)
local s = S.ShowExampleAppImageViewer local s = S.ShowExampleAppImageViewer
@@ -9715,7 +9714,7 @@ end
-- Demonstrate creating a simple log window with basic filtering. -- Demonstrate creating a simple log window with basic filtering.
S.ShowExampleAppLog = { S.ShowExampleAppLog = {
log = nil, -- ExampleAppLog, created on first use log = nil, -- [Port] ExampleAppLog, created on first use
counter = 0, counter = 0,
} }
function ShowExampleAppLog(p_open) function ShowExampleAppLog(p_open)
@@ -10036,7 +10035,7 @@ end
-- Demonstrate creating a simple property editor. -- Demonstrate creating a simple property editor.
S.ShowExampleAppPropertyEditor = { S.ShowExampleAppPropertyEditor = {
property_editor = nil, -- ExampleAppPropertyEditor, created on first use property_editor = nil, -- [Port] ExampleAppPropertyEditor, created on first use
demo_data = nil, -- [Port] fallback when called without demo_data demo_data = nil, -- [Port] fallback when called without demo_data
} }
function ShowExampleAppPropertyEditor(p_open, demo_data) function ShowExampleAppPropertyEditor(p_open, demo_data)
@@ -10428,7 +10427,7 @@ S.ShowExampleAppCustomRendering = {
opt_enable_grid = true, opt_enable_grid = true,
opt_enable_context_menu = true, opt_enable_context_menu = true,
adding_line = false, adding_line = false,
-- BG/FG draw lists -- [Port] BG/FG draw lists
draw_bg = true, draw_bg = true,
draw_fg = true, draw_fg = true,
} }
@@ -11149,9 +11148,9 @@ end
S.ShowExampleAppDocuments = { S.ShowExampleAppDocuments = {
app = ExampleAppDocuments(), app = ExampleAppDocuments(),
opt_target = nil, -- set below to Target_Tab opt_target = nil, -- [Port] set below to Target_Tab
opt_reorderable = true, opt_reorderable = true,
opt_fitting_flags = nil, -- set below to ImGuiTabBarFlags.FittingPolicyDefault_ opt_fitting_flags = nil, -- [Port] set below to ImGuiTabBarFlags.FittingPolicyDefault_
} }
function ShowExampleAppDocuments(p_open) function ShowExampleAppDocuments(p_open)
local s = S.ShowExampleAppDocuments local s = S.ShowExampleAppDocuments
+224 -128
View File
File diff suppressed because it is too large. Load diff
+40 -29
View File
@@ -14,7 +14,7 @@
-- Index of this file: -- Index of this file:
-- [SECTION] Forward declarations and basic types -- [SECTION] Forward declarations and basic types
-- [SECTION] METATABLE MANAGEMENT -- [Port] [SECTION] METATABLE MANAGEMENT
-- [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> -- [SECTION] Helpers: Debug log, memory allocations macros, ImVector<>
-- [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) -- [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData)
-- [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) -- [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData)
@@ -33,7 +33,7 @@
local type = type -- [Luau] builtin (FASTCALL); ImGui._GetTypeFunc() kept for compatibility local type = type -- [Luau] builtin (FASTCALL); ImGui._GetTypeFunc() kept for compatibility
local rawget = rawget; local rawset = rawset local rawget = rawget; local rawset = rawset
-- [LuaBitOp](https://bitop.luajit.org/semantics.html) -- [Port] [LuaBitOp](https://bitop.luajit.org/semantics.html)
local bitAnd = bit32.band; local bitOr = bit32.bor local bitAnd = bit32.band; local bitOr = bit32.bor
local bitLShift = bit32.lshift local bitLShift = bit32.lshift
@@ -138,22 +138,23 @@ IM_FREE = ImGui.MemFree
IM_DELETE = function(owner, field) if owner[field] ~= nil then owner[field] = nil; ImGui.MemFree(owner, field); end end IM_DELETE = function(owner, field) if owner[field] ~= nil then owner[field] = nil; ImGui.MemFree(owner, field); end end
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
-- [SECTION] METATABLE MANAGEMENT -- [Port] [SECTION] METATABLE MANAGEMENT
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
--- File-scope metatable storage --- [Port] File-scope metatable storage
local MT = {} local MT = {}
function ImGui.GetMetatables() return MT end function ImGui.GetMetatables() return MT end
--- @param _EXPR any --- @param _EXPR any
--- @param _MSG string? --- @param _MSG string?
@native
function IM_ASSERT(_EXPR, _MSG) assert((_EXPR), _MSG) end function IM_ASSERT(_EXPR, _MSG) assert((_EXPR), _MSG) end
IM_ASSERT_PARANOID = IM_ASSERT IM_ASSERT_PARANOID = IM_ASSERT
-- A primary data type -- A primary data type
--- Note that `S64` and `U64` are not supported --- [Port] Note that `S64` and `U64` are not supported
--- @enum ImGuiDataType --- @enum ImGuiDataType
ImGuiDataType = ImGuiDataType =
{ {
@@ -334,7 +335,7 @@ function ImVec2_SubVA(v, sub_x, sub_y) return v.x - sub_x, v.y - sub_y end
function ImVec2_MulVX(a, scalar) return a.x * scalar, a.y * scalar end function ImVec2_MulVX(a, scalar) return a.x * scalar, a.y * scalar end
--- An inlined version of `ImVec2_Copy` currently for use in certain ImVector<ImVec2> `push_back` --- [Port] An inlined version of `ImVec2_Copy` currently for use in certain ImVector<ImVec2> `push_back`
local function ImVec2_TCopy(t, k, v) local dest = t[k]; dest.x = v.x; dest.y = v.y; end local function ImVec2_TCopy(t, k, v) local dest = t[k]; dest.x = v.x; dest.y = v.y; end
-- ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type] -- ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type]
@@ -383,7 +384,7 @@ function ImVec4_Copy(dest, src) dest.x = src.x; dest.y = src.y; dest.z = src.z;
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
-- ImVector<> -- ImVector<>
--- A compact ImVector clone --- [Port] A compact ImVector clone
--- @class ImVector<T> --- @class ImVector<T>
--- @field Data T[] # 1-based table --- @field Data T[] # 1-based table
--- @field Size int # >= 0 --- @field Size int # >= 0
@@ -391,22 +392,24 @@ function ImVec4_Copy(dest, src) dest.x = src.x; dest.y = src.y; dest.z = src.z;
--- @field _CopyFunc function --- @field _CopyFunc function
local IM_VECTOR = {} local IM_VECTOR = {}
-- Support 1-based number key indexing while keep method accessing speed -- [Port] Support 1-based number key indexing while keep method accessing speed
--- @param t ImVector --- @param t ImVector
--- @param k string|int --- @param k string|int
--- @return any --- @return any
IM_VECTOR.__index = function(t, k) @native
local m = IM_VECTOR[k] -- methods first (hot path) local function IM_VECTOR_index(t, k)
local m = IM_VECTOR[k] -- [Port] methods first (hot path)
if m ~= nil then return m end if m ~= nil then return m end
if k == "Data" then return nil end -- Data has already been discarded if k == "Data" then return nil end -- [Port] Data has already been discarded
return t.Data[IM_ASSERT(k >= 1 and k <= t.Size) or k] -- if the mt access turns out nil, the k must be int index into Data return t.Data[IM_ASSERT(k >= 1 and k <= t.Size) or k] -- [Port] if the mt access turns out nil, the k must be int index into Data
end end
IM_VECTOR.__index = IM_VECTOR_index
--- @param t ImVector --- @param t ImVector
--- @param k int --- @param k int
--- @param v any --- @param v any
IM_VECTOR.__newindex = function(t, k, v) IM_VECTOR.__newindex = function(t, k, v)
if k == "Data" then rawset(t, "Data", v); return; end -- set new Data. old Data is already discarded if k == "Data" then rawset(t, "Data", v); return; end -- [Port] set new Data. old Data is already discarded
IM_ASSERT(k >= 1 and k <= t.Size) IM_ASSERT(k >= 1 and k <= t.Size)
t.Data[k] = v t.Data[k] = v
end end
@@ -422,14 +425,18 @@ local function _grow_capacity(v, sz) local new_capacity = (v.Capacity ~= 0) and
--- @nodiscard --- @nodiscard
function ImVector(T, COPY_FUNC) return setmetatable({Data = nil, Size = 0, Capacity = 0, _Constructor = T or _default_constructor, _CopyFunc = COPY_FUNC or _default_copyfunc}, IM_VECTOR) end function ImVector(T, COPY_FUNC) return setmetatable({Data = nil, Size = 0, Capacity = 0, _Constructor = T or _default_constructor, _CopyFunc = COPY_FUNC or _default_copyfunc}, IM_VECTOR) end
@native
function IM_VECTOR:push_back(value) if self.Size == self.Capacity then self:reserve(_grow_capacity(self, self.Size + 1)) end; self._CopyFunc(self.Data, self.Size + 1, value); self.Size = self.Size + 1; return value end function IM_VECTOR:push_back(value) if self.Size == self.Capacity then self:reserve(_grow_capacity(self, self.Size + 1)) end; self._CopyFunc(self.Data, self.Size + 1, value); self.Size = self.Size + 1; return value end
@native
function IM_VECTOR:pop_back() IM_ASSERT(self.Size > 0); self.Size = self.Size - 1; end function IM_VECTOR:pop_back() IM_ASSERT(self.Size > 0); self.Size = self.Size - 1; end
function IM_VECTOR:push_front(value) if self.Size == 0 then self:push_back(value) else self:insert(1, value) end end function IM_VECTOR:push_front(value) if self.Size == 0 then self:push_back(value) else self:insert(1, value) end end
function IM_VECTOR:clear() if self.Data then self.Size = 0; self.Capacity = 0; IM_FREE(self, "Data"); self.Data = nil end end function IM_VECTOR:clear() if self.Data then self.Size = 0; self.Capacity = 0; IM_FREE(self, "Data"); self.Data = nil end end
function IM_VECTOR:clear_delete() for i = 1, self.Size do self.Data[i] = nil end self.Size = 0 end function IM_VECTOR:clear_delete() for i = 1, self.Size do self.Data[i] = nil end self.Size = 0 end
function IM_VECTOR:empty() return self.Size == 0 end function IM_VECTOR:empty() return self.Size == 0 end
@native
function IM_VECTOR:back() IM_ASSERT(self.Size > 0) return self.Data[self.Size] end function IM_VECTOR:back() IM_ASSERT(self.Size > 0) return self.Data[self.Size] end
function IM_VECTOR:erase(i) IM_ASSERT(i >= 1 and i <= self.Size) local removed = (table.remove(self.Data, i)) ~= nil self.Size = self.Size - 1 return removed end function IM_VECTOR:erase(i) IM_ASSERT(i >= 1 and i <= self.Size) local removed = (table.remove(self.Data, i)) ~= nil self.Size = self.Size - 1 return removed end
@native
local function _iter(v, i) i = i + 1 if i <= v.Size then return i, v.Data[i] end end local function _iter(v, i) i = i + 1 if i <= v.Size then return i, v.Data[i] end end
function IM_VECTOR:iter() return _iter, self, 0 end function IM_VECTOR:iter() return _iter, self, 0 end
function IM_VECTOR:find_index(value) for i = 1, self.Size do if self.Data[i] == value then return i end end return nil end function IM_VECTOR:find_index(value) for i = 1, self.Size do if self.Data[i] == value then return i end end return nil end
@@ -469,10 +476,10 @@ end
function IM_VECTOR:swap(other) self.Size, other.Size = other.Size, self.Size; self.Capacity, other.Capacity = other.Capacity, self.Capacity; self.Data, other.Data = other.Data, self.Data end function IM_VECTOR:swap(other) self.Size, other.Size = other.Size, self.Size; self.Capacity, other.Capacity = other.Capacity, self.Capacity; self.Data, other.Data = other.Data, self.Data end
function IM_VECTOR:contains(v) for i = 1, self.Size do if self.Data[i] == v then return true end end return false end function IM_VECTOR:contains(v) for i = 1, self.Size do if self.Data[i] == v then return true end end return false end
-- NOTE: This currently does not use type-aware copy! -- [Port] NOTE: This currently does not use type-aware copy!
function IM_VECTOR:insert(pos, value) IM_ASSERT(pos >= 1 and pos <= self.Size + 1); if self.Size == self.Capacity then self:reserve(_grow_capacity(self, self.Size + 1)) end; for i = self.Size, pos, -1 do self.Data[i + 1] = self.Data[i] end self.Data[pos] = value self.Size = self.Size + 1 return value end function IM_VECTOR:insert(pos, value) IM_ASSERT(pos >= 1 and pos <= self.Size + 1); if self.Size == self.Capacity then self:reserve(_grow_capacity(self, self.Size + 1)) end; for i = self.Size, pos, -1 do self.Data[i + 1] = self.Data[i] end self.Data[pos] = value self.Size = self.Size + 1 return value end
-- NOTE: This currently does not copy type related info! -- [Port] NOTE: This currently does not copy type related info!
--- @nodiscard --- @nodiscard
function IM_VECTOR:copy() function IM_VECTOR:copy()
local v = ImVector(); v:resize(self.Size) local v = ImVector(); v:resize(self.Size)
@@ -481,7 +488,7 @@ function IM_VECTOR:copy()
return v return v
end end
-- Not keeping value-key records inside `ImVector`, instead just find it -- [Port] Not keeping value-key records inside `ImVector`, instead just find it
--- @return int # 0-based index --- @return int # 0-based index
function IM_VECTOR:index_from_ptr(p) function IM_VECTOR:index_from_ptr(p)
local data = self.Data; for i = 1, self.Size do if p == data[i] then return i - 1 end end local data = self.Data; for i = 1, self.Size do if p == data[i] then return i - 1 end end
@@ -599,7 +606,7 @@ function ImDrawChannel() return { _CmdBuffer = ImVector(), _IdxBuffer = ImVector
--- @return ImDrawListSplitter --- @return ImDrawListSplitter
--- @nodiscard --- @nodiscard
MT.ImDrawListSplitter = {} -- methods in imgui_draw.lua MT.ImDrawListSplitter = {} -- [Port] methods in imgui_draw.lua
MT.ImDrawListSplitter.__index = MT.ImDrawListSplitter MT.ImDrawListSplitter.__index = MT.ImDrawListSplitter
function ImDrawListSplitter() return setmetatable({ _Current = 0, _Count = 0, _Channels = ImVector() }, MT.ImDrawListSplitter) end function ImDrawListSplitter() return setmetatable({ _Current = 0, _Count = 0, _Channels = ImVector() }, MT.ImDrawListSplitter) end
@@ -1345,7 +1352,7 @@ function ImGuiIO()
-- - Suggested use, e.g. io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map to SHIFT modifier -- - Suggested use, e.g. io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map to SHIFT modifier
ConfigDebugDrawListDefaultsToStrokeLegacy = false, -- false -- Default all ImDrawList to ImDrawList_StrokeLegacy mode, mimicking pre-1.93.0 rendering. ConfigDebugDrawListDefaultsToStrokeLegacy = false, -- false -- Default all ImDrawList to ImDrawList_StrokeLegacy mode, mimicking pre-1.93.0 rendering.
IniFilename = "imgui.ini", -- Roblox: no disk access, only used as a flag (nil disables .ini handling) IniFilename = "imgui.ini", -- [Port] no disk access, only used as a flag (nil disables .ini handling)
IniSavingRate = 5.0, -- = 5.0f -- Minimum time between saving positions/sizes to .ini file, in seconds. IniSavingRate = 5.0, -- = 5.0f -- Minimum time between saving positions/sizes to .ini file, in seconds.
LogFilename = "imgui_log.txt", -- = "imgui_log.txt"-- Path to .log file (default parameter to ImGui.LogToFile when no file is specified). LogFilename = "imgui_log.txt", -- = "imgui_log.txt"-- Path to .log file (default parameter to ImGui.LogToFile when no file is specified).
WantSaveIniSettings = false, -- When manual .ini load/save is active (io.IniFilename == nil), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! WantSaveIniSettings = false, -- When manual .ini load/save is active (io.IniFilename == nil), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving!
@@ -1438,6 +1445,7 @@ end
--- @field InputPos ImVec2 --- @field InputPos ImVec2
--- @field InputLineHeight float --- @field InputLineHeight float
--- @field ViewportId ImGuiID --- @field ViewportId ImGuiID
--- @field SelectedText string
--- @return ImGuiPlatformImeData --- @return ImGuiPlatformImeData
--- @nodiscard --- @nodiscard
@@ -1447,7 +1455,8 @@ function ImGuiPlatformImeData()
WantTextInput = false, -- A widget wants text input, not necessarily IME to be visible. This is automatically set to the upcoming value of io.WantTextInput. WantTextInput = false, -- A widget wants text input, not necessarily IME to be visible. This is automatically set to the upcoming value of io.WantTextInput.
InputPos = ImVec2(), -- Position of input cursor (for IME). InputPos = ImVec2(), -- Position of input cursor (for IME).
InputLineHeight = 0.0, -- Line height (for IME). InputLineHeight = 0.0, -- Line height (for IME).
ViewportId = 0 -- ID of platform window/viewport. ViewportId = 0, -- ID of platform window/viewport.
SelectedText = "" -- [Port] Text currently selected in the widget wanting text input (backends may mirror it, e.g. for native copy).
} }
end end
@@ -1459,6 +1468,7 @@ function ImGuiPlatformImeData_Copy(dest, src)
ImVec2_Copy(dest.InputPos, src.InputPos) ImVec2_Copy(dest.InputPos, src.InputPos)
dest.InputLineHeight = src.InputLineHeight dest.InputLineHeight = src.InputLineHeight
dest.ViewportId = src.ViewportId dest.ViewportId = src.ViewportId
dest.SelectedText = src.SelectedText -- [Port]
end end
--- @param data1 ImGuiPlatformImeData --- @param data1 ImGuiPlatformImeData
@@ -1468,7 +1478,8 @@ function ImGuiPlatformImeData_Compare(data1, data2)
data1.WantTextInput ~= data2.WantTextInput or data1.WantTextInput ~= data2.WantTextInput or
data1.InputPos ~= data2.InputPos or data1.InputPos ~= data2.InputPos or
data1.InputLineHeight ~= data2.InputLineHeight or data1.InputLineHeight ~= data2.InputLineHeight or
data1.ViewportId ~= data2.ViewportId then data1.ViewportId ~= data2.ViewportId or
data1.SelectedText ~= data2.SelectedText then
return false return false
end end
@@ -2112,7 +2123,7 @@ ImGuiKey = {
RightCtrl = 531, RightShift = 532, RightAlt = 533, RightSuper = 534, RightCtrl = 531, RightShift = 532, RightAlt = 533, RightSuper = 534,
Menu = 535, Menu = 535,
-- 0 ~ 9 (upstream ImGuiKey_0..ImGuiKey_9: K0..K9 in this port, ImGuiKey["0"]..ImGuiKey["9"] are aliases) -- [Port] 0 ~ 9 (upstream ImGuiKey_0..ImGuiKey_9: K0..K9 in this port, ImGuiKey["0"]..ImGuiKey["9"] are aliases)
K0 = 536, K1 = 537, K2 = 538, K3 = 539, K4 = 540, K5 = 541, K6 = 542, K7 = 543, K8 = 544, K9 = 545, K0 = 536, K1 = 537, K2 = 538, K3 = 539, K4 = 540, K5 = 541, K6 = 542, K7 = 543, K8 = 544, K9 = 545,
["0"] = 536, ["1"] = 537, ["2"] = 538, ["3"] = 539, ["4"] = 540, ["5"] = 541, ["6"] = 542, ["7"] = 543, ["8"] = 544, ["9"] = 545, ["0"] = 536, ["1"] = 537, ["2"] = 538, ["3"] = 539, ["4"] = 540, ["5"] = 541, ["6"] = 542, ["7"] = 543, ["8"] = 544, ["9"] = 545,
@@ -2534,7 +2545,7 @@ ImGuiInputTextFlags = {
--- @class ImGuiInputTextCallbackData --- @class ImGuiInputTextCallbackData
--- @return ImGuiInputTextCallbackData --- @return ImGuiInputTextCallbackData
-- Buf is a 1-based zero-terminated byte table; positions (CursorPos, pos...) are 0-based byte offsets like upstream. -- [Port] Buf is a 1-based zero-terminated byte table; positions (CursorPos, pos...) are 0-based byte offsets like upstream.
MT.ImGuiInputTextCallbackData = {} MT.ImGuiInputTextCallbackData = {}
MT.ImGuiInputTextCallbackData.__index = MT.ImGuiInputTextCallbackData MT.ImGuiInputTextCallbackData.__index = MT.ImGuiInputTextCallbackData
function ImGuiInputTextCallbackData() function ImGuiInputTextCallbackData()
@@ -2544,7 +2555,7 @@ end
function MT.ImGuiInputTextCallbackData:DeleteChars(pos, bytes_count) function MT.ImGuiInputTextCallbackData:DeleteChars(pos, bytes_count)
IM_ASSERT(pos + bytes_count <= self.BufTextLen) IM_ASSERT(pos + bytes_count <= self.BufTextLen)
local buf = self.Buf local buf = self.Buf
local n = self.BufTextLen - bytes_count - pos + 1 -- includes zero terminator local n = self.BufTextLen - bytes_count - pos + 1 -- [Port] includes zero terminator
for i = 1, n do buf[pos + i] = buf[pos + bytes_count + i] end for i = 1, n do buf[pos + i] = buf[pos + bytes_count + i] end
if self.CursorPos >= pos + bytes_count then if self.CursorPos >= pos + bytes_count then
@@ -2565,10 +2576,10 @@ function MT.ImGuiInputTextCallbackData:InsertChars(pos, new_text)
-- We support partial insertion -- We support partial insertion
local avail = self.BufSize - 1 - self.BufTextLen local avail = self.BufSize - 1 - self.BufTextLen
if not is_resizable and new_text_len > avail then if not is_resizable and new_text_len > avail then
new_text_len = avail -- ponytail: truncates by bytes, not to the closest UTF-8 codepoint new_text_len = avail
end end
if new_text_len <= 0 then return end if new_text_len <= 0 then return end
-- ponytail: CallbackResize buffer growth not supported, text is truncated at BufSize instead
if self.BufTextLen + new_text_len + 1 > self.BufSize then if self.BufTextLen + new_text_len + 1 > self.BufSize then
new_text_len = self.BufSize - 1 - self.BufTextLen new_text_len = self.BufSize - 1 - self.BufTextLen
if new_text_len <= 0 then return end if new_text_len <= 0 then return end
@@ -2802,7 +2813,7 @@ end
-- Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() -- Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload()
--- @class ImGuiPayload --- @class ImGuiPayload
--- Drag and drop payload. `Data` is any Lua value (C++ stores raw bytes); `DataSize` kept for API parity. --- [Port] Drag and drop payload. `Data` is any Lua value (C++ stores raw bytes); `DataSize` kept for API parity.
local IM_PAYLOAD = {} local IM_PAYLOAD = {}
IM_PAYLOAD.__index = IM_PAYLOAD IM_PAYLOAD.__index = IM_PAYLOAD
function IM_PAYLOAD:Clear() ImGuiPayload_Clear(self) end function IM_PAYLOAD:Clear() ImGuiPayload_Clear(self) end
@@ -2980,15 +2991,15 @@ function ImGuiMultiSelectIO()
return { Requests = ImVector(ImGuiSelectionRequest, ImGuiSelectionRequest_Copy), RangeSrcItem = -1, NavIdItem = -1, NavIdSelected = false, RangeSrcReset = false, ItemsCount = 0 } return { Requests = ImVector(ImGuiSelectionRequest, ImGuiSelectionRequest_Copy), RangeSrcItem = -1, NavIdItem = -1, NavIdSelected = false, RangeSrcReset = false, ItemsCount = 0 }
end end
-- ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage: see [SECTION] Widgets: Multi-Select helpers in imgui_widgets.lua -- [Port] ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage: see [SECTION] Widgets: Multi-Select helpers in imgui_widgets.lua
-- (constructors and methods are defined there, like upstream's out-of-line definitions in imgui_widgets.cpp). -- (constructors and methods are defined there, like upstream's out-of-line definitions in imgui_widgets.cpp).
--- @class ImGuiSettingsHandler --- @class ImGuiSettingsHandler
--- Fns take (ctx, handler, ...) like upstream. ReadOpenFn(ctx, handler, name) returns entry; ReadLineFn(ctx, handler, entry, line); --- [Port] Fns take (ctx, handler, ...) like upstream. ReadOpenFn(ctx, handler, name) returns entry; ReadLineFn(ctx, handler, entry, line);
--- WriteAllFn(ctx, handler, buf: ImGuiTextBuffer) --- WriteAllFn(ctx, handler, buf: ImGuiTextBuffer)
function ImGuiSettingsHandler() function ImGuiSettingsHandler()
return { TypeName = nil, TypeHash = 0, ClearAllFn = nil, ReadInitFn = nil, ReadOpenFn = nil, ReadLineFn = nil, return { TypeName = nil, TypeHash = 0, ClearAllFn = nil, ReadInitFn = nil, ReadOpenFn = nil, ReadLineFn = nil,
ApplyAllFn = nil, WriteAllFn = nil, CleanupFn = nil, UserData = nil } ApplyAllFn = nil, WriteAllFn = nil, CleanupFn = nil, UserData = nil }
end end
return true -- [Roblox] ModuleScripts must return exactly one value return true -- [Port] [Roblox] ModuleScripts must return exactly one value
+53 -43
View File
@@ -26,7 +26,7 @@
-- [SECTION] ImFontLoader -- [SECTION] ImFontLoader
-- [SECTION] ImFontAtlas internal API -- [SECTION] ImFontAtlas internal API
-- --
-- PORT: the order of declarations in this file does not strictly follow upstream's imgui_internal.h. -- [Port] the order of declarations in this file does not strictly follow upstream's imgui_internal.h.
--- @meta --- @meta
@@ -44,11 +44,10 @@ local t_sort = table.sort
--- @alias ImGuiTableColumnIdx ImS16 --- @alias ImGuiTableColumnIdx ImS16
-- TODO: Implement actual ImString type -- [Port] TODO: Implement actual ImString type
--- @alias ImString char[]|string --- @alias ImString char[]|string
--- @alias ImStringBuffer char[] --- @alias ImStringBuffer char[]
-- NOTE: temporary solution
--- @param buf char[] --- @param buf char[]
--- @param buf_begin int --- @param buf_begin int
--- @param buf_end int # exclusive --- @param buf_end int # exclusive
@@ -64,7 +63,7 @@ end
-- Helper: ImPool<> -- Helper: ImPool<>
-- Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer, -- Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer,
-- Indexes have the same lifetime as the associated object. -- Indexes have the same lifetime as the associated object.
--- ImPool<T>: pool of objects keyed by ID. Public indices are 0-based like upstream (Buf is stored 1-based). --- [Port] ImPool<T>: pool of objects keyed by ID. Public indices are 0-based like upstream (Buf is stored 1-based).
--- `ctor` creates a new element. Removed slots are recycled via FreeIdx (-1 = none; free slots chain through `_NextFree`). --- `ctor` creates a new element. Removed slots are recycled via FreeIdx (-1 = none; free slots chain through `_NextFree`).
local IM_POOL = {} local IM_POOL = {}
IM_POOL.__index = IM_POOL IM_POOL.__index = IM_POOL
@@ -99,7 +98,7 @@ function IM_POOL:Remove(key, p)
self.AliveCount = self.AliveCount - 1 self.AliveCount = self.AliveCount - 1
end end
function IM_POOL:Reserve(n) end function IM_POOL:Reserve(n) end
-- NOTE: removed slots hold `false`; iterate with `for i = 0, pool:GetMapSize() - 1 do local t = pool:GetByIndex(i) if t then ... end end` -- [Port] NOTE: removed slots hold `false`; iterate with `for i = 0, pool:GetMapSize() - 1 do local t = pool:GetByIndex(i) if t then ... end end`
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
-- [SECTION] Context pointer -- [SECTION] Context pointer
@@ -109,7 +108,7 @@ function IM_POOL:Reserve(n) end
--- @type ImGuiContext? --- @type ImGuiContext?
local GImGui -- Current implicit context pointer local GImGui -- Current implicit context pointer
-- Sets local `GImGui` in this file(imgui_internal.lua). -- [Port] Sets local `GImGui` in this file(imgui_internal.lua).
-- This is currently only used in main code `ImGui.SetCurrentContext()` -- This is currently only used in main code `ImGui.SetCurrentContext()`
--- @param ctx ImGuiContext? --- @param ctx ImGuiContext?
function ImGui._SetCurrentContext_Internal(ctx) function ImGui._SetCurrentContext_Internal(ctx)
@@ -234,24 +233,30 @@ function ImLerp(a, b, t)
end end
--@hoist --@hoist
@native
local function _Trunc(val) if val >= 0 then return mathFloor(val) else return mathCeil(val) end end local function _Trunc(val) if val >= 0 then return mathFloor(val) else return mathCeil(val) end end
--- @overload fun(v: float): float --- @overload fun(v: float): float
--- @overload fun(v: ImVec2): ImVec2 --- @overload fun(v: ImVec2): ImVec2
--@hoist --@hoist
@native
function ImTrunc(v) function ImTrunc(v)
if type(v) == "number" then return _Trunc(v) if type(v) == "number" then return _Trunc(v)
elseif type(v) == "table" then return ImVec2(_Trunc(v.x), _Trunc(v.y)) elseif type(v) == "table" then return ImVec2(_Trunc(v.x), _Trunc(v.y))
end end
end end
ImTrunc64 = _Trunc -- [Luau] its own (hoisted) function instead of `ImTrunc64 = _Trunc`: calls get inlined (e.g. AddRect()) instead of calling
-- a separate function
--@hoist
@native
function ImTrunc64(val) if val >= 0 then return mathFloor(val) else return mathCeil(val) end end
-- Consider using the bit-hack version (search for "0x1p120f"). -- Consider using the bit-hack version (search for "0x1p120f").
--- @param f float --- @param f float
function ImCeilFast(f) function ImCeilFast(f)
local i local i
if f >= 0 then i = math.floor(f) else i = math.ceil(f) end -- same as `ImTrunc()` if f >= 0 then i = math.floor(f) else i = math.ceil(f) end -- [Port] same as `ImTrunc()`
if f > i then return i + 1 end if f > i then return i + 1 end
return i return i
end end
@@ -265,7 +270,11 @@ function ImIsTruncated(x) return x % 1 == 0 end -- (float)(int)x == x
-- Returns true if all parameters are whole numbers. -- Returns true if all parameters are whole numbers.
function ImIsTruncated4(x, y, z, w) return x % 1 == 0 and y % 1 == 0 and z % 1 == 0 and w % 1 == 0 end function ImIsTruncated4(x, y, z, w) return x % 1 == 0 and y % 1 == 0 and z % 1 == 0 and w % 1 == 0 end
--@hoist
@native
function IM_TRUNC(VAL) return math.floor(VAL) end -- Positive values only! function IM_TRUNC(VAL) return math.floor(VAL) end -- Positive values only!
--@hoist
@native
function IM_ROUND(VAL) return math.floor(VAL + 0.5) end -- Positive values only! function IM_ROUND(VAL) return math.floor(VAL + 0.5) end -- Positive values only!
--@hoist --@hoist
@@ -311,7 +320,7 @@ function ImStd.ImExponentialMovingAverage(avg, sample, n)
return avg return avg
end end
-- Uses `string.match` internally -- [Port] Uses `string.match` internally
--- @param str string --- @param str string
function ImAtof(str) function ImAtof(str)
return tonumber(string.match(str, "[+-]?%d*%.?%d+")) return tonumber(string.match(str, "[+-]?%d*%.?%d+"))
@@ -320,16 +329,17 @@ end
--- @param s table # 1-based --- @param s table # 1-based
--- @param c any --- @param c any
--- @param n int --- @param n int
@native
function ImStd.memset(s, c, n) function ImStd.memset(s, c, n)
for i = 1, n do s[i] = c end for i = 1, n do s[i] = c end
end end
do do
local _memmove = function(dest, dest_start, src, src_start, count) @native
local function _memmove(dest, dest_start, src, src_start, count)
if count <= 0 then return end if count <= 0 then return end
-- more compact instead of writing separate if-else and for loops
local c = (dest == src and dest_start >= src_start) local c = (dest == src and dest_start >= src_start)
for i = (c and count - 1 or 0), (c and 0 or count - 1), (c and -1 or 1) do for i = (c and count - 1 or 0), (c and 0 or count - 1), (c and -1 or 1) do
dest[dest_start + i] = src[src_start + i] dest[dest_start + i] = src[src_start + i]
@@ -337,13 +347,9 @@ local _memmove = function(dest, dest_start, src, src_start, count)
end end
if table.move then if table.move then
--- [GMod] Platform specific: the `table.move` polyfill in non-x86-64 currently uses `unpack` which will break if too many elements
-- Remove this check when the polyfill is fixed or removed
if not gmod or (gmod and BRANCH == "x86-64") then
_memmove = function(dest, dest_start, src, src_start, count) _memmove = function(dest, dest_start, src, src_start, count)
table.move(src, src_start, src_start + count - 1, dest_start, dest) table.move(src, src_start, src_start + count - 1, dest_start, dest)
end end
end
end end
ImStd.memmove = _memmove ImStd.memmove = _memmove
@@ -489,9 +495,9 @@ function ImStd.ImStrlen(str, begin)
IM_ASSERT(false) IM_ASSERT(false)
end end
-- FIXME: should also accept count? -- [Port] FIXME: should also accept count?
-- FIXME: avoid dynamic type checking? -- [Port] FIXME: avoid dynamic type checking?
-- string.find with patterns disabled -- [Port] string.find with patterns disabled
--- @param str string|char[] --- @param str string|char[]
--- @param s string|char --- @param s string|char
--- @param start_pos? int --- @param start_pos? int
@@ -539,8 +545,9 @@ IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT = ((IM_DRAWLIST_TEX_LINES_DETAILED_WI
-- - The message will always be a string literal, in order to increase likelihood of being display by an assert handler. -- - The message will always be a string literal, in order to increase likelihood of being display by an assert handler.
-- - See 'Demo->Configuration->Error Handling' and ImGuiIO definitions for details on error handling. -- - See 'Demo->Configuration->Error Handling' and ImGuiIO definitions for details on error handling.
-- - Read https://github.com/ocornut/imgui/wiki/Error-Handling for details on error handling. -- - Read https://github.com/ocornut/imgui/wiki/Error-Handling for details on error handling.
-- Upstream: `if (!(expr) && ErrorLog(msg)) IM_ASSERT(0)`. ErrorLog() returns io.ConfigErrorRecoveryEnableAssert. -- [Port] Upstream: `if (!(expr) && ErrorLog(msg)) IM_ASSERT(0)`. ErrorLog() returns io.ConfigErrorRecoveryEnableAssert.
function IM_ASSERT_USER_ERROR(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then if not ImGui.ErrorLog or ImGui.ErrorLog(_MSG) then error(_MSG, 2) end end end -- Recoverable User Error function IM_ASSERT_USER_ERROR(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then if not ImGui.ErrorLog or ImGui.ErrorLog(_MSG) then error(_MSG, 2) end end end -- Recoverable User Error
@native
function IM_ASSERT_USER_ERROR_RET(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then error(_MSG, 2) end end function IM_ASSERT_USER_ERROR_RET(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then error(_MSG, 2) end end
-- Debug Logging for ShowDebugLogWindow(). This is designed for relatively rare events so please don't spam. -- Debug Logging for ShowDebugLogWindow(). This is designed for relatively rare events so please don't spam.
@@ -581,6 +588,7 @@ ImGuiKeyOwner_NoOwner = 4294967295 -- Require key to have no owner.
function ImGui.MouseButtonToKey(button) IM_ASSERT(button >= 0 and button < ImGuiMouseButton.COUNT) return ImGuiKey.MouseLeft + button end function ImGui.MouseButtonToKey(button) IM_ASSERT(button >= 0 and button < ImGuiMouseButton.COUNT) return ImGuiKey.MouseLeft + button end
--- @param key ImGuiKey --- @param key ImGuiKey
@native
function ImGui.IsNamedKey(key) function ImGui.IsNamedKey(key)
return key >= ImGuiKey.NamedKey_BEGIN and key < ImGuiKey.NamedKey_END return key >= ImGuiKey.NamedKey_BEGIN and key < ImGuiKey.NamedKey_END
end end
@@ -1052,7 +1060,7 @@ end
-- Helper: ImBitArray class (wrapper over ImBitArray functions) -- Helper: ImBitArray class (wrapper over ImBitArray functions)
-- Store 1-bit per value. -- Store 1-bit per value.
--- NOTE: This struct is expensive to create --- [Port] NOTE: This struct is expensive to create
--- @class ImBitArray<BITCOUNT, OFFSET> --- @class ImBitArray<BITCOUNT, OFFSET>
--- @field Data ImU32[] --- @field Data ImU32[]
@@ -1276,7 +1284,7 @@ function ImFontAtlasBuilder()
this.PreloadedAllGlyphsRanges = false -- Set when missing ImGuiBackendFlags.RendererHasTextures features forces atlas to preload everything. this.PreloadedAllGlyphsRanges = false -- Set when missing ImGuiBackendFlags.RendererHasTextures features forces atlas to preload everything.
-- Cache of all ImFontBaked -- Cache of all ImFontBaked
this.BakedPool = ImVector() -- ImStableVector<ImFontBaked,32> this.BakedPool = ImVector() -- [Port] ImStableVector<ImFontBaked,32>
this.BakedMap = {} -- BakedId --> ImFontBaked this.BakedMap = {} -- BakedId --> ImFontBaked
this.BakedDiscardedCount = 0 this.BakedDiscardedCount = 0
@@ -1317,7 +1325,7 @@ end
-- [SECTION] Style support -- [SECTION] Style support
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
--- `GetVarPtr()` is currently only used on `g.Style` in Dear ImGui, and we don't have pointers! --- [Port] `GetVarPtr()` is currently only used on `g.Style` in Dear ImGui, and we don't have pointers!
--- @class ImGuiStyleVarInfo --- @class ImGuiStyleVarInfo
--- @field Count ImU32 # 1+ --- @field Count ImU32 # 1+
--- @field DataType ImGuiDataType --- @field DataType ImGuiDataType
@@ -1453,6 +1461,7 @@ MT.ImGuiNextItemData = {}
MT.ImGuiNextItemData.__index = MT.ImGuiNextItemData MT.ImGuiNextItemData.__index = MT.ImGuiNextItemData
-- Also cleared manually by ItemAdd()! -- Also cleared manually by ItemAdd()!
@native
function MT.ImGuiNextItemData:ClearFlags() function MT.ImGuiNextItemData:ClearFlags()
self.HasFlags = ImGuiNextItemDataFlags.None self.HasFlags = ImGuiNextItemDataFlags.None
self.ItemFlagsSet = ImGuiItemFlags.None self.ItemFlagsSet = ImGuiItemFlags.None
@@ -1502,6 +1511,7 @@ end
MT.ImGuiNextWindowData = {} MT.ImGuiNextWindowData = {}
MT.ImGuiNextWindowData.__index = MT.ImGuiNextWindowData MT.ImGuiNextWindowData.__index = MT.ImGuiNextWindowData
@native
function MT.ImGuiNextWindowData:ClearFlags() function MT.ImGuiNextWindowData:ClearFlags()
self.HasFlags = ImGuiNextWindowDataFlags.None self.HasFlags = ImGuiNextWindowDataFlags.None
end end
@@ -1832,7 +1842,7 @@ local function ImGuiInputTextState()
SelectedAllMouseLock = false, -- after a double-click to select all, we ignore further mouse drags to update selection SelectedAllMouseLock = false, -- after a double-click to select all, we ignore further mouse drags to update selection
EditedBefore = false, -- edited since activated EditedBefore = false, -- edited since activated
EditedThisFrame = false, -- edited this frame EditedThisFrame = false, -- edited this frame
ValidatedThisFrame = false, -- validated this frame (e.g. Enter pressed) ValidatedThisFrame = false,
WantReloadUserBuf = false, -- force a reload of user buf so it may be modified externally. may be automatic in future version. WantReloadUserBuf = false, -- force a reload of user buf so it may be modified externally. may be automatic in future version.
LastMoveDirectionLR = ImGuiDir.Left, -- ImGuiDir_Left or ImGuiDir_Right. track last movement direction so when cursor cross over a word-wrapping boundaries we can display it on either line depending on last move.s LastMoveDirectionLR = ImGuiDir.Left, -- ImGuiDir_Left or ImGuiDir_Right. track last movement direction so when cursor cross over a word-wrapping boundaries we can display it on either line depending on last move.s
ReloadSelectionStart = 0, ReloadSelectionStart = 0,
@@ -2125,7 +2135,7 @@ end
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
-- We always assume that -1 is an invalid value (which works for indices and pointers) -- We always assume that -1 is an invalid value (which works for indices and pointers)
-- (ImGuiSelectionUserData_Invalid is defined above with the ImGuiSelectionUserData alias) -- [Port] (ImGuiSelectionUserData_Invalid is defined above with the ImGuiSelectionUserData alias)
-- Temporary storage for multi-select -- Temporary storage for multi-select
--- @class ImGuiMultiSelectTempData --- @class ImGuiMultiSelectTempData
@@ -2266,7 +2276,7 @@ function ImGui.GetMultiSelectState(id) local g = GImGui; return g.MultiSelectSto
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
-- [SECTION] Tab bar, Tab item support -- [SECTION] Tab bar, Tab item support
-- PORT: public flags from imgui.h + private extensions -- [Port] public flags from imgui.h + private extensions
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
-- Flags for ImGui.BeginTabBar() -- Flags for ImGui.BeginTabBar()
@@ -2315,7 +2325,7 @@ ImGuiTabItemFlags = {
} }
ImGuiTabItemFlags.SectionMask_ = bitOr(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing) ImGuiTabItemFlags.SectionMask_ = bitOr(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing)
-- Storage for one active tab item. In this port the label is stored in `Name` (C++ uses NameOffset into TabBar.TabsNames) -- [Port] Storage for one active tab item. In this port the label is stored in `Name` (C++ uses NameOffset into TabBar.TabsNames)
--- @class ImGuiTabItem --- @class ImGuiTabItem
--- @return ImGuiTabItem --- @return ImGuiTabItem
function ImGuiTabItem() function ImGuiTabItem()
@@ -2334,7 +2344,7 @@ function ImGuiTabItem()
} }
end end
-- Storage for a tab bar. Tabs: ImVector of ImGuiTabItem tables (references; "pointers" stay valid across reorders) -- [Port] Storage for a tab bar. Tabs: ImVector of ImGuiTabItem tables (references; "pointers" stay valid across reorders)
--- @class ImGuiTabBar --- @class ImGuiTabBar
--- @return ImGuiTabBar --- @return ImGuiTabBar
function ImGuiTabBar() function ImGuiTabBar()
@@ -2366,7 +2376,7 @@ function ImGuiShrinkWidthItem() return { Index = 0, Width = 0.0, InitialWidth =
--- @param shared_font_atlas? ImFontAtlas --- @param shared_font_atlas? ImFontAtlas
--- @return ImGuiContext --- @return ImGuiContext
--- @nodiscard --- @nodiscard
function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this structure function ImGuiContext(shared_font_atlas)
local this = { local this = {
Style = ImGuiStyle(), Style = ImGuiStyle(),
ColorStack = ImVector(), -- Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() ColorStack = ImVector(), -- Stack for PushStyleColor()/PopStyleColor() - inherited by Begin()
@@ -2604,20 +2614,20 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct
ComboPreviewData = ImGuiComboPreviewData(), ComboPreviewData = ImGuiComboPreviewData(),
CurrentTabBar = nil, CurrentTabBar = nil,
TabBars = ImPool(ImGuiTabBar), -- ImPool<ImGuiTabBar> TabBars = ImPool(ImGuiTabBar), -- [Port] ImPool<ImGuiTabBar>
-- Docking -- Docking
DockContext = ImGuiDockContext(), DockContext = ImGuiDockContext(),
DockNodeWindowMenuHandler = nil, DockNodeWindowMenuHandler = nil,
DebugHoveredDockNode = nil, -- Hovered dock node. DebugHoveredDockNode = nil, -- Hovered dock node.
CurrentTabBarStack = ImVector(), -- ImVector<ImGuiPtrOrIndex> CurrentTabBarStack = ImVector(), -- [Port] ImVector<ImGuiPtrOrIndex>
ShrinkWidthBuffer = ImVector(), -- ImGuiShrinkWidthItem ShrinkWidthBuffer = ImVector(), -- [Port] ImGuiShrinkWidthItem
-- Multi-Select state -- Multi-Select state
BoxSelectState = ImGuiBoxSelectState(), BoxSelectState = ImGuiBoxSelectState(),
CurrentMultiSelect = nil, CurrentMultiSelect = nil,
MultiSelectTempDataStacked = 0, -- Temporary multi-select data size (because we leave previous instances undestructed, we generally don't use MultiSelectTempData.Size) MultiSelectTempDataStacked = 0, -- Temporary multi-select data size (because we leave previous instances undestructed, we generally don't use MultiSelectTempData.Size)
MultiSelectTempData = ImVector(), -- ImVector<ImGuiMultiSelectTempData>, 1-based MultiSelectTempData = ImVector(), -- [Port] ImVector<ImGuiMultiSelectTempData>, 1-based
MultiSelectStorage = ImPool(ImGuiMultiSelectState), -- ImPool<ImGuiMultiSelectState> MultiSelectStorage = ImPool(ImGuiMultiSelectState), -- [Port] ImPool<ImGuiMultiSelectState>
WindowResizeBorderExpectedRect = ImRect(), -- Expected border rect, switch to relative edit if moving WindowResizeBorderExpectedRect = ImRect(), -- Expected border rect, switch to relative edit if moving
WindowResizeRelativeMode = false, WindowResizeRelativeMode = false,
@@ -2739,7 +2749,7 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct
DebugAllocInfo = ImGuiDebugAllocInfo(), DebugAllocInfo = ImGuiDebugAllocInfo(),
--- Misc --- Misc
FramerateSecPerFrame = {}, -- size = 60 FramerateSecPerFrame = {}, -- [Port] size = 60
FramerateSecPerFrameIdx = 0, FramerateSecPerFrameIdx = 0,
FramerateSecPerFrameCount = 0, FramerateSecPerFrameCount = 0,
FramerateSecPerFrameAccum = 0, FramerateSecPerFrameAccum = 0,
@@ -2749,15 +2759,15 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct
WantTextInputNextFrame = -1, -- Copied in EndFrame() from g.PlatformImeData.WantTextInput. Needs to be set for some backends (SDL3) to emit character inputs. WantTextInputNextFrame = -1, -- Copied in EndFrame() from g.PlatformImeData.WantTextInput. Needs to be set for some backends (SDL3) to emit character inputs.
TempBuffer = ImVector(), -- Temporary text buffer TempBuffer = ImVector(), -- Temporary text buffer
-- Tables (imgui_tables.lua) -- [Port] Tables (imgui_tables.lua)
CurrentTable = nil, CurrentTable = nil,
DebugBreakInTable = 0, -- Set to break in BeginTable() call. DebugBreakInTable = 0, -- Set to break in BeginTable() call.
TablesTempDataStacked = 0, -- Temporary table data size (because we leave previous instances undestructed, we generally don't use TablesTempData.Size) TablesTempDataStacked = 0, -- Temporary table data size (because we leave previous instances undestructed, we generally don't use TablesTempData.Size)
TablesTempData = ImVector(), -- Temporary table data (buffers reused/shared across instances, support nesting) TablesTempData = ImVector(), -- Temporary table data (buffers reused/shared across instances, support nesting)
Tables = ImPool(), -- ImPool<ImGuiTable>, 0-based indices (imgui_tables.lua) Tables = ImPool(), -- [Port] ImPool<ImGuiTable>, 0-based indices (imgui_tables.lua)
TablesLastTimeActive = ImVector(), -- [table_idx + 1] = float TablesLastTimeActive = ImVector(), -- [Port] [table_idx + 1] = float
DrawChannelsTempMergeBuffer = ImVector(), DrawChannelsTempMergeBuffer = ImVector(),
SettingsTables = ImVector(), -- ImChunkStream<ImGuiTableSettings>: plain vector, SettingsOffset = 1-based index SettingsTables = ImVector(), -- [Port] ImChunkStream<ImGuiTableSettings>: plain vector, SettingsOffset = 1-based index
} }
for i = 0, 59 do this.FramerateSecPerFrame[i] = 0 end for i = 0, 59 do this.FramerateSecPerFrame[i] = 0 end
@@ -2932,7 +2942,7 @@ local function ImGuiWindowTempData()
TreeRecordsClippedNodesY2Mask = nil, -- Store whether we should keep recording Y2. Cleared when passing clip max. Equivalent TreeHasStackDataDepthMask value should always be set. TreeRecordsClippedNodesY2Mask = nil, -- Store whether we should keep recording Y2. Cleared when passing clip max. Equivalent TreeHasStackDataDepthMask value should always be set.
ChildWindows = ImVector(), ChildWindows = ImVector(),
CurrentTableIdx = -1, -- 0-based index into g.Tables, -1 if none CurrentTableIdx = -1, -- [Port] 0-based index into g.Tables, -1 if none
CurrentColumns = nil, -- ImGuiOldColumns (legacy Columns API) CurrentColumns = nil, -- ImGuiOldColumns (legacy Columns API)
StateStorage = nil, -- Current persistent per-window storage (store e.g. tree node open/close state) StateStorage = nil, -- Current persistent per-window storage (store e.g. tree node open/close state)
@@ -2994,7 +3004,7 @@ end
--- @return ImRect --- @return ImRect
--- @nodiscard --- @nodiscard
function MT.ImGuiWindow:TitleBarRect() function MT.ImGuiWindow:TitleBarRect()
return ImRect(self.Pos, ImVec2(self.Pos.x + self.SizeFull.x, self.Pos.y + self.TitleBarHeight)) return ImRect(self.Pos.x, self.Pos.y, self.Pos.x + self.SizeFull.x, self.Pos.y + self.TitleBarHeight) -- [Luau] scalar form: no temporary ImVec2
end end
--- @return ImRect --- @return ImRect
@@ -3130,7 +3140,7 @@ function ImGuiWindow(ctx, name)
LastTimeActive = -1.0, -- Last timestamp the window was Active (using float as we don't need high precision there) LastTimeActive = -1.0, -- Last timestamp the window was Active (using float as we don't need high precision there)
StateStorage = {}, StateStorage = {},
ColumnsStorage = ImVector(), -- ImVector<ImGuiOldColumns> ColumnsStorage = ImVector(), -- [Port] ImVector<ImGuiOldColumns>
WriteAccessed = false, -- Set to true when any widget access the current window WriteAccessed = false, -- Set to true when any widget access the current window
@@ -3140,7 +3150,7 @@ function ImGuiWindow(ctx, name)
HitTestHoleSize = ImVec2(), -- Define an optional rectangular hole where mouse will pass-through the window. HitTestHoleSize = ImVec2(), -- Define an optional rectangular hole where mouse will pass-through the window.
NavLastChildNavWindow = nil, -- When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) NavLastChildNavWindow = nil, -- When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.)
NavLastIds = {[0] = 0, [1] = 0}, -- FIXME: 1-based instead NavLastIds = {[0] = 0, [1] = 0}, -- [Port] FIXME: 1-based instead
NavRectRel = {[0] = ImRect(), [1] = ImRect()}, -- Reference rectangle, in window relative space NavRectRel = {[0] = ImRect(), [1] = ImRect()}, -- Reference rectangle, in window relative space
NavPreferredScoringPosRel = {[0] = ImVec2(), [1] = ImVec2()}, -- Preferred X/Y position updated when moving on a given axis, reset to FLT_MAX. NavPreferredScoringPosRel = {[0] = ImVec2(), [1] = ImVec2()}, -- Preferred X/Y position updated when moving on a given axis, reset to FLT_MAX.
NavRootFocusScopeId = 0 -- Focus Scope ID at the time of Begin() NavRootFocusScopeId = 0 -- Focus Scope ID at the time of Begin()
@@ -3966,4 +3976,4 @@ function ImGui.GetCurrentTabBar() local g = GImGui; return g.CurrentTabBar end
function ImGui.IsItemActiveAsInputText() local g = GImGui; return g.ActiveId ~= 0 and g.ActiveId == g.LastItemData.ID and g.InputTextState.ID == g.LastItemData.ID end function ImGui.IsItemActiveAsInputText() local g = GImGui; return g.ActiveId ~= 0 and g.ActiveId == g.LastItemData.ID and g.InputTextState.ID == g.LastItemData.ID end
return true -- [Roblox] ModuleScripts must return exactly one value return true -- [Port] [Roblox] ModuleScripts must return exactly one value
+62 -29
View File
@@ -176,22 +176,22 @@
-- - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false. -- - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false.
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
-- Port notes: -- [Port] Port notes:
-- - Column indices / display orders / draw channel indices are 0-based VALUES like upstream. -- [Port] - Column indices / display orders / draw channel indices are 0-based VALUES like upstream.
-- Per-column arrays (table.Columns, table.DisplayOrderToIndex, table.RowCellData) are Lua tables with 0-based keys. -- [Port] Per-column arrays (table.Columns, table.DisplayOrderToIndex, table.RowCellData) are Lua tables with 0-based keys.
-- table.ColumnsSize mirrors upstream `table->Columns.size()`. -- [Port] table.ColumnsSize mirrors upstream `table->Columns.size()`.
-- - ImBitArray masks are Lua tables { [n] = true }. -- [Port] - ImBitArray masks are Lua tables { [n] = true }.
-- - table.ColumnsNames is a Lua array of strings, column.NameOffset is a 0-based index into it (-1 = none). -- [Port] - table.ColumnsNames is a Lua array of strings, column.NameOffset is a 0-based index into it (-1 = none).
-- - g.SettingsTables is a plain vector of ImGuiTableSettings; table.SettingsOffset is a 1-based index into it (-1 = none). -- [Port] - g.SettingsTables is a plain vector of ImGuiTableSettings; table.SettingsOffset is a 1-based index into it (-1 = none).
-- Each settings entry owns `Columns` (0-based Lua table of ImGuiTableColumnSettings). -- [Port] Each settings entry owns `Columns` (0-based Lua table of ImGuiTableColumnSettings).
-- - ImGuiTableSortSpecs.Specs is a 1-based Lua array of ImGuiTableColumnSortSpecs. -- [Port] - ImGuiTableSortSpecs.Specs is a 1-based Lua array of ImGuiTableColumnSortSpecs.
--- @type ImGuiContext? --- @type ImGuiContext?
local GImGui local GImGui
local MT = ImGui.GetMetatables() local MT = ImGui.GetMetatables()
-- Sets local `GImGui` in this file(imgui_tables.lua). -- [Port] Sets local `GImGui` in this file(imgui_tables.lua).
-- This is currently only used in main code `ImGui.SetCurrentContext()` -- This is currently only used in main code `ImGui.SetCurrentContext()`
--- @param ctx ImGuiContext? --- @param ctx ImGuiContext?
function ImGui._SetCurrentContext_Tables(ctx) function ImGui._SetCurrentContext_Tables(ctx)
@@ -355,6 +355,8 @@ end
ImGuiTableColumnFlags.NoDirectResize_ = ImGuiTableColumnFlags.NoDirectResize_ or lshift(1, 30) -- [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) ImGuiTableColumnFlags.NoDirectResize_ = ImGuiTableColumnFlags.NoDirectResize_ or lshift(1, 30) -- [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge)
local function Rect(r) return ImRect(r.Min.x, r.Min.y, r.Max.x, r.Max.y) end local function Rect(r) return ImRect(r.Min.x, r.Min.y, r.Max.x, r.Max.y) end
-- [Luau] scratch rects for TableUpdateLayout()/TableMergeDrawChannels() locals that never escape
local TableUpdateLayout_work_rect, TableUpdateLayout_host_clip_rect, TableUpdateLayout_mouse_hit_rect, TableMergeDrawChannels_merge_clip_rect = ImRect(), ImRect(), ImRect(), ImRect()
local function V2(v) return ImVec2(v.x, v.y) end local function V2(v) return ImVec2(v.x, v.y) end
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
@@ -429,6 +431,7 @@ end
--- @param table_ ImGuiTable --- @param table_ ImGuiTable
--- @param instance_no int --- @param instance_no int
@native
function ImGui.TableGetInstanceData(table_, instance_no) function ImGui.TableGetInstanceData(table_, instance_no)
if instance_no == 0 then if instance_no == 0 then
return table_.InstanceDataFirst return table_.InstanceDataFirst
@@ -451,9 +454,10 @@ function ImGui.BeginTable(str_id, columns_count, flags, outer_size, inner_width)
return ImGui.BeginTableEx(str_id, id, columns_count, flags, outer_size, inner_width) return ImGui.BeginTableEx(str_id, id, columns_count, flags, outer_size, inner_width)
end end
local BeginTableEx_outer_size_default = ImVec2(0.0, 0.0) -- [Luau] shared read-only default (only read below)
function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_width) function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_width)
if flags == nil then flags = 0 end if flags == nil then flags = 0 end
if outer_size == nil then outer_size = ImVec2(0.0, 0.0) end if outer_size == nil then outer_size = BeginTableEx_outer_size_default end
if inner_width == nil then inner_width = 0.0 end if inner_width == nil then inner_width = 0.0 end
local g = GImGui local g = GImGui
@@ -477,8 +481,10 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi
-- - always performing the GetOrAddByKey() O(log N) query in g.Tables.Map[]. -- - always performing the GetOrAddByKey() O(log N) query in g.Tables.Map[].
local use_child_window = band(flags, bor(ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY)) ~= 0 local use_child_window = band(flags, bor(ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY)) ~= 0
local avail_size = ImGui.GetContentRegionAvail() local avail_size = ImGui.GetContentRegionAvail()
local actual_outer_size = ImTrunc(ImGui.CalcItemSize(outer_size, mathMax(avail_size.x, IMGUI_WINDOW_HARD_MIN_SIZE), use_child_window and mathMax(avail_size.y, IMGUI_WINDOW_HARD_MIN_SIZE) or 0.0)) local actual_outer_size_x, actual_outer_size_y = ImGui._CalcItemSizeXY(outer_size.x, outer_size.y, mathMax(avail_size.x, IMGUI_WINDOW_HARD_MIN_SIZE), use_child_window and mathMax(avail_size.y, IMGUI_WINDOW_HARD_MIN_SIZE) or 0.0)
local outer_rect = ImRect(outer_window.DC.CursorPos, outer_window.DC.CursorPos + actual_outer_size) actual_outer_size_x, actual_outer_size_y = ImTrunc(actual_outer_size_x), ImTrunc(actual_outer_size_y) -- [Luau] scalar ImTrunc(CalcItemSize(...))
local outer_cursor = outer_window.DC.CursorPos
local outer_rect = ImRect(outer_cursor.x, outer_cursor.y, outer_cursor.x + actual_outer_size_x, outer_cursor.y + actual_outer_size_y) -- [Luau] scalar form: no temporary ImVec2
local outer_window_is_measuring_size = (outer_window.AutoFitFramesX > 0) or (outer_window.AutoFitFramesY > 0) -- Doesn't apply to AlwaysAutoResize windows! local outer_window_is_measuring_size = (outer_window.AutoFitFramesX > 0) or (outer_window.AutoFitFramesY > 0) -- Doesn't apply to AlwaysAutoResize windows!
if use_child_window and ImGui.IsClippedEx(outer_rect, 0) and not outer_window_is_measuring_size then if use_child_window and ImGui.IsClippedEx(outer_rect, 0) and not outer_window_is_measuring_size then
ImGui.ItemSize(outer_rect) ImGui.ItemSize(outer_rect)
@@ -489,7 +495,7 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi
-- Acquire storage for the table -- Acquire storage for the table
local table_ = g.Tables:GetOrAddByKey(id) local table_ = g.Tables:GetOrAddByKey(id)
if table_.Columns == nil then -- pool created a plain table if table_.Columns == nil then -- [Port] pool created a plain table
for k, v in pairs(ImGuiTable()) do table_[k] = v end for k, v in pairs(ImGuiTable()) do table_[k] = v end
end end
@@ -928,6 +934,7 @@ function ImGui.TableQueueSetColumnDisplayOrder(table_, column_n, dst_order)
end end
-- Adjust flags: default width mode + stretch columns are not allowed when auto extending -- Adjust flags: default width mode + stretch columns are not allowed when auto extending
@native
local function TableSetupColumnFlags(table_, column, column_n, flags_in) local function TableSetupColumnFlags(table_, column, column_n, flags_in)
local flags = flags_in local flags = flags_in
@@ -987,6 +994,7 @@ end
-- Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() and other TableSetupXXXXX() functions to be called first. -- Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() and other TableSetupXXXXX() functions to be called first.
-- FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns. -- FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns.
-- Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns? -- Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns?
@native
function ImGui.TableUpdateLayout(table_) function ImGui.TableUpdateLayout(table_)
local g = GImGui local g = GImGui
local temp_data = table_.TempData local temp_data = table_.TempData
@@ -1230,7 +1238,7 @@ function ImGui.TableUpdateLayout(table_)
table_.ColumnsStretchSumWeights = stretch_sum_weights table_.ColumnsStretchSumWeights = stretch_sum_weights
-- [Part 4] Apply final widths based on requested widths -- [Part 4] Apply final widths based on requested widths
local work_rect = Rect(table_.WorkRect) local work_rect = TableUpdateLayout_work_rect; ImRect_Copy(work_rect, table_.WorkRect) -- [Luau] scratch copy
local width_spacings = (table_.OuterPaddingX * 2.0) + (table_.CellSpacingX1 + table_.CellSpacingX2) * (table_.ColumnsEnabledCount - 1) local width_spacings = (table_.OuterPaddingX * 2.0) + (table_.CellSpacingX1 + table_.CellSpacingX2) * (table_.ColumnsEnabledCount - 1)
local width_removed = (table_.HasScrollbarYPrev and not table_.InnerWindow.ScrollbarY) and g.Style.ScrollbarSize or 0.0 -- To synchronize decoration width of synced tables with mismatching scrollbar state (#5920) local width_removed = (table_.HasScrollbarYPrev and not table_.InnerWindow.ScrollbarY) and g.Style.ScrollbarSize or 0.0 -- To synchronize decoration width of synced tables with mismatching scrollbar state (#5920)
local width_avail = mathMax(1.0, ((band(table_.Flags, ImGuiTableFlags.ScrollX) ~= 0 and table_.InnerWidth == 0.0) and table_.InnerClipRect:GetWidth() or work_rect:GetWidth()) - width_removed) local width_avail = mathMax(1.0, ((band(table_.Flags, ImGuiTableFlags.ScrollX) ~= 0 and table_.InnerWidth == 0.0) and table_.InnerClipRect:GetWidth() or work_rect:GetWidth()) - width_removed)
@@ -1286,7 +1294,8 @@ function ImGui.TableUpdateLayout(table_)
table_instance.HoveredRowLast = table_instance.HoveredRowNext table_instance.HoveredRowLast = table_instance.HoveredRowNext
table_instance.HoveredRowNext = -1 table_instance.HoveredRowNext = -1
table_.HoveredColumnBody = -1; table_.HoveredColumnBorder = -1 table_.HoveredColumnBody = -1; table_.HoveredColumnBorder = -1
local mouse_hit_rect = ImRect(table_.OuterRect.Min.x, table_.OuterRect.Min.y, table_.OuterRect.Max.x, mathMax(table_.OuterRect.Max.y, table_.OuterRect.Min.y + table_instance.LastOuterHeight)) local mouse_hit_rect = TableUpdateLayout_mouse_hit_rect -- [Luau] scratch, ItemHoverable() only reads it
mouse_hit_rect.Min.x, mouse_hit_rect.Min.y, mouse_hit_rect.Max.x, mouse_hit_rect.Max.y = table_.OuterRect.Min.x, table_.OuterRect.Min.y, table_.OuterRect.Max.x, mathMax(table_.OuterRect.Max.y, table_.OuterRect.Min.y + table_instance.LastOuterHeight)
local backup_active_id = g.ActiveId local backup_active_id = g.ActiveId
g.ActiveId = 0 g.ActiveId = 0
local is_hovering_table = ImGui.ItemHoverable(mouse_hit_rect, 0, ImGuiItemFlags.None) local is_hovering_table = ImGui.ItemHoverable(mouse_hit_rect, 0, ImGuiItemFlags.None)
@@ -1305,7 +1314,7 @@ function ImGui.TableUpdateLayout(table_)
local has_at_least_one_column_requesting_output = false local has_at_least_one_column_requesting_output = false
local offset_x_frozen = (table_.FreezeColumnsCount > 0) local offset_x_frozen = (table_.FreezeColumnsCount > 0)
local offset_x = ((table_.FreezeColumnsCount > 0) and table_.OuterRect.Min.x or work_rect.Min.x) + table_.OuterPaddingX - table_.CellSpacingX1 local offset_x = ((table_.FreezeColumnsCount > 0) and table_.OuterRect.Min.x or work_rect.Min.x) + table_.OuterPaddingX - table_.CellSpacingX1
local host_clip_rect = Rect(table_.InnerClipRect) local host_clip_rect = TableUpdateLayout_host_clip_rect; ImRect_Copy(host_clip_rect, table_.InnerClipRect) -- [Luau] scratch copy
--host_clip_rect.Max.x += table.CellPaddingX + table.CellSpacingX2 --host_clip_rect.Max.x += table.CellPaddingX + table.CellSpacingX2
BitArrayClearAll(table_.VisibleMaskByIndex) BitArrayClearAll(table_.VisibleMaskByIndex)
for order_n = 0, columns_count - 1 do for order_n = 0, columns_count - 1 do
@@ -1560,6 +1569,8 @@ function ImGui.TableApplyExternalUnclipRect(table_, rect)
end end
end end
local TableUpdateBorders_hit_rect = ImRect()
-- Process hit-testing on resizing borders. Actual size change will be applied in EndTable() -- Process hit-testing on resizing borders. Actual size change will be applied in EndTable()
-- - Set table.HoveredColumnBorder with a short delay/timer to reduce visual feedback noise. -- - Set table.HoveredColumnBorder with a short delay/timer to reduce visual feedback noise.
function ImGui.TableUpdateBorders(table_) function ImGui.TableUpdateBorders(table_)
@@ -1599,7 +1610,8 @@ function ImGui.TableUpdateBorders(table_)
end end
local column_id = ImGui.TableGetColumnResizeID(table_, column_n, table_.InstanceCurrent) local column_id = ImGui.TableGetColumnResizeID(table_, column_n, table_.InstanceCurrent)
local hit_rect = ImRect(column.MaxX - hit_half_width, hit_y1, column.MaxX + hit_half_width, border_y2_hit) local hit_rect = TableUpdateBorders_hit_rect -- [Luau] scratch: ItemAdd() copies it, ButtonBehavior() reads it
hit_rect.Min.x = column.MaxX - hit_half_width; hit_rect.Min.y = hit_y1; hit_rect.Max.x = column.MaxX + hit_half_width; hit_rect.Max.y = border_y2_hit
ImGui.ItemAdd(hit_rect, column_id, nil, ImGuiItemFlags.NoNav) ImGui.ItemAdd(hit_rect, column_id, nil, ImGuiItemFlags.NoNav)
--ImGui.GetForegroundDrawList():AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100)) --ImGui.GetForegroundDrawList():AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100))
@@ -1993,7 +2005,7 @@ function ImGui.TableReconcileColumns(table_)
end end
-- Remaining entries are matched sequentially. -- Remaining entries are matched sequentially.
local dst_idx = 1 -- index in reconcile array (1-based) local dst_idx = 1 -- [Port] index in reconcile array (1-based)
if matches ~= reconcile_requests.Size then if matches ~= reconcile_requests.Size then
for src_n = 0, src_count - 1 do for src_n = 0, src_count - 1 do
local src_column = src_columns[src_n] local src_column = src_columns[src_n]
@@ -2085,7 +2097,7 @@ function ImGui.TableGetColumnCount()
return table_ and table_.ColumnsCount or 0 return table_ and table_.ColumnsCount or 0
end end
-- Overloads: TableGetColumnName(column_n?) / TableGetColumnName(table, column_n) -- [Port] Overloads: TableGetColumnName(column_n?) / TableGetColumnName(table, column_n)
function ImGui.TableGetColumnName(a, b) function ImGui.TableGetColumnName(a, b)
local table_, column_n local table_, column_n
if type(a) == "table" then if type(a) == "table" then
@@ -2259,6 +2271,7 @@ end
-- [Public] Starts into the first cell of a new row -- [Public] Starts into the first cell of a new row
--- @param row_flags? ImGuiTableRowFlags --- @param row_flags? ImGuiTableRowFlags
--- @param row_min_height? float --- @param row_min_height? float
@native
function ImGui.TableNextRow(row_flags, row_min_height) function ImGui.TableNextRow(row_flags, row_min_height)
if row_flags == nil then row_flags = 0 end if row_flags == nil then row_flags = 0 end
if row_min_height == nil then row_min_height = 0.0 end if row_min_height == nil then row_min_height = 0.0 end
@@ -2288,6 +2301,7 @@ function ImGui.TableNextRow(row_flags, row_min_height)
end end
-- [Internal] Only called by TableNextRow() -- [Internal] Only called by TableNextRow()
@native
function ImGui.TableBeginRow(table_) function ImGui.TableBeginRow(table_)
local window = table_.InnerWindow local window = table_.InnerWindow
IM_ASSERT(not table_.IsInsideRow) IM_ASSERT(not table_.IsInsideRow)
@@ -2332,6 +2346,7 @@ end
local TableEndRow_RowMin, TableEndRow_RowMax = ImVec2(), ImVec2() local TableEndRow_RowMin, TableEndRow_RowMax = ImVec2(), ImVec2()
-- [Internal] Called by TableNextRow() -- [Internal] Called by TableNextRow()
@native
function ImGui.TableEndRow(table_) function ImGui.TableEndRow(table_)
local g = GImGui local g = GImGui
local window = g.CurrentWindow local window = g.CurrentWindow
@@ -2509,6 +2524,7 @@ function ImGui.TableGetColumnIndex()
end end
-- [Public] Append into a specific column -- [Public] Append into a specific column
@native
function ImGui.TableSetColumnIndex(column_n) function ImGui.TableSetColumnIndex(column_n)
local g = GImGui local g = GImGui
local table_ = g.CurrentTable local table_ = g.CurrentTable
@@ -2610,7 +2626,21 @@ function ImGui.TableBeginCell(table_, column_n)
--IM_ASSERT(table.DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP) --IM_ASSERT(table.DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP)
else else
-- FIXME-TABLE: Could avoid this if draw channel is dummy channel? -- FIXME-TABLE: Could avoid this if draw channel is dummy channel?
ImGui.SetWindowClipRectBeforeSetChannel(window, column.ClipRect) -- [Luau] inline ImGui.SetWindowClipRectBeforeSetChannel(window, column.ClipRect)
local cr = column.ClipRect
local x1, y1, x2, y2 = cr.Min.x, cr.Min.y, cr.Max.x, cr.Max.y
local wcr = window.ClipRect
wcr.Min.x = x1; wcr.Min.y = y1; wcr.Max.x = x2; wcr.Max.y = y2
local draw_list = window.DrawList
local hcr = draw_list._CmdHeader.ClipRect
hcr.x = x1; hcr.y = y1; hcr.z = x2; hcr.w = y2
local stack = draw_list._ClipRectStack
local top = stack.Data[stack.Size]
if top ~= nil then
top.x = x1; top.y = y1; top.z = x2; top.w = y2
else
stack.Data[stack.Size] = ImVec4(x1, y1, x2, y2)
end
local channel = column.DrawChannelCurrent local channel = column.DrawChannelCurrent
if splitter._Current ~= channel then if splitter._Current ~= channel then
splitter:SetCurrentChannel(window.DrawList, channel) splitter:SetCurrentChannel(window.DrawList, channel)
@@ -2669,6 +2699,7 @@ end
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
-- Maximum column content width given current layout. Use column.MinX so this value differs on a per-column basis. -- Maximum column content width given current layout. Use column.MinX so this value differs on a per-column basis.
@native
function ImGui.TableCalcMaxColumnWidth(table_, column_n) function ImGui.TableCalcMaxColumnWidth(table_, column_n)
local column = table_.Columns[column_n] local column = table_.Columns[column_n]
local max_width = FLT_MAX local max_width = FLT_MAX
@@ -2696,6 +2727,7 @@ function ImGui.TableCalcMaxColumnWidth(table_, column_n)
end end
-- Note this is meant to be stored in column.WidthAuto, please generally use the WidthAuto field -- Note this is meant to be stored in column.WidthAuto, please generally use the WidthAuto field
@native
function ImGui.TableGetColumnWidthAuto(table_, column) function ImGui.TableGetColumnWidthAuto(table_, column)
local content_width_body = mathMax(column.ContentMaxXFrozen, column.ContentMaxXUnfrozen) - column.WorkMinX local content_width_body = mathMax(column.ContentMaxXFrozen, column.ContentMaxXUnfrozen) - column.WorkMinX
local content_width_headers = column.ContentMaxXHeadersIdeal - column.WorkMinX local content_width_headers = column.ContentMaxXHeadersIdeal - column.WorkMinX
@@ -2931,6 +2963,7 @@ end
-- - FreezeRows --> 2+D+N*2 (unless scrolling value is zero) -- - FreezeRows --> 2+D+N*2 (unless scrolling value is zero)
-- - FreezeRows || FreezeColumns --> 3+D+N*2 (unless scrolling value is zero) -- - FreezeRows || FreezeColumns --> 3+D+N*2 (unless scrolling value is zero)
-- Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0. -- Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0.
@native
function ImGui.TableSetupDrawChannels(table_) function ImGui.TableSetupDrawChannels(table_)
local freeze_row_multiplier = (table_.FreezeRowsCount > 0) and 2 or 1 local freeze_row_multiplier = (table_.FreezeRowsCount > 0) and 2 or 1
local channels_for_row = (band(table_.Flags, ImGuiTableFlags.NoClip) ~= 0) and 1 or table_.ColumnsEnabledCount local channels_for_row = (band(table_.Flags, ImGuiTableFlags.NoClip) ~= 0) and 1 or table_.ColumnsEnabledCount
@@ -3003,7 +3036,7 @@ end
-- Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd. -- Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd.
-- --
-- This function is particularly tricky to understand.. take a breath. -- This function is particularly tricky to understand.. take a breath.
-- (Lua: splitter channel n lives in splitter._Channels.Data[n + 1]; bit arrays are Lua sets) -- [Port] (Lua: splitter channel n lives in splitter._Channels.Data[n + 1]; bit arrays are Lua sets)
local TableMergeDrawChannels_MergeGroups = {} local TableMergeDrawChannels_MergeGroups = {}
for n = 0, 3 do for n = 0, 3 do
TableMergeDrawChannels_MergeGroups[n] = { ClipRect = ImRect(), ChannelsCount = 0, ChannelsMask = {} } TableMergeDrawChannels_MergeGroups[n] = { ClipRect = ImRect(), ChannelsCount = 0, ChannelsMask = {} }
@@ -3112,7 +3145,7 @@ function ImGui.TableMergeDrawChannels(table_)
local merge_channels_count = merge_groups[merge_group_n].ChannelsCount local merge_channels_count = merge_groups[merge_group_n].ChannelsCount
if merge_channels_count ~= 0 then if merge_channels_count ~= 0 then
local merge_group = merge_groups[merge_group_n] local merge_group = merge_groups[merge_group_n]
local merge_clip_rect = Rect(merge_group.ClipRect) local merge_clip_rect = TableMergeDrawChannels_merge_clip_rect; ImRect_Copy(merge_clip_rect, merge_group.ClipRect) -- [Luau] scratch copy
-- Extend outer-most clip limits to match those of host, so draw calls can be merged even if -- Extend outer-most clip limits to match those of host, so draw calls can be merged even if
-- outer-most columns have some outer padding offsetting them from their parent ClipRect. -- outer-most columns have some outer padding offsetting them from their parent ClipRect.
@@ -3301,7 +3334,7 @@ end
-- changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, -- changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting,
-- else you may wastefully sort your data every frame! -- else you may wastefully sort your data every frame!
-- Lifetime: don't hold on this table over multiple frames or past any subsequent call to BeginTable()! -- Lifetime: don't hold on this table over multiple frames or past any subsequent call to BeginTable()!
-- PORT: Specs is a 1-based Lua array. -- [Port] Specs is a 1-based Lua array.
function ImGui.TableGetSortSpecs() function ImGui.TableGetSortSpecs()
local g = GImGui local g = GImGui
local table_ = g.CurrentTable local table_ = g.CurrentTable
@@ -3393,7 +3426,7 @@ function ImGui.TableSortSpecsSanitize(table_)
-- Clear SortOrder from hidden column and verify that there's no gap or duplicate. -- Clear SortOrder from hidden column and verify that there's no gap or duplicate.
local sort_order_count = 0 local sort_order_count = 0
local sort_order_set = {} -- C++: ImU64 sort_order_mask local sort_order_set = {} -- [Port] C++: ImU64 sort_order_mask
local sort_order_dup = false local sort_order_dup = false
for column_n = 0, table_.ColumnsCount - 1 do for column_n = 0, table_.ColumnsCount - 1 do
local column = table_.Columns[column_n] local column = table_.Columns[column_n]
@@ -3408,7 +3441,7 @@ function ImGui.TableSortSpecsSanitize(table_)
end end
end end
-- need_fix_linearize: (1 << count) != (mask + 1) <=> the set of sort orders isn't exactly {0..count-1} -- [Port] need_fix_linearize: (1 << count) != (mask + 1) <=> the set of sort orders isn't exactly {0..count-1}
local need_fix_linearize = sort_order_dup local need_fix_linearize = sort_order_dup
for n = 0, sort_order_count - 1 do for n = 0, sort_order_count - 1 do
if not sort_order_set[n] then need_fix_linearize = true end if not sort_order_set[n] then need_fix_linearize = true end
@@ -4592,7 +4625,7 @@ function ImGui.TableRemove(table_)
end end
-- Free up/compact internal Table buffers for when it gets unused -- Free up/compact internal Table buffers for when it gets unused
-- Overloads: (ImGuiTable) / (ImGuiTableTempData) -- [Port] Overloads: (ImGuiTable) / (ImGuiTableTempData)
function ImGui.TableGcCompactTransientBuffers(t) function ImGui.TableGcCompactTransientBuffers(t)
if not t then return end if not t then return end
if t.TableIndex ~= nil then -- ImGuiTableTempData if t.TableIndex ~= nil then -- ImGuiTableTempData
@@ -4670,7 +4703,7 @@ end
-- - EndColumns() -- - EndColumns()
-- - Columns() -- - Columns()
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
-- (Lua: columns.Columns is an ImVector, column n lives in .Data[n + 1]) -- [Port] (Lua: columns.Columns is an ImVector, column n lives in .Data[n + 1])
function ImGui.GetColumnIndex() function ImGui.GetColumnIndex()
local window = ImGui.GetCurrentWindowRead() local window = ImGui.GetCurrentWindowRead()
@@ -5086,4 +5119,4 @@ function ImGui.Columns(columns_count, id, borders)
end end
end end
return true -- [Roblox] ModuleScripts must return exactly one value return true -- [Port] [Roblox] ModuleScripts must return exactly one value
+356 -202
View File
File diff suppressed because it is too large. Load diff
+17 -4
View File
@@ -1,8 +1,8 @@
--- Dear ImGui --- 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! -- [Port] ALL TABLES IN THIS FILE ARE 1-BASED!
-- Avoids table creation when possible -- [Port] Avoids table creation when possible
-- [DEAR IMGUI] -- [DEAR IMGUI]
-- This is a slightly modified version of stb_rect_pack.h 1.01. -- This is a slightly modified version of stb_rect_pack.h 1.01.
@@ -105,6 +105,7 @@ local STBRP__PREV_LINK_TYPE = {
--- @return stbrp_rect --- @return stbrp_rect
--- @nodiscard --- @nodiscard
@native
local function stbrp_rect() local function stbrp_rect()
return { return {
-- reserved for your use: -- reserved for your use:
@@ -128,6 +129,7 @@ end
--- @return stbrp_node --- @return stbrp_node
--- @nodiscard --- @nodiscard
@native
local function stbrp_node() local function stbrp_node()
return { return {
x = 0, x = 0,
@@ -149,6 +151,7 @@ end
--- @return stbrp_context --- @return stbrp_context
--- @nodiscard --- @nodiscard
@native
local function stbrp_context() local function stbrp_context()
return { return {
width = 0, width = 0,
@@ -171,6 +174,7 @@ end
--- @field prev_link_type? int --- @field prev_link_type? int
--- @return stbrp__findresult --- @return stbrp__findresult
@native
local function stbrp__findresult() local function stbrp__findresult()
return { return {
x = 0, x = 0,
@@ -191,6 +195,7 @@ end
-- If you call init again, this will be reset to the default. -- If you call init again, this will be reset to the default.
--- @param context stbrp_context --- @param context stbrp_context
--- @param heuristic int --- @param heuristic int
@native
local function stbrp_setup_heuristic(context, heuristic) local function stbrp_setup_heuristic(context, heuristic)
if context.init_mode == STBRP__INIT_skyline then if context.init_mode == STBRP__INIT_skyline then
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight or heuristic == STBRP_HEURISTIC_Skyline.BF_sortHeight) STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight or heuristic == STBRP_HEURISTIC_Skyline.BF_sortHeight)
@@ -205,6 +210,7 @@ end
-- If you call init again, this will be reset to the default (false). -- If you call init again, this will be reset to the default (false).
--- @param context stbrp_context --- @param context stbrp_context
--- @param allow_out_of_mem boolean --- @param allow_out_of_mem boolean
@native
local function stbrp_setup_allow_out_of_mem(context, allow_out_of_mem) local function stbrp_setup_allow_out_of_mem(context, allow_out_of_mem)
if allow_out_of_mem then if allow_out_of_mem then
-- if it's ok to run out of memory, then don't bother aligning them; -- if it's ok to run out of memory, then don't bother aligning them;
@@ -248,6 +254,7 @@ end
--- @param height int --- @param height int
--- @param nodes stbrp_node[] --- @param nodes stbrp_node[]
--- @param num_nodes int --- @param num_nodes int
@native
function stbrp_init_target(context, width, height, nodes, num_nodes) function stbrp_init_target(context, width, height, nodes, num_nodes)
for i = 1, num_nodes - 1 do for i = 1, num_nodes - 1 do
nodes[i].next = nodes[i + 1] nodes[i].next = nodes[i + 1]
@@ -272,12 +279,13 @@ function stbrp_init_target(context, width, height, nodes, num_nodes)
end end
-- find minimum y position if it starts at x1 -- find minimum y position if it starts at x1
-- Returns (min_y, waste_area) -- [Port] Returns (min_y, waste_area)
--- @param c stbrp_context --- @param c stbrp_context
--- @param first stbrp_node --- @param first stbrp_node
--- @param x0 int --- @param x0 int
--- @param width int --- @param width int
--- @return int, int --- @return int, int
@native
local function stbrp__skyline_find_min_y(c, first, x0, width) local function stbrp__skyline_find_min_y(c, first, x0, width)
local node = first local node = first
local x1 = x0 + width local x1 = x0 + width
@@ -325,6 +333,7 @@ end
--- @param width int --- @param width int
--- @param height int --- @param height int
--- @return stbrp__findresult --- @return stbrp__findresult
@native
local function stbrp__skyline_find_best_pos(c, width, height) local function stbrp__skyline_find_best_pos(c, width, height)
local best_waste = bit32.lshift(1, 30) local best_waste = bit32.lshift(1, 30)
local best_x = 0 local best_x = 0
@@ -454,6 +463,7 @@ end
--- @param width int --- @param width int
--- @param height int --- @param height int
--- @return stbrp__findresult --- @return stbrp__findresult
@native
local function stbrp__skyline_pack_rectangle(context, width, height) local function stbrp__skyline_pack_rectangle(context, width, height)
-- find best position according to heuristic -- find best position according to heuristic
local res = stbrp__skyline_find_best_pos(context, width, height) local res = stbrp__skyline_find_best_pos(context, width, height)
@@ -522,6 +532,7 @@ end
--- @param b stbrp_rect --- @param b stbrp_rect
--- @return bool --- @return bool
--- @package --- @package
@native
local function rect_height_compare(a, b) local function rect_height_compare(a, b)
if a.h > b.h then if a.h > b.h then
return true return true
@@ -536,6 +547,7 @@ end
--- @param b stbrp_rect --- @param b stbrp_rect
--- @return bool --- @return bool
--- @package --- @package
@native
local function rect_original_order(a, b) local function rect_original_order(a, b)
return a.was_packed < b.was_packed return a.was_packed < b.was_packed
end end
@@ -567,6 +579,7 @@ end
--- @param rects stbrp_rect[] --- @param rects stbrp_rect[]
--- @param num_rects int --- @param num_rects int
--- @return int --- @return int
@native
local function stbrp_pack_rects(context, rects, num_rects) local function stbrp_pack_rects(context, rects, num_rects)
local all_rects_packed = 1 local all_rects_packed = 1
+6 -6
View File
@@ -1,5 +1,5 @@
--- Dear ImGui --- Dear ImGui
-- This is a Lua port of original `imstb_textedit.h` -- [Port] This is a Lua port of original `imstb_textedit.h`
-- [DEAR IMGUI] -- [DEAR IMGUI]
-- This is a slightly modified version of stb_textedit.h 1.14. -- This is a slightly modified version of stb_textedit.h 1.14.
@@ -38,7 +38,7 @@
-- --
-- Uses the C runtime function 'memmove', which you can override -- Uses the C runtime function 'memmove', which you can override
-- by defining IMSTB_TEXTEDIT_memmove before the implementation. -- by defining IMSTB_TEXTEDIT_memmove before the implementation.
-- (In this port: ImStb.TEXTEDIT_memmove.) -- [Port] (In this port: ImStb.TEXTEDIT_memmove.)
-- --
-- --
-- VERSION HISTORY -- VERSION HISTORY
@@ -216,7 +216,7 @@
-- efficient, but it's not horrible on modern computers. But you wouldn't -- efficient, but it's not horrible on modern computers. But you wouldn't
-- want to edit million-line files with it. -- want to edit million-line files with it.
-- ALL TABLES IN THIS FILE ARE 1-BASED! -- [Port] ALL TABLES IN THIS FILE ARE 1-BASED!
-- Character Indexing: -- Character Indexing:
-- idx=n, the n'th char (1-based) -- idx=n, the n'th char (1-based)
-- Cursor Indexing: -- Cursor Indexing:
@@ -455,7 +455,7 @@ end
local stb_text_locate_coord do local stb_text_locate_coord do
-- only create once, reuse later -- [Port] only create once, reuse later
local r = StbTexteditRow() local r = StbTexteditRow()
--- traverse the layout to locate the nearest character to a display position --- traverse the layout to locate the nearest character to a display position
@@ -964,7 +964,7 @@ function stb_textedit_key(str, state, key)
if not is_page and state.single_line then if not is_page and state.single_line then
-- on windows, up&down in single-line behave like left&right -- 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)) 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 end
if sel then if sel then
@@ -1037,7 +1037,7 @@ function stb_textedit_key(str, state, key)
if not is_page and state.single_line then if not is_page and state.single_line then
-- on windows, up&down become left&right -- on windows, up&down become left&right
key = bit32.bor(STB_TEXTEDIT_K_LEFT, bit32.band(key, STB_TEXTEDIT_K_SHIFT)) 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 end
if sel then if sel then
+196 -50
View File
@@ -1,5 +1,5 @@
--- Dear ImGui --- Dear ImGui
-- This is a Lua port of original `imstb_truetype.h` -- [Port] This is a Lua port of original `imstb_truetype.h`
-- [DEAR IMGUI] -- [DEAR IMGUI]
-- This is a slightly modified version of stb_truetype.h 1.26. -- This is a slightly modified version of stb_truetype.h 1.26.
@@ -76,7 +76,7 @@
-- accurately measures pixel coverage for anti-aliasing, except in the case -- accurately measures pixel coverage for anti-aliasing, except in the case
-- where multiple shapes overlap, in which case it overestimates the AA pixel -- where multiple shapes overlap, in which case it overestimates the AA pixel
-- coverage. Thus, anti-aliasing of intersecting shapes may look wrong. -- coverage. Thus, anti-aliasing of intersecting shapes may look wrong.
-- (This port only implements the new rasterizer.) -- [Port] (This port only implements the new rasterizer.)
-- --
-- ADDITIONAL DOCUMENTATION -- ADDITIONAL DOCUMENTATION
-- --
@@ -168,7 +168,7 @@ local stbtt_MakeGlyphBitmapSubpixelPrefilter
local stbtt_GetFontVMetrics local stbtt_GetFontVMetrics
local stbtt__GetGlyphInfoT2 local stbtt__GetGlyphInfoT2
local stbtt__GetGlyphShapeT2 local stbtt__GetGlyphShapeT2
local stbtt_GetGlyphShape local stbtt_GetGlyphShape, stbtt_GetGlyphShapeUncached
local stbtt_GetGlyphBitmapBox local stbtt_GetGlyphBitmapBox
local stbtt_GetGlyphBitmapBoxSubpixel local stbtt_GetGlyphBitmapBoxSubpixel
local stbtt_GetGlyphHMetrics local stbtt_GetGlyphHMetrics
@@ -194,7 +194,7 @@ local STBTT_MS_EID = { -- encodingID for STBTT_PLATFORM_ID_MICROSOFT
UNICODE_FULL = 10 UNICODE_FULL = 10
} }
-- original enum doesn't have a name, so we name it -- [Port] original enum doesn't have a name, so we name it
--- @enum STBTT_VTX --- @enum STBTT_VTX
local STBTT_VTX = { local STBTT_VTX = {
MOVE = 1, MOVE = 1,
@@ -213,7 +213,8 @@ local STBTT_fabs = math.abs
local STBTT_ifloor = math.floor local STBTT_ifloor = math.floor
local STBTT_iceil = math.ceil local STBTT_iceil = math.ceil
local trunc = function(x) @native
local function trunc(x)
if x >= 0 then if x >= 0 then
return math.floor(x) return math.floor(x)
else else
@@ -221,6 +222,7 @@ local trunc = function(x)
end end
end end
@native
local function STBTT__NOTUSED(_) return end local function STBTT__NOTUSED(_) return end
--- @alias stbtt_int32 int --- @alias stbtt_int32 int
@@ -243,6 +245,7 @@ local unsigned_char = stbtt_uint8
--- @param initial_offset? int --- @param initial_offset? int
--- @return stbtt__buf --- @return stbtt__buf
--- @nodiscard --- @nodiscard
@native
local function stbtt__buf(initial_offset) local function stbtt__buf(initial_offset)
return { return {
data = nil, data = nil,
@@ -277,6 +280,7 @@ end
--- @field fdselect stbtt__buf # map from glyph to fontdict --- @field fdselect stbtt__buf # map from glyph to fontdict
--- @return stbtt_fontinfo --- @return stbtt_fontinfo
@native
function stbtt_fontinfo() function stbtt_fontinfo()
return { return {
data = nil, data = nil,
@@ -317,6 +321,7 @@ end
--- @return stbtt_vertex --- @return stbtt_vertex
--- @nodiscard --- @nodiscard
@native
local function stbtt_vertex() local function stbtt_vertex()
return { return {
x = nil, x = nil,
@@ -346,6 +351,7 @@ end
--- @return stbtt__csctx --- @return stbtt__csctx
--- @nodiscard --- @nodiscard
@native
local function stbtt__csctx() local function stbtt__csctx()
return { return {
bounds = false, bounds = false,
@@ -400,6 +406,7 @@ end
--- @return stbtt__edge --- @return stbtt__edge
--- @nodiscard --- @nodiscard
@native
local function stbtt__edge() local function stbtt__edge()
return { return {
x0 = nil, x0 = nil,
@@ -414,6 +421,7 @@ end
--- @return stbtt__active_edge --- @return stbtt__active_edge
--- @nodiscard --- @nodiscard
@native
local function stbtt__active_edge() local function stbtt__active_edge()
return { return {
next = nil, next = nil,
@@ -428,8 +436,15 @@ end
--- @return stbtt__active_edge --- @return stbtt__active_edge
--- @nodiscard --- @nodiscard
local active_pool, active_pool_n = {}, 0 -- [Luau] reused per stbtt__rasterize_sorted_edges() call (C: stbtt__hheap)
@native
local function stbtt__new_active(e, off_x, start_point) local function stbtt__new_active(e, off_x, start_point)
local z = stbtt__active_edge() active_pool_n = active_pool_n + 1
local z = active_pool[active_pool_n]
if z == nil then
z = stbtt__active_edge()
active_pool[active_pool_n] = z
end
local dxdy = (e.x1 - e.x0) / (e.y1 - e.y0) local dxdy = (e.x1 - e.x0) / (e.y1 - e.y0)
z.fdx = dxdy z.fdx = dxdy
@@ -453,6 +468,7 @@ end
--- @return stbtt__bitmap --- @return stbtt__bitmap
--- @nodiscard --- @nodiscard
@native
local function stbtt__bitmap() local function stbtt__bitmap()
return { return {
w = nil, w = nil,
@@ -468,6 +484,7 @@ end
--- @return stbtt__point --- @return stbtt__point
--- @nodiscard --- @nodiscard
@native
local function stbtt__point() return { x = nil, y = nil } end local function stbtt__point() return { x = nil, y = nil } end
---------------------------------------------- ----------------------------------------------
@@ -478,6 +495,7 @@ local function stbtt__point() return { x = nil, y = nil } end
--- ---
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__buf_get8(b) local function stbtt__buf_get8(b)
if b.cursor >= b.size then return 0 end if b.cursor >= b.size then return 0 end
local result = b.data[b.offset + b.cursor + 1] local result = b.data[b.offset + b.cursor + 1]
@@ -486,6 +504,7 @@ local function stbtt__buf_get8(b)
end end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__buf_peek8(b) local function stbtt__buf_peek8(b)
if b.cursor >= b.size then return 0 end if b.cursor >= b.size then return 0 end
return b.data[b.offset + b.cursor + 1] return b.data[b.offset + b.cursor + 1]
@@ -493,6 +512,7 @@ end
--- @param b stbtt__buf --- @param b stbtt__buf
--- @param o int --- @param o int
@native
local function stbtt__buf_seek(b, o) local function stbtt__buf_seek(b, o)
STBTT_assert(not (o > b.size or o < 0)) STBTT_assert(not (o > b.size or o < 0))
if o > b.size or o < 0 then if o > b.size or o < 0 then
@@ -504,10 +524,12 @@ end
--- @param b stbtt__buf --- @param b stbtt__buf
--- @param o int --- @param o int
@native
local function stbtt__buf_skip(b, o) local function stbtt__buf_skip(b, o)
stbtt__buf_seek(b, b.cursor + o) stbtt__buf_seek(b, b.cursor + o)
end end
@native
local function stbtt__buf_get(b, n) local function stbtt__buf_get(b, n)
local v = 0 local v = 0
STBTT_assert(n >= 1 and n <= 4) STBTT_assert(n >= 1 and n <= 4)
@@ -522,6 +544,7 @@ end
--- @param offset? int --- @param offset? int
--- @return stbtt__buf --- @return stbtt__buf
--- @nodiscard --- @nodiscard
@native
local function stbtt__new_buf(p, size, offset) local function stbtt__new_buf(p, size, offset)
local r = stbtt__buf(offset) local r = stbtt__buf(offset)
STBTT_assert(size < 0x40000000) STBTT_assert(size < 0x40000000)
@@ -532,8 +555,10 @@ local function stbtt__new_buf(p, size, offset)
end end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__buf_get16(b) return stbtt__buf_get(b, 2) end local function stbtt__buf_get16(b) return stbtt__buf_get(b, 2) end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__buf_get32(b) return stbtt__buf_get(b, 4) end local function stbtt__buf_get32(b) return stbtt__buf_get(b, 4) end
--- @param b stbtt__buf --- @param b stbtt__buf
@@ -541,6 +566,7 @@ local function stbtt__buf_get32(b) return stbtt__buf_get(b, 4) end
--- @param s int --- @param s int
--- @return stbtt__buf --- @return stbtt__buf
--- @nodiscard --- @nodiscard
@native
local function stbtt__buf_range(b, o, s) local function stbtt__buf_range(b, o, s)
local r = stbtt__new_buf(nil, 0) local r = stbtt__new_buf(nil, 0)
if (o < 0 or s < 0 or o > b.size or s > (b.size - o)) then if (o < 0 or s < 0 or o > b.size or s > (b.size - o)) then
@@ -685,15 +711,23 @@ end
--- stbtt_GetNumberOfFonts_internal --- stbtt_GetNumberOfFonts_internal
--- stbtt__get_svg --- stbtt__get_svg
@native
local function ttUSHORT(p, offset) return stbtt_uint16(p[offset + 1] * 256 + p[offset + 2]) end local function ttUSHORT(p, offset) return stbtt_uint16(p[offset + 1] * 256 + p[offset + 2]) end
@native
local function ttSHORT(p, offset) return stbtt_int16(p[offset + 1] * 256 + p[offset + 2]) end local function ttSHORT(p, offset) return stbtt_int16(p[offset + 1] * 256 + p[offset + 2]) end
@native
local function ttULONG(p, offset) return stbtt_uint32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end local function ttULONG(p, offset) return stbtt_uint32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end
@native
local function ttLONG(p, offset) return stbtt_int32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end local function ttLONG(p, offset) return stbtt_int32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end
@native
local function ttBYTE(p, offset) return stbtt_uint8(p[offset + 1]) end local function ttBYTE(p, offset) return stbtt_uint8(p[offset + 1]) end
@native
local function ttCHAR(p, offset) return stbtt_int8(p[offset + 1]) end local function ttCHAR(p, offset) return stbtt_int8(p[offset + 1]) end
@native
local function stbtt_tag4(p, c0, c1, c2, c3, offset) offset = offset or 0; return p[offset + 1] == c0 and p[offset + 2] == c1 and p[offset + 3] == c2 and p[offset + 4] == c3 end local function stbtt_tag4(p, c0, c1, c2, c3, offset) offset = offset or 0; return p[offset + 1] == c0 and p[offset + 2] == c1 and p[offset + 3] == c2 and p[offset + 4] == c3 end
@native
local function stbtt_tag(p, str, offset) local c0, c1, c2, c3 = string.byte(str, 1, 4); return stbtt_tag4(p, c0, c1, c2, c3, offset) end local function stbtt_tag(p, str, offset) local c0, c1, c2, c3 = string.byte(str, 1, 4); return stbtt_tag4(p, c0, c1, c2, c3, offset) end
local function stbtt__isfont(font) local function stbtt__isfont(font)
@@ -793,7 +827,7 @@ local function stbtt_InitFont_internal(info, data, fontstart)
info.fdselect = stbtt__new_buf(nil, 0) info.fdselect = stbtt__new_buf(nil, 0)
-- @TODO this should use size from table (not 512MB) -- @TODO this should use size from table (not 512MB)
info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- PORT: 64MB here instead of 512MB info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- [Port] 64MB here instead of 512MB
local b = info.cff local b = info.cff
-- read the header -- read the header
@@ -884,6 +918,7 @@ end
-- Returns 0 if the character codepoint is not defined in the font. -- Returns 0 if the character codepoint is not defined in the font.
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
--- @param unicode_codepoint int --- @param unicode_codepoint int
@native
function stbtt_FindGlyphIndex(info, unicode_codepoint) function stbtt_FindGlyphIndex(info, unicode_codepoint)
local data = info.data local data = info.data
local index_map = info.index_map local index_map = info.index_map
@@ -989,6 +1024,7 @@ end
--- @param y stbtt_int32 --- @param y stbtt_int32
--- @param cx stbtt_int32 --- @param cx stbtt_int32
--- @param cy stbtt_int32 --- @param cy stbtt_int32
@native
local function stbtt_setvertex(v, vtx_type, x, y, cx, cy) local function stbtt_setvertex(v, vtx_type, x, y, cx, cy)
v.type = vtx_type v.type = vtx_type
v.x = (stbtt_int16)(x) v.x = (stbtt_int16)(x)
@@ -997,6 +1033,7 @@ local function stbtt_setvertex(v, vtx_type, x, y, cx, cy)
v.cy = (stbtt_int16)(cy) v.cy = (stbtt_int16)(cy)
end end
@native
local function stbtt__GetGlyfOffset(info, glyph_index) local function stbtt__GetGlyfOffset(info, glyph_index)
STBTT_assert(info.cff.size == 0) STBTT_assert(info.cff.size == 0)
@@ -1017,6 +1054,7 @@ end
-- Gets the bounding box of the visible part of the glyph, in unscaled coordinates -- Gets the bounding box of the visible part of the glyph, in unscaled coordinates
--- @return integer, integer?, integer?, integer?, integer? --- @return integer, integer?, integer?, integer?, integer?
@native
local function stbtt_GetGlyphBox(info, glyph_index) local function stbtt_GetGlyphBox(info, glyph_index)
local n, x0, y0, x1, y1 local n, x0, y0, x1, y1
@@ -1045,6 +1083,7 @@ end
--- @param scy stbtt_int32 --- @param scy stbtt_int32
--- @param cx stbtt_int32 --- @param cx stbtt_int32
--- @param cy stbtt_int32 --- @param cy stbtt_int32
@native
local function stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy) local function stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy)
if start_off then if start_off then
if was_off then if was_off then
@@ -1069,6 +1108,7 @@ end
--- @param glyph_index int --- @param glyph_index int
--- @return int num_vertices --- @return int num_vertices
--- @return stbtt_vertex[]? vertices --- @return stbtt_vertex[]? vertices
@native
local function stbtt__GetGlyphShapeTT(info, glyph_index) local function stbtt__GetGlyphShapeTT(info, glyph_index)
local data = info.data local data = info.data
local num_vertices local num_vertices
@@ -1084,7 +1124,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index)
if numberOfContours > 0 then if numberOfContours > 0 then
local endPtsOfContours = g + 10 local endPtsOfContours = g + 10
local ins = ttUSHORT(data, endPtsOfContours + numberOfContours * 2) local ins = ttUSHORT(data, endPtsOfContours + numberOfContours * 2)
local points = (endPtsOfContours + numberOfContours * 2 + 2 + ins) + 1 -- 1-based idx local points = (endPtsOfContours + numberOfContours * 2 + 2 + ins) + 1 -- [Port] 1-based idx
local n = 1 + ttUSHORT(data, endPtsOfContours + numberOfContours * 2 - 2) local n = 1 + ttUSHORT(data, endPtsOfContours + numberOfContours * 2 - 2)
local m = n + 2 * numberOfContours -- a loose bound on how many vertices we might need local m = n + 2 * numberOfContours -- a loose bound on how many vertices we might need
@@ -1288,7 +1328,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index)
n = STBTT_sqrt(mtx[3] * mtx[3] + mtx[4] * mtx[4]) n = STBTT_sqrt(mtx[3] * mtx[3] + mtx[4] * mtx[4])
-- Get indexed glyph. -- Get indexed glyph.
comp_num_vertices, comp_verts = stbtt_GetGlyphShape(info, gidx) comp_num_vertices, comp_verts = stbtt_GetGlyphShapeUncached(info, gidx) -- [Luau] transformed in place below: must be a fresh copy
if comp_num_vertices > 0 then if comp_num_vertices > 0 then
-- Transform vertices. -- Transform vertices.
for i = 1, comp_num_vertices do for i = 1, comp_num_vertices do
@@ -1304,7 +1344,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index)
end end
-- Append vertices. -- Append vertices.
if num_vertices == 0 then -- LUA: No malloc if num_vertices == 0 then -- [Port] No malloc
vertices = comp_verts vertices = comp_verts
else else
for i = 1, comp_num_vertices do for i = 1, comp_num_vertices do
@@ -1454,7 +1494,7 @@ local function stbtt__run_charstring(info, glyph_index, c)
local has_subrs = 0 local has_subrs = 0
local clear_stack local clear_stack
local s = {} -- size = 48, 0-based local s = {} -- [Port] size = 48, 0-based
local subr_stack = {} for i = 1, 10 do subr_stack[i] = stbtt__buf() end local subr_stack = {} for i = 1, 10 do subr_stack[i] = stbtt__buf() end
@@ -1765,7 +1805,8 @@ end
-- its x,y, using cx,cy as the bezier control point. -- its x,y, using cx,cy as the bezier control point.
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
--- @param glyph_index int --- @param glyph_index int
function stbtt_GetGlyphShape(info, glyph_index) @native
function stbtt_GetGlyphShapeUncached(info, glyph_index)
if info.cff.size == 0 then if info.cff.size == 0 then
return stbtt__GetGlyphShapeTT(info, glyph_index) return stbtt__GetGlyphShapeTT(info, glyph_index)
else else
@@ -1773,11 +1814,32 @@ function stbtt_GetGlyphShape(info, glyph_index)
end end
end end
@native
function stbtt_GetGlyphShape(info, glyph_index)
-- [Luau] shapes don't depend on the size: cache them per font (baking a new size re-used to re-parse every glyph).
-- Callers only read the vertices (stbtt_FreeShape is a no-op).
local cache = info._ShapeCache
if cache == nil then cache = {}; info._ShapeCache = cache end
local e = cache[glyph_index]
if e == nil then
local n, v
if info.cff.size == 0 then
n, v = stbtt__GetGlyphShapeTT(info, glyph_index)
else
n, v = stbtt__GetGlyphShapeT2(info, glyph_index)
end
e = { n, v }
cache[glyph_index] = e
end
return e[1], e[2]
end
-- leftSideBearing is the offset from the current horizontal position to the left edge of the character -- leftSideBearing is the offset from the current horizontal position to the left edge of the character
-- advanceWidth is the offset from the current horizontal position to the next horizontal position -- advanceWidth is the offset from the current horizontal position to the next horizontal position
-- these are expressed in unscaled coordinates -- these are expressed in unscaled coordinates
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
--- @param glyph_index int --- @param glyph_index int
@native
function stbtt_GetGlyphHMetrics(info, glyph_index) function stbtt_GetGlyphHMetrics(info, glyph_index)
local numOfLongHorMetrics = ttUSHORT(info.data, info.hhea + 34) local numOfLongHorMetrics = ttUSHORT(info.data, info.hhea + 34)
@@ -1800,6 +1862,7 @@ end
-- these are expressed in unscaled coordinates, so you must multiply by -- these are expressed in unscaled coordinates, so you must multiply by
-- the scale factor for a given size -- the scale factor for a given size
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
@native
function stbtt_GetFontVMetrics(info) function stbtt_GetFontVMetrics(info)
local ascent = ttSHORT(info.data, info.hhea + 4) local ascent = ttSHORT(info.data, info.hhea + 4)
local descent = ttSHORT(info.data, info.hhea + 6) local descent = ttSHORT(info.data, info.hhea + 6)
@@ -1816,6 +1879,7 @@ end
-- so if you prefer to measure height by the ascent only, use a similar calculation. -- so if you prefer to measure height by the ascent only, use a similar calculation.
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
--- @param height float --- @param height float
@native
function stbtt_ScaleForPixelHeight(info, height) function stbtt_ScaleForPixelHeight(info, height)
local fheight = ttSHORT(info.data, info.hhea + 4) - ttSHORT(info.data, info.hhea + 6) local fheight = ttSHORT(info.data, info.hhea + 4) - ttSHORT(info.data, info.hhea + 6)
return height / fheight return height / fheight
@@ -1836,6 +1900,7 @@ end
--- @param scale_y float --- @param scale_y float
--- @param shift_x float --- @param shift_x float
--- @param shift_y float --- @param shift_y float
@native
function stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, shift_x, shift_y) function stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, shift_x, shift_y)
local n, x0, y0, x1, y1 = stbtt_GetGlyphBox(font, glyph) local n, x0, y0, x1, y1 = stbtt_GetGlyphBox(font, glyph)
@@ -1866,6 +1931,7 @@ end
--- @param glyph int --- @param glyph int
--- @param scale_x float --- @param scale_x float
--- @param scale_y float --- @param scale_y float
@native
function stbtt_GetGlyphBitmapBox(font, glyph, scale_x, scale_y) function stbtt_GetGlyphBitmapBox(font, glyph, scale_x, scale_y)
return stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, 0.0, 0.0) return stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, 0.0, 0.0)
end end
@@ -1893,6 +1959,7 @@ end
--- @param y0 float --- @param y0 float
--- @param x1 float --- @param x1 float
--- @param y1 float --- @param y1 float
@native
local function stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1) local function stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1)
if y0 == y1 then return end if y0 == y1 then return end
STBTT_assert(y0 < y1) STBTT_assert(y0 < y1)
@@ -1934,6 +2001,7 @@ end
--- @param height float --- @param height float
--- @param top_width float --- @param top_width float
--- @param bottom_width float --- @param bottom_width float
@native
local function stbtt__sized_trapezoid_area(height, top_width, bottom_width) local function stbtt__sized_trapezoid_area(height, top_width, bottom_width)
STBTT_assert(top_width >= 0) STBTT_assert(top_width >= 0)
STBTT_assert(bottom_width >= 0) STBTT_assert(bottom_width >= 0)
@@ -1945,12 +2013,14 @@ end
--- @param tx1 float --- @param tx1 float
--- @param bx0 float --- @param bx0 float
--- @param bx1 float --- @param bx1 float
@native
local function stbtt__position_trapezoid_area(height, tx0, tx1, bx0, bx1) local function stbtt__position_trapezoid_area(height, tx0, tx1, bx0, bx1)
return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0) return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0)
end end
--- @param height float --- @param height float
--- @param width float --- @param width float
@native
local function stbtt__sized_triangle_area(height, width) local function stbtt__sized_triangle_area(height, width)
return height * width / 2 return height * width / 2
end end
@@ -1960,6 +2030,7 @@ end
--- @param len int --- @param len int
--- @param e stbtt__active_edge --- @param e stbtt__active_edge
--- @param y_top float --- @param y_top float
@native
local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_top) local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_top)
local y_bottom = y_top + 1 local y_bottom = y_top + 1
@@ -1972,11 +2043,25 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t
if e.fdx == 0 then if e.fdx == 0 then
local x0 = e.fx local x0 = e.fx
if x0 < len then if x0 < len then
-- [Luau] the stbtt__handle_clipped_edge() calls, inlined (every edge of pixel fonts like ProggyClean is
-- vertical): x0 == x1, so clipping to sy/ey keeps x, and the same arithmetic gives the same results
local y0, y1 = y_top, y_bottom
local sy, ey = e.sy, e.ey
if y0 <= ey and y1 >= sy then
if y0 < sy then y0 = sy end
if y1 > ey then y1 = ey end
local height = e.direction * (y1 - y0)
if x0 >= 0 then if x0 >= 0 then
stbtt__handle_clipped_edge(scanline, trunc(x0), e, x0, y_top, x0, y_bottom) local x = math.floor(x0) -- trunc(x0)
stbtt__handle_clipped_edge(scanline_fill, trunc(x0) + 1, e, x0, y_top, x0, y_bottom) if x0 <= x then
scanline[x] = scanline[x] + height
else else
stbtt__handle_clipped_edge(scanline_fill, 0, e, x0, y_top, x0, y_bottom) scanline[x] = scanline[x] + height * (1 - ((x0 - x) + (x0 - x)) / 2)
end
scanline_fill[x + 1] = scanline_fill[x + 1] + height
else
scanline_fill[0] = scanline_fill[0] + height
end
end end
end end
else else
@@ -2182,11 +2267,14 @@ end
--- @param vsubsample int --- @param vsubsample int
--- @param off_x int --- @param off_x int
--- @param off_y int --- @param off_y int
local rasterize_scanline, rasterize_scanline2 = {}, {} -- [Luau] reused: fully cleared per scanline below
@native
local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y) local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y)
local active = nil local active = nil
local scanline = {} -- size = result.w, 0-based active_pool_n = 0 -- every active edge of the previous call is dead
local scanline2 = {} -- size = result.w + 1, 0-based local scanline = rasterize_scanline -- [Port] size = result.w, 0-based
local scanline2 = rasterize_scanline2 -- [Port] size = result.w + 1, 0-based
STBTT__NOTUSED(vsubsample) STBTT__NOTUSED(vsubsample)
@@ -2244,20 +2332,18 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of
do do
local sum = 0 local sum = 0
local pixels, base = result.pixels, j * result.stride + 1
for i = 0, result.w - 1 do for i = 0, result.w - 1 do
local k
local m
sum = sum + scanline2[i] sum = sum + scanline2[i]
k = scanline[i] + sum -- [Luau] k >= 0: trunc == floor, and m is already 0..255 (unsigned_char() is a no-op)
k = STBTT_fabs(k) * 255 + 0.5 local m = math.floor(math.abs(scanline[i] + sum) * 255 + 0.5)
m = trunc(k)
if m > 255 then m = 255 end if m > 255 then m = 255 end
result.pixels[j * result.stride + i + 1] = unsigned_char(m) pixels[base + i] = m
end end
end end
-- advance all the edges -- advance all the edges
step = active local step = active
while step do while step do
step.fx = step.fx + step.fdx -- advance to position for current scanline step.fx = step.fx + step.fdx -- advance to position for current scanline
step = step.next -- advance through list step = step.next -- advance through list
@@ -2271,16 +2357,53 @@ end
--- @param a stbtt__edge --- @param a stbtt__edge
--- @param b stbtt__edge --- @param b stbtt__edge
local STBTT__COMPARE = function(a, b) local STBTT__COMPARE = function(a, b)
if a.y0 == nil then return false end -- sentinels on the back if a.y0 == nil then return false end -- [Port] sentinels on the back
if b.y0 == nil then return true end if b.y0 == nil then return true end
return a.y0 < b.y0 return a.y0 < b.y0
end end
--- @param p stbtt__edge[] --- @param p stbtt__edge[]
@native
local function stbtt__sort_edges(p) local function stbtt__sort_edges(p)
STBTT_sort(p, STBTT__COMPARE) STBTT_sort(p, STBTT__COMPARE)
end end
-- [Luau] sorts p[lo..hi] by y0 without a comparator callback (like upstream's stbtt__sort_edges_quicksort + ins_sort)
@native
local function stbtt__sort_edges_range(p, lo, hi)
while hi - lo > 12 do
-- median of three -> p[lo]
local m = math.floor((lo + hi) / 2)
local a, b, c = p[lo], p[m], p[hi]
if b.y0 < a.y0 then a, b = b, a end
if c.y0 < b.y0 then b, c = c, b; if b.y0 < a.y0 then a, b = b, a end end
p[lo], p[m], p[hi] = b, a, c
local pivot = p[lo].y0
local i, j = lo + 1, hi
while true do
while p[i].y0 < pivot do i = i + 1 end
while pivot < p[j].y0 do j = j - 1 end
if i >= j then break end
p[i], p[j] = p[j], p[i]
i = i + 1; j = j - 1
end
p[lo], p[j] = p[j], p[lo]
-- recurse into the smaller side, loop on the larger
if j - lo < hi - j then
stbtt__sort_edges_range(p, lo, j - 1); lo = j + 1
else
stbtt__sort_edges_range(p, j + 1, hi); hi = j - 1
end
end
for i = lo + 1, hi do
local t = p[i]
local y = t.y0
local j = i - 1
while j >= lo and p[j].y0 > y do p[j + 1] = p[j]; j = j - 1 end
p[j + 1] = t
end
end
--- @param result stbtt__bitmap --- @param result stbtt__bitmap
--- @param pts stbtt__point[] --- @param pts stbtt__point[]
--- @param wcount int[] --- @param wcount int[]
@@ -2292,6 +2415,8 @@ end
--- @param off_x int --- @param off_x int
--- @param off_y int --- @param off_y int
--- @param invert bool --- @param invert bool
local rasterize_edges = {}
@native
local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, shift_x, shift_y, off_x, off_y, invert) local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, shift_x, shift_y, off_x, off_y, invert)
local y_scale_inv = (invert) and -scale_y or scale_y local y_scale_inv = (invert) and -scale_y or scale_y
local vsubsample = 1 -- STBTT_RASTERIZER_VERSION == 2 local vsubsample = 1 -- STBTT_RASTERIZER_VERSION == 2
@@ -2303,7 +2428,13 @@ local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y,
n = n + wcount[i] n = n + wcount[i]
end end
local e = {} for i = 1, n + 1 do e[i] = stbtt__edge() end -- add an extra one as a sentinel -- [Luau] edges reused across calls; unused entries are sentinels (y0 = nil) like the unfilled ones upstream
local e = rasterize_edges
for i = 1, n + 1 do
local ed = e[i]
if ed == nil then e[i] = stbtt__edge() else ed.y0 = nil; ed.invert = false end
end
for i = n + 2, #e do e[i].y0 = nil end
n = 0 n = 0
local m = 0 local m = 0
@@ -2347,7 +2478,7 @@ local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y,
end end
-- now sort the edges by their highest point (should snap to integer, and then by x) -- now sort the edges by their highest point (should snap to integer, and then by x)
stbtt__sort_edges(e) stbtt__sort_edges_range(e, 1, n) -- [Luau] e[n + 1..] are y0 == nil sentinels, already last
-- now, traverse the scanlines and find the intersections on each scanline, use xor winding rule -- now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y) stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y)
@@ -2357,6 +2488,7 @@ end
--- @param n int --- @param n int
--- @param x float --- @param x float
--- @param y float --- @param y float
@native
local function stbtt__add_point(points, n, x, y) local function stbtt__add_point(points, n, x, y)
if points == nil then return end -- during first pass, it's unallocated if points == nil then return end -- during first pass, it's unallocated
points[n + 1].x = x points[n + 1].x = x
@@ -2375,6 +2507,7 @@ end
--- @param objspace_flatness_squared float --- @param objspace_flatness_squared float
--- @param n int --- @param n int
--- @return int num_points # updated num_points passed in --- @return int num_points # updated num_points passed in
@native
local function stbtt__tesselate_curve(points, num_points, x0, y0, x1, y1, x2, y2, objspace_flatness_squared, n) local function stbtt__tesselate_curve(points, num_points, x0, y0, x1, y1, x2, y2, objspace_flatness_squared, n)
-- midpoint -- midpoint
local mx = (x0 + 2 * x1 + x2) / 4 local mx = (x0 + 2 * x1 + x2) / 4
@@ -2462,6 +2595,8 @@ end
--- @return stbtt__point[]? points --- @return stbtt__point[]? points
--- @return int? num_contours --- @return int? num_contours
--- @return int[]? contour_lengths --- @return int[]? contour_lengths
local flatten_points = {}
@native
local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness)
local points = nil local points = nil
local num_points = 0 local num_points = 0
@@ -2470,9 +2605,12 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness)
local n = 0 local n = 0
local start = 0 local start = 0
-- [Luau] vertex types and the current vertex in locals, stbtt__add_point() inlined (same values)
local VTX_MOVE, VTX_LINE, VTX_CURVE, VTX_CUBIC = STBTT_VTX.MOVE, STBTT_VTX.LINE, STBTT_VTX.CURVE, STBTT_VTX.CUBIC
-- count how many "moves" there are to get the contour count -- count how many "moves" there are to get the contour count
for i = 1, num_verts do for i = 1, num_verts do
if vertices[i].type == STBTT_VTX.MOVE then if vertices[i].type == VTX_MOVE then
n = n + 1 n = n + 1
end end
end end
@@ -2480,19 +2618,21 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness)
local num_contours = n local num_contours = n
if n == 0 then return nil end if n == 0 then return nil end
local contour_lengths = {} -- size = n local contour_lengths = {} -- [Port] size = n
-- make two passes through the points so we don't need to realloc -- make two passes through the points so we don't need to realloc
for pass = 0, 1 do for pass = 0, 1 do
local x, y = 0, 0 local x, y = 0, 0
if pass == 1 then if pass == 1 then
points = {} points = flatten_points -- [Luau] reused across calls (only [1..num_points] is read)
for i = 1, num_points do points[i] = stbtt__point() end for i = #points + 1, num_points do points[i] = stbtt__point() end
end end
num_points = 0 num_points = 0
n = -1 n = -1
for i = 1, num_verts do for i = 1, num_verts do
if vertices[i].type == STBTT_VTX.MOVE then local v = vertices[i]
local vtype = v.type
if vtype == VTX_MOVE then
-- start the next contour -- start the next contour
if n >= 0 then if n >= 0 then
contour_lengths[n + 1] = num_points - start contour_lengths[n + 1] = num_points - start
@@ -2500,30 +2640,30 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness)
n = n + 1 n = n + 1
start = num_points start = num_points
x = vertices[i].x x = v.x
y = vertices[i].y y = v.y
stbtt__add_point(points, num_points, x, y)
num_points = num_points + 1 num_points = num_points + 1
elseif vertices[i].type == STBTT_VTX.LINE then if points then local pt = points[num_points]; pt.x = x; pt.y = y end -- stbtt__add_point()
x = vertices[i].x elseif vtype == VTX_LINE then
y = vertices[i].y x = v.x
stbtt__add_point(points, num_points, x, y) y = v.y
num_points = num_points + 1 num_points = num_points + 1
elseif vertices[i].type == STBTT_VTX.CURVE then if points then local pt = points[num_points]; pt.x = x; pt.y = y end -- stbtt__add_point()
elseif vtype == VTX_CURVE then
num_points = stbtt__tesselate_curve(points, num_points, x, y, num_points = stbtt__tesselate_curve(points, num_points, x, y,
vertices[i].cx, vertices[i].cy, v.cx, v.cy,
vertices[i].x, vertices[i].y, v.x, v.y,
objspace_flatness_squared, 0) objspace_flatness_squared, 0)
x = vertices[i].x x = v.x
y = vertices[i].y y = v.y
elseif vertices[i].type == STBTT_VTX.CUBIC then elseif vtype == VTX_CUBIC then
num_points = stbtt__tesselate_cubic(points, num_points, x, y, num_points = stbtt__tesselate_cubic(points, num_points, x, y,
vertices[i].cx, vertices[i].cy, v.cx, v.cy,
vertices[i].cx1, vertices[i].cy1, v.cx1, v.cy1,
vertices[i].x, vertices[i].y, v.x, v.y,
objspace_flatness_squared, 0) objspace_flatness_squared, 0)
x = vertices[i].x x = v.x
y = vertices[i].y y = v.y
end end
end end
contour_lengths[n + 1] = num_points - start contour_lengths[n + 1] = num_points - start
@@ -2544,6 +2684,7 @@ end
--- @param x_off int --- @param x_off int
--- @param y_off int --- @param y_off int
--- @param invert bool --- @param invert bool
@native
local function stbtt_Rasterize(result, flatness_in_pixels, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert) local function stbtt_Rasterize(result, flatness_in_pixels, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert)
local scale = (scale_x > scale_y) and scale_y or scale_x local scale = (scale_x > scale_y) and scale_y or scale_x
@@ -2571,6 +2712,7 @@ end
--- @param shift_x float --- @param shift_x float
--- @param shift_y float --- @param shift_y float
--- @param glyph int --- @param glyph int
@native
local function stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, glyph) local function stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, glyph)
local num_verts, vertices = stbtt_GetGlyphShape(info, glyph) local num_verts, vertices = stbtt_GetGlyphShape(info, glyph)
local gbm = stbtt__bitmap() local gbm = stbtt__bitmap()
@@ -2624,6 +2766,7 @@ local STBTT__OVER_MASK = STBTT_MAX_OVERSAMPLE - 1
--- @param h int --- @param h int
--- @param stride_in_bytes int --- @param stride_in_bytes int
--- @param kernel_width unsigned_int --- @param kernel_width unsigned_int
@native
local function stbtt__h_prefilter(pixels, w, h, stride_in_bytes, kernel_width) local function stbtt__h_prefilter(pixels, w, h, stride_in_bytes, kernel_width)
local buffer = {} local buffer = {}
local safe_w = w - kernel_width local safe_w = w - kernel_width
@@ -2653,6 +2796,7 @@ end
--- @param h int --- @param h int
--- @param stride_in_bytes int --- @param stride_in_bytes int
--- @param kernel_width unsigned_int --- @param kernel_width unsigned_int
@native
local function stbtt__v_prefilter(pixels, w, h, stride_in_bytes, kernel_width) local function stbtt__v_prefilter(pixels, w, h, stride_in_bytes, kernel_width)
local buffer = {} local buffer = {}
local safe_h = h - kernel_width local safe_h = h - kernel_width
@@ -2679,6 +2823,7 @@ end
--- @param oversample int --- @param oversample int
--- @return float --- @return float
@native
local function stbtt__oversample_shift(oversample) local function stbtt__oversample_shift(oversample)
if oversample == 0 then if oversample == 0 then
return 0.0 return 0.0
@@ -2705,6 +2850,7 @@ end
--- @param prefilter_x int --- @param prefilter_x int
--- @param prefilter_y int --- @param prefilter_y int
--- @param glyph int --- @param glyph int
@native
function stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, prefilter_x, prefilter_y, glyph) function stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, prefilter_x, prefilter_y, glyph)
stbtt_MakeGlyphBitmapSubpixel(info, output, out_w - (prefilter_x - 1), out_h - (prefilter_y - 1), out_stride, scale_x, scale_y, shift_x, shift_y, glyph) stbtt_MakeGlyphBitmapSubpixel(info, output, out_w - (prefilter_x - 1), out_h - (prefilter_y - 1), out_stride, scale_x, scale_y, shift_x, shift_y, glyph)
+13 -14
View File
@@ -1,13 +1,13 @@
--- Dear ImGui --- 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) -- - %x, %X, %nx, %nX (where n is a number)
-- - %d, %nd, %u, %nu (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) -- - length modifiers h, hh, l, ll, I64 on integers: ll/I64 = 64-bit range (doubles: exact only within +-2^53)
-- - %f, %lf (very limited) -- - %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 local _byte = string.byte
@@ -40,7 +40,7 @@ local function hex_digit_to_int(c)
if c >= CHAR_A and c <= CHAR_F then return c - CHAR_A + 10 end if c >= CHAR_A and c <= CHAR_F then return c - CHAR_A + 10 end
end end
-- we force this behavior by default -- [Port] we force this behavior by default
local function clamp_if_overflow(spec, val, is_64) local function clamp_if_overflow(spec, val, is_64)
if spec == CHAR_d or spec == CHAR_x or spec == CHAR_X then if spec == CHAR_d or spec == CHAR_x or spec == CHAR_X then
local max = is_64 and 9223372036854775807 or INT_MAX local max = is_64 and 9223372036854775807 or INT_MAX
@@ -61,7 +61,7 @@ end
--- @param result table # table to store parsed values --- @param result table # table to store parsed values
local function sscanf(buffer, buffer_begin, format, result) local function sscanf(buffer, buffer_begin, format, result)
local p = buffer_begin local p = buffer_begin
local f = 1 -- format_begin local f = 1 -- [Port] format_begin
local format_len = #format local format_len = #format
local assigned = 0 local assigned = 0
local items_matched = 0 local items_matched = 0
@@ -88,10 +88,10 @@ local function sscanf(buffer, buffer_begin, format, result)
break break
end end
-- encountered % in fmt -- [Port] encountered % in fmt
f = f + 1 f = f + 1
-- %% -- [Port] %%
if _byte(format, f, f) == CHAR_PERCENT then if _byte(format, f, f) == CHAR_PERCENT then
if buffer[p] == CHAR_PERCENT then if buffer[p] == CHAR_PERCENT then
p = p + 1 p = p + 1
@@ -103,7 +103,7 @@ local function sscanf(buffer, buffer_begin, format, result)
break break
end end
-- handle optional width -- [Port] handle optional width
local width = 0 local width = 0
while isdigit(_byte(format, f, f)) do while isdigit(_byte(format, f, f)) do
width = width * 10 + _byte(format, f, f) - CHAR_0 width = width * 10 + _byte(format, f, f) - CHAR_0
@@ -113,7 +113,7 @@ local function sscanf(buffer, buffer_begin, format, result)
width = math.huge width = math.huge
end end
-- length modifiers -- [Port] length modifiers
local n_l = 0 local n_l = 0
while _byte(format, f, f) == CHAR_l or _byte(format, f, f) == CHAR_h do 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 if _byte(format, f, f) == CHAR_l then n_l = n_l + 1 end
@@ -133,7 +133,7 @@ local function sscanf(buffer, buffer_begin, format, result)
elseif spec == CHAR_d or spec == CHAR_u then elseif spec == CHAR_d or spec == CHAR_u then
base = 10 base = 10
elseif spec == CHAR_f or spec == CHAR_F then elseif spec == CHAR_f or spec == CHAR_F then
is_float = true -- TODO: distinguish %lf from %f? is_float = true -- [Port] TODO: distinguish %lf from %f?
else else
return items_matched return items_matched
end end
@@ -153,7 +153,7 @@ local function sscanf(buffer, buffer_begin, format, result)
p = p + 1 p = p + 1
end end
-- inf, nan are not handled -- [Port] inf, nan are not handled
local p_start = p local p_start = p
local int_part = 0 local int_part = 0
@@ -181,7 +181,7 @@ local function sscanf(buffer, buffer_begin, format, result)
val = sign * (int_part + frac_part / frac_div) val = sign * (int_part + frac_part / frac_div)
else else
local sign = 1 local sign = 1
-- optional sign -- [Port] optional sign
if base == 10 then if base == 10 then
if buffer[p] == CHAR_PLUS then if buffer[p] == CHAR_PLUS then
p = p + 1 p = p + 1
@@ -200,7 +200,6 @@ local function sscanf(buffer, buffer_begin, format, result)
end end
if p == p_start then if p == p_start then
-- failed to match
return items_matched return items_matched
end end
@@ -217,7 +216,7 @@ local function sscanf(buffer, buffer_begin, format, result)
end end
end end
if spec == CHAR_u and val < 0 then if spec == CHAR_u and val < 0 then
val = val + (is_64 and 18446744073709551616 or 4294967296) -- unsigned wrap-around like strtoul() val = val + (is_64 and 18446744073709551616 or 4294967296) -- [Port] unsigned wrap-around like strtoul()
end end
end end
+150 -25
View File
@@ -1,12 +1,16 @@
#!/usr/bin/env python3 #!/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) # --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). # --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. # 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. # 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. # 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, ...). # The module returns a table with every global the library defines (ImGui, ImVec2, ImGuiConfigFlags, ImGui_ImplRoblox, ...).
# Roblox target also writes ImGuiTyped.luau (types + require(script.Impl), see tools/gen_types.py). # Roblox target also writes ImGuiTyped.luau (types + require(script.Impl), see tools/gen_types.py) and
# ImGuiWorker.client.luau: the parallel raster Actor LocalScript (backends/roblox/worker.luau with its
# `require(...Raster...)` line replaced by backends/roblox/raster.lua itself: self-contained, no require).
# The Roblox backend's modules are inlined into one function (see "Backend modules" below).
# #
# Build-time optimizations (token rewrites with minify.py's lexer: strings/comments are never touched, every source line # 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: # stays on its line so linemap.json still maps errors). IMGUI_BUNDLE_NOOPT=1 turns all off, IMGUI_BUNDLE_NO_<X>=1 one:
@@ -19,6 +23,14 @@
# C `--@hoist` functions in the sources (pure numeric helpers: ImMin, ImMax, ImClamp, ...) are moved to the bundle top # 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. # 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. # E statement-form `IM_ASSERT(...)` becomes `assert(...)` (fast builtin); expression uses are left alone.
# L (Roblox) library-internal `ImGui.Foo` reads inside function bodies become `ImGui_Foo`, a local of the file's
# __FILES function or of a wrapper around it (the file's most used names, within the 200 locals / upvalues
# limits; the rest stays ImGui.Foo). Luau's inline cache only
# remembers hash slots < 256 and ImGui has ~1000 keys: most ImGui.Foo lookups missed it. Each file registers a
# binder (`ImGui_Foo = ImGui.Foo`, ...) that IM_INCLUDE runs after every file it loads, so they are set before
# any user code runs. Only names assigned exactly once, at load time, are localized (checked here); ImGui.Foo
# stays set (public table unchanged). An app that replaces ImGui.Foo no longer intercepts the library's own
# calls, except for the names in L_PATCHABLE (hooked by tests/apps: those stay table lookups).
import os, re, sys, json, shutil, subprocess, tempfile import os, re, sys, json, shutil, subprocess, tempfile
HERE = os.path.dirname(os.path.abspath(__file__)) HERE = os.path.dirname(os.path.abspath(__file__))
@@ -31,19 +43,44 @@ LOVE = False
if "--target" in sys.argv: if "--target" in sys.argv:
i = sys.argv.index("--target"); LOVE = sys.argv[i + 1] == "love"; del sys.argv[i:i + 2] 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"] sys.argv = [a for a in sys.argv if a != "--no-demo"]
OPT = {x: os.environ.get("IMGUI_BUNDLE_NOOPT") != "1" and os.environ.get("IMGUI_BUNDLE_NO_" + x) != "1" for x in "ABCE"} OPT = {x: os.environ.get("IMGUI_BUNDLE_NOOPT") != "1" and os.environ.get("IMGUI_BUNDLE_NO_" + x) != "1" for x in "ABCEL"}
# A limits: Luau 200 locals in the main chunk (+ helpers, __FILES, ...), 200 upvalues per function; LuaJIT 60 upvalues # A limits: Luau 200 locals in the main chunk (A's hot globals + C's hoisted functions <= MAX_LOCALS, + helpers, __FILES,
# per function (margin left for nested functions that also capture file locals) # ...), 200 upvalues per function; LuaJIT 60 upvalues per function (margin left for nested functions that also capture
MAX_LOCALS, MAX_UPVALUES = 160, (45 if LOVE else 150) # file locals)
BACKEND = "imgui_impl_love.lua" if LOVE else "imgui_impl_roblox.lua" MAX_LOCALS, MAX_UPVALUES = 169, (45 if LOVE else 150)
SKIP = {"imgui_impl_roblox.lua", "imgui_impl_roblox_fonts.lua"} if LOVE else {"imgui_impl_love.lua"} TARGET = "love" if LOVE else "roblox"
BACKEND = "imgui_impl_%s.lua" % TARGET
BACKEND_DIR = os.path.join(ROOT, "backends", TARGET) # every *.lua in it is bundled (*.luau, e.g. the worker, is not)
FILES = {} 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)): 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() src = open(os.path.join(d, f)).read()
if LOVE: src = re.sub(r"^@native$", "", src, flags=re.M) # keep line numbers 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 ORIG = dict(FILES) # for gen_types
ENTRY = ["imgui.lua", BACKEND] + ([] if NO_DEMO else ["imgui_demo.lua"]) # run order ENTRY = ["imgui.lua", BACKEND] + ([] if NO_DEMO else ["imgui_demo.lua"]) # run order
@@ -52,6 +89,7 @@ names = set()
for src in FILES.values(): for src in FILES.values():
names.update(re.findall(r"^function ([A-Za-z_]\w*)\s*\(", src, re.M)) 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)) 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 ---- # ---- 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()) KW = set("and break do else elseif end false for function goto if in local nil not or repeat return then true until while".split())
@@ -147,13 +185,13 @@ if OPT["E"]:
hoisted = [rewrite_assert(s) for s in hoisted] hoisted = [rewrite_assert(s) for s in hoisted]
# ---- B: enum / constant folding ---- # ---- B: enum / constant folding ----
LUAU = shutil.which("luau") or "/nix/store/2m2ja613nndihc8qm10f2rhq6znp1nh4-luau-0.734/bin/luau" LUAU = shutil.which("luau") or (sorted(__import__("glob").glob("/nix/store/*-luau-*/bin/luau")) or ["luau"])[-1]
def header(): def header(bind=False):
return ["local __FILES, __LOADED = {}, {}", return ["local __FILES, __LOADED%s = {}, {}%s" % ((", __BIND", ", {}") if bind else ("", "")),
"function IM_INCLUDE(name)", "function IM_INCLUDE(name)",
" local r = __LOADED[name]", " local r = __LOADED[name]",
" if r == nil then r = __FILES[name](); if r == nil then r = true end; __LOADED[name] = r end", " if r == nil then r = __FILES[name](); if r == nil then r = true end; __LOADED[name] = r%s end" % ("; for i = 1, #__BIND do __BIND[i]() end" if bind else ""),
" return r", " return r",
"end", ""] "end", ""]
@@ -234,32 +272,112 @@ if OPT["B"]:
# ---- A: hot globals -> bundle locals ---- # ---- A: hot globals -> bundle locals ----
hot = [] hot = []
if OPT["A"]: if OPT["A"]:
count, used = {}, [] count, used = {}, {}
for src in FILES.values(): for f, src in FILES.items():
toks = lex(src) toks = lex(src)
used.append({t for i, (k, t, _) in enumerate(toks) if isref(toks, i)}) used.setdefault(GROUP.get(f, f), set()).update(t for i, (k, t, _) in enumerate(toks) if isref(toks, i))
for i, (k, t, _) in enumerate(toks): for i, (k, t, _) in enumerate(toks):
if t in names and isref(toks, i): count[t] = count.get(t, 0) + 1 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 # 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] 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)): 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 len(hot) + len(hoisted_names) >= MAX_LOCALS: break
if all(taken[i] < MAX_UPVALUES for i, u in enumerate(used) if n in u): if all(taken[i] < MAX_UPVALUES for i, u in enumerate(used) if n in u):
hot.append(n) hot.append(n)
taken = [c + (n in u) for c, u in zip(taken, used)] taken = [c + (n in u) for c, u in zip(taken, used)]
# ---- L: ImGui.Foo reads in function bodies -> per-file locals ----
# (L only rewrites `ImGui.Foo` reads: MT.* methods and other globals, e.g. what backends/roblox/patches.lua replaces at
# load time - MT.ImFont.RenderText, MT.ImDrawList.AddText, ImFontCalcTextSizeXY - are never copied. Assignments in
# backend modules count too: a name set in two places is not localized.)
L_PATCHABLE = re.compile(r"(Begin|End|TreeNode\w*|CollapsingHeader|ItemAdd|ItemHoverable|ItemSize|BeginTabItem|ShowDemoWindow)$")
L_LOCALS, L_UPVALUES = 200 - 20 - 10, 200 - 5 # Luau limits per function, minus the registers check's 20, minus margin
localized = {} # __FILES function -> ([Foo, ...] in a wrapper function, [Foo, ...] in the function itself)
def imgui_read(toks, d, i, ok):
"""toks[i] starts an `ImGui.Foo` read (Foo in ok) inside a function body"""
return toks[i][1] == "ImGui" and d[i] > 0 and isref(toks, i) and toks[i - 1][1] != "function" and nexttext(toks, i) == "." and toks[i + 2][1] in ok and nexttext(toks, i + 2) != "="
def nlocal(toks, i):
"""names declared by the `local` at toks[i]"""
if nexttext(toks, i) == "function": return 1
n, j = 1, i + 2
while nexttext(toks, j - 1) == "," : n += 1; j += 2
return n
if OPT["L"] and not LOVE:
lexed = {f: lex(s) for f, s in FILES.items()}
sets, idents = {}, set()
for f, toks in lexed.items():
d = fdepths(toks)
idents.update(t for k, t, _ in toks if k == "name")
for i, (k, t, p) in enumerate(toks):
if t != "ImGui" or not isref(toks, i): continue
nx = nexttext(toks, i)
if nx != ".":
assert nx == "=" and d[i] == 0 and nexttext(toks, i + 1) == "{", "L: %s: ImGui used as a value (%r): can't prove single assignment of its fields" % (f, nx)
continue
key, after = toks[i + 2][1], nexttext(toks, i + 2)
j = i + 3 # `ImGui.Foo, x = ...` (multiple assignment)? walk a target list
while after == "," and j < len(toks) and (toks[j][0] == "name" or toks[j][1] in (".", ",")): j += 1
if i > 0 and toks[i - 1][1] == "function": sets.setdefault(key, []).append((f, d[i - 1]))
elif after == "=" or (after == "," and j < len(toks) and toks[j][1] == "="): sets.setdefault(key, []).append((f, d[i]))
ok = {n for n, w in sets.items() if len(w) == 1 and w[0][1] == 0 and not L_PATCHABLE.match(n)}
clash = {"ImGui_" + n for n in ok} & idents
assert not clash, "L: local names clash with source identifiers: %s" % sorted(clash)
# where the locals go (most used names first): the __FILES function itself (room left next to its own top-level
# locals) and, when that's not enough, a wrapper function around it first (`(function() local ImGui_Foo, ...
# return function() <file> end end)()`: they are upvalues of the file function, next to the bundle-level A/C locals).
# The rest stays ImGui.Foo (small tables `ImGui__1.Foo` for them, always cache hits, measured no faster).
upvals = set(hot + hoisted_names + re.findall(r"\w+", HOIST_DEPS.split("=")[0]))
count, nlocals, nupvals = {}, {}, {}
for f, toks in lexed.items():
fn, d = GROUP.get(f, f), fdepths(toks)
nlocals[fn] = nlocals.get(fn, 0) + sum(nlocal(toks, i) for i in range(len(toks)) if toks[i][1] == "local" and d[i] == 0)
nupvals.setdefault(fn, set()).update(t for i, (k, t, _) in enumerate(toks) if t in upvals and isref(toks, i))
if "ImGui" in declared(toks): count[fn] = None
if count.get(fn, {}) is None: continue
c = count.setdefault(fn, {})
for i in range(len(toks)):
if imgui_read(toks, d, i, ok): c[toks[i + 2][1]] = c.get(toks[i + 2][1], 0) + 1
if BACKEND in nlocals: nlocals[BACKEND] += len(MODULES)
for fn, c in count.items():
c = sorted(c or (), key=lambda n: (-c[n], n))
inner = max(0, L_LOCALS - nlocals[fn])
outer = 0 if fn == BACKEND or len(c) <= inner else min(L_LOCALS, L_UPVALUES - len(nupvals[fn])) # (registers check: the backend's function line stays plain)
if c: localized[fn] = (sorted(c[:outer]), sorted(c[outer:outer + inner]))
for f, toks in lexed.items():
sel = set().union(*localized.get(GROUP.get(f, f), ()))
if not sel: continue
d = fdepths(toks)
FILES[f] = apply(FILES[f], [(toks[i][2], toks[i + 2][2] + len(toks[i + 2][1]), "ImGui_" + toks[i + 2][1]) for i in range(len(toks)) if imgui_read(toks, d, i, sel)])
out = ["--!optimize 2", "-- GENERATED by tools/bundle.py from *.lua, backends/, fonts/ - do not edit", ""] out = ["--!optimize 2", "-- GENERATED by tools/bundle.py from *.lua, backends/, fonts/ - do not edit", ""]
if LOVE: if LOVE:
out = ["-- GENERATED by tools/bundle.py --target love - do not edit", re.search(r"--@compat-begin\n(.*?)--@compat-end", open(os.path.join(ROOT, "backends", "imgui_impl_love.lua")).read(), re.S).group(1), ""] out = ["-- GENERATED by tools/bundle.py --target love - do not edit", re.search(r"--@compat-begin\n(.*?)--@compat-end", open(os.path.join(BACKEND_DIR, BACKEND)).read(), re.S).group(1), ""]
if hot: out.append("local " + ", ".join(hot)) if hot: out.append("local " + ", ".join(hot))
if hoisted: out += [HOIST_DEPS] + hoisted if hoisted: out += [HOIST_DEPS] + hoisted
out += header() out += header(bool(localized))
linemap = [] # (first bundle line, file) for error -> source mapping (tools/test/run.py) 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()): for name, src in sorted(FILES.items()):
out.append("__FILES[%r] = function()" % name) if name in GROUP: continue
linemap.append((sum(x.count("\n") + 1 for x in out) + 1, name)) outer, inner = localized.get(name, ((), ()))
out.append(src.rstrip("\n")) out.append("__FILES[%r] = %sfunction()" % (name, "(" if outer else ""))
for ns in (outer, inner): # declared + bound (now and after every IM_INCLUDE: load-time calls into other files)
if not ns: continue
out.append("local " + ", ".join("ImGui_" + n for n in ns))
out.append("__BIND[#__BIND + 1] = function() if ImGui then " + " ".join("ImGui_%s = ImGui.%s" % (n, n) for n in ns) + " end end; __BIND[#__BIND]()")
if ns is outer: out.append("return function()")
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") out.append("end")
src = INCLUDE.sub("", src)
linemap.append((nextline(), name))
out.append(src.rstrip("\n"))
out.append("end end)()" if outer else "end")
out.append("") out.append("")
for name in ENTRY: for name in ENTRY:
out.append("IM_INCLUDE(%r)" % name) out.append("IM_INCLUDE(%r)" % name)
@@ -277,4 +395,11 @@ json.dump(linemap, open(os.path.join(OUT, NAME.rsplit(".", 1)[0] + ".linemap.jso
if not LOVE: if not LOVE:
from gen_types import wrapper from gen_types import wrapper
open(os.path.join(OUT, "ImGuiTyped.luau"), "w").write(wrapper(ORIG)) open(os.path.join(OUT, "ImGuiTyped.luau"), "w").write(wrapper(ORIG))
print("wrote build/%s (%d files, %d exports)" % (NAME, len(FILES), len(names))) 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%s)" % (NAME, len(FILES), len(names), ", %d ImGui.* localized" % sum(len(a) + len(b) for a, b in localized.values()) if localized else ""))
+19 -2
View File
@@ -113,15 +113,32 @@ def types_header(files):
lines += [" [string]: any,", "}"] lines += [" [string]: any,", "}"]
for name, keys in sorted(enums(files).items()): 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))) 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): def wrapper(files):
return "\n".join(["--!strict", "-- GENERATED by tools/gen_types.py - do not edit. The library is the child ModuleScript 'Impl'.", ""] 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", ""]) + 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): def module_type(enum_names):
# the bundle is too large for Luau to infer, so its return value is cast to this explicit type # 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: (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)] lines += [" %s: %s," % (n, n) for n in sorted(enum_names)]
return lines + [" [string]: any,", "}"] return lines + [" [string]: any,", "}"]
+112
View File
@@ -0,0 +1,112 @@
-- Benchmark scenes shared by the Studio bench (slopgame place, ReplicatedStorage.Shared.BenchScenes) and the headless
-- tools/test/scripts/t_stress2.luau. Deterministic: everything animates from the frame number f, never from time.
-- return function(G, ImPlot?) -> { plots = fn(f), colorpicker = fn(f), implot = fn(f) (if ImPlot), demo_all = fn(f) }
return function(G, ImPlot)
local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4
local Cond = G.ImGuiCond
local S = { values = table.create(90, 0), col1 = ImVec4(0.4, 0.7, 0.2, 0.5), col2 = ImVec4(0.9, 0.3, 0.6, 0.8),
edits = { ImVec4(1, 0, 0, 1), ImVec4(0, 1, 0, 0.5), ImVec4(0, 0, 1, 1), ImVec4(1, 1, 0, 0.25) } }
local scenes = {}
local function Place(name, x, y, w, h)
ImGui.SetNextWindowPos(ImVec2(x, y), Cond.Always)
ImGui.SetNextWindowSize(ImVec2(w, h), Cond.Always)
return ImGui.Begin(name)
end
-- PlotLines + PlotHistogram over a 90-sample ring buffer, one new sample per frame (demo "Plots Widgets" pattern)
function scenes.plots(f)
local v = S.values
local off = f % 90
v[off + 1] = math.sin(f * 0.13) * 0.7 + math.sin(f * 0.031) * 0.3
Place("Plots", 60, 60, 520, 640)
ImGui.PlotLines("Lines", v, nil, 90, off, "avg", -1.0, 1.0, ImVec2(0, 120))
ImGui.PlotHistogram("Histogram", v, nil, 90, off, nil, -1.0, 1.0, ImVec2(0, 120))
ImGui.PlotLines("Lines small", v, nil, 90, off, nil, -1.0, 1.0, ImVec2(0, 60))
ImGui.PlotHistogram("Histogram small", v, nil, 90, off, nil, -1.0, 1.0, ImVec2(0, 60))
ImGui.End()
end
-- ColorPicker4 with hue bar and with hue wheel (+ alpha bars), colour animated every frame, plus ColorEdit4s
function scenes.colorpicker(f)
local h = (f * 0.005) % 1
local r, g, b = ImGui.ColorConvertHSVtoRGB(h, 0.7, 0.9)
S.col1.x, S.col1.y, S.col1.z = r, g, b
r, g, b = ImGui.ColorConvertHSVtoRGB((h + 0.5) % 1, 0.5, 0.8)
S.col2.x, S.col2.y, S.col2.z = r, g, b
local F = G.ImGuiColorEditFlags
Place("Colors", 60, 60, 520, 640)
ImGui.ColorPicker4("bar", S.col1, bit32.bor(F.PickerHueBar, F.AlphaBar))
ImGui.ColorPicker4("wheel", S.col2, bit32.bor(F.PickerHueWheel, F.AlphaBar))
for i, c in S.edits do ImGui.ColorEdit4("edit " .. i, c) end
ImGui.End()
end
if ImPlot then
local xs, ys, sx, sy, bars, xs101, y1, y2, heat = {}, {}, {}, {}, {}, {}, {}, {}, {}
for i = 1, 1001 do xs[i] = (i - 1) * 0.001 end
for i = 1, 100 do
sx[i] = ((i * 7919) % 1000) / 1000
sy[i] = ((i * 104729) % 1000) / 1000
end
for i = 1, 101 do xs101[i] = i - 1 end
-- line (1001 pts, animated), scatter (100 pts), bars (10, animated), shaded (2x101, animated), heatmap (10x10, animated)
function scenes.implot(f)
for i = 1, 1001 do ys[i] = 0.5 + 0.5 * math.sin(50 * (xs[i] + f * 0.002)) end
for i = 1, 10 do bars[i] = 5 + 4 * math.sin(f * 0.05 + i) end
for i = 1, 101 do
y1[i] = 250 + 100 * math.sin((i + f) * 0.07)
y2[i] = 200 + 80 * math.cos((i + f) * 0.05)
end
for i = 1, 100 do heat[i] = 0.5 + 0.5 * math.sin(i * 0.37 + f * 0.04) end
Place("ImPlot", 60, 60, 620, 900)
local sz = ImVec2(-1, 200)
if ImPlot.BeginPlot("Line", sz) then
ImPlot.SetupAxesLimits(0, 1, 0, 1, Cond.Always)
ImPlot.PlotLine("f(x)", xs, ys, 1001)
ImPlot.EndPlot()
end
if ImPlot.BeginPlot("Scatter + Bars", sz) then
ImPlot.SetupAxesLimits(0, 10, 0, 10, Cond.Always)
ImPlot.PlotBars("bars", bars, 10, 0.7, 0)
local sxx, syy = {}, {}
for i = 1, 100 do sxx[i], syy[i] = sx[i] * 10, sy[i] * 10 end
ImPlot.PlotScatter("pts", sxx, syy, 100)
ImPlot.EndPlot()
end
if ImPlot.BeginPlot("Shaded", sz) then
ImPlot.SetupAxesLimits(0, 100, 0, 500, Cond.Always)
ImPlot.PlotShaded("a", xs101, y1, 101, 0)
ImPlot.PlotShaded("b", xs101, y2, 101, 0)
ImPlot.PlotLine("a", xs101, y1, 101)
ImPlot.PlotLine("b", xs101, y2, 101)
ImPlot.EndPlot()
end
if ImPlot.BeginPlot("##Heatmap", ImVec2(220, 220)) then
ImPlot.PlotHeatmap("heat", heat, 10, 10, 0, 1, "%.1f")
ImPlot.EndPlot()
end
ImGui.End()
end
end
-- the whole demo window, every CollapsingHeader / TreeNode forced open, static
local realCH, realTN, forcing = ImGui.CollapsingHeader, ImGui.TreeNode, false
ImGui.CollapsingHeader = function(label, ...)
if forcing then ImGui.SetNextItemOpen(true, Cond.Always) end
return realCH(label, ...)
end
ImGui.TreeNode = function(label, ...)
if forcing then ImGui.SetNextItemOpen(true, Cond.Always) end
return realTN(label, ...)
end
function scenes.demo_all(f)
ImGui.SetNextWindowPos(ImVec2(60, 40), Cond.Always)
ImGui.SetNextWindowSize(ImVec2(620, 900), Cond.Always)
forcing = true
ImGui.ShowDemoWindow()
forcing = false
end
return scenes
end
+14
View File
@@ -4,6 +4,8 @@
# HASHES=1 tools/test/check_all.sh (also prints the draw-data checksums, see hashes.sh) # HASHES=1 tools/test/check_all.sh (also prints the draw-data checksums, see hashes.sh)
cd "$(dirname "$0")/../.." cd "$(dirname "$0")/../.."
export PATH="$PATH:/nix/store/2m2ja613nndihc8qm10f2rhq6znp1nh4-luau-0.734/bin:/nix/store/4qxq4arv32ly13kl3g0m5q80gm3a35xr-luajit-2.1.1741730670/bin" 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) T=$(mktemp -d /tmp/imgui_check.XXXX)
R="python3 tools/test/run.py --quiet --roblox --timeout 600" R="python3 tools/test/run.py --quiet --roblox --timeout 600"
@@ -29,6 +31,7 @@ CHECKS=(
"passthru|PASSTHRU OK|$R --main tools/test/scripts/t_passthru.luau --frames 40" "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" "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|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_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" "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" "apps|APPS OK|$R --main tools/test/scripts/t_apps.luau --frames 120 --open"
@@ -36,7 +39,18 @@ CHECKS=(
"demo_open|DRAWHASH|$R --main tools/test/scripts/t_drawhash.luau --frames 150 --open" "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" "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" "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"
"move_pixels|MOVEPIX SAME|a=\$($R --main tools/test/scripts/t_move_pixels.luau --frames 245 | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_move_pixels.luau --frames 245 | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo MOVEPIX SAME"
"scene_pixels|SCENEPIX SAME|M='--module BenchScenes=tools/test/bench_scenes.luau'; [ -f extensions/implot-luau/ImPlot.lua ] && M=\"\$M --module ImPlot=extensions/implot-luau/ImPlot.lua\"; a=\$($R --main tools/test/scripts/t_scene_pixels.luau --frames 170 \$M | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_scene_pixels.luau --frames 170 \$M | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo SCENEPIX SAME"
"scroll_pixels|SCROLLPIX SAME|a=\$($R --main tools/test/scripts/t_scroll_pixels.luau --frames 212 | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_scroll_pixels.luau --frames 212 | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo SCROLLPIX SAME"
"recolor_pixels|RECOLORPIX SAME|a=\$($R --main tools/test/scripts/t_recolor_pixels.luau --frames 140 | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_recolor_pixels.luau --frames 140 | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo RECOLORPIX 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 620"
"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" "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"
"native|NATIVE OK|python3 tools/test/native_size.py"
"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" "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"
) )
+2
View File
@@ -5,6 +5,8 @@
# demo = t_drawhash with Widgets,Basic / whole demo open: changes with any demo edit # demo = t_drawhash with Widgets,Basic / whole demo open: changes with any demo edit
cd "$(dirname "$0")/../.." cd "$(dirname "$0")/../.."
export PATH="$PATH:/nix/store/2m2ja613nndihc8qm10f2rhq6znp1nh4-luau-0.734/bin:/nix/store/4qxq4arv32ly13kl3g0m5q80gm3a35xr-luajit-2.1.1741730670/bin" 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"; }
REV=${1:-HEAD} REV=${1:-HEAD}
hashes() { # $1 = repo dir hashes() { # $1 = repo dir
( cd "$1" ( cd "$1"
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Native code size of the Roblox bundle (and the worker), per ModuleScript, per source file and per function.
python3 tools/test/native_size.py # bundles to a temp dir, measures ImGui.luau + ImGuiWorker.client.luau
python3 tools/test/native_size.py --top 40 # also the 40 largest @native functions (with source file:line)
python3 tools/test/native_size.py a.luau ... # measure given files (e.g. an extension: ImPlot.lua)
Why: Roblox compiles each script's @native functions together into ONE allocation that must fit in one 4 MB block
of executable memory (Luau CodeGen's CodeAllocator, LuauCodeGenBlockSize). A module whose native code is bigger gets
NO native code at all, silently: every @native function of it runs interpreted (Studio: render 4-9x slower). Measured
in Studio (probe bundles, Oct 2026): native up to 4,083,418 bytes, interpreted from 4,103,258 bytes (sizes as reported
by luau-compile 0.738 --codegennull -O2 for x64). The Luau CLI fails a little later (~4.18 MB), and `run.py` puts the
bundle, the main script and every --module into one chunk, so headless runs with ImPlot hit it ~0.5 MB earlier.
Prints NATIVE OK when every module is under BUDGET (margin for compiler version drift), NATIVE OVER otherwise."""
import argparse, glob, json, os, shutil, subprocess, sys, tempfile, collections
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
STUDIO_LIMIT = 4083418 # largest module measured native in Studio (next probe, 4,103,258, ran interpreted)
BUDGET = 3900000 # NATIVE OVER above this (~180 KB margin below the Studio limit)
LC = shutil.which("luau-compile") or (sorted(glob.glob("/nix/store/*-luau-*/bin/luau-compile")) or ["luau-compile"])[-1]
def measure(path):
stats = tempfile.mktemp(suffix=".json")
subprocess.run([LC, "--codegennull", "-O2", "--record-stats=function", "--stats-file=" + stats, path],
check=True, stdout=subprocess.DEVNULL)
d = json.load(open(stats)); os.remove(stats)
d = next(iter(d.values())) if "codegen" not in d else d
return d["codegen"], d["lowerStats"]["functions"]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("files", nargs="*")
ap.add_argument("--top", type=int, default=0)
a = ap.parse_args()
files = a.files
if not files:
out = tempfile.mkdtemp(prefix="imgui_native_")
subprocess.run([sys.executable, os.path.join(ROOT, "tools", "bundle.py"), out], check=True, stdout=subprocess.DEVNULL)
files = [os.path.join(out, "ImGui.luau"), os.path.join(out, "ImGuiWorker.client.luau")]
ok = True
for path in files:
total, fns = measure(path)
lmp = os.path.join(os.path.dirname(path), "ImGui.linemap.json")
lm = json.load(open(lmp)) if os.path.basename(path) == "ImGui.luau" and os.path.exists(lmp) else []
def loc(n):
best = None
for start, name in lm:
if start <= n: best = (start, name)
return (best[1], n - best[0] + 1) if best else (os.path.basename(path), n)
over = total > BUDGET
ok = ok and not over
print("%s: %d bytes native (%d functions), %.0f%% of the Studio module limit, %d KB headroom%s" % (
os.path.basename(path), total, len(fns), 100 * total / STUDIO_LIMIT, (STUDIO_LIMIT - total) // 1024,
" OVER BUDGET" if over else ""))
if lm:
byfile = collections.Counter()
for f in fns: byfile[loc(f["line"])[0]] += f["asmSize"]
for name, size in byfile.most_common(): print(" %8.1f KB %s" % (size / 1024, name))
for f in sorted(fns, key=lambda f: -f["asmSize"])[:a.top]:
print(" %8.1f KB %-40s %s:%d" % ((f["asmSize"] / 1024, f["name"] or "?") + loc(f["line"])))
print("NATIVE OK" if ok else "NATIVE OVER")
sys.exit(0 if ok else 1)
main()
+3 -2
View File
@@ -2,11 +2,12 @@
# Summarise profile.out from `run.py --profile`: top functions by self and inclusive samples, mapped to source file lines # Summarise profile.out from `run.py --profile`: top functions by self and inclusive samples, mapped to source file lines
import collections, json, os, re, sys, glob import collections, json, os, re, sys, glob
path = sys.argv[1] if len(sys.argv) > 1 else "profile.out" path = sys.argv[1] if len(sys.argv) > 1 else "profile.out"
tmp = max(glob.glob("/tmp/imgui_test_*/ImGui.linemap.json"), key=os.path.getmtime) import tempfile # run.py uses tempfile.mkdtemp, i.e. $TMPDIR (not always /tmp)
tmp = max(glob.glob(os.path.join(tempfile.gettempdir(), "imgui_test_*/ImGui.linemap.json")) + glob.glob("/tmp/imgui_test_*/ImGui.linemap.json"), key=os.path.getmtime)
lm = json.load(open(tmp)) lm = json.load(open(tmp))
def loc(n): def loc(n):
if not n.isdigit(): return "C" 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: for start, name in lm:
if start <= n: best = (start, name) if start <= n: best = (start, name)
return "%s:%d" % (best[1], n - best[0] + 1) if best else "?" return "%s:%d" % (best[1], n - best[0] + 1) if best else "?"
+13 -1
View File
@@ -58,6 +58,8 @@ end })
-- Instances -- Instances
local InstMethods = {} local InstMethods = {}
local InstMT = {} 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) InstMT.__index = function(t, k)
if k == "Parent" then return rawget(t, "_parent") end if k == "Parent" then return rawget(t, "_parent") end
local pv = rawget(t, "_props")[k]; if pv ~= nil then return pv end local pv = rawget(t, "_props")[k]; if pv ~= nil then return pv end
@@ -67,11 +69,13 @@ InstMT.__index = function(t, k)
end end
InstMT.__newindex = function(t, k, v) InstMT.__newindex = function(t, k, v)
if k == "Parent" then if k == "Parent" then
MOCK.Parents += 1
local old = rawget(t, "_parent") 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 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) rawset(t, "_parent", v)
if v then table.insert(rawget(v, "_children"), t) end if v then table.insert(rawget(v, "_children"), t) end
else else
MOCK.Sets += 1
local props = rawget(t, "_props") local props = rawget(t, "_props")
local old = props[k] local old = props[k]
props[k] = v props[k] = v
@@ -96,6 +100,11 @@ end
function InstMethods:WaitForChild(name) return assert(self:FindFirstChild(name), "WaitForChild would hang: " .. name) 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: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: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) function InstMethods:IsA(class)
if class == "GuiObject" then return self.ClassName == "Frame" or self.ClassName == "ImageLabel" end if class == "GuiObject" then return self.ClassName == "Frame" or self.ClassName == "ImageLabel" end
return self.ClassName == class 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 last_pixels -- last buffer written to an EditableImage
local AssetService = {} local AssetService = {}
function AssetService:CreateEditableImage(opts) function AssetService:CreateEditableImage(opts)
MOCK.EIs += 1
local img = { Size = opts.Size, Pixels = buffer.create(opts.Size.X * opts.Size.Y * 4) } local img = { Size = opts.Size, Pixels = buffer.create(opts.Size.X * opts.Size.Y * 4) }
UPLOADS = 0 UPLOADS = 0
function img:WritePixelsBuffer(origin, size, buf) function img:WritePixelsBuffer(origin, size, buf)
assert(buffer.len(buf) == size.X * size.Y * 4, "WritePixelsBuffer: buffer size mismatch") 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") 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 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 _G_UPLOADS = (_G_UPLOADS or 0) + 1; _G_UPLOAD_PX = (_G_UPLOAD_PX or 0) + size.X * size.Y
end end
function img:Destroy() end function img:Destroy() end
@@ -168,7 +179,7 @@ end
ROBLOX = setmetatable({ ROBLOX = setmetatable({
game = game, workspace = { CurrentCamera = { ViewportSize = v2(SCREEN_W, SCREEN_H) } }, require = rbxrequire, _G = fakeG, 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, Enum = Enum, Vector2 = Vector2,
Vector3 = { new = function(x, y, z) return { X = x, Y = y, Z = z } end }, 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 }, 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 }) }, { __index = realG })
local mod = newInst("ModuleScript", "ImGui", ReplicatedStorage); rawset(mod, "_src", "ImGui.luau") 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 -- Run main.lua as a LocalScript
local main = loadAsScript("main.client.luau", newInst("LocalScript", "main")) local main = loadAsScript("main.client.luau", newInst("LocalScript", "main"))
main() main()
+11 -5
View File
@@ -11,7 +11,7 @@ TMP = tempfile.mkdtemp(prefix="imgui_test_") # per process: parallel runs must
HERE = os.path.dirname(os.path.abspath(__file__)) HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE)) 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" G = "game, workspace, Instance, Enum, Vector2, Vector3, UDim2, Color3, Content, UDim, CFrame, warn, require, script, os"
def build_run(args, flags): def build_run(args, flags):
@@ -24,9 +24,15 @@ def build_run(args, flags):
out.append("SOURCE_FNS[%r] = function(%s)\n%s\nend" % (key, G, s)) out.append("SOURCE_FNS[%r] = function(%s)\n%s\nend" % (key, G, s))
add("ImGui.luau", os.path.join(TMP, "ImGui.luau")) add("ImGui.luau", os.path.join(TMP, "ImGui.luau"))
add("main.client.luau", args.main) 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()) out.append(open(os.path.join(HERE, "roblox_mock.luau")).read())
global OFFSET, LAST_LINE global OFFSET, LAST_LINE, STRIPPED
LAST_LINE = open(os.path.join(TMP, "ImGui.luau")).read().count("\n") 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) OFFSET = 5 # lines before the ImGui function body in run.luau (flags/header lines + "function(...)" line)
path = os.path.join(TMP, "run.luau") path = os.path.join(TMP, "run.luau")
open(path, "w").write("\n".join(out)) open(path, "w").write("\n".join(out))
@@ -45,8 +51,7 @@ def remap(text):
import json, re import json, re
lm = json.load(open(os.path.join(TMP, "ImGui.linemap.json"))) lm = json.load(open(os.path.join(TMP, "ImGui.linemap.json")))
def sub(m): def sub(m):
n = int(m.group(1)) - OFFSET # line inside build/ImGui.luau (minus its 2 stripped --! lines) n = int(m.group(1)) - OFFSET + STRIPPED # line inside build/ImGui.luau
n += 2
best = None best = None
if n > LAST_LINE: return "<harness>:%d" % n if n > LAST_LINE: return "<harness>:%d" % n
for start, name in lm: for start, name in lm:
@@ -65,6 +70,7 @@ def main():
ap.add_argument("--profile", action="store_true", help="sampling profile (no codegen) -> profile.out; see tools/test/prof.py") 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("--open", action="store_true", help="force all CollapsingHeader/TreeNode open")
ap.add_argument("--timeout", type=int, default=120) 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)") ap.add_argument("--quiet", action="store_true", help="no random input (scripted tests drive io themselves)")
args = ap.parse_args() args = ap.parse_args()
+108
View File
@@ -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)
+102
View File
@@ -0,0 +1,102 @@
-- Moving-window pixel oracle (like t_pixels): a window with circles, rounded rects, bullets and curves moves by whole
-- pixels (some frames by half a pixel), "PIX <frame> <hash>" every 4 frames. Trig-generated vertices drift by an ulp
-- off the exact shift: the backend must still redraw what they touch. Run with RUN_FLAGS="ARG_FORCE=true" for a full
-- redraw every frame: incremental output must match it exactly.
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
local frame = 0
local pos = ImVec2(40, 40)
local radio = 1
game:GetService("RunService").Stepped:Connect(function()
frame += 1
if frame > 240 then return end
G.ImGui_ImplRoblox.NewFrame()
io.DeltaTime = 1 / 60
io:AddMousePosEvent(1200, 740)
if frame > 4 then
if frame < 120 then pos = ImVec2(pos.x + 3, pos.y + 2) else pos = ImVec2(pos.x - 5, pos.y - 1) end
if frame % 37 == 0 then pos = ImVec2(pos.x + 0.5, pos.y) end -- fractional: full path
end
ImGui.NewFrame()
ImGui.SetNextWindowPos(pos, G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(420, 460), G.ImGuiCond.Always)
ImGui.Begin("Stress")
for i = 1, 6 do ImGui.Button("Button " .. i); ImGui.SameLine(); slider = ImGui.SliderFloat("##s" .. i, slider, 0, 1) end
for i = 1, 4 do if ImGui.RadioButton("r" .. i, radio == i) then radio = i end; ImGui.SameLine() end
ImGui.NewLine()
ImGui.Checkbox("check", true)
ImGui.Bullet(); ImGui.Text("bullet")
if ImGui.TreeNode("tree") then ImGui.Text("inside"); ImGui.TreePop() end
ImGui.ColorButton("cb", col)
local dl = ImGui.GetWindowDrawList()
local p = ImGui.GetCursorScreenPos()
dl:AddCircleFilled(ImVec2(p.x + 40, p.y + 40), 33.3, 0xFF3080F0)
dl:AddCircle(ImVec2(p.x + 120, p.y + 40), 27.7, 0xFFF08030, 0, 2.5)
dl:AddRectFilled(ImVec2(p.x + 170, p.y + 10), ImVec2(p.x + 260, p.y + 70), 0x8040F040, 12.3)
dl:AddBezierCubic(ImVec2(p.x, p.y + 90), ImVec2(p.x + 90, p.y + 60), ImVec2(p.x + 180, p.y + 140), ImVec2(p.x + 300, p.y + 90), 0xFFFFFFFF, 1.7)
ImGui.Dummy(ImVec2(300, 150))
for i = 1, 40 do ImGui.TextWrapped("Line %d: the quick brown fox jumps over the lazy dog.", i) end
ImGui.End()
ImGui.Render()
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
if frame % 4 == 0 then
print("PIX", frame, composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui")))
end
if frame == 240 then print("MOVEPIX DONE") end
end)
+179
View File
@@ -0,0 +1,179 @@
-- 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 (5 scenarios: >= 600)
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 },
{ "fonts", function(f) -- a new font size every frame: glyph uploads, atlas grow/repack (Actor texture patches)
ImGui.SetNextWindowPos(ImVec2(40, 30), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(620, 600), G.ImGuiCond.Always)
ImGui.Begin("Fonts")
ImGui.PushFont(nil, 12 + (f * 0.25) % 40)
for i = 1, 12 do ImGui.TextWrapped("Line %d: the quick brown fox jumps over the lazy dog, %d times.", i, f) end
ImGui.PopFont()
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)
+32
View File
@@ -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)
+145
View File
@@ -0,0 +1,145 @@
-- Pixel oracle for the "recolored" path (CompareDrawList 4 + PatchDrawList recolor: same vertex positions, a few
-- vertices' colour / uv changed, e.g. hover): animated style colours on buttons, text, frames, a colour button, a
-- scrolled child, a wide button over several tiles and AddRectFilledMultiColor cycling flat <-> gradient (kind changes
-- fall back to the full path), between still frames, structure changes, hover, a colour picker (too many changed
-- vertices) and a tile limit (deferred tiles). Composites the ScreenGui every few frames and prints "PIX <frame> <hash>".
-- Run with RUN_FLAGS="ARG_FORCE=true" for a full redraw every frame: incremental output must match it exactly (also with
-- ARG_PAR=true: the parallel executor).
-- python3 tools/test/run.py --main tools/test/scripts/t_recolor_pixels.luau --frames 140 --quiet --roblox
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_PAR then G.ImGui_ImplRoblox.EnableParallel({ Sync = true, Actors = 4 }) end
local io = ImGui.GetIO()
local Col = G.ImGuiCol
local W, H = 1280, 760
local SW, SH = 720, 560 -- composited area (the windows are inside it)
local hsv = ImVec4(0.4, 0.7, 0.2, 1)
local function composite(gui)
local screen = buffer.create(SW * SH * 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 * SW + 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, SW, SH)
local h = 0
for i = 0, SW * SH * 3 - 4, 4 do h = (h * 31 + buffer.readu32(screen, i)) % 2147483647 end
return h
end
-- phases: name, frames
local PHASES = { { "recolor", 24 }, { "still", 6 }, { "grow", 8 }, { "recolor", 16 }, { "hover", 24 },
{ "picker", 10 }, { "limit", 30 }, { "recolor", 12 }, { "still", 6 } }
local frame, pi, pf, extra, t = 0, 1, 0, 0, 0
game:GetService("RunService").Stepped:Connect(function()
local ph = PHASES[pi]
if not ph then return end
frame += 1
pf += 1
local name = ph[1]
G.ImGui_ImplRoblox.NewFrame()
io.DeltaTime = 1 / 60
io:AddMousePosEvent(1200, 740)
io.BackendPlatformUserData.TileLimit = name == "limit" and 2 or nil
if name == "recolor" or name == "limit" then t += 1 end
if name == "grow" and pf % 3 == 0 then extra += 1 end
if name == "hover" then io:AddMousePosEvent(50 + (pf * 37) % 420, 60 + (pf * 29) % 300) end
if name == "picker" then hsv.x = (hsv.x + 0.03) % 1 end
ImGui.NewFrame()
local c1 = ImVec4(0.5 + 0.5 * math.sin(t * 0.3), 0.4, 0.5 + 0.5 * math.cos(t * 0.2), 1)
local c2 = ImVec4(0.2, 0.5 + 0.5 * math.sin(t * 0.25), 0.3, 0.6 + 0.4 * math.cos(t * 0.4))
ImGui.SetNextWindowPos(ImVec2(20, 20), G.ImGuiCond.Always)
ImGui.SetNextWindowSize(ImVec2(470, 520), G.ImGuiCond.Always)
ImGui.Begin("Recolor")
ImGui.PushStyleColor(Col.Button, c1)
ImGui.PushStyleColor(Col.FrameBg, c2)
for i = 1, 6 do
ImGui.Button("Button " .. i)
if i % 3 ~= 0 then ImGui.SameLine() end
end
ImGui.Button("A wide button over several tiles", ImVec2(400, 40))
ImGui.PopStyleColor(2)
ImGui.TextColored(c1, "Coloured text %d", 7)
ImGui.ColorButton("##cb", c2)
ImGui.SameLine()
local dl = ImGui.GetWindowDrawList()
local p = ImGui.GetCursorScreenPos()
-- flat (t % 8 < 2), horizontal / vertical gradient otherwise: kind changes take the full path
local u1 = ImGui.GetColorU32(c1)
local u2 = (t % 8 < 2) and u1 or ImGui.GetColorU32(c2)
if t % 16 < 8 then
dl:AddRectFilledMultiColor(p, ImVec2(p.x + 140, p.y + 30), u1, u2, u2, u1)
else
dl:AddRectFilledMultiColor(p, ImVec2(p.x + 140, p.y + 30), u1, u1, u2, u2)
end
ImGui.Dummy(ImVec2(140, 30))
for i = 1, extra do ImGui.Text("Extra line %d", i) end
ImGui.BeginChild("scrolled", ImVec2(0, 200), G.ImGuiChildFlags.Borders)
ImGui.SetScrollY(37)
ImGui.PushStyleColor(Col.Text, c1)
for i = 1, 20 do ImGui.Text("Child line %d", i) end
ImGui.PopStyleColor()
ImGui.PushStyleColor(Col.Button, c2)
ImGui.Button("Child button")
ImGui.PopStyleColor()
ImGui.EndChild()
_ = ImGui.Checkbox("Check", true)
ImGui.End()
if name == "picker" or pi > 6 then
ImGui.SetNextWindowPos(ImVec2(500, 20), G.ImGuiCond.Always)
ImGui.SetNextWindowSize(ImVec2(210, 300), G.ImGuiCond.Always)
ImGui.Begin("Picker")
ImGui.ColorPicker4("##p", hsv, G.ImGuiColorEditFlags.PickerHueBar)
ImGui.End()
end
ImGui.Render()
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
if ARG_PAR then G.ImGui_ImplRoblox.FinishParallel() end
-- (checkpoints: exact as long as no tile is deferred, i.e. not during "limit"; the frame after it redraws them)
if name ~= "limit" and (frame % 3 == 0 or pf == ph[2]) then
print("PIX", name, frame, composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui")))
end
if pf == ph[2] then
pi += 1
pf = 0
if not PHASES[pi] then print("RECOLORPIX DONE") end
end
end)
+89
View File
@@ -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)
+88
View File
@@ -0,0 +1,88 @@
-- Pixel oracle for the bench scenes (tools/test/bench_scenes.luau: plots, colorpicker, implot if ImPlot is given,
-- demo_all), animated: composites the ScreenGui (like t_pixels) every few frames and prints "PIX <scene> <frame> <hash>".
-- 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).
-- python3 tools/test/run.py --main tools/test/scripts/t_scene_pixels.luau --frames 200 --quiet --roblox \
-- --module BenchScenes=tools/test/bench_scenes.luau [--module ImPlot=extensions/implot-luau/ImPlot.lua]
local RS = game:GetService("ReplicatedStorage")
local G = require(RS:WaitForChild("ImGui"))
local ImGui = G.ImGui
local ImPlot = RS:FindFirstChild("ImPlot") and require(RS.ImPlot)(G)
ImGui.CreateContext()
if ImPlot then ImPlot.CreateContext() end
G.ImGui_ImplRoblox.Init()
G.ImGui_ImplRoblox.SetRenderRate(0)
local io = ImGui.GetIO()
local W, H = 1280, 760
local scenes = require(RS:WaitForChild("BenchScenes"))(G, ImPlot)
local ORDER = {}
for _, name in { "plots", "colorpicker", "implot", "demo_all" } do
if scenes[name] then table.insert(ORDER, name) end
end
local FRAMES, EVERY = 40, 8
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 frame = 0
game:GetService("RunService").Stepped:Connect(function()
frame += 1
local si = (frame - 1) // FRAMES + 1
local name = ORDER[si]
if not name then return end
G.ImGui_ImplRoblox.NewFrame()
io.DeltaTime = 1 / 60
io:AddMousePosEvent(-1000, -1000)
ImGui.NewFrame()
scenes[name](frame)
ImGui.Render()
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
if frame % EVERY == 0 then
print("PIX", name, frame, composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui")))
end
if frame == #ORDER * FRAMES then print("SCENEPIX DONE") end
end)
+99
View File
@@ -0,0 +1,99 @@
-- Scroll / resize pixel oracle (like t_pixels): the bench's stress window (buttons + sliders, a 60 x 6 table with row
-- backgrounds and borders, wrapped text) scrolls by 6 px a frame (down, then up), resizes from the bottom-right, then
-- from the top-left, "PIX <frame> <hash>" every 3 frames. Rows entering / leaving tiles and items shifting by one in a
-- tile's primitive list exercise DirtyRects' list diff. Run with RUN_FLAGS="ARG_FORCE=true" for a full redraw every
-- frame: incremental output must match it exactly.
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)
if ARG_TILELIMIT then ImGui.GetIO().BackendPlatformUserData.TileLimit = ARG_TILELIMIT end
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 frame = 0
local pos, size, scroll, slider, check = ImVec2(60, 40), ImVec2(520, 640), 0, 0.5, true
local LAST = 210
game:GetService("RunService").Stepped:Connect(function()
frame += 1
if frame > LAST then return end
G.ImGui_ImplRoblox.NewFrame()
io.DeltaTime = 1 / 60
io:AddMousePosEvent(1200, 740)
if frame > 4 and frame <= 60 then scroll += 6
elseif frame > 60 and frame <= 100 then scroll -= 7
elseif frame > 100 and frame <= 150 then size = ImVec2(size.x + 3, size.y - 2)
elseif frame > 150 and frame <= 200 then pos, size = ImVec2(pos.x + 2, pos.y + 2), ImVec2(size.x - 2, size.y - 2) end
ImGui.NewFrame()
ImGui.SetNextWindowPos(pos, G.ImGuiCond.Always); ImGui.SetNextWindowSize(size, G.ImGuiCond.Always)
ImGui.Begin("Stress")
ImGui.SetScrollY(scroll)
for i = 1, 20 do
ImGui.Button("Button " .. i); ImGui.SameLine()
slider = ImGui.SliderFloat("##s" .. i, slider, 0, 1)
end
_, check = ImGui.Checkbox("Checkbox", check)
if ImGui.BeginTable("tbl", 6, bit32.bor(G.ImGuiTableFlags.Borders, G.ImGuiTableFlags.RowBg)) then
for r = 1, 60 do
ImGui.TableNextRow()
for c = 1, 6 do ImGui.TableNextColumn(); ImGui.Text("r%d c%d", r, c) end
end
ImGui.EndTable()
end
for i = 1, 40 do ImGui.TextWrapped("Line %d: the quick brown fox jumps over the lazy dog, again and again.", i) end
ImGui.End()
ImGui.Render()
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
if frame % 3 == 0 then
print("PIX", frame, composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui")))
end
if frame == LAST then print("SCROLLPIX DONE") end
end)
+72
View File
@@ -0,0 +1,72 @@
-- Library CPU cost of the Studio bench's scene (demo window + "Stress" window: 20 buttons/sliders, a 60x6 table,
-- 80 TextWrapped lines), mouse sweeping over it. Prints the median ImGui.NewFrame..Render time (real clock, backend
-- excluded) and a checksum of the draw data. Use with --roblox (only @native functions native, like Studio); the machine
-- is often busy, so compare runs interleaved and look at the lower quartile (lowq-mean).
-- RUN_FLAGS="ARG_MODE='scroll'" python3 tools/test/run.py --main tools/test/scripts/t_stress.luau --frames 800 --quiet --roblox
-- ARG_MODE: "hover" (default), "idle" (mouse outside, like the bench's idle), "scroll", "resize", "fonts".
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 MODE = type(ARG_MODE) == "string" and ARG_MODE or "hover"
local clock = os.realclock or os.clock
local S = { fsize = 13, scroll = 0, pos = ImVec2(60, 60), size = ImVec2(520, 640), slider = 0.5, check = true }
local function StressWindow()
ImGui.SetNextWindowPos(S.pos, G.ImGuiCond.Always)
ImGui.SetNextWindowSize(S.size, G.ImGuiCond.Always)
ImGui.PushFont(nil, S.fsize)
ImGui.Begin("Stress")
ImGui.SetScrollY(S.scroll)
for i = 1, 20 do
if ImGui.Button("Button " .. i) then end
ImGui.SameLine()
S.slider = ImGui.SliderFloat("##s" .. i, S.slider, 0, 1)
end
_, S.check = ImGui.Checkbox("Checkbox", S.check)
if ImGui.BeginTable("tbl", 6, bit32.bor(G.ImGuiTableFlags.Borders, G.ImGuiTableFlags.RowBg)) then
for r = 1, 60 do
ImGui.TableNextRow()
for c = 1, 6 do ImGui.TableNextColumn(); ImGui.Text("r%d c%d", r, c) end
end
ImGui.EndTable()
end
for i = 1, 80 do ImGui.TextWrapped("Line %d: the quick brown fox jumps over the lazy dog, again and again and again.", i) end
ImGui.PopFont()
ImGui.End()
end
local frame, h, times = 0, 0, {}
local function mix(v) h = (h * 31 + math.floor(v * 64 + 0.5)) % 2147483647 end
game:GetService("RunService").Stepped:Connect(function()
frame += 1
G.ImGui_ImplRoblox.NewFrame()
io.DeltaTime = 1 / 60
if MODE == "idle" then io:AddMousePosEvent(-1000, -1000) else io:AddMousePosEvent(70 + (frame * 7) % 480, 80 + (frame * 13) % 560) end
if MODE == "scroll" then S.scroll = (S.scroll + 6) % 2400 end
if MODE == "resize" then S.size = ImVec2(420 + (frame * 3) % 300, 500 + (frame * 2) % 200) end
if MODE == "fonts" then S.fsize = 12 + (frame * 0.25) % 40 end
local t0 = clock()
ImGui.NewFrame()
ImGui.SetNextWindowPos(ImVec2(620, 40), G.ImGuiCond.Once)
ImGui.ShowDemoWindow()
StressWindow()
ImGui.Render()
if frame > 20 then table.insert(times, clock() - t0) end
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
table.sort(times)
local lo = 0
for i = 1, #times // 4 do lo += times[i] end
print(string.format("STRESS %s med %.3f ms p25 %.3f ms lowq-mean %.3f ms", MODE, times[#times // 2 + 1] * 1000, times[#times // 4] * 1000, lo / (#times // 4) * 1000))
print("STRESSHASH", h)
end
end)
+55
View File
@@ -0,0 +1,55 @@
-- Headless twin of the Studio bench's round-3 scenes (tools/test/bench_scenes.luau): plots, colorpicker, implot,
-- demo_all. Prints the median / lower-quartile library time (NewFrame..Render) and backend time (RenderDrawData), and a
-- checksum of the draw data (must not change with internal optimizations).
-- RUN_FLAGS="ARG_MODE='plots'" python3 tools/test/run.py --main tools/test/scripts/t_stress2.luau --frames 400 --quiet --roblox \
-- --module BenchScenes=tools/test/bench_scenes.luau [--module ImPlot=../implot-luau/ImPlot.lua]
local RS = game:GetService("ReplicatedStorage")
local G = require(RS:WaitForChild("ImGui"))
local ImGui = G.ImGui
local ImPlot = RS:FindFirstChild("ImPlot") and require(RS.ImPlot)(G)
ImGui.CreateContext()
if ImPlot then ImPlot.CreateContext() end
G.ImGui_ImplRoblox.Init()
G.ImGui_ImplRoblox.SetRenderRate(0)
local io = ImGui.GetIO()
local MODE = type(ARG_MODE) == "string" and ARG_MODE or "plots"
local scene = require(RS:WaitForChild("BenchScenes"))(G, ImPlot)[MODE]
assert(scene, "unknown or unavailable scene " .. MODE)
local clock = os.realclock or os.clock
local frame, h, lib, be = 0, 0, {}, {}
local function mix(v) h = (h * 31 + math.floor(v * 64 + 0.5)) % 2147483647 end
local function stats(t)
table.sort(t)
local lo = 0
for i = 1, #t // 4 do lo += t[i] end
return t[#t // 2 + 1] * 1000, lo / (#t // 4) * 1000
end
game:GetService("RunService").Stepped:Connect(function()
frame += 1
G.ImGui_ImplRoblox.NewFrame()
io.DeltaTime = 1 / 60
io:AddMousePosEvent(-1000, -1000)
local t0 = clock()
ImGui.NewFrame()
scene(frame)
ImGui.Render()
local t1 = clock()
local dd = ImGui.GetDrawData()
for _, dl in dd.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
local t2 = clock()
G.ImGui_ImplRoblox.RenderDrawData(dd)
local t3 = clock()
if frame > 20 then table.insert(lib, t1 - t0); table.insert(be, t3 - t2) end
if frame == ARG_FRAMES - 1 then
local lm, ll = stats(lib)
local bm, bl = stats(be)
print(string.format("STRESS2 %s lib med %.3f lowq %.3f ms | backend med %.3f lowq %.3f ms", MODE, lm, ll, bm, bl))
print("STRESS2HASH", MODE, h)
end
end)
+1 -1
View File
@@ -64,7 +64,7 @@ game:GetService("RunService").Stepped:Connect(function()
assert(st.TextLen == 0, "backspace should delete imgui's whole selection, len " .. st.TextLen) assert(st.TextLen == 0, "backspace should delete imgui's whole selection, len " .. st.TextLen)
print("BACKSPACE OK") print("BACKSPACE OK")
end 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 st = ImGui.GetCurrentContext().InputTextState
local got = G.ImGui._ByteArrayToString(st.TextA.Data, 1, st.TextLen + 1) local got = G.ImGui._ByteArrayToString(st.TextA.Data, 1, st.TextLen + 1)
assert(got:find("z"), "key fallback while proxy focused: " .. got) 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)
+49
View File
@@ -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)
+3 -2
View File
@@ -4,11 +4,12 @@
""" """
import os, re, collections import os, re, collections
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 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 import sys
NO_DEMO = "--no-demo" in sys.argv NO_DEMO = "--no-demo" in sys.argv
files = {} 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: for f in fn:
if f.endswith(".lua") and not (NO_DEMO and f == "imgui_demo.lua"): 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() files[os.path.relpath(os.path.join(dp, f), SRC)] = open(os.path.join(dp, f)).read()
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "4dbug/imgui-luau" name = "4dbug/imgui-luau"
version = "0.3.0" version = "0.4.4"
registry = "https://github.com/UpliftGames/wally-index" registry = "https://github.com/UpliftGames/wally-index"
realm = "shared" realm = "shared"
license = "MIT" license = "MIT"