0.4.0
Build & Release / build (push) Canceled after 0s

This commit is contained in:
4DBug committed 2026-10-16 22:53:18 -05:00
1 parent 1a83724317
commit 386b0c475e
46 files changed
+7897 -4414

No files matched your search

+60 -13
View File
@@ -1,12 +1,16 @@
#!/usr/bin/env python3
# Bundles the root *.lua (library + imgui_demo.lua), backends/ and fonts/ into ONE ModuleScript: build/ImGui.luau
# Bundles the root *.lua (library + imgui_demo.lua), the target's backend folder (backends/roblox/*.lua, or
# backends/love/*.lua) and fonts/ (Roblox) into ONE ModuleScript: build/ImGui.luau
# --no-demo: library only (imgui_demo.lua left out, like not compiling imgui_demo.cpp)
# --target love: build/imgui_love.lua for LÖVE/LuaJIT instead (LÖVE backend, shims from the LÖVE backend's COMPAT section, @native stripped).
# The default (roblox) build is unaffected by it.
# Why: ModuleScripts don't share globals, and the setfenv() alternative turns off Luau's fast paths / native codegen.
# Each source file becomes a function in __FILES; IM_INCLUDE(name) runs it once and caches the result.
# The module returns a table with every global the library defines (ImGui, ImVec2, ImGuiConfigFlags, ImGui_ImplRoblox, ...).
# Roblox target also writes ImGuiTyped.luau (types + require(script.Impl), see tools/gen_types.py).
# Roblox target also writes ImGuiTyped.luau (types + require(script.Impl), see tools/gen_types.py) and
# ImGuiWorker.client.luau: the parallel raster Actor LocalScript (backends/roblox/worker.luau with its
# `require(...Raster...)` line replaced by backends/roblox/raster.lua itself: self-contained, no require).
# The Roblox backend's modules are inlined into one function (see "Backend modules" below).
#
# Build-time optimizations (token rewrites with minify.py's lexer: strings/comments are never touched, every source line
# stays on its line so linemap.json still maps errors). IMGUI_BUNDLE_NOOPT=1 turns all off, IMGUI_BUNDLE_NO_<X>=1 one:
@@ -35,15 +39,39 @@ OPT = {x: os.environ.get("IMGUI_BUNDLE_NOOPT") != "1" and os.environ.get("IMGUI_
# A limits: Luau 200 locals in the main chunk (+ helpers, __FILES, ...), 200 upvalues per function; LuaJIT 60 upvalues
# per function (margin left for nested functions that also capture file locals)
MAX_LOCALS, MAX_UPVALUES = 160, (45 if LOVE else 150)
BACKEND = "imgui_impl_love.lua" if LOVE else "imgui_impl_roblox.lua"
SKIP = {"imgui_impl_roblox.lua", "imgui_impl_roblox_fonts.lua"} if LOVE else {"imgui_impl_love.lua"}
TARGET = "love" if LOVE else "roblox"
BACKEND = "imgui_impl_%s.lua" % TARGET
BACKEND_DIR = os.path.join(ROOT, "backends", TARGET) # every *.lua in it is bundled (*.luau, e.g. the worker, is not)
FILES = {}
for d in (ROOT, os.path.join(ROOT, "backends"), os.path.join(ROOT, "fonts")):
for d in [ROOT, BACKEND_DIR] + ([] if LOVE else [os.path.join(ROOT, "fonts")]):
for f in sorted(os.listdir(d)):
if f.endswith(".lua") and not (NO_DEMO and f == "imgui_demo.lua") and f not in SKIP:
if f.endswith(".lua") and not (NO_DEMO and f == "imgui_demo.lua"):
src = open(os.path.join(d, f)).read()
if LOVE: src = re.sub(r"^@native$", "", src, flags=re.M) # keep line numbers
FILES[f] = src
FILES[f if d != BACKEND_DIR or f == BACKEND else TARGET + "/" + f] = src
# Backend modules (backends/<target>/*.lua besides the main file, keyed "<target>/x.lua") are inlined into the main
# file's __FILES function: `local X = IM_INCLUDE("<target>/x.lua")` lines become blank (X is declared once at the top of
# the function), each module body goes in its own do ... end in dependency order, its final `return M` becomes `X = M`.
# Cross-module access is then a local of the same function, no IM_INCLUDE at load time. In source, the same files work
# with plain IM_INCLUDE (each a function returning its table).
INCLUDE = re.compile(r'^local (\w+) = IM_INCLUDE\("(%s/\w+\.lua)"\)[ \t]*$' % TARGET, re.M)
MODULES, EXPORT = [], {} # inline order, key -> local name
def visit(f, stack=()):
assert f not in stack, "backend modules: circular IM_INCLUDE %s" % " -> ".join(stack + (f,))
for name, key in INCLUDE.findall(FILES[f]):
assert EXPORT.setdefault(key, name) == name, "%s is included as both %s and %s" % (key, EXPORT[key], name)
if key not in MODULES: visit(key, stack + (f,)); MODULES.append(key)
visit(BACKEND)
unused = [f for f in FILES if f.startswith(TARGET + "/") and f not in MODULES]
assert not unused, "backend modules never included: %s" % unused
GROUP = {f: BACKEND for f in MODULES} # file -> __FILES function it is emitted in
def inline_module(key, src):
src = INCLUDE.sub("", src)
m = re.search(r"^return (\w+)[ \t]*\n*\Z", src, re.M)
assert m and m.group(1) != EXPORT[key], "%s must end with `return M` (a name other than %s)" % (key, EXPORT[key])
return src[:m.start()] + "%s = %s\n" % (EXPORT[key], m.group(1))
ORIG = dict(FILES) # for gen_types
ENTRY = ["imgui.lua", BACKEND] + ([] if NO_DEMO else ["imgui_demo.lua"]) # run order
@@ -52,6 +80,7 @@ names = set()
for src in FILES.values():
names.update(re.findall(r"^function ([A-Za-z_]\w*)\s*\(", src, re.M))
names.update(re.findall(r"^([A-Za-z_]\w*)\s*=[^=]", src, re.M))
assert not names & set(EXPORT.values()), "backend module names clash with globals: %s" % (names & set(EXPORT.values()))
# ---- lexer helpers ----
KW = set("and break do else elseif end false for function goto if in local nil not or repeat return then true until while".split())
@@ -147,7 +176,7 @@ if OPT["E"]:
hoisted = [rewrite_assert(s) for s in hoisted]
# ---- B: enum / constant folding ----
LUAU = shutil.which("luau") or "/nix/store/2m2ja613nndihc8qm10f2rhq6znp1nh4-luau-0.734/bin/luau"
LUAU = shutil.which("luau") or (sorted(__import__("glob").glob("/nix/store/*-luau-*/bin/luau")) or ["luau"])[-1]
def header():
return ["local __FILES, __LOADED = {}, {}",
@@ -234,13 +263,14 @@ if OPT["B"]:
# ---- A: hot globals -> bundle locals ----
hot = []
if OPT["A"]:
count, used = {}, []
for src in FILES.values():
count, used = {}, {}
for f, src in FILES.items():
toks = lex(src)
used.append({t for i, (k, t, _) in enumerate(toks) if isref(toks, i)})
used.setdefault(GROUP.get(f, f), set()).update(t for i, (k, t, _) in enumerate(toks) if isref(toks, i))
for i, (k, t, _) in enumerate(toks):
if t in names and isref(toks, i): count[t] = count.get(t, 0) + 1
# greedy by reference count; each file function's upvalues (hoisted names it uses) stay <= MAX_UPVALUES
used = list(used.values())
taken = [len(u & set(hoisted_names + re.findall(r"\w+", HOIST_DEPS.split("=")[0]))) for u in used]
for n in sorted((n for n in count if n not in hoisted_names), key=lambda n: (-count[n], n)):
if len(hot) == MAX_LOCALS: break
@@ -250,14 +280,24 @@ if OPT["A"]:
out = ["--!optimize 2", "-- GENERATED by tools/bundle.py from *.lua, backends/, fonts/ - do not edit", ""]
if LOVE:
out = ["-- GENERATED by tools/bundle.py --target love - do not edit", re.search(r"--@compat-begin\n(.*?)--@compat-end", open(os.path.join(ROOT, "backends", "imgui_impl_love.lua")).read(), re.S).group(1), ""]
out = ["-- GENERATED by tools/bundle.py --target love - do not edit", re.search(r"--@compat-begin\n(.*?)--@compat-end", open(os.path.join(BACKEND_DIR, BACKEND)).read(), re.S).group(1), ""]
if hot: out.append("local " + ", ".join(hot))
if hoisted: out += [HOIST_DEPS] + hoisted
out += header()
linemap = [] # (first bundle line, file) for error -> source mapping (tools/test/run.py)
def nextline(): return sum(x.count("\n") + 1 for x in out) + 1
for name, src in sorted(FILES.items()):
if name in GROUP: continue
out.append("__FILES[%r] = function()" % name)
linemap.append((sum(x.count("\n") + 1 for x in out) + 1, name))
if name == BACKEND and MODULES:
out.append("local " + ", ".join(EXPORT[k] for k in MODULES))
for k in MODULES:
out.append("do")
linemap.append((nextline(), k))
out.append(inline_module(k, FILES[k]).rstrip("\n"))
out.append("end")
src = INCLUDE.sub("", src)
linemap.append((nextline(), name))
out.append(src.rstrip("\n"))
out.append("end")
out.append("")
@@ -277,4 +317,11 @@ json.dump(linemap, open(os.path.join(OUT, NAME.rsplit(".", 1)[0] + ".linemap.jso
if not LOVE:
from gen_types import wrapper
open(os.path.join(OUT, "ImGuiTyped.luau"), "w").write(wrapper(ORIG))
worker = open(os.path.join(BACKEND_DIR, "worker.luau")).read()
req = re.search(r"^local Raster = require\(.*\)$", worker, re.M)
assert req, "worker: no `local Raster = require(...)` line"
raster = ORIG["roblox/raster.lua"].rstrip("\n")
open(os.path.join(OUT, "ImGuiWorker.client.luau"), "w").write(
"--!optimize 2\n-- GENERATED by tools/bundle.py from backends/roblox/worker.luau + raster.lua - do not edit\n"
+ worker[:req.start()] + "local Raster = (function()\n" + raster + "\nend)()" + worker[req.end():])
print("wrote build/%s (%d files, %d exports)" % (NAME, len(FILES), len(names)))
+19 -2
View File
@@ -113,15 +113,32 @@ def types_header(files):
lines += [" [string]: any,", "}"]
for name, keys in sorted(enums(files).items()):
lines.append("export type %s = { %s, [string]: number }" % (name, ", ".join("%s: number" % k for k in keys)))
return lines + module_type(set(enums(files)))
return lines + impl_type(files) + module_type(set(enums(files)))
def wrapper(files):
return "\n".join(["--!strict", "-- GENERATED by tools/gen_types.py - do not edit. The library is the child ModuleScript 'Impl'.", ""]
+ types_header(files) + ["", "return (require(script:WaitForChild(\"Impl\")) :: any) :: ImGuiModule", ""])
IMPL_SIGS = { # backend functions with exact types; the rest of ImGui_ImplRoblox is loose
"EnableParallel": "(opts: ImGuiParallelConfig?) -> ()",
"DisableParallel": "() -> ()", "FinishParallel": "() -> ()", "BeginParallelFrame": "() -> ()",
"GetParallelStats": "() -> { [string]: number }",
"GetParallelConfig": "() -> ImGuiParallelConfig",
}
def impl_type(files):
"""ImGui_ImplRoblox: the keys of the backend's public table (ImGui_ImplRoblox = { Name = ..., })"""
src = files.get("imgui_impl_roblox.lua", "")
m = re.search(r"^ImGui_ImplRoblox = \{\n(.*?)^\}", src, re.M | re.S)
keys = re.findall(r"^\s+(\w+)\s*=", m.group(1), re.M) if m else []
return (["export type ImGuiParallelConfig = { Actors: number?, MinTiles: number?, MinPixels: number?,"
" MaxBytesPerPixel: number?, Worker: any, Sync: boolean?, SyncDrop: boolean?, Inline: boolean?,"
" [string]: any }", "export type ImGuiImplRoblox = {"]
+ [" %s: %s," % (k, IMPL_SIGS.get(k, LOOSE)) for k in keys] + [" [string]: any,", "}"])
def module_type(enum_names):
# the bundle is too large for Luau to infer, so its return value is cast to this explicit type
lines = ["export type ImGuiModule = {", " ImGui: ImGuiAPI,"]
lines = ["export type ImGuiModule = {", " ImGui: ImGuiAPI,", " ImGui_ImplRoblox: ImGuiImplRoblox,"]
lines += [" %s: (x: number?, y: number?, z: number?, w: number?) -> %s," % (n, n) for n in ("ImVec2", "ImVec4")]
lines += [" %s: %s," % (n, n) for n in sorted(enum_names)]
return lines + [" [string]: any,", "}"]
+7
View File
@@ -4,6 +4,8 @@
# HASHES=1 tools/test/check_all.sh (also prints the draw-data checksums, see hashes.sh)
cd "$(dirname "$0")/../.."
export PATH="$PATH:/nix/store/2m2ja613nndihc8qm10f2rhq6znp1nh4-luau-0.734/bin:/nix/store/4qxq4arv32ly13kl3g0m5q80gm3a35xr-luajit-2.1.1741730670/bin"
command -v luau >/dev/null || { l=$(ls -d /nix/store/*-luau-*/bin 2>/dev/null | tail -1); [ -n "$l" ] && export PATH="$PATH:$l"; }
command -v luajit >/dev/null || { l=$(ls -d /nix/store/*-luajit-2*/bin 2>/dev/null | grep -v -- -env | tail -1); [ -n "$l" ] && export PATH="$PATH:$l"; }
T=$(mktemp -d /tmp/imgui_check.XXXX)
R="python3 tools/test/run.py --quiet --roblox --timeout 600"
@@ -36,7 +38,12 @@ CHECKS=(
"demo_open|DRAWHASH|$R --main tools/test/scripts/t_drawhash.luau --frames 150 --open"
"demo_random|^|python3 tools/test/run.py --roblox --timeout 600 --frames 400 --open"
"pixels|PIXELS SAME|a=\$($R --main tools/test/scripts/t_pixels.luau --frames 600 | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_pixels.luau --frames 600 | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo PIXELS SAME"
"tile_bound|TILEBOUND OK|$R --main tools/test/scripts/t_tile_bound.luau --frames 200"
"parallel|PARALLEL OK|$R --main tools/test/scripts/t_parallel.luau --frames 500"
"pool_ctx|POOLCTX OK|$R --main tools/test/scripts/t_pool_ctx.luau --frames 60"
"assets_scroll|ASSETS OK|$R --main tools/test/scripts/t_assets_scroll.luau --frames 1010"
"shot|wrote|python3 tools/test/shot.py /tmp/imgui_shot.png --app"
"registers|REGS OK|mkdir -p $T/regs && python3 tools/bundle.py $T/regs >/dev/null && h=\"\$(printf 'local _h%d = {} ' \$(seq 20))\" && grep -q \"^__FILES\\['imgui_impl_roblox.lua'\\] = function()\$\" $T/regs/ImGui.luau && for f in $T/regs/*.luau; do { echo \"\$h\"; sed \"/^__FILES\\['imgui_impl_roblox.lua'\\] = function()\$/a \$h\" \$f; } > \$f.h && luau-compile -O0 --null \$f.h || exit 1; done && ! grep -q require $T/regs/ImGuiWorker.client.luau && echo REGS OK"
"love|DRAWHASH|python3 tools/bundle.py --target love >/dev/null && luajit tools/test/love/t_drawhash.lua 60 Widgets,Basic && luajit tools/test/love/t_examples.lua"
)
+1 -1
View File
@@ -6,7 +6,7 @@ tmp = max(glob.glob("/tmp/imgui_test_*/ImGui.linemap.json"), key=os.path.getmtim
lm = json.load(open(tmp))
def loc(n):
if not n.isdigit(): return "C"
n = int(n) - 5 + 2; best = None
n = int(n) - 5 + 1; best = None # run.luau header lines, 1 stripped --! line (see run.py)
for start, name in lm:
if start <= n: best = (start, name)
return "%s:%d" % (best[1], n - best[0] + 1) if best else "?"
+12 -1
View File
@@ -58,6 +58,8 @@ end })
-- Instances
local InstMethods = {}
local InstMT = {}
local MOCK = { Sets = 0, Parents = 0, News = 0, EIs = 0, Uploads = 0, UploadPx = 0 } -- engine call counters (global MOCK), for perf benches
MOCK_STATS = MOCK
InstMT.__index = function(t, k)
if k == "Parent" then return rawget(t, "_parent") end
local pv = rawget(t, "_props")[k]; if pv ~= nil then return pv end
@@ -67,11 +69,13 @@ InstMT.__index = function(t, k)
end
InstMT.__newindex = function(t, k, v)
if k == "Parent" then
MOCK.Parents += 1
local old = rawget(t, "_parent")
if old then local ch = rawget(old, "_children"); for i, c in ipairs(ch) do if c == t then table.remove(ch, i) break end end end
rawset(t, "_parent", v)
if v then table.insert(rawget(v, "_children"), t) end
else
MOCK.Sets += 1
local props = rawget(t, "_props")
local old = props[k]
props[k] = v
@@ -96,6 +100,11 @@ end
function InstMethods:WaitForChild(name) return assert(self:FindFirstChild(name), "WaitForChild would hang: " .. name) end
function InstMethods:FindFirstChildOfClass(class) for _, c in ipairs(rawget(self, "_children")) do if c.ClassName == class then return c end end end
function InstMethods:GetChildren() return table.clone(rawget(self, "_children")) end
function InstMethods:GetDescendants()
local out = {}
for _, c in ipairs(rawget(self, "_children")) do table.insert(out, c); for _, d in ipairs(c:GetDescendants()) do table.insert(out, d) end end
return out
end
function InstMethods:IsA(class)
if class == "GuiObject" then return self.ClassName == "Frame" or self.ClassName == "ImageLabel" end
return self.ClassName == class
@@ -124,12 +133,14 @@ local RunService = { Heartbeat = Signal(), Stepped = Signal(), PreAnimation = Si
local last_pixels -- last buffer written to an EditableImage
local AssetService = {}
function AssetService:CreateEditableImage(opts)
MOCK.EIs += 1
local img = { Size = opts.Size, Pixels = buffer.create(opts.Size.X * opts.Size.Y * 4) }
UPLOADS = 0
function img:WritePixelsBuffer(origin, size, buf)
assert(buffer.len(buf) == size.X * size.Y * 4, "WritePixelsBuffer: buffer size mismatch")
assert(origin.X >= 0 and origin.Y >= 0 and origin.X + size.X <= opts.Size.X and origin.Y + size.Y <= opts.Size.Y, "WritePixelsBuffer: out of bounds")
for y = 0, size.Y - 1 do buffer.copy(img.Pixels, ((origin.Y + y) * opts.Size.X + origin.X) * 4, buf, y * size.X * 4, size.X * 4) end
MOCK.Uploads += 1; MOCK.UploadPx += size.X * size.Y
_G_UPLOADS = (_G_UPLOADS or 0) + 1; _G_UPLOAD_PX = (_G_UPLOAD_PX or 0) + size.X * size.Y
end
function img:Destroy() end
@@ -168,7 +179,7 @@ end
ROBLOX = setmetatable({
game = game, workspace = { CurrentCamera = { ViewportSize = v2(SCREEN_W, SCREEN_H) } }, require = rbxrequire, _G = fakeG,
Instance = { new = function(class) return newInst(class) end },
Instance = { new = function(class) MOCK.News += 1; return newInst(class) end },
Enum = Enum, Vector2 = Vector2,
Vector3 = { new = function(x, y, z) return { X = x, Y = y, Z = z } end },
UDim2 = { new = function(...) return { ... } end, fromScale = function(...) return { ... } end, fromOffset = function(x, y) return { X = x, Y = y } end },
+6 -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__))
ROOT = os.path.dirname(os.path.dirname(HERE))
LUAU = shutil.which("luau") or "/nix/store/2m2ja613nndihc8qm10f2rhq6znp1nh4-luau-0.734/bin/luau"
LUAU = shutil.which("luau") or (sorted(__import__("glob").glob("/nix/store/*-luau-*/bin/luau")) or ["luau"])[-1]
G = "game, workspace, Instance, Enum, Vector2, Vector3, UDim2, Color3, Content, UDim, CFrame, warn, require, script, os"
def build_run(args, flags):
@@ -25,8 +25,10 @@ def build_run(args, flags):
add("ImGui.luau", os.path.join(TMP, "ImGui.luau"))
add("main.client.luau", args.main)
out.append(open(os.path.join(HERE, "roblox_mock.luau")).read())
global OFFSET, LAST_LINE
LAST_LINE = open(os.path.join(TMP, "ImGui.luau")).read().count("\n")
global OFFSET, LAST_LINE, STRIPPED
bundle = open(os.path.join(TMP, "ImGui.luau")).read()
LAST_LINE = bundle.count("\n")
STRIPPED = sum(l.startswith("--!") for l in bundle.split("\n")) # removed by add() (all at the top)
OFFSET = 5 # lines before the ImGui function body in run.luau (flags/header lines + "function(...)" line)
path = os.path.join(TMP, "run.luau")
open(path, "w").write("\n".join(out))
@@ -45,8 +47,7 @@ def remap(text):
import json, re
lm = json.load(open(os.path.join(TMP, "ImGui.linemap.json")))
def sub(m):
n = int(m.group(1)) - OFFSET # line inside build/ImGui.luau (minus its 2 stripped --! lines)
n += 2
n = int(m.group(1)) - OFFSET + STRIPPED # line inside build/ImGui.luau
best = None
if n > LAST_LINE: return "<harness>:%d" % n
for start, name in lm:
+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)
+171
View File
@@ -0,0 +1,171 @@
-- Parallel raster executor (ImGui_ImplRoblox.EnableParallel) vs the inline backend, pixel for pixel. Two contexts draw the same
-- benchmark scenarios every frame: A inline (Config.Inline), B through the executor in Sync mode (the mock has no Actors: the "workers"
-- run inline, same code). Frames cycle through: dispatch window open (batches pending until Finish, like
-- PreSimulation -> PostSimulation), open with SyncDrop (half the worker results lost -> Finish falls back), and closed
-- (late RenderDrawData: rasterized + uploaded at once). The composites of A and B must match at every checkpoint.
-- Prints the executor's main-thread pack cost per frame next to A's inline raster + upload cost.
-- run: python3 tools/test/run.py --main tools/test/scripts/t_parallel.luau --frames 900 --quiet --roblox
local RS = game:GetService("ReplicatedStorage")
local G = require(RS:WaitForChild("ImGui"))
local ImGui, ImVec2 = G.ImGui, G.ImVec2
local Impl = G.ImGui_ImplRoblox
local W, H = 1280, 760
local N = ARG_N or 120 -- frames per scenario
local function composite(gui)
local screen = buffer.create(W * H * 3)
local function walk(inst, ox, oy, kx0, ky0, kx1, ky1)
local kids = inst:GetChildren()
table.sort(kids, function(a, b) return (a.ZIndex or 1) < (b.ZIndex or 1) end)
for _, c in ipairs(kids) do
if c.Visible ~= false then
local x, y = ox + (c.Position and c.Position.X or 0), oy + (c.Position and c.Position.Y or 0)
local cx0, cy0, cx1, cy1 = kx0, ky0, kx1, ky1
if c.ClipsDescendants then
cx0, cy0 = math.max(cx0, x), math.max(cy0, y)
cx1, cy1 = math.min(cx1, x + c.Size.X), math.min(cy1, y + c.Size.Y)
end
if c.ClassName == "ImageLabel" then
local px, sz = c.ImageContent.Object.Pixels, c.ImageContent.Object.Size.X
for ty = math.max(0, cy0 - y), math.min(sz, cy1 - y) - 1 do
local sy = y + ty
for tx = math.max(0, cx0 - x), math.min(sz, cx1 - x) - 1 do
local o = (ty * sz + tx) * 4
local a = buffer.readu8(px, o + 3)
if a > 0 then
local d = (sy * W + x + tx) * 3
local fa = a / 255
for ch = 0, 2 do
buffer.writeu8(screen, d + ch, math.floor(buffer.readu8(px, o + ch) * fa + buffer.readu8(screen, d + ch) * (1 - fa) + 0.5))
end
end
end
end
end
walk(c, x, y, cx0, cy0, cx1, cy1)
end
end
end
walk(gui, 0, 0, 0, 0, W, H)
local h = 0
for i = 0, W * H * 3 - 4, 4 do h = (h * 31 + buffer.readu32(screen, i)) % 2147483647 end
return h
end
local plot = table.create(120, 0)
local SCEN = {
{ "resize", function(f)
local s = 520 + ((f % 80) < 40 and (f % 40) * 7 or (40 - f % 40) * 7)
ImGui.ShowDemoWindow()
ImGui.SetWindowPos("Dear ImGui Demo", ImVec2(30, 20)); ImGui.SetWindowSize("Dear ImGui Demo", ImVec2(s, s * 0.8 + 60))
end },
{ "assets", function(f)
ImGui.SetNextWindowPos(ImVec2(20, 20), G.ImGuiCond.Always)
G.ShowExampleAppAssetsBrowser(true)
local w = ImGui.FindWindowByName("Example: Assets Browser")
if w and f > 2 then for _, c in ipairs(w.DC.ChildWindows.Data) do ImGui.SetScrollY(c, (f * 40) % 6000) end end
end },
{ "list", function(f)
ImGui.SetNextWindowPos(ImVec2(40, 30), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(560, 680), G.ImGuiCond.Always)
ImGui.Begin("Long list")
ImGui.SetScrollY(13 * (f <= 60 and f or 120 - f))
local clipper = G.ImGuiListClipper()
clipper:Begin(10000)
while clipper:Step() do
for i = clipper.DisplayStart, clipper.DisplayEnd - 1 do ImGui.Text("%05d: The quick brown fox jumps over the lazy dog", i) end
end
ImGui.End()
end },
{ "plots", function(f)
for i = 1, 120 do plot[i] = math.sin((i + f) * 0.15) + 0.3 * math.sin((i * 3 + f) * 0.4) end
ImGui.SetNextWindowPos(ImVec2(40, 30), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(620, 520), G.ImGuiCond.Always)
ImGui.Begin("Plots")
ImGui.PlotLines("Lines", plot, nil, 120, 0, nil, -1.5, 1.5, ImVec2(0, 160))
ImGui.PlotHistogram("Histogram", plot, nil, 120, 0, nil, -1.5, 1.5, ImVec2(0, 160))
ImGui.Text("frame %d", f)
ImGui.End()
end },
}
local ctx, gui = {}, {}
for i = 1, 2 do
ctx[i] = ImGui.CreateContext()
ImGui.SetCurrentContext(ctx[i])
local parent = Instance.new("Folder")
Impl.Init(parent)
Impl.SetRenderRate(0)
Impl.SetStageTiming(true)
gui[i] = parent:FindFirstChild("ImGui")
end
Impl.EnableParallel({ Sync = true, Actors = 4 })
local C = Impl.GetParallelConfig()
local si, f, checks, bad = 1, 0, 0, 0
local pack, inline, flushes = {}, {}, { open = 0, drop = 0, closed = 0 }
local S = Impl.GetParallelStats()
local s0 = table.clone(S)
local kb = { 0, 0 } -- KB allocated in RenderDrawData (+ Finish for the executor context), per context
local function k_add(i, k0) local d = collectgarbage("count") - k0; if f > 5 and d > 0 then kb[i] += d end end
game:GetService("RunService").Stepped:Connect(function()
local sc = SCEN[si]
if not sc then return end
f += 1
local mode = f % 3 -- 0 closed, 1 open, 2 open + SyncDrop
C.SyncDrop = mode == 2
if mode ~= 0 then Impl.BeginParallelFrame() end
flushes[mode == 0 and "closed" or mode == 1 and "open" or "drop"] += 1
for i = 1, 2 do
ImGui.SetCurrentContext(ctx[i])
C.Inline = i == 1
Impl.NewFrame()
local io = ImGui.GetIO()
io.DeltaTime = 1 / 60
io:AddMousePosEvent(1270, 750)
ImGui.NewFrame()
sc[2](f)
ImGui.Render()
local fake = os.clock
os.clock = os.realclock -- (mock: os.clock is frozen; real time for the stage / pack timers)
local p0, k0 = S.Pack, collectgarbage("count")
Impl.RenderDrawData(ImGui.GetDrawData())
k_add(i, k0)
os.clock = fake
if f > 5 then
if i == 1 then local st = Impl.GetStats().Frame; table.insert(inline, (st.Raster + st.Upload) * 1000)
else table.insert(pack, (S.Pack - p0) * 1000) end
end
end
local k0 = collectgarbage("count")
Impl.FinishParallel()
k_add(2, k0)
if f % 10 == 0 or f == N then
checks += 1
local a, b = composite(gui[1]), composite(gui[2])
if a ~= b then bad += 1; print("MISMATCH", sc[1], f, a, b) end
end
if f == N then
local function stats(t)
local s, m = 0, 0
for _, v in t do s += v; m = math.max(m, v) end
return s / math.max(#t, 1), m
end
local pm, px = stats(pack)
local im, ix = stats(inline)
print(string.format("PACK %-7s mean %.3f max %.3f ms/frame | inline raster+upload mean %.3f max %.3f ms/frame | tiles %.1f rects %.1f send %d KB/frame, tex resends %d (%d KB)",
sc[1], pm, px, im, ix, (S.Tiles - s0.Tiles) / N, (S.Rects - s0.Rects) / N, (S.SendBytes - s0.SendBytes) / 1024 / N, S.TexSends - s0.TexSends, (S.TexBytes - s0.TexBytes) / 1024))
print(string.format("ALLOC %-7s KB/frame inline %.1f executor %.1f (Sync: includes the inline worker raster)", sc[1], kb[1] / (N - 5), kb[2] / (N - 5)))
kb = { 0, 0 }
s0 = table.clone(S)
pack, inline = {}, {}
for i = 1, 2 do ImGui.SetCurrentContext(ctx[i]); Impl.SetRenderScale(2); Impl.SetRenderScale(1) end
si += 1; f = 0
Impl.EnableParallel({ Actors = si }) -- runtime re-Enable with a different actor count (pixels must still match)
assert(C.Sync and Impl.GetParallelConfig() == C, "re-Enable kept Sync")
if not SCEN[si] then
print(string.format("STATS parallel flushes %d serial %d tiles %d fallbacks %d | frames open %d drop %d closed %d",
S.ParallelFlushes, S.SerialFlushes, S.Tiles, S.Fallbacks, flushes.open, flushes.drop, flushes.closed))
assert(S.ParallelFlushes > 0 and S.SerialFlushes > 0 and S.Fallbacks > 0, "a path was not exercised")
if bad == 0 then print("PARALLEL OK " .. checks .. " checkpoints") else print("PARALLEL FAIL " .. bad .. "/" .. checks) end
end
end
end)
+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)
+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
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
SRC = ROOT # library *.lua at the root + backends/ (--no-demo: leave imgui_demo.lua out to check the library never needs it)
SRC = ROOT # library *.lua at the root + backends/roblox, backends/love (--no-demo: leave imgui_demo.lua out to check the library never needs it)
import sys
NO_DEMO = "--no-demo" in sys.argv
files = {}
for dp, fn in ((ROOT, os.listdir(ROOT)), (os.path.join(ROOT, "backends"), os.listdir(os.path.join(ROOT, "backends")))):
for dp in (ROOT, os.path.join(ROOT, "backends", "roblox"), os.path.join(ROOT, "backends", "love")):
fn = os.listdir(dp)
for f in fn:
if f.endswith(".lua") and not (NO_DEMO and f == "imgui_demo.lua"):
files[os.path.relpath(os.path.join(dp, f), SRC)] = open(os.path.join(dp, f)).read()