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

File diff suppressed because it is too large. Load diff
File renamed without changes.
+484
View File
@@ -0,0 +1,484 @@
-- ImGui backend for Roblox: platform, input, files, Init/Shutdown and the public API; rendering in render.lua.
-- Requires "Allow Mesh / Image APIs" (EditableImage) in game settings.
local Textures = IM_INCLUDE("roblox/textures.lua")
local Layers = IM_INCLUDE("roblox/layers.lua")
local Render = IM_INCLUDE("roblox/render.lua")
local Parallel = IM_INCLUDE("roblox/parallel.lua")
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local floor, min = math.floor, math.min
local EditableImages, PB, PE = Textures.EditableImages, Textures.PB, Textures.PE
local ImGui_ImplRoblox_GetBackendData = Textures.GetBackendData
local ImGui_ImplRoblox_RenderDrawData = Render.RenderDrawData
local DestroyTiles = Layers.DestroyTiles
local KEY_MAP = {}
do
local names = {
Return = "Enter", Escape = "Escape", Backspace = "Backspace", Tab = "Tab", Space = "Space",
KeypadEnter = "KeypadEnter",
Up = "UpArrow", Down = "DownArrow", Left = "LeftArrow", Right = "RightArrow",
Home = "Home", End = "End", PageUp = "PageUp", PageDown = "PageDown", Insert = "Insert", Delete = "Delete",
LeftControl = "LeftCtrl", RightControl = "RightCtrl", LeftShift = "LeftShift", RightShift = "RightShift",
LeftAlt = "LeftAlt", RightAlt = "RightAlt", LeftSuper = "LeftSuper", RightSuper = "RightSuper",
Quote = "Apostrophe", Comma = "Comma", Minus = "Minus", Period = "Period", Slash = "Slash",
Semicolon = "Semicolon",
Equals = "Equal", LeftBracket = "LeftBracket", BackSlash = "Backslash", RightBracket = "RightBracket",
Backquote = "GraveAccent",
CapsLock = "CapsLock",
KeypadPeriod = "KeypadDecimal", KeypadDivide = "KeypadDivide", KeypadMultiply = "KeypadMultiply",
KeypadMinus = "KeypadSubtract", KeypadPlus = "KeypadAdd", KeypadEquals = "KeypadEqual",
}
local digits = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }
for i = 0, 9 do
names[digits[i + 1]] = "K" .. i
names["Keypad" .. digits[i + 1]] = "Keypad" .. i
end
for i = 1, 12 do names["F" .. i] = "F" .. i end
for c in ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"):gmatch(".") do names[c] = c end
for rbx_name, imgui_name in pairs(names) do
KEY_MAP[Enum.KeyCode[rbx_name]] = ImGuiKey[imgui_name]
end
end
-- No text input event: characters come from KeyCode.Value (printable ASCII) + a US layout shift table
local SHIFTED = {
["1"] = "!", ["2"] = "@", ["3"] = "#", ["4"] = "$", ["5"] = "%", ["6"] = "^", ["7"] = "&", ["8"] = "*", ["9"] = "(",
["0"] = ")",
["-"] = "_", ["="] = "+", ["["] = "{", ["]"] = "}", ["\\"] = "|", [";"] = ":", ["'"] = "\"", [","] = "<",
["."] = ">", ["/"] = "?", ["`"] = "~",
}
local MOUSE_BUTTONS = {
[Enum.UserInputType.MouseButton1] = 0,
[Enum.UserInputType.MouseButton2] = 1,
[Enum.UserInputType.MouseButton3] = 2,
}
local function ImGui_ImplRoblox_UpdateKeyModifiers()
local io = ImGui.GetIO()
local K = Enum.KeyCode
local ctrl = UserInputService:IsKeyDown(K.LeftControl) or UserInputService:IsKeyDown(K.RightControl)
local shift = UserInputService:IsKeyDown(K.LeftShift) or UserInputService:IsKeyDown(K.RightShift)
local alt = UserInputService:IsKeyDown(K.LeftAlt) or UserInputService:IsKeyDown(K.RightAlt)
io:AddKeyEvent(ImGuiMod_Ctrl, ctrl)
io:AddKeyEvent(ImGuiMod_Shift, shift)
io:AddKeyEvent(ImGuiMod_Alt, alt)
io:AddKeyEvent(ImGuiMod_Super, UserInputService:IsKeyDown(K.LeftSuper) or UserInputService:IsKeyDown(K.RightSuper))
return ctrl, shift, alt
end
local function ImGui_ImplRoblox_UpdateMonitors(w, h)
local platform_io = ImGui.GetPlatformIO()
platform_io.Monitors:resize(0)
local imgui_monitor = ImGuiPlatformMonitor()
ImVec2_Copy(imgui_monitor.MainSize, ImVec2(w, h))
ImVec2_Copy(imgui_monitor.WorkSize, ImVec2(w, h))
platform_io.Monitors:push_back(imgui_monitor)
end
-- Games can't touch the OS clipboard, so copy/paste only works inside ImGui
local Clipboard = ""
local function ImGui_ImplRoblox_PlatformSetClipboardText(ctx, text) Clipboard = text end
local ProxyFocused = false
local function ImGui_ImplRoblox_PlatformGetClipboardText(ctx) if ProxyFocused then return "" end return Clipboard end
local VFS = {}
local function ImGui_ImplRoblox_AddFile(path, bytes) VFS[path] = bytes end
for path, hex in pairs(IM_INCLUDE("imgui_impl_roblox_fonts.lua")) do
VFS[path] = hex:gsub("%s", ""):gsub("%x%x", function(h) return string.char(tonumber(h, 16)) end)
end
function ImStd.ImFileOpen(filename, mode)
local data = VFS[filename]
return data and { Data = data, Pos = 0 } or nil
end
function ImStd.ImFileClose(f) end
function ImStd.ImFileGetSize(f) return #f.Data end
function ImStd.ImFileRead(f, data, count)
local s, pos = f.Data, f.Pos
count = min(count, #s - pos)
for i = 1, count do data[i] = string.byte(s, pos + i) end
f.Pos = pos + count
return count
end
function ImStd.ImFileLoadToMemory(filename, mode)
local f = ImStd.ImFileOpen(filename, mode)
if not f or #f.Data == 0 then return end
local file_data = {}
local size = ImStd.ImFileRead(f, file_data, #f.Data)
return file_data, size
end
-- render_scale: imgui pixels per Roblox UI point (default 1; 1.5 on a 150% display = physical resolution)
function ImGui_ImplRoblox_Init(parent, render_scale)
local io = ImGui.GetIO()
local gui = Instance.new("ScreenGui")
gui.Name = "ImGui"
gui.IgnoreGuiInset = true -- so GetMouseLocation() and the tiles share the same origin
gui.ResetOnSpawn = false
gui.DisplayOrder = 1000
gui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling -- layers (one Frame per draw list) stack by ZIndex
gui.Parent = parent or Players.LocalPlayer:WaitForChild("PlayerGui")
local BackendData = {
Time = os.clock(), Gui = gui, Connections = {},
Textures = Textures.Records, MouseX = -1, MouseY = -1,
Layers = {}, Overlays = {}, OverlayHolders = {}, OverlayShown = {}, FrameNo = 0, Scale = render_scale or 1,
TilesActive = false, RenderRate = 60, BusyRenderRate = 0, RedrawBudget = 0, HeartbeatCount = 0,
NextRender = 0, LastPrimCount = 0, ForceRedraw = true,
}
io.BackendPlatformUserData = BackendData
EditableImages.Backends[BackendData] = true
io.BackendPlatformName = "imgui_impl_roblox"
io.BackendRendererName = "imgui_impl_roblox"
io.BackendFlags = bit32.bor(io.BackendFlags, ImGuiBackendFlags.RendererHasTextures,
ImGuiBackendFlags.RendererHasVtxOffset)
local platform_io = ImGui.GetPlatformIO()
platform_io.Platform_SetClipboardTextFn = ImGui_ImplRoblox_PlatformSetClipboardText
platform_io.Platform_GetClipboardTextFn = ImGui_ImplRoblox_PlatformGetClipboardText
local screen = gui.AbsoluteSize
ImGui_ImplRoblox_UpdateMonitors(screen.X, screen.Y)
local function connect(signal, fn) table.insert(BackendData.Connections, signal:Connect(fn)) end
connect(UserInputService.InputBegan, function(input, game_processed)
local io = ImGui.GetIO()
local button = MOUSE_BUTTONS[input.UserInputType]
if button then
io:AddMouseSourceEvent(ImGuiMouseSource.Mouse)
io:AddMouseButtonEvent(button, true)
elseif input.UserInputType == Enum.UserInputType.Keyboard and (not game_processed or ProxyFocused) then
local ctrl, shift, alt = ImGui_ImplRoblox_UpdateKeyModifiers()
local key = KEY_MAP[input.KeyCode]
if key then io:AddKeyEvent(key, true) end
if ProxyFocused and (key == ImGuiKey.Backspace or key == ImGuiKey.Delete) then
ImGui_ImplRoblox_GetBackendData().DeleteKeySeen = true
end
local v = input.KeyCode.Value
if v >= 32 and v < 127 and not (ctrl or alt) then
local c = string.char(v)
if shift then c = SHIFTED[c] or c:upper() end
-- while the proxy may own input, hold the char: NewFrame types it only if the proxy didn't deliver text
if ProxyFocused then table.insert(ImGui_ImplRoblox_GetBackendData().PendingChars, string.byte(c))
else io:AddInputCharacter(string.byte(c)) end
end
end
end)
connect(UserInputService.InputEnded, function(input, game_processed)
local io = ImGui.GetIO()
local button = MOUSE_BUTTONS[input.UserInputType]
if button then
io:AddMouseButtonEvent(button, false)
elseif input.UserInputType == Enum.UserInputType.Keyboard then
ImGui_ImplRoblox_UpdateKeyModifiers()
local key = KEY_MAP[input.KeyCode]
if key then io:AddKeyEvent(key, false) end
end
end)
connect(UserInputService.InputChanged, function(input, game_processed)
if input.UserInputType == Enum.UserInputType.MouseWheel then
ImGui.GetIO():AddMouseWheelEvent(0, input.Position.Z)
end
end)
BackendData.PendingChars = {}
-- Render rate cap trailing edge: the last frame submitted is always drawn, even if the app then stopped rendering
connect(game:GetService("RunService").Heartbeat, function()
local d = BackendData.Pending
if d and os.clock() + 0.002 >= BackendData.NextRender then
BackendData.Pending = nil
ImGui_ImplRoblox_RenderDrawData(d)
elseif BackendData.Stale and BackendData.HeartbeatCount > BackendData.StaleHeartbeat then
ImGui_ImplRoblox_RenderDrawData(BackendData.Stale)
end
BackendData.HeartbeatCount += 1
end)
connect(UserInputService.WindowFocused, function() ImGui.GetIO():AddFocusEvent(true) end)
connect(UserInputService.WindowFocusReleased, function() ImGui.GetIO():AddFocusEvent(false) end)
end
-- Text proxy (opt-in): a hidden TextBox holds focus while a text field is active (OS typing, paste, copy/cut)
function ImGui_ImplRoblox_SetTextProxy(enabled)
local BackendData = ImGui_ImplRoblox_GetBackendData()
if not enabled then
if BackendData.Proxy then
BackendData.Proxy:Destroy()
BackendData.Proxy = nil
end
ProxyFocused = false
return
end
if BackendData.Proxy then return end
local proxy = Instance.new("TextBox")
proxy.Name = "TextProxy"
proxy.BackgroundTransparency = 1
proxy.TextTransparency = 0 -- kept opaque but parked off screen: a transparent TextBox may not get native paste
proxy.BorderSizePixel = 0
proxy.Size = UDim2.fromOffset(200, 20)
proxy.Position = UDim2.fromOffset(-10000, -10000)
proxy.MultiLine = true
proxy.ClearTextOnFocus = false
proxy.TextEditable = true
proxy.Text = ""
proxy.Parent = BackendData.Gui
BackendData.Proxy, BackendData.ProxyText = proxy, ""
-- Text is polled in NewFrame: TextBox change signals are deferred in Roblox
proxy.FocusLost:Connect(function()
if BackendData.ProxyReleasing then return end
-- Roblox drops TextBox focus on any click, also inside imgui: only a click outside imgui ends the edit
if ImGui.GetIO().WantCaptureMouse then
BackendData.ProxyLostId = nil
return
end
BackendData.ProxyLostId = BackendData.ProxyActiveId
local g = ImGui.GetCurrentContext()
if g and g.ActiveId ~= 0 and g.ActiveId == BackendData.ProxyActiveId then ImGui.ClearActiveID() end
end)
end
local function ImGui_ImplRoblox_Shutdown()
local io = ImGui.GetIO()
local BackendData = ImGui_ImplRoblox_GetBackendData()
for _, c in ipairs(BackendData.Connections) do c:Disconnect() end
DestroyTiles(BackendData)
EditableImages.Backends[BackendData] = nil
BackendData.Gui:Destroy()
io.BackendPlatformUserData = nil
io.BackendPlatformName = nil
io.BackendRendererName = nil
io.BackendFlags = bit32.band(io.BackendFlags, bit32.bnot(bit32.bor(
ImGuiBackendFlags.RendererHasTextures,
ImGuiBackendFlags.RendererHasVtxOffset
)))
end
function ImGui_ImplRoblox_NewFrame()
PB("ImGui NewFrame (backend)")
local io = ImGui.GetIO()
local BackendData = ImGui_ImplRoblox_GetBackendData()
if BackendData.Pending then -- skipped frame superseded (its draw lists get reset)
BackendData.Pending = nil
table.clear(BackendData.Overlays)
end
BackendData.Stale = nil
local screen = BackendData.Gui.AbsoluteSize
local w, h = floor(screen.X * BackendData.Scale), floor(screen.Y * BackendData.Scale)
if w ~= BackendData.ScreenW or h ~= BackendData.ScreenH then
BackendData.ScreenW, BackendData.ScreenH = w, h
ImGui_ImplRoblox_UpdateMonitors(w, h)
end
ImVec2_CopyV(io.DisplaySize, w, h)
local current_time = os.clock()
io.DeltaTime = (current_time > BackendData.Time) and (current_time - BackendData.Time) or (1.0 / 60.0)
BackendData.Time = current_time
local m = UserInputService:GetMouseLocation()
if m.X ~= BackendData.MouseX or m.Y ~= BackendData.MouseY then
BackendData.MouseX, BackendData.MouseY = m.X, m.Y
io:AddMouseSourceEvent(ImGuiMouseSource.Mouse)
io:AddMousePosEvent(m.X * BackendData.Scale, m.Y * BackendData.Scale)
end
local proxy = BackendData.Proxy
local g = ImGui.GetCurrentContext()
local focused_box = proxy and UserInputService:GetFocusedTextBox()
if not proxy then
elseif io.WantTextInput and g.ActiveId ~= 0 then
if g.ActiveId ~= BackendData.ProxyActiveId or g.ActiveIdIsJustActivated or g.IO.MouseClicked[0] then
BackendData.ProxyActiveId = g.ActiveId
BackendData.ProxyLostId = nil
end
local mouse_up = not (io.MouseDown[0] or io.MouseDown[1] or io.MouseDown[2])
if focused_box ~= proxy and mouse_up and BackendData.ProxyLostId ~= g.ActiveId
and (focused_box == nil or not focused_box:IsDescendantOf(game)) then
-- what it already holds is not new input (else re-typing it would collapse imgui's selection)
BackendData.ProxyText = proxy.Text
proxy:CaptureFocus()
focused_box = UserInputService:GetFocusedTextBox()
end
elseif focused_box == proxy then
BackendData.ProxyReleasing = true
proxy:ReleaseFocus()
BackendData.ProxyReleasing = false
focused_box = nil
end
ProxyFocused = proxy ~= nil and focused_box == proxy
local used_proxy_text = false
if ProxyFocused then
local text = proxy.Text
if text ~= BackendData.ProxyText and text ~= BackendData.ProxyLastRaw then
BackendData.ProxyLastRaw = text
-- InputText ignores chars while Ctrl is held; a paste arrives with Ctrl down, so release it around them
local ctrl = io.KeyCtrl or UserInputService:IsKeyDown(Enum.KeyCode.LeftControl)
or UserInputService:IsKeyDown(Enum.KeyCode.RightControl)
if ctrl then io:AddKeyEvent(ImGuiMod_Ctrl, false) end
local prev = BackendData.ProxyText or ""
if #text < #prev and prev:sub(1, #text) == text and text:sub(-1) ~= "\n" then
-- the TextBox deleted from its own text (no real selection): one Backspace on imgui's selection
if not BackendData.DeleteKeySeen then
io:AddKeyEvent(ImGuiKey.Backspace, true)
io:AddKeyEvent(ImGuiKey.Backspace, false)
end
elseif text ~= "\n" and text ~= "\r" and text ~= "\t" then -- Enter/Tab arrive as key events
local prev = BackendData.ProxyText or ""
if #text > 0 and (prev == "" or text:sub(1, #prev) ~= prev or #text <= #prev) then
for _, cp in utf8.codes(text) do io:AddInputCharacter(cp) end
elseif #text > #prev then
for _, cp in utf8.codes(text:sub(#prev + 1)) do io:AddInputCharacter(cp) end
end
end
if ctrl then io:AddKeyEvent(ImGuiMod_Ctrl, true) end
used_proxy_text = true
BackendData.ProxyText = nil
end
local st = g.InputTextState
local sel = ""
if st and st.ID ~= 0 and st.ID == g.ActiveId and st.Stb and st:HasSelection() then
local a, b = math.min(st.Stb.select_start, st.Stb.select_end),
math.max(st.Stb.select_start, st.Stb.select_end)
sel = ImGui._ByteArrayToString(st.TextA.Data, a, b) -- stb positions are 1-based in this port
end
if sel ~= BackendData.ProxyText then
proxy.Text = sel
BackendData.ProxyLastRaw = nil
BackendData.ProxyText = sel
end
-- mirror imgui's selection, fully selected, so native Ctrl+C copies it and typing/Ctrl+V replaces it
local want_sel, want_cur = (#sel > 0) and 1 or -1, #sel + 1
if proxy.SelectionStart ~= want_sel then proxy.SelectionStart = want_sel end
if proxy.CursorPosition ~= want_cur then proxy.CursorPosition = want_cur end
end
BackendData.DeleteKeySeen = false
local pending = BackendData.PendingChars
if #pending > 0 then
if not used_proxy_text then for _, c in ipairs(pending) do io:AddInputCharacter(c) end end
table.clear(pending)
end
-- Tiles Active while over imgui, so Roblox stops passing clicks/wheel to the game (camera zoom etc.)
local want = io.WantCaptureMouse
if want ~= BackendData.TilesActive then
BackendData.TilesActive = want
for _, set in pairs(BackendData.Layers) do
for kind = 1, 3 do
local layer = set[kind]
if layer then for _, tile in pairs(layer.Tiles) do tile.Label.Active = want end end
end
end
end
PE()
end
-- Public API (documented in README.md)
function ImGui_ImplRoblox_SetRedrawBudget(ms)
ImGui_ImplRoblox_GetBackendData().RedrawBudget = (ms or 0) / 1000
end
function ImGui_ImplRoblox_SetRenderRate(hz)
ImGui_ImplRoblox_GetBackendData().RenderRate = hz or 0
end
function ImGui_ImplRoblox_SetBusyRenderRate(hz)
ImGui_ImplRoblox_GetBackendData().BusyRenderRate = hz or 0
end
function ImGui_ImplRoblox_SetProfiling(enabled) Textures.SetProfiling(enabled) end
local ImGui_ImplRoblox_IsProfiling = Textures.IsProfiling
function ImGui_ImplRoblox_SetStageTiming(enabled)
EditableImages.StageTiming = enabled and true or false
if not EditableImages.StageTiming then EditableImages.StageFrame = nil end
end
function ImGui_ImplRoblox_SetRenderScale(scale)
local BackendData = ImGui_ImplRoblox_GetBackendData()
if scale == BackendData.Scale then return end
BackendData.Scale = scale
DestroyTiles(BackendData)
BackendData.ForceRedraw = true
end
function ImGui_ImplRoblox_GetStats()
local BackendData = ImGui_ImplRoblox_GetBackendData()
local tiles = 0
for _, set in pairs(BackendData.Layers) do
for kind = 1, 3 do if set[kind] then for _ in pairs(set[kind].Tiles) do tiles += 1 end end end
end
return { Tiles = tiles, EditableImages = EditableImages.Count, EditableImageBytes = EditableImages.Bytes,
EditableImageCap = EditableImages.Cap, Instances = #BackendData.Gui:GetDescendants(),
Frame = BackendData.FrameStats, Renders = BackendData.FrameNo }
end
function ImGui_ImplRoblox_SetEditableImageCap(bytes)
EditableImages.Cap = bytes or 64 * 1024 * 1024
EditableImages.Evict(EditableImages.Bytes - EditableImages.Cap)
end
function ImGui_ImplRoblox_EnableParallel(opts) Parallel.Enable(opts) end
function ImGui_ImplRoblox_DisableParallel() Parallel.Disable() end
function ImGui_ImplRoblox_FinishParallel() Parallel.Finish() end
function ImGui_ImplRoblox_BeginParallelFrame() Parallel.BeginFrame() end
function ImGui_ImplRoblox_GetParallelStats() return Parallel.Stats end
function ImGui_ImplRoblox_GetParallelConfig() return Parallel.Config end
ImGui_ImplRoblox = {
Init = ImGui_ImplRoblox_Init,
Shutdown = ImGui_ImplRoblox_Shutdown,
NewFrame = ImGui_ImplRoblox_NewFrame,
RenderDrawData = ImGui_ImplRoblox_RenderDrawData,
AddFile = ImGui_ImplRoblox_AddFile,
CreateTexture = ImGui_ImplRoblox_CreateTexture,
DestroyTexture = ImGui_ImplRoblox_DestroyTexture,
SetOverlay = ImGui_ImplRoblox_SetOverlay,
SetTextProxy = ImGui_ImplRoblox_SetTextProxy,
SetRenderScale = ImGui_ImplRoblox_SetRenderScale,
GetRenderScale = function() return ImGui_ImplRoblox_GetBackendData().Scale end,
SetRenderRate = ImGui_ImplRoblox_SetRenderRate,
SetBusyRenderRate = ImGui_ImplRoblox_SetBusyRenderRate,
SetRedrawBudget = ImGui_ImplRoblox_SetRedrawBudget,
SetProfiling = ImGui_ImplRoblox_SetProfiling,
IsProfiling = ImGui_ImplRoblox_IsProfiling,
SetStageTiming = ImGui_ImplRoblox_SetStageTiming,
GetStats = ImGui_ImplRoblox_GetStats,
SetEditableImageCap = ImGui_ImplRoblox_SetEditableImageCap,
EnableParallel = ImGui_ImplRoblox_EnableParallel,
DisableParallel = ImGui_ImplRoblox_DisableParallel,
FinishParallel = ImGui_ImplRoblox_FinishParallel,
BeginParallelFrame = ImGui_ImplRoblox_BeginParallelFrame,
GetParallelStats = ImGui_ImplRoblox_GetParallelStats,
GetParallelConfig = ImGui_ImplRoblox_GetParallelConfig,
}
return true -- [Roblox] ModuleScripts must return exactly one value
+335
View File
@@ -0,0 +1,335 @@
-- Layers and tiles (one Frame per draw list and kind, TILE x TILE EditableImages); draw list snapshot/compare
local Raster = IM_INCLUDE("roblox/raster.lua")
local Textures = IM_INCLUDE("roblox/textures.lua")
local floor, max = math.floor, math.max
local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64
local TILE = Raster.TILE
local EditableImages = Textures.EditableImages
local M = {}
-- content up to this far off screen is kept, so dragging a window past the edge doesn't redraw it
local CLIP_PAD = 2048
M.CLIP_PAD = CLIP_PAD
-- per draw command, filled by CollectPrims for Snapshot: no primitive clipped, layer kind, bounds of its primitives
local CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1 = {}, {}, {}, {}, {}, {}
M.CmdUnclipped, M.CmdKind, M.CmdBoundsX0, M.CmdBoundsY0, M.CmdBoundsX1, M.CmdBoundsY1 =
CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1
-- free per-tile primitive lists, 4 at a time
EditableImages.ListPool = {}
-- Kinds: 1 = before the window content (background, title bar, scrollbar), 2 = content (at the scroll origin in a
-- ClipsDescendants frame, so scrolling just moves it), 3 = drawn after content, not clipped to it (menu bar).
local function NewFrame(parent, clips)
local frame = Instance.new("Frame")
frame.Name = "Layer"
frame.BackgroundTransparency = 1
frame.BorderSizePixel = 0
frame.Size = UDim2.fromOffset(0, 0)
frame.ClipsDescendants = clips
frame.Visible = false
frame.Parent = parent
return frame
end
function M.GetLayer(BackendData, draw_list, kind)
local set = BackendData.Layers[draw_list]
if not set then
set = { LastUsed = 0 }
BackendData.Layers[draw_list] = set
end
local layer = set[kind]
if layer then return layer end
local root, frame
if kind == 2 then
root = NewFrame(BackendData.Gui, true)
frame = NewFrame(root, false)
frame.Visible = true
else
frame = NewFrame(BackendData.Gui, false)
root = frame
end
layer = {
Root = root, Frame = frame, Tiles = {},
TileHash1 = {}, TileHash2 = {}, TileCounts = {}, TileLists = {},
TileListHash1 = {}, TileListHash2 = {}, TileListFlat = {}, TileX = {}, TileY = {},
Touched = {}, TouchedCount = 0,
Visible = false, X = false, Y = false, Z = -1,
ClipX0 = false, ClipY0 = false, ClipX1 = false, ClipY1 = false,
}
set[kind] = layer
return layer
end
function M.HideLayer(layer)
if layer.Visible then
layer.Visible = false
layer.Root.Visible = false
end
end
-- recycle: to EditableImages.Pool. Its label stays parented (hidden): Studio reparenting costs far more than a
-- property set, and a scrolling layer's next tile usually goes back into the same frame
function EditableImages.FreeTile(layer, key, recycle)
local tile = layer.Tiles[key]
if recycle and #EditableImages.Pool < EditableImages.PoolMax then
table.insert(EditableImages.Pool, tile)
else
EditableImages.Destroy(tile.Image)
tile.Label:Destroy()
end
layer.Tiles[key] = nil
if EditableImages.StageTiming then EditableImages.AddStat("TilesFreed", 1) end
if (layer.TileCounts[key] or 0) > 0 then return end -- touched this frame: its primitive list is still needed
local lp = EditableImages.ListPool
if layer.TileLists[key] and #lp < 256 then
lp[#lp + 1] = layer.TileLists[key]
lp[#lp + 1] = layer.TileListHash1[key]
lp[#lp + 1] = layer.TileListHash2[key]
lp[#lp + 1] = layer.TileListFlat[key]
end
layer.TileLists[key], layer.TileListHash1[key], layer.TileListHash2[key], layer.TileListFlat[key] =
nil, nil, nil, nil
layer.TileHash1[key], layer.TileHash2[key], layer.TileCounts[key], layer.TileX[key], layer.TileY[key] =
nil, nil, nil, nil, nil
end
function M.GetTile(BackendData, layer, key, tx, ty)
local tile = layer.Tiles[key]
if tile then return tile end
local scale = BackendData.Scale
local old = table.remove(EditableImages.Pool)
local label, img
if old then
label, img = old.Label, old.Image
else
img = EditableImages.Create(TILE, TILE)
if not img then return nil end -- over the budget even after eviction: the caller skips this tile this frame
label = Instance.new("ImageLabel")
label.Name = "Tile"
label.BackgroundTransparency = 1
label.BorderSizePixel = 0
label.ResampleMode = Enum.ResamplerMode.Pixelated
label.ImageContent = Content.fromObject(img)
label.Visible = false
end
if not old or old.Scale ~= scale then label.Size = UDim2.fromOffset(TILE / scale, TILE / scale) end
label.Position = UDim2.fromOffset(tx * TILE / scale, ty * TILE / scale)
if not old or old.Active ~= BackendData.TilesActive then label.Active = BackendData.TilesActive end
if not old or old.Parent ~= layer.Frame then label.Parent = layer.Frame end
-- Content*: content bounds; Valid*: where Buffer == image pixels. A recycled tile keeps both (they still describe
-- its image): its first draw is a full one (DrawnCount -1) that only clears old + new content bounds.
if old then
tile = old
tile.Hash1, tile.Hash2, tile.Visible, tile.Used, tile.Deferred, tile.DrawnCount =
-1, -1, false, BackendData.FrameNo, nil, -1
tile.Scale, tile.Active, tile.Parent = scale, BackendData.TilesActive, layer.Frame
else
tile = {
Image = img, Label = label, Buffer = buffer.create(TILE * TILE * 4),
Hash1 = -1, Hash2 = -1, Visible = false, Used = BackendData.FrameNo,
ContentX0 = TILE, ContentY0 = TILE, ContentX1 = 0, ContentY1 = 0,
ValidX0 = 0, ValidY0 = 0, ValidX1 = TILE, ValidY1 = TILE,
Scale = scale, Active = BackendData.TilesActive, Parent = layer.Frame,
DrawnCount = -1, DrawnHash1 = {}, DrawnHash2 = {}, DrawnFlat = {},
DrawnX0 = {}, DrawnY0 = {}, DrawnX1 = {}, DrawnY1 = {},
}
end
layer.Tiles[key] = tile
if EditableImages.StageTiming then EditableImages.AddStat("TilesCreated", 1) end
return tile
end
function M.DestroyLayerSet(set)
for kind = 1, 3 do
local layer = set[kind]
if layer then
for _, tile in pairs(layer.Tiles) do EditableImages.Destroy(tile.Image) end
for _, t in EditableImages.Pool do
if t.Parent == layer.Frame then
t.Label.Parent = nil
t.Parent = nil
end
end
layer.Root:Destroy()
end
end
end
function M.DestroyTiles(BackendData)
for _, set in pairs(BackendData.Layers) do M.DestroyLayerSet(set) end
BackendData.Layers = {}
end
-- Snapshot compared exactly with the next frame's list: 1 = identical (only restack), 2 = moved by whole pixels
-- (only move the layers), 0 = changed. Per command: clip (4 f64), ElemCount, IdxOffset, VtxOffset (u32), tex id
-- (f64), kind (u8), unclipped (u8), bounds of its primitives (4 x i32).
local CMD_STRIDE = 70
@native
function M.Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
local nv = draw_list.VtxBuffer.Size * VTX_STRIDE
local idx, ni = draw_list.IdxBuffer.Data, draw_list.IdxBuffer.Size
local ncmd = draw_list.CmdBuffer.Size
local sv, si, sc = set.SnapVtx, set.SnapIdx, set.SnapCmds
if not sv or buffer.len(sv) < nv then
sv = buffer.create(max(nv, 64) * 2)
set.SnapVtx = sv
end
if not si then
si = {}
set.SnapIdx = si
end
if not sc or buffer.len(sc) < ncmd * CMD_STRIDE then
sc = buffer.create(max(ncmd, 4) * CMD_STRIDE * 2)
set.SnapCmds = sc
end
buffer.copy(sv, 0, draw_list.VtxBuffer.Buf, 0, nv)
table.move(idx, 1, ni, 1, si)
local o, ci = 0, 0
for _, pcmd in draw_list.CmdBuffer:iter() do
if pcmd.UserCallback ~= nil then
set.SnapOK = false
return
end
local c = pcmd.ClipRect
writef64(sc, o, c.x)
writef64(sc, o + 8, c.y)
writef64(sc, o + 16, c.z)
writef64(sc, o + 24, c.w)
writeu32(sc, o + 32, pcmd.ElemCount)
writeu32(sc, o + 36, pcmd.IdxOffset)
writeu32(sc, o + 40, pcmd.VtxOffset)
writef64(sc, o + 44, pcmd:GetTexID())
ci += 1
buffer.writeu8(sc, o + 52, CmdKind[ci] or 0)
buffer.writeu8(sc, o + 53, CmdUnclipped[ci] and 1 or 0)
if CmdUnclipped[ci] then
buffer.writei32(sc, o + 54, CmdBoundsX0[ci])
buffer.writei32(sc, o + 58, CmdBoundsY0[ci])
buffer.writei32(sc, o + 62, CmdBoundsX1[ci])
buffer.writei32(sc, o + 66, CmdBoundsY1[ci])
end
o += CMD_STRIDE
end
set.SnapVtxBytes, set.SnapIdxCount, set.SnapCmdCount = nv, ni, ncmd
set.SnapOriginX, set.SnapOriginY, set.SnapScreenW, set.SnapScreenH = ox, oy, ScreenWidth, ScreenHeight
set.SnapHasContent = draw_list._ContentClipX0 ~= nil
set.SnapContentX0, set.SnapContentY0, set.SnapContentX1, set.SnapContentY1 =
draw_list._ContentClipX0 or 0, draw_list._ContentClipY0 or 0, draw_list._ContentClipX1 or 0,
draw_list._ContentClipY1 or 0
set.SnapScrollX, set.SnapScrollY = draw_list._ScrollOriginX or 0, draw_list._ScrollOriginY or 0
set.SnapOK = true
end
-- a + d == b exactly, with no rounding in a + d (so every later "x - origin" gives the same result as before the move)
@native
local function ShiftedExact(a, d, b)
local s = a + d
if s ~= b then return false end
local bb = s - a
return (a - (s - bb)) + (d - bb) == 0
end
@native
function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
if not set or not set.SnapOK then return 0 end
local nv = draw_list.VtxBuffer.Size * VTX_STRIDE
local ni, ncmd = draw_list.IdxBuffer.Size, draw_list.CmdBuffer.Size
if nv ~= set.SnapVtxBytes or ni ~= set.SnapIdxCount or ncmd ~= set.SnapCmdCount or ox ~= set.SnapOriginX
or oy ~= set.SnapOriginY or ScreenWidth ~= set.SnapScreenW or ScreenHeight ~= set.SnapScreenH then
return 0
end
if (draw_list._ContentClipX0 ~= nil) ~= set.SnapHasContent then return 0 end
local vb, sv = draw_list.VtxBuffer.Buf, set.SnapVtx
if nv == 0 then return 1 end
-- translation from the first vertex: whole pixels only, and only with DisplayPos at 0 (so it stays exact)
local dx, dy = readf64(vb, 0) - readf64(sv, 0), readf64(vb, 8) - readf64(sv, 8)
if dx ~= dx or dy ~= dy then return 0 end
if dx == 0 and dy == 0 then
-- u32 loop, not readstring ==: that allocated 2 vertex-buffer strings per list per frame (GC spikes)
for o = 0, nv - 4, 4 do if readu32(vb, o) ~= readu32(sv, o) then return 0 end end
else
if dx ~= floor(dx) or dy ~= floor(dy) or ox ~= 0 or oy ~= 0 or not set.SnapLimitFree then return 0 end
-- everything must stay as far from the clip limits as before (nothing newly clamped)
if set.SnapExtentX0 + dx < -CLIP_PAD or set.SnapExtentY0 + dy < -CLIP_PAD
or set.SnapExtentX1 + dx > ScreenWidth + CLIP_PAD or set.SnapExtentY1 + dy > ScreenHeight + CLIP_PAD then
return 0
end
end
local idx, si = draw_list.IdxBuffer.Data, set.SnapIdx
for i = 1, ni do if idx[i] ~= si[i] then return 0 end end
local sc, o = set.SnapCmds, 0
local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1,
draw_list._ContentClipY1
local seen_content = false
for _, pcmd in draw_list.CmdBuffer:iter() do
if pcmd.UserCallback ~= nil then return 0 end
if pcmd.ElemCount ~= readu32(sc, o + 32) or pcmd.IdxOffset ~= readu32(sc, o + 36)
or pcmd.VtxOffset ~= readu32(sc, o + 40) or pcmd:GetTexID() ~= readf64(sc, o + 44) then
return 0
end
local c = pcmd.ClipRect
if dx == 0 and dy == 0 then
if c.x ~= readf64(sc, o) or c.y ~= readf64(sc, o + 8) or c.z ~= readf64(sc, o + 16)
or c.w ~= readf64(sc, o + 24) then
return 0
end
elseif not (ShiftedExact(readf64(sc, o), dx, c.x) and ShiftedExact(readf64(sc, o + 8), dy, c.y)
and ShiftedExact(readf64(sc, o + 16), dx, c.z) and ShiftedExact(readf64(sc, o + 24), dy, c.w)) then
-- an unchanged clip rect (e.g. the viewport) is fine if it clips none of this command's primitives
if c.x ~= readf64(sc, o) or c.y ~= readf64(sc, o + 8) or c.z ~= readf64(sc, o + 16)
or c.w ~= readf64(sc, o + 24)
or buffer.readu8(sc, o + 53) == 0 then return 0 end
if buffer.readi32(sc, o + 54) + dx < floor(c.x) or buffer.readi32(sc, o + 58) + dy < floor(c.y)
or buffer.readi32(sc, o + 62) + dx > floor(c.z)
or buffer.readi32(sc, o + 66) + dy > floor(c.w) then return 0 end
end
if pcmd.ElemCount > 0 then
local kind = 1
if ccx0 and c.x >= ccx0 and c.y >= ccy0 and c.z <= ccx1 and c.w <= ccy1 then
kind = 2
seen_content = true
elseif seen_content then kind = 3 end
if kind ~= buffer.readu8(sc, o + 52) then return 0 end
end
o += CMD_STRIDE
end
if dx == 0 and dy == 0 then
if set.SnapHasContent and (draw_list._ContentClipX0 ~= set.SnapContentX0
or draw_list._ContentClipY0 ~= set.SnapContentY0 or draw_list._ContentClipX1 ~= set.SnapContentX1
or draw_list._ContentClipY1 ~= set.SnapContentY1 or draw_list._ScrollOriginX ~= set.SnapScrollX
or draw_list._ScrollOriginY ~= set.SnapScrollY) then return 0 end
return 1
end
if set.SnapHasContent and not (ShiftedExact(set.SnapContentX0, dx, draw_list._ContentClipX0)
and ShiftedExact(set.SnapContentY0, dy, draw_list._ContentClipY0)
and ShiftedExact(set.SnapContentX1, dx, draw_list._ContentClipX1)
and ShiftedExact(set.SnapContentY1, dy, draw_list._ContentClipY1)
and ShiftedExact(set.SnapScrollX, dx, draw_list._ScrollOriginX)
and ShiftedExact(set.SnapScrollY, dy, draw_list._ScrollOriginY)) then return 0 end
for v = 0, nv - VTX_STRIDE, VTX_STRIDE do
if not ShiftedExact(readf64(sv, v), dx, readf64(vb, v))
or not ShiftedExact(readf64(sv, v + 8), dy, readf64(vb, v + 8))
or readf64(vb, v + 16) ~= readf64(sv, v + 16) or readf64(vb, v + 24) ~= readf64(sv, v + 24)
or readu32(vb, v + 32) ~= readu32(sv, v + 32) then return 0 end
end
return 2, dx, dy
end
function M.ShiftLayer(layer, dx, dy, scale)
layer.X += dx
layer.Y += dy
local root = layer.Root
if root ~= layer.Frame then
layer.ClipX0 += dx
layer.ClipY0 += dy
layer.ClipX1 += dx
layer.ClipY1 += dy
root.Position = UDim2.fromOffset(layer.ClipX0 / scale, layer.ClipY0 / scale)
else
root.Position = UDim2.fromOffset(layer.X / scale, layer.Y / scale)
end
end
return M
+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
+398
View File
@@ -0,0 +1,398 @@
-- Parallel executor (opt-in, EnableParallel): Tile packs each dirty tile per Actor, Flush sends the batch while the
-- dispatch window (PreAnimation .. Finish) is open, else rasterizes it at once; Finish uploads every result.
local Raster = IM_INCLUDE("roblox/raster.lua")
local Textures = IM_INCLUDE("roblox/textures.lua")
local Render = IM_INCLUDE("roblox/render.lua")
local Players = game:GetService("Players")
local EditableImages, Records = Textures.EditableImages, Textures.Records
local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient = Render.PrimA, Render.PrimB, Render.PrimC, Render.PrimD,
Render.PrimTexture, Render.PrimGradient
local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = Render.PrimClipX0, Render.PrimClipY0, Render.PrimClipX1,
Render.PrimClipY1
local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = Render.PrimBoundsX0, Render.PrimBoundsY0,
Render.PrimBoundsX1, Render.PrimBoundsY1
local PrimTexId, PrimVtxBuffer = Render.PrimTexId, Render.PrimVtxBuffer
local M = Render.Parallel
local writei32, writef64, copy = buffer.writei32, buffer.writef64, buffer.copy
local RasterJobs = Raster.RasterJobs
local VTX, REC, REC_A, REC_B, REC_C, JOB = Raster.VTX, Raster.REC, Raster.REC_A, Raster.REC_B, Raster.REC_C, Raster.JOB
assert(VTX == VTX_STRIDE, "raster.lua: vertex layout differs from ImDrawVert")
-- Sync / SyncDrop / Inline: test hooks (inline "workers"; drop half their results; bypass the executor)
M.Config = { Actors = 4, MinTiles = 4, MinPixels = 16384, MaxBytesPerPixel = 3, Sync = false, SyncDrop = false,
Inline = false, Worker = nil }
M.Stats = {
ParallelFlushes = 0, SerialFlushes = 0, Tiles = 0, Fallbacks = 0, Late = 0, Pack = 0, Flush = 0, Finish = 0,
SendBytes = 0, TexSends = 0, TexBytes = 0, Rects = 0, Recv = 0, RecvBytes = 0,
}
local Stats = M.Stats
local NA = 1
local Pb, Pn, Tb, Tn, load, used = {}, {}, {}, {}, {}, {}
local stamp, poff, stamp_base = {}, {}, 0
local free_batches, free_bufs, free_bytes = {}, {}, 0
local function newBatch()
return table.remove(free_batches)
or { N = 0, Px = 0, Img = {}, Actor = {}, NR = {}, Rect = {}, P = {}, T = {}, TL = {}, Res = {} }
end
local function takeBuf(len: number): buffer
local l = free_bufs[len]
local b = l and table.remove(l)
if b then
free_bytes -= len
return b
end
return buffer.create(len)
end
local function giveBuf(b: buffer)
local len = buffer.len(b)
local l = free_bufs[len]
if not l then
l = {}
free_bufs[len] = l
end
if #l < 8 and free_bytes + len <= 4194304 then
l[#l + 1] = b
free_bytes += len
end
end
local jobs = newBatch()
local NO_TEX = {}
local cur = {}
local pending, by_id, batch_no = {}, {}, 0
local open = false
local actors, ready, conns, folder = {}, false, {}, nil
local sent = {}
local function grow(b: buffer, need: number): buffer
local n = buffer.len(b)
if need <= n then
return b
end
while n < need do
n *= 2
end
local nb = buffer.create(n)
copy(nb, 0, b)
return nb
end
local function reset()
for a = 1, NA do
Pn[a], Tn[a], load[a] = 0, 0, 0
if used[a] then
table.clear(used[a])
end
end
stamp_base += 64
jobs = newBatch()
end
-- One dirty tile (rects in EditableImages.DX0..DY1[1..nr], primitives list[1..count]) -> the least loaded Actor
@native
function M.Tile(img, list, count: number, x0: number, y0: number, tox: number, toy: number, nr: number)
local t0 = os.clock()
local DX0, DY0, DX1, DY1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1
local area = 0
for r = 1, nr do
area += (DX1[r] - DX0[r]) * (DY1[r] - DY0[r])
end
local a = 1
for i = 2, NA do
if load[i] < load[a] then
a = i
end
end
load[a] += area + 200
jobs.Px += area
local j = jobs.N + 1
jobs.N = j
jobs.Img[j], jobs.Actor[j], jobs.NR[j] = img, a, nr
Stats.Rects += nr
local R = jobs.Rect
local ri = #R
for r = 1, nr do
R[ri + 1], R[ri + 2], R[ri + 3], R[ri + 4] = DX0[r], DY0[r], DX1[r], DY1[r]
ri += 4
end
local T, to = grow(Tb[a], Tn[a] + JOB + nr * 16 + count * 4), Tn[a]
Tb[a] = T
writef64(T, to, tox)
writef64(T, to + 8, toy)
writei32(T, to + 16, x0)
writei32(T, to + 20, y0)
writei32(T, to + 24, nr)
writei32(T, to + 28, count)
to += JOB
for r = 1, nr do
writei32(T, to, DX0[r])
writei32(T, to + 4, DY0[r])
writei32(T, to + 8, DX1[r])
writei32(T, to + 12, DY1[r])
to += 16
end
local P, pn = grow(Pb[a], Pn[a] + count * REC), Pn[a]
Pb[a] = P
local st = stamp_base + a
local u = used[a]
for k = 1, count do
local p = list[k]
if stamp[p] ~= st then
stamp[p], poff[p] = st, pn
local d, t = PrimD[p], PrimTexture[p]
local gk = PrimGradient[p]
writei32(P, pn, d and (gk and gk + 1 or 1) or 0)
writei32(P, pn + 4, t and PrimTexId[p] or -1)
if t then
u[t] = PrimTexId[p]
end
writei32(P, pn + 8, PrimClipX0[p])
writei32(P, pn + 12, PrimClipY0[p])
writei32(P, pn + 16, PrimClipX1[p])
writei32(P, pn + 20, PrimClipY1[p])
writei32(P, pn + 24, PrimBoundsX0[p])
writei32(P, pn + 28, PrimBoundsY0[p])
writei32(P, pn + 32, PrimBoundsX1[p])
writei32(P, pn + 36, PrimBoundsY1[p])
local vb = PrimVtxBuffer[p]
copy(P, pn + REC_A, vb, PrimA[p], VTX)
copy(P, pn + REC_C, vb, PrimC[p], VTX)
if not d then
copy(P, pn + REC_B, vb, PrimB[p], VTX)
end
pn += REC
end
writei32(T, to, poff[p])
to += 4
end
Pn[a], Tn[a] = pn, to
Stats.Pack += os.clock() - t0
end
local function upload(b)
local alive, R, ri = EditableImages.ImageBytes, b.Rect, 0
table.clear(cur)
for j = 1, b.N do
local a = b.Actor[j]
local outs, c = b.Res[a], cur[a] or 0
local img = b.Img[j]
for _ = 1, b.NR[j] do
c += 1
if alive[img] then
local x0, y0 = R[ri + 1], R[ri + 2]
img:WritePixelsBuffer(Vector2.new(x0, y0), Vector2.new(R[ri + 3] - x0, R[ri + 4] - y0), outs[c])
end
ri += 4
end
cur[a] = c
end
end
-- Uploads every pending batch (late worker results rasterized here) and closes the dispatch window
function M.Finish()
open = false
if #pending == 0 then
return
end
local t0 = os.clock()
for _, b in pending do
for a = 1, NA do
if b.TL[a] > 0 and not b.Res[a] then
b.Res[a] = RasterJobs(b.P[a], b.T[a], b.TL[a], Records)
if b.Sent then
Stats.Fallbacks += 1
end
end
end
upload(b)
by_id[b.Id] = nil
for a = 1, NA do
if b.P[a] then
giveBuf(b.P[a])
giveBuf(b.T[a])
end
end
b.N, b.Px, b.Sent = 0, 0, false
table.clear(b.Img)
table.clear(b.Actor)
table.clear(b.NR)
table.clear(b.Rect)
table.clear(b.P)
table.clear(b.T)
table.clear(b.TL)
table.clear(b.Res)
if #free_batches < 8 then
free_batches[#free_batches + 1] = b
end
end
table.clear(pending)
Stats.Finish += os.clock() - t0
end
function M.Flush()
local n = jobs.N
if n == 0 then
if not open then
M.Finish()
end
return
end
local t0 = os.clock()
local cfg = M.Config
local par = open and (cfg.Sync or ready) and n >= cfg.MinTiles and jobs.Px >= cfg.MinPixels
if par and cfg.MaxBytesPerPixel > 0 then
local bytes = 0
for a = 1, NA do
bytes += Pn[a] + Tn[a]
end
par = bytes <= cfg.MaxBytesPerPixel * jobs.Px
end
batch_no += 1
local b = jobs
b.Id, b.Sent = batch_no, par
for a = 1, NA do
local tl = Tn[a]
b.TL[a] = tl
if tl == 0 then
continue
end
if not par then
b.Res[a] = RasterJobs(Pb[a], Tb[a], tl, Records)
continue
end
-- recycled copies rounded up to 4 KB (SendMessage copies the whole buffer)
local P, T = takeBuf(Pn[a] + 4095 - (Pn[a] + 4095) % 4096), takeBuf(tl + 4095 - (tl + 4095) % 4096)
copy(P, 0, Pb[a], 0, Pn[a])
copy(T, 0, Tb[a], 0, tl)
b.P[a], b.T[a] = P, T
local tex, s = NO_TEX, sent[a]
for rec, id in used[a] do
local v = rec.V or 0
if s[rec] ~= v then
if tex == NO_TEX then
tex = {}
end
s[rec] = v
tex[#tex + 1] = { id, rec.Buffer, rec.Width, rec.Height }
Stats.TexSends += 1
Stats.TexBytes += buffer.len(rec.Buffer)
end
end
Stats.SendBytes += Pn[a] + tl
if cfg.Sync then
if not (cfg.SyncDrop and a % 2 == 0) then
b.Res[a] = RasterJobs(P, T, tl, Records)
end
else
actors[a]:SendMessage("job", batch_no, P, T, tex, tl)
end
end
if par then
Stats.ParallelFlushes += 1
else
Stats.SerialFlushes += 1
end
Stats.Tiles += n
by_id[batch_no] = b
pending[#pending + 1] = b
reset()
Stats.Flush += os.clock() - t0
if not open then
M.Finish()
end
end
function M.BeginFrame()
open = true
end
local function setActors(n)
NA = n
for a = 1, n do
Pb[a] = Pb[a] or buffer.create(4096)
Tb[a] = Tb[a] or buffer.create(1024)
used[a] = used[a] or {}
sent[a] = setmetatable({}, { __mode = "k" })
end
reset()
end
setActors(1)
function M.Disable()
M.Finish()
for _, c in conns do
c:Disconnect()
end
table.clear(conns)
if folder then
folder:Destroy()
folder = nil
end
table.clear(actors)
ready, open = false, false
M.On, M.Active = false, false
end
function M.Enable(opts)
M.Disable()
for k, v in opts or {} do
M.Config[k] = v
end
local cfg = M.Config
setActors(math.max(1, cfg.Actors))
M.On = true
if cfg.Sync then
return
end
local RunService = game:GetService("RunService")
-- bundle: script is the library ModuleScript (e.g. ImGui.Impl under the typed module)
local template = cfg.Worker or script:FindFirstChild("Worker")
or (script.Parent and script.Parent:FindFirstChild("Worker"))
assert(template, "ImGui_ImplRoblox.EnableParallel: no Worker LocalScript (build/ImGuiWorker.client.luau) as a"
.. " child of the ImGui module; or pass { Worker = ... }")
folder = Instance.new("Folder")
folder.Name = "ImGuiRasterActors"
for a = 1, NA do
local actor = Instance.new("Actor")
actor.Name = "Raster" .. a
local done = Instance.new("BindableEvent")
done.Name = "Done"
done.Parent = actor
table.insert(conns, done.Event:Connect(function(id, outs)
local t0, b = os.clock(), by_id[id]
if b then
b.Res[a] = outs
else
Stats.Late += 1
end
for _, o in outs do
Stats.RecvBytes += buffer.len(o)
end
Stats.Recv += os.clock() - t0
end))
local w = template:Clone()
w.Parent = actor
actor.Parent = folder
actors[a] = actor
end
folder.Parent = Players.LocalPlayer:WaitForChild("PlayerScripts")
ready = false
table.insert(conns, RunService.PreAnimation:Connect(function()
if not ready then
ready = true
for _, act in actors do
if not act:GetAttribute("Ready") then
ready = false
end
end
end
open = true
end))
table.insert(conns, RunService.PostSimulation:Connect(M.Finish))
end
return M
+474
View File
@@ -0,0 +1,474 @@
-- Software rasterizer: pure buffer code shared by the backend and the parallel worker (inlined into ImGuiWorker).
-- Target: RGBA8 row-major (ImU32 is already R | G<<8 | B<<16 | A<<24), non-premultiplied "over" onto transparent.
local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max
local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
local readf64 = buffer.readf64
local band, rshift = bit32.band, bit32.rshift
local readi32 = buffer.readi32
local M = {
TILE = 128,
-- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs.
-- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2), tex id (-1: none), clip x0 y0 x1 y1,
-- bounds x0 y0 x1 y1 (screen pixels, i32), then raw vertices (VTX bytes: x y u v f64, col u32): a at REC_A,
-- c at REC_C, b at REC_B.
-- T job: tox toy (f64), x0 y0 nr count (i32), nr x rect x0 y0 x1 y1 (i32, tile pixels), count x P offset (i32).
VTX = 36, REC = 148, REC_A = 40, REC_C = 76, REC_B = 112, JOB = 32,
}
local TILE = M.TILE
local TargetBuffer: buffer, TargetWidth = buffer.create(0), 0
local PrevRow = buffer.create(1024)
-- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else
-- remembers this row. u32 loop, not readstring ==: that allocated a string per row.
@native
local function RowRepeats(o: number, len: number, has_prev: boolean): boolean
if has_prev then
local same = true
for k = 0, len - 4, 4 do
if readu32(TargetBuffer, o + k) ~= readu32(PrevRow, k) then
same = false
break
end
end
if same then return true end
end
if buffer.len(PrevRow) < len then PrevRow = buffer.create(len) end
buffer.copy(PrevRow, 0, TargetBuffer, o, len)
return false
end
local RectColumns = table.create(256, 0)
-- FillSpan and DrawTriangle's flat path inline this math with per-span constants: keep them in sync.
@native
local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number, b: number, a: number)
if a >= 255 then
writeu32(TargetBuffer, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080)
return
end
if a <= 0 then return end
local d = readu32(TargetBuffer, o)
if d < 16777216 then
writeu32(TargetBuffer, o,
floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216)
return
end
local sa = a / 255
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
local ns = 1 - sa
writeu32(TargetBuffer, o,
floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256 + floor(b * sa + db * ns + 0.5) * 65536
+ 4278190080)
else
local k = rshift(d, 24) * ((1 - sa) / 255)
local oa = sa + k
local inv = 1 / oa
writeu32(TargetBuffer, o, floor((r * sa + dr * k) * inv + 0.5) + floor((g * sa + dg * k) * inv + 0.5) * 256
+ floor((b * sa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
end
end
@native
local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number,
b: number, a: number)
if a <= 0 then return end
local w4 = (x1 - x0 - 1) * 4
if a >= 255 then
local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080
local first = (y0 * TargetWidth + x0) * 4
for o = first, first + w4, 4 do writeu32(TargetBuffer, o, packed) end
for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end
return
end
local packed0 = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216
local sa = a / 255
local ns = 1 - sa
local c1 = ns / 255
local rs, gs, bs = r * sa, g * sa, b * sa
local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination
for y = y0, y1 - 1 do
local o0 = (y * TargetWidth + x0) * 4
for o = o0, o0 + w4, 4 do
local d = readu32(TargetBuffer, o)
if d == last_d then
writeu32(TargetBuffer, o, last_v)
elseif d < 16777216 then
writeu32(TargetBuffer, o, packed0)
else
last_d = d
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
last_v = floor(rs + dr * ns + 0.5) + floor(gs + dg * ns + 0.5) * 256
+ floor(bs + db * ns + 0.5) * 65536 + 4278190080
else
local k = rshift(d, 24) * c1
local oa = sa + k
local inv = 1 / oa
last_v = floor((rs + dr * k) * inv + 0.5) + floor((gs + dg * k) * inv + 0.5) * 256
+ floor((bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
end
writeu32(TargetBuffer, o, last_v)
end
end
end
end
@native
local function UnpackColor(col: number)
return col % 256, floor(col / 256) % 256, floor(col / 65536) % 256, floor(col / 16777216) % 256
end
@native
local function SampleTexture(t, u: number, v: number)
local tw, th = t.Width, t.Height
local tx, ty = floor(u * tw), floor(v * th)
if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
local o = (ty * tw + tx) * 4
local tb = t.Buffer
return readu8(tb, o), readu8(tb, o + 1), readu8(tb, o + 2), readu8(tb, o + 3)
end
@native
local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, u0: number, v0: number,
u1: number, v1: number, col: number, t, cx0: number, cy0: number, cx1: number, cy1: number)
local r, g, b, a = UnpackColor(col)
if a == 0 then return end
local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0)
local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1)
if px0 >= px1 or py0 >= py1 then return end
if not t or (u0 == u1 and v0 == v1) then
if t then
local tr, tg, tb, ta = SampleTexture(t, u0, v0)
r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255
end
if a <= 0 then return end
if a >= 255 or px1 - px0 < 32 then
FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a)
return
end
-- Wide translucent rect: rows usually blend over identical rows, so copy the previous row's result
local len = (px1 - px0) * 4
local prev_o = 0
for y = py0, py1 - 1 do
local o = (y * TargetWidth + px0) * 4
if RowRepeats(o, len, y > py0) then
buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len)
else
FillSpan(TargetBuffer, y, y + 1, px0, px1, r, g, b, a)
end
prev_o = o
end
return
end
local du, dv = (u1 - u0) / (x1 - x0), (v1 - v0) / (y1 - y0)
local tw: number, th: number, tbuf: buffer, dbuf: buffer = t.Width, t.Height, t.Buffer, TargetBuffer
local r255, g255, b255, a255 = r / 255, g / 255, b / 255, a / 255
local ncol = px1 - px0
local cols = RectColumns
for c = 1, ncol do
local tx = floor((u0 + (px0 + c - 1 + 0.5 - x0) * du) * tw)
if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end
cols[c] = tx * 4
end
for y = py0, py1 - 1 do
local ty = floor((v0 + (y + 0.5 - y0) * dv) * th)
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
local trow4 = ty * tw * 4
local o = (y * TargetWidth + px0) * 4
for c = 1, ncol do
local tv = readu32(tbuf, trow4 + cols[c])
if tv >= 16777216 then
local sa = rshift(tv, 24) * a255
local sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255,
band(rshift(tv, 16), 255) * b255
if sa >= 255 then
writeu32(dbuf, o, floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + 4278190080)
else
BlendPixel(dbuf, o, sr, sg, sb, sa)
end
end
o = o + 4
end
end
end
@native
local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, vc: number, t, cx0: number, cy0: number,
cx1: number, cy1: number, ox: number, oy: number)
local x0, y0 = readf64(vbuf, va) - ox, readf64(vbuf, va + 8) - oy
local x1, y1 = readf64(vbuf, vb) - ox, readf64(vbuf, vb + 8) - oy
local x2, y2 = readf64(vbuf, vc) - ox, readf64(vbuf, vc + 8) - oy
local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0)
if area == 0 then return end
if area < 0 then
vb, vc = vc, vb
x1, y1, x2, y2 = x2, y2, x1, y1
area = -area
end
local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1)
local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1)
if minx > maxx or miny > maxy then return end
local A0, B0 = y1 - y2, x2 - x1
local C0 = -(A0 * x1 + B0 * y1)
local A1, B1 = y2 - y0, x0 - x2
local C1 = -(A1 * x2 + B1 * y2)
local A2, B2 = y0 - y1, x1 - x0
local C2 = -(A2 * x0 + B2 * y0)
local tl0 = A0 > 0 or (A0 == 0 and B0 > 0)
local tl1 = A1 > 0 or (A1 == 0 and B1 > 0)
local tl2 = A2 > 0 or (A2 == 0 and B2 > 0)
local inv = 1 / area
local n0, n1, n2 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0
local ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32))
local rb, gb, bb, ab = UnpackColor(readu32(vbuf, vb + 32))
local rc, gc, bc, ac = UnpackColor(readu32(vbuf, vc + 32))
local ua, vva, ub, vvb, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vb + 16),
readf64(vbuf, vb + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24)
local textured = t and not (ua == ub and ua == uc and vva == vvb and vva == vvc)
if t and not textured then -- constant uv (atlas white pixel): fold the texel into the vertex colours
local tr, tg, tb, ta = SampleTexture(t, ua, vva)
ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255
rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255
rc, gc, bc, ac = rc * tr / 255, gc * tg / 255, bc * tb / 255, ac * ta / 255
end
local flat = not textured and ra == rb and ra == rc and ga == gb and ga == gc and ba == bb and ba == bc and aa == ab
and aa == ac
if flat and aa <= 0 then return end
local f_opaque, f_packed, f_sa, f_ns, f_c1, f_rs, f_gs, f_bs = false, 0, 0, 0, 0, 0, 0, 0
if flat then
f_opaque = aa >= 255
f_packed = floor(ra + 0.5) + floor(ga + 0.5) * 256 + floor(ba + 0.5) * 65536
+ (f_opaque and 4278190080 or floor(aa + 0.5) * 16777216)
f_sa = aa / 255
f_ns = 1 - f_sa
f_c1 = f_ns / 255
f_rs, f_gs, f_bs = ra * f_sa, ga * f_sa, ba * f_sa
end
for y = miny, maxy do
local py = y + 0.5
local xl, xr = minx, maxx
local e0, e1, e2 = B0 * py + C0, B1 * py + C1, B2 * py + C2
-- (e * n is -e / A within an ulp; the 1e-6 margin covers that, and the exact tests below decide)
if A0 > 0 then
xl = max(xl, floor(e0 * n0 - 0.500001))
elseif A0 < 0 then
xr = min(xr, ceil(e0 * n0 - 0.499999))
end
if A1 > 0 then
xl = max(xl, floor(e1 * n1 - 0.500001))
elseif A1 < 0 then
xr = min(xr, ceil(e1 * n1 - 0.499999))
end
if A2 > 0 then
xl = max(xl, floor(e2 * n2 - 0.500001))
elseif A2 < 0 then
xr = min(xr, ceil(e2 * n2 - 0.499999))
end
while xl <= xr do
local px = xl + 0.5
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
break
end
xl += 1
end
while xr > xl do
local px = xr + 0.5
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
break
end
xr -= 1
end
if xl > xr then continue end
local o = (y * TargetWidth + xl) * 4
if flat then
local o1 = o + (xr - xl) * 4
if f_opaque then
for oo = o, o1, 4 do writeu32(dbuf, oo, f_packed) end
continue
end
local last_d, last_v = -1, 0
for oo = o, o1, 4 do
local d = readu32(dbuf, oo)
if d == last_d then
writeu32(dbuf, oo, last_v)
elseif d < 16777216 then
writeu32(dbuf, oo, f_packed)
else
last_d = d
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
last_v = floor(f_rs + dr * f_ns + 0.5) + floor(f_gs + dg * f_ns + 0.5) * 256
+ floor(f_bs + db * f_ns + 0.5) * 65536 + 4278190080
else
local k = rshift(d, 24) * f_c1
local oa = f_sa + k
local inv = 1 / oa
last_v = floor((f_rs + dr * k) * inv + 0.5) + floor((f_gs + dg * k) * inv + 0.5) * 256
+ floor((f_bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
end
writeu32(dbuf, oo, last_v)
end
end
continue
end
for x = xl, xr do
local px = x + 0.5
local w0, w1, w2 = (A0 * px + e0) * inv, (A1 * px + e1) * inv, (A2 * px + e2) * inv
local a = w0 * aa + w1 * ab + w2 * ac
if textured then
local r = w0 * ra + w1 * rb + w2 * rc
local g = w0 * ga + w1 * gb + w2 * gc
local b = w0 * ba + w1 * bb + w2 * bc
local tr, tg, tb, ta = SampleTexture(t, w0 * ua + w1 * ub + w2 * uc, w0 * vva + w1 * vvb + w2 * vvc)
BlendPixel(dbuf, o, r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255)
elseif a > 0 then
BlendPixel(dbuf, o, w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc,
w0 * ba + w1 * bb + w2 * bc, a)
end
o += 4
end
end
end
-- Linear gradient quad, constant uv. kind 1: along y (ca top, cb bottom), 2: along x. Same pixels as the triangles.
@native
local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, ca: number,
cb: number, kind: number, t, u: number, v: number, cx0: number, cy0: number, cx1: number, cy1: number)
local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0)
local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1)
if px0 >= px1 or py0 >= py1 then return end
local ra, ga, ba, aa = UnpackColor(ca)
local rb, gb, bb, ab = UnpackColor(cb)
if t then
local tr, tg, tb, ta = SampleTexture(t, u, v)
ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255
rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255
end
if kind == 1 then
local inv = 1 / (y1 - y0)
for y = py0, py1 - 1 do
local f = (y + 0.5 - y0) * inv
local nf = 1 - f
FillSpan(TargetBuffer, y, y + 1, px0, px1, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f,
aa * nf + ab * f)
end
else
local inv = 1 / (x1 - x0)
local len = (px1 - px0) * 4
local opaque = aa >= 255 and ab >= 255
local prev_o = 0
for y = py0, py1 - 1 do
local o = (y * TargetWidth + px0) * 4
if y > py0 and (opaque or RowRepeats(o, len, true))
or (y == py0 and not opaque and RowRepeats(o, len, false)) then
buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len)
else
local oo = o
for x = px0, px1 - 1 do
local f = (x + 0.5 - x0) * inv
local nf = 1 - f
BlendPixel(TargetBuffer, oo, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f)
oo = oo + 4
end
end
prev_o = o
end
end
end
function M.SetTarget(buf: buffer, width: number)
TargetBuffer, TargetWidth = buf, width
end
@native
function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number)
local rw = rx1 - rx0
if rw == TargetWidth then
buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4)
else
for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4, 0, rw * 4) end
end
end
@native
function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: number)
for y = 0, rh - 1 do
buffer.copy(dst, y * rw * 4, TargetBuffer, ((ry0 + y) * TargetWidth + rx0) * 4, rw * 4)
end
end
-- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2
@native
local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, tox: number, toy: number,
cx0: number, cy0: number, cx1: number, cy1: number)
if kind == 0 then
DrawTriangle(TargetBuffer, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, tox, toy)
return
end
local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox,
readf64(vbuf, vc + 8) - toy
if kind == 1 then
DrawRect(TargetBuffer, ax, ay, cx, cy, readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16),
readf64(vbuf, vc + 24), readu32(vbuf, va + 32), t, cx0, cy0, cx1, cy1)
else
DrawRectGradient(TargetBuffer, ax, ay, cx, cy, readu32(vbuf, va + 32), readu32(vbuf, vc + 32), kind - 1, t,
readf64(vbuf, va + 16), readf64(vbuf, va + 24), cx0, cy0, cx1, cy1)
end
end
M.DrawPrim = DrawPrim
-- Packed tile jobs -> one exact-size buffer per rect, in job order (worker + main-thread fallback)
local Scratch = buffer.create(TILE * TILE * 4)
@native
function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect
local REC_A, REC_B, REC_C = M.REC_A, M.REC_B, M.REC_C
M.SetTarget(Scratch, TILE)
local out, no = {}, 0
local o = 0
while o < tlen do
local tox, toy = readf64(T, o), readf64(T, o + 8)
local x0, y0, nr, count = readi32(T, o + 16), readi32(T, o + 20), readi32(T, o + 24), readi32(T, o + 28)
local ro = o + 32
local po = ro + nr * 16
o = po + count * 4
for r = 0, nr - 1 do
local rx0, ry0, rx1, ry1 = readi32(T, ro + r * 16), readi32(T, ro + r * 16 + 4),
readi32(T, ro + r * 16 + 8), readi32(T, ro + r * 16 + 12)
ClearRect(rx0, ry0, rx1, ry1)
for k = 0, count - 1 do
local q = readi32(T, po + k * 4)
local cx0, cy0 = max(readi32(P, q + 8) - x0, rx0), max(readi32(P, q + 12) - y0, ry0)
local cx1, cy1 = min(readi32(P, q + 16) - x0, rx1), min(readi32(P, q + 20) - y0, ry1)
if cx0 >= cx1 or cy0 >= cy1 or readi32(P, q + 24) - x0 >= rx1 or readi32(P, q + 28) - y0 >= ry1
or readi32(P, q + 32) - x0 <= rx0 or readi32(P, q + 36) - y0 <= ry0 then
continue
end
local tid, t = readi32(P, q + 4), nil
if tid >= 0 then t = textures[tid] end
DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, tox, toy, cx0, cy0, cx1, cy1)
end
local rw, rh = rx1 - rx0, ry1 - ry0
local sub = buffer.create(rw * rh * 4)
CopySubRect(sub, rx0, ry0, rw, rh)
no += 1
out[no] = sub
end
end
return out
end
return M
+843
View File
@@ -0,0 +1,843 @@
-- Rendering: collect primitives, hash them into tiles, redraw + upload changed tiles (RenderDrawData).
local Raster = IM_INCLUDE("roblox/raster.lua")
local Textures = IM_INCLUDE("roblox/textures.lua")
local Layers = IM_INCLUDE("roblox/layers.lua")
local Overlays = IM_INCLUDE("roblox/overlays.lua")
local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max
local readu32, readf64 = buffer.readu32, buffer.readf64
local SetTarget, ClearRect, DrawPrim, CopySubRect = Raster.SetTarget, Raster.ClearRect, Raster.DrawPrim,
Raster.CopySubRect
local TILE = Raster.TILE
local TILE_SIZE = Vector2.new(TILE, TILE)
local EditableImages, PB, PE, GetBackendData, UpdateTexture = Textures.EditableImages, Textures.PB, Textures.PE,
Textures.GetBackendData, Textures.UpdateTexture
local GetLayer, HideLayer, GetTile, DestroyLayerSet, Snapshot, CompareDrawList, ShiftLayer = Layers.GetLayer,
Layers.HideLayer, Layers.GetTile, Layers.DestroyLayerSet, Layers.Snapshot, Layers.CompareDrawList, Layers.ShiftLayer
local CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1 = Layers.CmdUnclipped, Layers.CmdKind,
Layers.CmdBoundsX0, Layers.CmdBoundsY0, Layers.CmdBoundsX1, Layers.CmdBoundsY1
local CLIP_PAD = Layers.CLIP_PAD
local PlaceOverlays = Overlays.PlaceOverlays
local M = {}
-- Parallel executor state; parallel.lua adds its functions. On: enabled; Active: used by the current RenderDrawData.
local Parallel = { On = false, Active = false }
M.Parallel = Parallel
local P1, P2 = 2147483647, 2147483629 -- two independent 31 bit hashes per tile (collision odds ~2^-62)
local LAYER_KEEP_FRAMES = 120
local MAX_DEFER_FRAMES = 8 -- a changed tile is redrawn at the latest this many frames later, even over the budget
local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient = {}, {}, {}, {}, {}, {}
local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = {}, {}, {}, {}
local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = {}, {}, {}, {}
local PrimTexId, PrimVtxBuffer, PrimKind = {}, {}, {}
local LayerPrims1, LayerPrims2, LayerPrims3 = {}, {}, {}
M.PrimA, M.PrimB, M.PrimC, M.PrimD = PrimA, PrimB, PrimC, PrimD
M.PrimTexture, M.PrimGradient = PrimTexture, PrimGradient
M.PrimClipX0, M.PrimClipY0, M.PrimClipX1, M.PrimClipY1 = PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1
M.PrimBoundsX0, M.PrimBoundsY0, M.PrimBoundsX1, M.PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1
M.PrimTexId, M.PrimVtxBuffer = PrimTexId, PrimVtxBuffer
-- Adds [a, c) x [b, d) to the n dirty rects DX0..DY1 (merged unless that wastes area), returns the count
EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1 = {}, {}, {}, {}
@native
function EditableImages.AddRect(n: number, a: number, b: number, c: number, d: number): number
if a >= c or b >= d then return n end
local X0, Y0, X1, Y1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1
local best, best_grow = 1, math.huge
for i = 1, n do
local e, f, g, h = X0[i], Y0[i], X1[i], Y1[i]
local ux0, uy0, ux1, uy1 = min(a, e), min(b, f), max(c, g), max(d, h)
local box, own = (ux1 - ux0) * (uy1 - uy0), (g - e) * (h - f)
local ov = max(min(c, g) - max(a, e), 0) * max(min(d, h) - max(b, f), 0)
-- waste outside both rects vs. apart: the overlap twice + a primitive pass and an upload (~2048 px)
if box - ((c - a) * (d - b) + own - ov) <= ov + 2048 then
X0[i], Y0[i], X1[i], Y1[i] = ux0, uy0, ux1, uy1
return n
end
if box - own < best_grow then best, best_grow = i, box - own end
end
if n < 4 then
n += 1
X0[n], Y0[n], X1[n], Y1[n] = a, b, c, d
else
X0[best], Y0[best], X1[best], Y1[best] = min(a, X0[best]), min(b, Y0[best]), max(c, X1[best]), max(d, Y1[best])
end
return n
end
@native
local function HashVertex(h1: number, h2: number, vbuf: buffer, v: number, ox: number, oy: number)
local x, y = readf64(vbuf, v) - ox, readf64(vbuf, v + 8) - oy
local uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24)
local c = readu32(vbuf, v + 32)
h1 = (h1 * 48271 + x * 4096 + y) % P1
h1 = (h1 * 48271 + uv * 4096 + c) % P1
h2 = (h2 * 16807 + y * 4093 + x) % P2
h2 = (h2 * 16807 + uv * 65521 + c * 3) % P2
return h1, h2
end
@native
local function HashTiles(layer, plist, np, lx0, ly0, ox, oy)
local TileHash1, TileHash2, TileCounts, TileLists, Touched =
layer.TileHash1, layer.TileHash2, layer.TileCounts, layer.TileLists, layer.Touched
local TileListHash1, TileListHash2, TileListFlat = layer.TileListHash1, layer.TileListHash2, layer.TileListFlat
for k = 1, layer.TouchedCount do TileCounts[Touched[k]] = 0 end
local TouchedCount = 0
local CurKey, CurCount, CurHash1, CurHash2, CurList, CurListHash1, CurListHash2, CurListFlat =
nil, 0, 0, 0, nil, nil, nil, nil
local TileXs, TileYs = layer.TileX, layer.TileY
for pi = 1, np do
local p = plist[pi]
local tex_id = PrimTexId[p]
-- hash the clipped bounds, not the clip: a window clipped by the fixed viewport stays hash-stable when moved
local cx0, cy0, cx1, cy1 = PrimBoundsX0[p] - lx0, PrimBoundsY0[p] - ly0, PrimBoundsX1[p] - lx0,
PrimBoundsY1[p] - ly0
local vbuf = PrimVtxBuffer[p]
local va, vd = PrimA[p], PrimD[p]
-- flat rect: hash its clipped rect per tile, so resizing only changes the tiles its edges cross
local FlatRect, RectColor, RectUV = false, 0, 0
if vd and not PrimGradient[p] then
local u0, v0 = readf64(vbuf, va + 16), readf64(vbuf, va + 24)
local vc = PrimC[p]
if not PrimTexture[p] or (u0 == readf64(vbuf, vc + 16) and v0 == readf64(vbuf, vc + 24)) then
FlatRect, RectColor, RectUV = true, readu32(vbuf, va + 32), u0 * 8192 + v0
end
end
local h1, h2 = 0, 0
local FlatSig = -1
if FlatRect then FlatSig = ((RectColor * 8191 + RectUV * 4096) % P1 * 64 + tex_id) % P1 end
if not FlatRect then
h1 = ((cx0 * 8191 + cy0) * 8191 + cx1) % P1
h2 = ((cy1 * 8191 + cx1) * 8191 + cy0 + tex_id) % P2
local vax, vay = lx0 + ox, ly0 + oy
if vd then
-- axis aligned quad: CollectPrims checked that TR/BL follow from TL/BR (+ kind)
h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay)
h1, h2 = HashVertex(h1, h2, vbuf, PrimC[p], vax, vay)
local gk = PrimGradient[p]
if gk then
h1 = (h1 * 48271 + gk) % P1
h2 = (h2 * 16807 + gk * 3) % P2
end
else
h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay)
h1, h2 = HashVertex(h1, h2, vbuf, PrimB[p], vax, vay)
h1, h2 = HashVertex(h1, h2, vbuf, PrimC[p], vax, vay)
end
end
for ty = floor((PrimBoundsY0[p] - ly0) / TILE), floor((PrimBoundsY1[p] - 1 - ly0) / TILE) do
for tx = floor((PrimBoundsX0[p] - lx0) / TILE), floor((PrimBoundsX1[p] - 1 - lx0) / TILE) do
if FlatRect then
local tx0, ty0 = tx * TILE, ty * TILE
local ix0, iy0 = max(cx0 - tx0, 0), max(cy0 - ty0, 0)
local ix1, iy1 = min(cx1 - tx0, TILE), min(cy1 - ty0, TILE)
local r = ((ix0 * 131 + iy0) * 131 + ix1) * 131 + iy1
h1 = ((r * 48271 + RectColor) % P1 * 48271 + RectUV * 4096 + 7) % P1
h2 = ((r * 16807 + RectColor + tex_id) % P2 * 16807 + RectUV * 65521 + 11) % P2
end
-- unique for |tx|, |ty| < 32768 (content tiles go negative)
local key = (ty + 32768) * 65536 + tx + 32768
if key ~= CurKey then
if CurKey then
TileCounts[CurKey], TileHash1[CurKey], TileHash2[CurKey] = CurCount, CurHash1, CurHash2
end
CurKey = key
CurCount = TileCounts[key]
if not CurCount or CurCount == 0 then
CurCount, CurHash1, CurHash2 = 0, 0, 0
if not TileLists[key] then
local ListPool = EditableImages.ListPool
local m = #ListPool
if m >= 4 then
TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key] =
ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m]
ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m] = nil, nil, nil, nil
else
TileLists[key] = {}
TileListHash1[key] = {}
TileListHash2[key] = {}
TileListFlat[key] = {}
end
end
TouchedCount = TouchedCount + 1
Touched[TouchedCount] = key
TileXs[key], TileYs[key] = tx, ty
else
CurHash1, CurHash2 = TileHash1[key], TileHash2[key]
end
CurList, CurListHash1, CurListHash2, CurListFlat =
TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key]
end
CurCount += 1
CurList[CurCount], CurListHash1[CurCount], CurListHash2[CurCount], CurListFlat[CurCount] =
p, h1, h2, FlatSig
CurHash1 = (CurHash1 * 48271 + h1) % P1
CurHash2 = (CurHash2 * 16807 + h2 + CurCount) % P2
end
end
end
if CurKey then TileCounts[CurKey], TileHash1[CurKey], TileHash2[CurKey] = CurCount, CurHash1, CurHash2 end
layer.TouchedCount = TouchedCount
return TouchedCount
end
local function PlaceLayer(layer, scale, lx0, ly0, z, clip_x0, clip_y0, clip_x1, clip_y1)
local root = layer.Root
if root ~= layer.Frame then
if layer.ClipX0 ~= clip_x0 or layer.ClipY0 ~= clip_y0 or layer.ClipX1 ~= clip_x1 or layer.ClipY1 ~= clip_y1 then
layer.ClipX0, layer.ClipY0, layer.ClipX1, layer.ClipY1 = clip_x0, clip_y0, clip_x1, clip_y1
root.Position = UDim2.fromOffset(clip_x0 / scale, clip_y0 / scale)
root.Size = UDim2.fromOffset((clip_x1 - clip_x0) / scale, (clip_y1 - clip_y0) / scale)
layer.X = false
end
if layer.X ~= lx0 or layer.Y ~= ly0 then
layer.X, layer.Y = lx0, ly0
layer.Frame.Position = UDim2.fromOffset((lx0 - clip_x0) / scale, (ly0 - clip_y0) / scale)
end
elseif layer.X ~= lx0 or layer.Y ~= ly0 then
layer.X, layer.Y = lx0, ly0
root.Position = UDim2.fromOffset(lx0 / scale, ly0 / scale)
end
if layer.Z ~= z then
layer.Z = z
root.ZIndex = z
end
if not layer.Visible then
layer.Visible = true
root.Visible = true
end
end
local function SweepTiles(BackendData, layer, TouchedCount, lx0, ly0, clip_x0, clip_y0, clip_x1, clip_y1)
local TileCounts, Touched = layer.TileCounts, layer.Touched
-- content layer: only tiles inside its clip frame are kept, so scrolling holds the visible tiles + a few spares
local FrameNo, VisibleCount, SpareCap = BackendData.FrameNo, TouchedCount, TouchedCount
if layer.Root ~= layer.Frame then
for kk = 1, TouchedCount do
local key = Touched[kk]
local x0, y0 = lx0 + layer.TileX[key] * TILE, ly0 + layer.TileY[key] * TILE
if x0 >= clip_x1 or y0 >= clip_y1 or x0 + TILE <= clip_x0 or y0 + TILE <= clip_y0 then
TileCounts[key] = 0
VisibleCount -= 1
end
end
SpareCap = min(VisibleCount, 4)
end
-- unused tiles stay for a quick scroll back: at most SpareCap of them, for at most KEEP_FRAMES
local spare = 0
for key, tile in pairs(layer.Tiles) do
if not TileCounts[key] or TileCounts[key] == 0 then
if tile.Visible then
tile.Visible = false
tile.Label.Visible = false
tile.Hash1 = -1
tile.DrawnCount = -1
end
spare += 1
if spare > SpareCap or FrameNo - tile.Used > EditableImages.KEEP_FRAMES then
EditableImages.FreeTile(layer, key, true)
end
end
end
end
@native
local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, vy0, vx1, vy1)
local qx0, qy0, qx1, qy1 = tile.ValidX0, tile.ValidY0, tile.ValidX1, tile.ValidY1
local list, ListHash1, ListHash2 = layer.TileLists[key], layer.TileListHash1[key], layer.TileListHash2[key]
local DrawnHash1, DrawnHash2, DrawnX0, DrawnY0, DrawnX1, DrawnY1, DrawnCount =
tile.DrawnHash1, tile.DrawnHash2, tile.DrawnX0, tile.DrawnY0, tile.DrawnX1, tile.DrawnY1,
tile.DrawnCount
local nx0, ny0, nx1, ny1 = TILE, TILE, 0, 0
for k = 1, count do
local p = list[k]
local a, b = PrimBoundsX0[p] - x0, PrimBoundsY0[p] - y0
local c, d = PrimBoundsX1[p] - x0, PrimBoundsY1[p] - y0
if a < nx0 then nx0 = a end
if b < ny0 then ny0 = b end
if c > nx1 then nx1 = c end
if d > ny1 then ny1 = d end
end
nx0, ny0, nx1, ny1 = max(nx0, 0), max(ny0, 0), min(nx1, TILE), min(ny1, TILE)
local DX0, DY0, DX1, DY1, AddRect = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1,
EditableImages.DY1, EditableImages.AddRect
local DirtyCount = 0
if force or DrawnCount < 0 then
-- outside the old + new content bounds the valid part is already transparent
DirtyCount = AddRect(AddRect(0, tile.ContentX0, tile.ContentY0, tile.ContentX1, tile.ContentY1), nx0,
ny0, nx1, ny1)
else
-- partial redraw: a pixel no changed primitive (old or new) touches is covered by the same primitives in the
-- same order, so only the bounds of the changed ones are redrawn
local i, lim = 1, min(DrawnCount, count)
while i <= lim and DrawnHash1[i] == ListHash1[i] and DrawnHash2[i] == ListHash2[i] do i += 1 end
local j = 0
while j <= lim - i and DrawnHash1[DrawnCount - j] == ListHash1[count - j]
and DrawnHash2[DrawnCount - j] == ListHash2[count - j] do
j += 1
end
local of, lf = tile.DrawnFlat, layer.TileListFlat[key]
local paired = DrawnCount - j - i == count - j - i
for k = i, count - j do
local p = list[k]
local a, b, c, d = max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0),
min(PrimBoundsX1[p] - x0, TILE), min(PrimBoundsY1[p] - y0, TILE)
local oa, ob, oc, od = DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k]
if paired and lf[k] >= 0 and lf[k] == of[k] then
-- same flat rect, new bounds: only the strips between the old and new edges can differ
local uy0, uy1 = min(b, ob), max(d, od)
local ux0, ux1 = min(a, oa), max(c, oc)
if a ~= oa then DirtyCount = AddRect(DirtyCount, ux0, uy0, max(a, oa), uy1) end
if c ~= oc then DirtyCount = AddRect(DirtyCount, min(c, oc), uy0, ux1, uy1) end
if b ~= ob then DirtyCount = AddRect(DirtyCount, ux0, uy0, ux1, max(b, ob)) end
if d ~= od then DirtyCount = AddRect(DirtyCount, ux0, min(d, od), ux1, uy1) end
else
DirtyCount = AddRect(DirtyCount, a, b, c, d)
if k <= DrawnCount - j then DirtyCount = AddRect(DirtyCount, oa, ob, oc, od) end
end
end
for k = count - j + 1, DrawnCount - j do
DirtyCount = AddRect(DirtyCount, DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k])
end
end
-- clip D to V, then add the exposed part that isn't valid. cut: part of D inside the valid rect was clipped away
local cut, RectCount = false, 0
for r = 1, DirtyCount do
local a, b, c, d = DX0[r], DY0[r], DX1[r], DY1[r]
local ix0, iy0, ix1, iy1 = max(a, qx0), max(b, qy0), min(c, qx1), min(d, qy1)
if ix0 < ix1 and iy0 < iy1 and (ix0 < vx0 or iy0 < vy0 or ix1 > vx1 or iy1 > vy1) then cut = true end
a, b, c, d = max(a, vx0), max(b, vy0), min(c, vx1), min(d, vy1)
if a < c and b < d then
RectCount += 1
DX0[RectCount], DY0[RectCount], DX1[RectCount], DY1[RectCount] = a, b, c, d
end
end
if exposed then
local ex0, ey0, ex1, ey1 = vx0, vy0, vx1, vy1
if qx0 <= vx0 and qx1 >= vx1 then
if qy0 <= vy0 and qy1 > vy0 then ey0 = qy1 elseif qy1 >= vy1 and qy0 < vy1 then ey1 = qy0 end
elseif qy0 <= vy0 and qy1 >= vy1 then
if qx0 <= vx0 and qx1 > vx0 then ex0 = qx1 elseif qx1 >= vx1 and qx0 < vx1 then ex1 = qx0 end
end
RectCount = AddRect(RectCount, ex0, ey0, ex1, ey1)
end
if cut then
qx0, qy0, qx1, qy1 = vx0, vy0, vx1, vy1
elseif exposed then
if (qx0 == vx0 and qx1 == vx1 and qy0 <= vy1 and vy0 <= qy1)
or (qy0 == vy0 and qy1 == vy1 and qx0 <= vx1 and vx0 <= qx1)
or (qx0 >= vx0 and qy0 >= vy0 and qx1 <= vx1 and qy1 <= vy1) then
qx0, qy0, qx1, qy1 = min(qx0, vx0), min(qy0, vy0), max(qx1, vx1), max(qy1, vy1)
else
qx0, qy0, qx1, qy1 = vx0, vy0, vx1, vy1
end
end
tile.ValidX0, tile.ValidY0, tile.ValidX1, tile.ValidY1 = qx0, qy0, qx1, qy1
tile.ContentX0, tile.ContentY0, tile.ContentX1, tile.ContentY1 = nx0, ny0, nx1, ny1
local DrawnFlat, ListFlat = tile.DrawnFlat, layer.TileListFlat[key]
for k = 1, count do
local p = list[k]
DrawnHash1[k], DrawnHash2[k], DrawnFlat[k] = ListHash1[k], ListHash2[k], ListFlat[k]
DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k] =
max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0), min(PrimBoundsX1[p] - x0, TILE),
min(PrimBoundsY1[p] - y0, TILE)
end
tile.DrawnCount = count
return RectCount
end
@native
local function RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1)
ClearRect(rx0, ry0, rx1, ry1)
for k = 1, count do
local p = list[k]
local cx0, cy0 = max(PrimClipX0[p] - x0, rx0), max(PrimClipY0[p] - y0, ry0)
local cx1, cy1 = min(PrimClipX1[p] - x0, rx1), min(PrimClipY1[p] - y0, ry1)
if cx0 >= cx1 or cy0 >= cy1 or PrimBoundsX0[p] - x0 >= rx1 or PrimBoundsY0[p] - y0 >= ry1
or PrimBoundsX1[p] - x0 <= rx0 or PrimBoundsY1[p] - y0 <= ry0 then
continue
end
local kind, gk = 0, PrimGradient[p]
if PrimD[p] then kind = gk and gk + 1 or 1 end
DrawPrim(kind, PrimTexture[p], PrimVtxBuffer[p], PrimA[p], PrimB[p], PrimC[p], tox, toy, cx0, cy0, cx1, cy1)
end
end
-- WritePixelsBuffer needs the exact size: partial upload buffers are reused by size
local SubBuffers, SubBufferCount = {}, 0
local function UploadRect(img, buf, rx0, ry0, rx1, ry1)
local rw, rh = rx1 - rx0, ry1 - ry0
if rw == TILE and rh == TILE then
img:WritePixelsBuffer(Vector2.zero, TILE_SIZE, buf)
return
end
local sk = rw * 1024 + rh
local sub = SubBuffers[sk]
if not sub then
if SubBufferCount >= 256 then
table.clear(SubBuffers)
SubBufferCount = 0
end
sub = buffer.create(rw * rh * 4)
SubBuffers[sk] = sub
SubBufferCount += 1
end
CopySubRect(sub, rx0, ry0, rw, rh)
img:WritePixelsBuffer(Vector2.new(rx0, ry0), Vector2.new(rw, rh), sub)
end
local function RedrawTile(BackendData, layer, key, tile, count, x0, y0, ox, oy, force, exposed, vx0, vy0, vx1, vy1)
BackendData.RedrawStarted = true
BackendData.FrameTiles += 1
tile.Deferred = 0
tile.Hash1, tile.Hash2 = layer.TileHash1[key], layer.TileHash2[key]
local RectCount = DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, vy0, vx1, vy1)
local list = layer.TileLists[key]
local tox, toy = ox + x0, oy + y0
local Timing = EditableImages.StageTiming and EditableImages.StageFrame
if Timing and RectCount > 0 then Timing.TilesRasterized += 1 end
-- parallel: rasterized + uploaded later in the frame (pixels outside the rects are never read)
if Parallel.Active and RectCount > 0 then
Parallel.Tile(tile.Image, list, count, x0, y0, tox, toy, RectCount)
return
end
SetTarget(tile.Buffer, TILE)
local DX0, DY0, DX1, DY1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1
for r = 1, RectCount do
local rx0, ry0, rx1, ry1 = DX0[r], DY0[r], DX1[r], DY1[r]
RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1)
PB("ImGui upload")
local t_up = Timing and os.clock()
if Timing then
Timing.PixelsRasterized += (rx1 - rx0) * (ry1 - ry0)
Timing.Uploads += 1
end
UploadRect(tile.Image, tile.Buffer, rx0, ry0, rx1, ry1)
if Timing then Timing.Upload += os.clock() - t_up end
PE()
end
end
local function DrawLayer(BackendData, layer, plist, np, lx0, ly0, ox, oy, force, z, clip_x0, clip_y0, clip_x1, clip_y1)
PB("ImGui tile hash")
if EditableImages.StageTiming then EditableImages.BeginStage() end
local TouchedCount = HashTiles(layer, plist, np, lx0, ly0, ox, oy)
if EditableImages.StageTiming then EditableImages.EndStage("Hash") end
PE()
PlaceLayer(layer, BackendData.Scale, lx0, ly0, z, clip_x0, clip_y0, clip_x1, clip_y1)
PB("ImGui raster+upload")
if EditableImages.StageTiming then EditableImages.BeginStage() end
SweepTiles(BackendData, layer, TouchedCount, lx0, ly0, clip_x0, clip_y0, clip_x1, clip_y1)
local TileCounts, Touched, TileHash1, TileHash2 = layer.TileCounts, layer.Touched, layer.TileHash1, layer.TileHash2
local content = layer.Root ~= layer.Frame
local FrameNo, deferred = BackendData.FrameNo, false
for kk = 1, TouchedCount do
local key = Touched[kk]
local count = TileCounts[key]
if not count or count == 0 then continue end -- outside the content clip, or list freed
local tx, ty = layer.TileX[key], layer.TileY[key]
local tile = GetTile(BackendData, layer, key, tx, ty)
if not tile then continue end
tile.Used = FrameNo
local x0, y0 = lx0 + tx * TILE, ly0 + ty * TILE
-- redraws are clipped to the visible part; a part scrolled into view that isn't valid is redrawn then
local vx0, vy0, vx1, vy1 = 0, 0, TILE, TILE
if content then
vx0, vy0, vx1, vy1 = max(clip_x0 - x0, 0), max(clip_y0 - y0, 0), min(clip_x1 - x0, TILE), min(clip_y1 - y0,
TILE)
end
local exposed = vx0 < tile.ValidX0 or vy0 < tile.ValidY0 or vx1 > tile.ValidX1 or vy1 > tile.ValidY1
local dirty = force or exposed or tile.Hash1 ~= TileHash1[key] or tile.Hash2 ~= TileHash2[key]
if dirty and BackendData.RedrawStarted and (tile.Deferred or 0) < MAX_DEFER_FRAMES
and ((BackendData.RedrawBudget > 0 and os.clock() - BackendData.FrameStartTime >= BackendData.RedrawBudget)
or (BackendData.TileLimit and BackendData.FrameTiles >= BackendData.TileLimit)) then
-- over budget (TileLimit: t_pixels hook): keep the old pixels (the stored hashes describe them)
tile.Deferred = (tile.Deferred or 0) + 1
if force then
tile.Hash1 = -1
tile.DrawnCount = -1
end
deferred = true
dirty = false
end
if dirty then RedrawTile(BackendData, layer, key, tile, count, x0, y0, ox, oy, force, exposed, vx0, vy0, vx1, vy1) end
-- a deferred tile that was hidden holds old pixels: stays hidden until drawn
if not tile.Visible and (tile.Deferred or 0) == 0 then
tile.Visible = true
tile.Label.Visible = true
end
end
if EditableImages.StageTiming then
EditableImages.EndStage("Raster")
end
PE()
return deferred
end
local function UpdateTextures(draw_data)
PB("ImGui textures")
if draw_data.Textures ~= nil then
for _, tex in draw_data.Textures:iter() do
if tex.Status ~= ImTextureStatus.OK then
-- WantUpdates only writes regions no tile has sampled yet: no redraw needed
UpdateTexture(tex)
end
end
end
PE()
end
local function RenderRateAllows(BackendData, draw_data)
local rate = BackendData.RenderRate
if BackendData.BusyRenderRate > 0 then
local g = ImGui.GetCurrentContext()
local busy = g.WheelingWindow ~= nil or g.MovingWindow ~= nil -- (io.MouseWheel is already cleared by EndFrame)
if not busy and g.ActiveId ~= 0 then
local w = g.ActiveIdWindow
local cur = g.MouseCursor
busy = (cur >= ImGuiMouseCursor.ResizeAll and cur <= ImGuiMouseCursor.ResizeNWSE)
or (w ~= nil and (g.ActiveId == ImGui.GetWindowScrollbarID(w, ImGuiAxis.X)
or g.ActiveId == ImGui.GetWindowScrollbarID(w, ImGuiAxis.Y)))
end
if busy and (rate <= 0 or BackendData.BusyRenderRate < rate) then rate = BackendData.BusyRenderRate end
end
if rate > 0 then
local now = os.clock()
-- skipped: kept pending, Heartbeat draws it if no new frame comes
if now + 0.002 < BackendData.NextRender then
BackendData.Pending = draw_data
return false
end
BackendData.NextRender = math.max(BackendData.NextRender + 1 / rate, now)
end
return true
end
local function ReuseDrawList(BackendData, set, draw_list, same, sdx, sdy, z, ox, oy, ScreenWidth, ScreenHeight)
for kind = 1, 3 do
local layer = set[kind]
if layer and layer.Visible then
if same == 2 then ShiftLayer(layer, sdx, sdy, BackendData.Scale) end
z += 1
if layer.Z ~= z then
layer.Z = z
layer.Root.ZIndex = z
end
end
end
if same == 2 then
Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
set.SnapExtentX0 += sdx
set.SnapExtentY0 += sdy
set.SnapExtentX1 += sdx
set.SnapExtentY1 += sdy
end
set.LastUsed = BackendData.FrameNo
return PlaceOverlays(BackendData, draw_list, z, ox, oy)
end
-- Collects primitives into Prim* (from n + 1) and commands into Cmd*; returns n, LimitFree and the extents
@native
local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, LimitX1, LimitY1)
local vbuf, idx = draw_list.VtxBuffer.Buf, draw_list.IdxBuffer.Data
local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1,
draw_list._ContentClipY1
local SeenContent = false
local ex0, ey0, ex1, ey1 = math.huge, math.huge, -math.huge, -math.huge
local LimitFree = true
if ccx0 then
local a, b, c, d = floor(ccx0 - ox), floor(ccy0 - oy), floor(ccx1 - ox), floor(ccy1 - oy)
if a < LimitX0 or b < LimitY0 or c > LimitX1 or d > LimitY1 then LimitFree = false end
ex0, ey0, ex1, ey1 = min(ex0, a), min(ey0, b), max(ex1, c), max(ey1, d)
end
local ci = 0
for _, pcmd in draw_list.CmdBuffer:iter() do
ci += 1
CmdUnclipped[ci], CmdKind[ci] = false, 0
if pcmd.UserCallback ~= nil then
pcmd.UserCallback(draw_list, pcmd)
elseif pcmd.ElemCount > 0 then
local clip = pcmd.ClipRect
local rcx0, rcy0, rcx1, rcy1 = floor(clip.x - ox), floor(clip.y - oy), floor(clip.z - ox),
floor(clip.w - oy)
if rcx0 < LimitX0 or rcy0 < LimitY0 or rcx1 > LimitX1 or rcy1 > LimitY1 then LimitFree = false end
if rcx0 < ex0 then ex0 = rcx0 end
if rcy0 < ey0 then ey0 = rcy0 end
if rcx1 > ex1 then ex1 = rcx1 end
if rcy1 > ey1 then ey1 = rcy1 end
local cx0, cy0 = max(rcx0, LimitX0), max(rcy0, LimitY0)
local cx1, cy1 = min(rcx1, LimitX1), min(rcy1, LimitY1)
local kind = 1
if ccx0 and clip.x >= ccx0 and clip.y >= ccy0 and clip.z <= ccx1 and clip.w <= ccy1 then
kind = 2
SeenContent = true
if clip.x == ccx0 and clip.y == ccy0 and clip.z == ccx1 and clip.w == ccy1 then
-- clipped by the layer's clip frame instead: partly visible rows stay hash-stable while scrolling
cx0, cy0, cx1, cy1 = LimitX0, LimitY0, LimitX1, LimitY1
end
elseif SeenContent then
kind = 3
end
CmdKind[ci] = kind
local CmdFree, cex0, cey0, cex1, cey1 =
cx1 > cx0 and cy1 > cy0, math.huge, math.huge, -math.huge, -math.huge
if cx1 > cx0 and cy1 > cy0 then
local tex_id = pcmd:GetTexID()
local t = BackendData.Textures[tex_id]
local vo = pcmd.VtxOffset
local i, last = pcmd.IdxOffset + 1, pcmd.IdxOffset + pcmd.ElemCount
while i <= last do
local ia, ic = idx[i], idx[i + 2]
local va, vb, vc = (vo + ia - 1) * VTX_STRIDE, (vo + idx[i + 1] - 1) * VTX_STRIDE,
(vo + ic - 1) * VTX_STRIDE
local vd = false
local gk = false
local pax, pay = readf64(vbuf, va), readf64(vbuf, va + 8)
local pbx, pby = readf64(vbuf, vb), readf64(vbuf, vb + 8)
local pcx, pcy = readf64(vbuf, vc), readf64(vbuf, vc + 8)
local bx0, by0, bx1, by1
if i + 5 <= last and idx[i + 3] == ia and idx[i + 4] == ic then
local d = (vo + idx[i + 5] - 1) * VTX_STRIDE
local pdx, pdy = readf64(vbuf, d), readf64(vbuf, d + 8)
if pay == pby and pbx == pcx and pcy == pdy and pdx == pax and pax < pbx and pay < pdy then
local col, colb, colc, cold = readu32(vbuf, va + 32), readu32(vbuf, vb + 32),
readu32(vbuf, vc + 32), readu32(vbuf, d + 32)
local tax, tay = readf64(vbuf, va + 16), readf64(vbuf, va + 24)
local tbx, tby = readf64(vbuf, vb + 16), readf64(vbuf, vb + 24)
local tcx, tcy = readf64(vbuf, vc + 16), readf64(vbuf, vc + 24)
local tdx, tdy = readf64(vbuf, d + 16), readf64(vbuf, d + 24)
if colb == col and colc == col and cold == col then
if tbx == tcx and tby == tay and tdx == tax and tdy == tcy then vd = d end
elseif tax == tbx and tax == tcx and tax == tdx and tay == tby and tay == tcy
and tay == tdy then
if colb == col and cold == colc then
vd = d
gk = 1
elseif cold == col and colb == colc then
vd = d
gk = 2
end
end
if vd then
bx0, by0 = ceil(pax - ox - 0.5), ceil(pay - oy - 0.5)
bx1, by1 = ceil(pcx - ox - 0.5), ceil(pcy - oy - 0.5)
end
end
end
if vd then
i = i + 6
else
bx0, by0 = floor(min(pax, pbx, pcx) - ox), floor(min(pay, pby, pcy) - oy)
bx1, by1 = ceil(max(pax, pbx, pcx) - ox) + 1, ceil(max(pay, pby, pcy) - oy) + 1
i = i + 3
end
if bx0 < cx0 or by0 < cy0 or bx1 > cx1 or by1 > cy1 then CmdFree = false end
if bx0 < cex0 then cex0 = bx0 end
if by0 < cey0 then cey0 = by0 end
if bx1 > cex1 then cex1 = bx1 end
if by1 > cey1 then cey1 = by1 end
if bx0 < ex0 then ex0 = bx0 end
if by0 < ey0 then ey0 = by0 end
if bx1 > ex1 then ex1 = bx1 end
if by1 > ey1 then ey1 = by1 end
if bx0 < LimitX0 or by0 < LimitY0 or bx1 > LimitX1 or by1 > LimitY1 then LimitFree = false end
if bx0 < cx0 then bx0 = cx0 end
if by0 < cy0 then by0 = cy0 end
if bx1 > cx1 then bx1 = cx1 end
if by1 > cy1 then by1 = cy1 end
if bx0 < bx1 and by0 < by1 then
n = n + 1
PrimA[n], PrimB[n], PrimC[n], PrimD[n], PrimTexture[n], PrimGradient[n], PrimTexId[n],
PrimVtxBuffer[n] = va, vb, vc, vd, t, gk, tex_id, vbuf
PrimClipX0[n], PrimClipY0[n], PrimClipX1[n], PrimClipY1[n] = cx0, cy0, cx1, cy1
PrimBoundsX0[n], PrimBoundsY0[n], PrimBoundsX1[n], PrimBoundsY1[n] = bx0, by0, bx1, by1
PrimKind[n] = kind
end
end
end
if cex0 > cex1 then cex0, cey0, cex1, cey1 = 0, 0, 0, 0 end
CmdUnclipped[ci] = CmdFree
CmdBoundsX0[ci], CmdBoundsY0[ci], CmdBoundsX1[ci], CmdBoundsY1[ci] = cex0, cey0, cex1, cey1
end
end
return n, LimitFree, ex0, ey0, ex1, ey1
end
@native
local function DrawLists(BackendData, draw_list, first, n, z, ox, oy, force, LimitX0, LimitY0, LimitX1, LimitY1)
local set = BackendData.Layers[draw_list]
local ListDeferred = false
local Kind1Count, Kind2Count, Kind3Count = 0, 0, 0
local Kind1X, Kind1Y, Kind3X, Kind3Y = math.huge, math.huge, math.huge, math.huge
for p = first, n do
local k = PrimKind[p]
if k == 1 then
Kind1Count += 1
LayerPrims1[Kind1Count] = p
if PrimBoundsX0[p] < Kind1X then Kind1X = PrimBoundsX0[p] end
if PrimBoundsY0[p] < Kind1Y then Kind1Y = PrimBoundsY0[p] end
elseif k == 2 then
Kind2Count += 1
LayerPrims2[Kind2Count] = p
else
Kind3Count += 1
LayerPrims3[Kind3Count] = p
if PrimBoundsX0[p] < Kind3X then Kind3X = PrimBoundsX0[p] end
if PrimBoundsY0[p] < Kind3Y then Kind3Y = PrimBoundsY0[p] end
end
end
if Kind1Count > 0 then
z += 1
if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 1), LayerPrims1, Kind1Count, Kind1X, Kind1Y, ox,
oy, force, z) then
ListDeferred = true
end
elseif set and set[1] then HideLayer(set[1]) end
if Kind2Count > 0 then
local ccx0 = draw_list._ContentClipX0
local ContentX0, ContentY0, ContentX1, ContentY1
if ccx0 then
ContentX0, ContentY0 = max(floor(ccx0 - ox), LimitX0), max(floor(draw_list._ContentClipY0 - oy), LimitY0)
ContentX1, ContentY1 = min(floor(draw_list._ContentClipX1 - ox), LimitX1),
min(floor(draw_list._ContentClipY1 - oy), LimitY1)
end
z += 1
if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 2), LayerPrims2, Kind2Count,
floor(draw_list._ScrollOriginX - ox), floor(draw_list._ScrollOriginY - oy), ox, oy, force, z,
ContentX0, ContentY0, ContentX1, ContentY1) then ListDeferred = true end
elseif set and set[2] then HideLayer(set[2]) end
if Kind3Count > 0 then
z += 1
if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 3), LayerPrims3, Kind3Count, Kind3X, Kind3Y, ox,
oy, force, z) then
ListDeferred = true
end
elseif set and set[3] then HideLayer(set[3]) end
return z, ListDeferred
end
-- Overlay frames are only hidden (the user owns them); unused layers hidden, long unused ones freed
local function SweepLayers(BackendData, FrameNo)
for frame, shown in pairs(BackendData.OverlayShown) do
if shown ~= FrameNo then
frame.Visible = false
BackendData.OverlayShown[frame] = nil
end
end
table.clear(BackendData.Overlays)
for draw_list, set in pairs(BackendData.Layers) do
if set.LastUsed ~= FrameNo then
set.SnapOK = false
for kind = 1, 3 do if set[kind] then HideLayer(set[kind]) end end
if FrameNo - set.LastUsed > LAYER_KEEP_FRAMES then
DestroyLayerSet(set)
BackendData.Layers[draw_list] = nil
end
end
end
end
function M.RenderDrawData(draw_data)
local BackendData = GetBackendData()
PB("ImGui RenderDrawData")
BackendData.FrameStartTime = os.clock()
if EditableImages.StageTiming then
EditableImages.StageFrame = { Compare = 0, Collect = 0, Hash = 0, Raster = 0, Upload = 0, Other = 0, Total = 0,
TilesRasterized = 0, PixelsRasterized = 0, Uploads = 0, TilesCreated = 0, TilesFreed = 0 } end
BackendData.FrameTiles = 0
-- the first dirty tile of a frame is always redrawn (progress), the rest within the budget
BackendData.RedrawStarted = false
BackendData.Stale = nil
UpdateTextures(draw_data)
if not RenderRateAllows(BackendData, draw_data) then
PE()
return
end
local ScreenWidth, ScreenHeight = floor(draw_data.DisplaySize.x), floor(draw_data.DisplaySize.y)
if ScreenWidth <= 0 or ScreenHeight <= 0 then
PE()
return
end
local ox, oy = draw_data.DisplayPos.x, draw_data.DisplayPos.y
local LimitX0, LimitY0, LimitX1, LimitY1 = -CLIP_PAD, -CLIP_PAD, ScreenWidth + CLIP_PAD, ScreenHeight + CLIP_PAD
BackendData.FrameNo += 1
local FrameNo = BackendData.FrameNo
local force = BackendData.ForceRedraw
BackendData.ForceRedraw = false
Parallel.Active = Parallel.On and not Parallel.Config.Inline
local n = 0
local z = 0
local AnyDeferred = false
for _, draw_list in draw_data.CmdLists:iter() do
PB("ImGui unchanged check")
if EditableImages.StageTiming then EditableImages.BeginStage() end
local set = BackendData.Layers[draw_list]
local same, sdx, sdy = 0, 0, 0
if not force then same, sdx, sdy = CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) end
if same ~= 0 then
z = ReuseDrawList(BackendData, set, draw_list, same, sdx, sdy, z, ox, oy, ScreenWidth, ScreenHeight)
if EditableImages.StageTiming then EditableImages.EndStage("Compare") end
PE()
continue
end
if EditableImages.StageTiming then EditableImages.EndStage("Compare") end
PE()
PB("ImGui collect")
if EditableImages.StageTiming then EditableImages.BeginStage() end
local first = n + 1
local LimitFree, ex0, ey0, ex1, ey1
n, LimitFree, ex0, ey0, ex1, ey1 = CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, LimitX1,
LimitY1)
if EditableImages.StageTiming then EditableImages.EndStage("Collect") end
PE()
local ListDeferred
z, ListDeferred = DrawLists(BackendData, draw_list, first, n, z, ox, oy, force, LimitX0, LimitY0, LimitX1,
LimitY1)
set = BackendData.Layers[draw_list]
-- deferred tiles: not "unchanged" next frame, so they get redrawn
if set then
set.LastUsed = FrameNo
if ListDeferred then set.SnapOK = false else
Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
set.SnapLimitFree = LimitFree
set.SnapExtentX0, set.SnapExtentY0, set.SnapExtentX1, set.SnapExtentY1 = ex0, ey0, ex1, ey1
end
end
if ListDeferred then AnyDeferred = true end
z = PlaceOverlays(BackendData, draw_list, z, ox, oy)
end
SweepLayers(BackendData, FrameNo)
-- drop references so old vertex tables can be collected
for k = n + 1, BackendData.LastPrimCount do PrimTexture[k], PrimVtxBuffer[k] = nil, nil end
BackendData.LastPrimCount = n
-- Tiles left for later: if the app doesn't submit a new frame, Heartbeat finishes them from this draw data
if AnyDeferred then
BackendData.Stale = draw_data
BackendData.StaleHeartbeat = BackendData.HeartbeatCount
end
if Parallel.Active then
Parallel.Flush()
end
if EditableImages.StageTiming and EditableImages.StageFrame then
local f = EditableImages.StageFrame
f.Raster -= f.Upload
f.Total = os.clock() - BackendData.FrameStartTime
f.Other = f.Total - f.Compare - f.Collect - f.Hash - f.Raster - f.Upload
BackendData.FrameStats = f
end
PE()
end
return M
+169
View File
@@ -0,0 +1,169 @@
-- Texture records, the module-wide EditableImage budget, profiling labels and stage timing stats.
local Raster = IM_INCLUDE("roblox/raster.lua")
local AssetService = game:GetService("AssetService")
local writeu32 = buffer.writeu32
local TILE = Raster.TILE
local M = {}
-- One table, not locals: shared by every context and module. FreeTile is set by layers.lua (Evict needs it).
local EditableImages = {
Cap = 64 * 1024 * 1024, Bytes = 0, Count = 0, ImageBytes = setmetatable({}, { __mode = "k" }),
Pool = {}, PoolMax = 16,
Backends = setmetatable({}, { __mode = "k" }),
LastTextureId = 0, KEEP_FRAMES = 30,
StageTiming = false,
}
M.EditableImages = EditableImages
local ProfileBegin, ProfileEnd = debug.profilebegin, debug.profileend
local Profiling = false
function M.PB(name) if Profiling then ProfileBegin(name) end end
function M.PE() if Profiling then ProfileEnd() end end
function M.SetProfiling(enabled) Profiling = enabled and true or false end
function M.IsProfiling() return Profiling end
-- StageTiming on: RenderDrawData accumulates os.clock per stage into StageFrame (GetStats().Frame)
function EditableImages.BeginStage() EditableImages.StageStart = os.clock() end
function EditableImages.EndStage(stage)
local f = EditableImages.StageFrame
if f then f[stage] += os.clock() - EditableImages.StageStart end
end
function EditableImages.AddStat(name, n)
local f = EditableImages.StageFrame
if f then f[name] += n end
end
function M.GetBackendData()
return ImGui.GetCurrentContext() and ImGui.GetIO().BackendPlatformUserData or nil
end
@native
local function CopyTexturePixels(tex, dst, x, y, w, h)
local bpp, tex_w = tex.BytesPerPixel, tex.Width
for row = 0, h - 1 do
local src, src_base = tex:GetPixelsAt(x, y + row)
local dst_off = ((y + row) * tex_w + x) * 4
if bpp == 4 then
for i = 0, w - 1 do
local s = src_base + i * 4
writeu32(dst, dst_off + i * 4, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216)
end
else -- Alpha8: white with alpha
for i = 0, w - 1 do
writeu32(dst, dst_off + i * 4, 16777215 + src[src_base + i] * 16777216)
end
end
end
end
-- Shared by every context: a font atlas shared between contexts is created under one, drawn under the others
local Records = {}
M.Records = Records
local function CreateTextureRecord(tex)
local t = { Buffer = buffer.create(tex.Width * tex.Height * 4), Width = tex.Width, Height = tex.Height }
CopyTexturePixels(tex, t.Buffer, 0, 0, tex.Width, tex.Height)
EditableImages.LastTextureId += 1
Records[EditableImages.LastTextureId] = t
tex.BackendUserData = EditableImages.LastTextureId
tex:SetTexID(EditableImages.LastTextureId)
tex:SetStatus(ImTextureStatus.OK)
end
function M.UpdateTexture(tex)
if tex.Status == ImTextureStatus.WantCreate then
CreateTextureRecord(tex)
elseif tex.Status == ImTextureStatus.WantUpdates then
local t = Records[tex.BackendUserData]
if t == nil or t.Width ~= tex.Width or t.Height ~= tex.Height then
CreateTextureRecord(tex)
return
end
for _, r in tex.Updates:iter() do
CopyTexturePixels(tex, t.Buffer, r.x, r.y, r.w, r.h)
end
t.V = (t.V or 0) + 1 -- parallel workers hold copies, resent when this changes
tex:SetStatus(ImTextureStatus.OK)
elseif tex.Status == ImTextureStatus.WantDestroy then
if tex.BackendUserData then
Records[tex.BackendUserData] = nil
tex.BackendUserData = nil
end
tex:SetTexID(ImTextureID_Invalid)
tex:SetStatus(ImTextureStatus.Destroyed)
end
end
-- User texture from RGBA8 pixels. Ids are never reused, so cached tiles can't show a stale image.
function ImGui_ImplRoblox_CreateTexture(pixels, w, h)
EditableImages.LastTextureId += 1
Records[EditableImages.LastTextureId] = { Buffer = pixels, Width = w, Height = h }
return ImTextureRef(EditableImages.LastTextureId)
end
function ImGui_ImplRoblox_DestroyTexture(tex_ref)
Records[tex_ref._TexID] = nil
end
-- Every EditableImage goes through Create/Destroy, counted against Cap. Over the cap (or CreateEditableImage failing):
-- evict idle tiles, retry once; still nothing -> nil, the caller skips the tile this frame.
function EditableImages.Create(w, h)
local need = w * h * 4
if need > EditableImages.Cap then return nil end
for attempt = 1, 2 do
if EditableImages.Bytes + need <= EditableImages.Cap then
local ok, img = pcall(AssetService.CreateEditableImage, AssetService, { Size = Vector2.new(w, h) })
if ok and img then
EditableImages.ImageBytes[img] = need
EditableImages.Bytes += need
EditableImages.Count += 1
return img
end
if attempt == 1 then EditableImages.Evict(math.huge) end -- engine refused: free everything evictable
elseif attempt == 1 then
EditableImages.Evict(EditableImages.Bytes + need - EditableImages.Cap)
end
end
return nil
end
function EditableImages.Destroy(img)
local s = EditableImages.ImageBytes[img]
if s then
EditableImages.ImageBytes[img] = nil
EditableImages.Bytes -= s
EditableImages.Count -= 1
end
img:Destroy()
end
-- The free list first, then idle tiles (not shown, not used this frame) of every context
function EditableImages.Evict(need)
local freed = 0
while freed < need and #EditableImages.Pool > 0 do
local t = table.remove(EditableImages.Pool)
EditableImages.Destroy(t.Image)
t.Label:Destroy()
freed += TILE * TILE * 4
end
if freed >= need then return end
for BackendData in EditableImages.Backends do
for _, set in pairs(BackendData.Layers) do
for kind = 1, 3 do
local l = set[kind]
if l then
for k, t in pairs(l.Tiles) do
if t.Used ~= BackendData.FrameNo and not (t.Visible and l.Visible) then
EditableImages.FreeTile(l, k)
freed += TILE * TILE * 4
end
end
end
end
end
end
end
return M
+20
View File
@@ -0,0 +1,20 @@
-- Parallel raster worker (Actor LocalScript). The build inlines raster.lua for the Raster line.
local Actor = script:GetActor()
if not Actor then
return
end
local Raster = require(script.Parent:WaitForChild("Raster"))
local Done = Actor:WaitForChild("Done")
local Textures = {}
Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength)
for _, Texture in TexUpdates do
Textures[Texture[1]] = { Buffer = Texture[2], Width = Texture[3], Height = Texture[4] }
end
local Results = Raster.RasterJobs(Prims, Tiles, TileLength, Textures)
task.synchronize()
Done:Fire(Id, Results)
end)
Actor:SetAttribute("Ready", true)