gum-layout-engine
Skill659 starsChanged 2 months agoMITView on GitHub
Deep internals of Gum's layout engine — UpdateLayout call chain, UpdateChildren ordering, stacking pipeline, dirty state, perf. Triggers: debugging/optimizing UpdateLayout/UpdateChildren, RefreshParentRowColumnDimensionForThis, GetWhatToStackAfter, MakeDirty, ResumeLayoutUpdateIfDirtyRecursive, _cachedSiblingIndex.
In this repository69 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- debuggingSkill
- frb-build-verificationSkill
- frb-pixel-harnessSkill
- gum-architecture-layersSkill
- gum-bundleSkill
- gum-cliSkill
- gum-cross-platform-unificationSkill
- gum-docs-writingSkill
- gum-file-pathsSkill
- gum-forms-behaviorsSkill
- gum-forms-controlsSkill
- gum-forms-default-visualsSkill
- gum-forms-itemscontrolSkill
- gum-forms-theme-importSkill
- gum-iconsSkill
- gum-issue-creationSkill
- gum-kernsmith-integrationsSkill
- gum-layoutSkill
- gum-localizationSkill
- gum-monogame-renderingSkill
- gum-monthly-releaseSkill
- gum-project-versioningSkill
- gum-property-assignmentSkill
- gum-raylib-renderingSkill
- gum-releaseSkill
- gum-runtime-animation-chainsSkill
- gum-runtime-bindingSkill
- gum-runtime-fontsSkill
- gum-runtime-hot-reloadSkill
- gum-runtime-syntax-versionSkill
- gum-runtime-systemmanagers-initSkill
- gum-runtime-topologySkill
- gum-runtime-variable-referencesSkill
- gum-samplesSkill
- gum-serviceSkill
- gum-source-linked-projectSkill
- gum-themingSkill
- gum-tool-animationsSkill
- gum-tool-codegenSkill
- gum-tool-copy-pasteSkill
- gum-tool-delete-logicSkill
- gum-tool-dialogsSkill
- gum-tool-errorsSkill
- gum-tool-file-watchSkill
- gum-tool-font-generationSkill
- gum-tool-import-from-gumxSkill
- gum-tool-loggingSkill
- gum-tool-outputSkill
- gum-tool-pluginsSkill
- gum-tool-save-classesSkill
- gum-tool-screenshotsSkill
- gum-tool-selectionSkill
- gum-tool-tree-viewSkill
- gum-tool-undoSkill
- gum-tool-variable-gridSkill
- gum-tool-variable-referencesSkill
- gum-tool-viewmodelsSkill
- gum-unit-testsSkill
- gum-variable-deep-diveSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
7 rules. About 0 are common, 4 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈4
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 13
All layout logic lives in GraphicalUiElement, a partial class split across GumRuntime/GraphicalUiElement.*.cs:
- Very specific: line 136
When some children use Ratio width/height and siblings use complex units (RelativeToChildren, PercentageOfOtherDimension, …
- Distinctive: line 189
O(1) fast path: if this child's dimension >= stored max, just set it.
- Distinctive: line 192
O(n) fallback: if this child's dimension < stored max, it may have been the max-holder and shrunk.
- Very specific: line 225
If currentDirtyState != null, call UpdateLayout with accumulated state
- Distinctive: line 252
When true, the *originating* call delegates to the parent (flow step 3).
- Distinctive: line 316
If an engine change instead makes the RaylibGum draw-call-count tests fail, suspect pre-existing test isolation before suspecting your …
≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Gum Layout Engine Internals
For user-facing layout concepts (units, stacking, wrapping, Anchor/Dock), see the gum-layout skill. This skill is for people debugging, optimizing, or extending the engine itself.
All layout logic lives in GraphicalUiElement, a partial class split across GumRuntime/GraphicalUiElement.*.cs:
| File | Holds |
.LayoutProperties.cs | X/Y/Width/Height, units, origins, Min/Max, ChildrenLayout, stacking and grid settings |
.UpdateLayout.cs | UpdateLayout and its parent climb |
.Dimensions.cs | UpdateDimensions, UpdateHeight, UpdateWidth, GetMaxCell* |
.RequiredSize.cs | GetRequiredParent*, GetParentDimensions, texture-based dimensions |
.ChildUpdates.cs | GetChildLayoutType, UpdateChildren, wrapped-line helpers |
.Position.cs | UpdatePosition and the offset helpers |
.Stacking.cs | row and column dimensions, grid cells, sibling helpers, GetWhatToStackAfter |
.Suspension.cs | MakeDirty, SuspendLayout, ResumeLayout |
.DockAndAnchor.cs | Dock and Anchor |
The other .cs partials hold properties, state application, rendering hookup and animation.
UpdateLayout Call Chain
Entry point: UpdateLayout(ParentUpdateType, int childrenUpdateDepth, XOrY?)
Flow (in order)
- Resolve
updateParent— evaluateParentUpdateTypeflags against actual parent state (stacks? depends on children? has ratio children?). - Early out — suspended or invisible — if layout is suspended
(
mIsLayoutSuspendedorIsAllLayoutSuspended) OR the element is invisible and not needed for parent update, callMakeDirty()and return. "Invisible" isIsHiddenWithinRenderTarget(): the element or an ancestor below the nearest render target is not visible. A render target (hidden or not) is never hidden, and its ownVisibledoes not hide its content, but elements hidden inside it are skipped like anywhere else (#7240). - Propagate to parent (originating call only) — if
updateParentANDGetIfShouldCallUpdateOnParent(), the originating call (the element that changed) hands off toparent.UpdateLayout()withchildrenUpdateDepth + 1and returns; the parent lays this element out as a child. A propagated climb (already size-gated — see Upward Propagation) instead falls through and re-evaluates whether to keep climbing at the end of the method. - Clear dirty state —
currentDirtyState = null. This is critical: it prevents double-updates duringResumeLayoutUpdateIfDirtyRecursive(see below). - Pre-children dimensions — update dimensions that do NOT depend on children (Absolute, PercentageOfParent, etc.) so children have correct parent sizes when they lay out.
- First children pass (if dimensions depend on children) — update children
with absolute layout types so the parent can measure them. With
UseFixedStackChildrenSize, only the first child is updated here (O(1) instead of O(n)), and only when the width is not measured from the children: the other children are unmeasured, so they would give a width that is too small. - Post-children dimensions — update RelativeToChildren / RelativeToMaxParentOrChildren dimensions now that children have been measured.
- Wrapped children pass — if
WrapsChildren, updateStackedWrappedchildren and re-measure dimensions with wrapping considered. - UpdatePosition — calculate X/Y based on units, origin, parent stacking.
For stacked children, this calls
GetWhatToStackAfterto find position relative to the previous sibling. - RefreshParentRowColumnDimensionForThis — if parent stacks, update the per-row/column max dimension.
- Full children pass —
UpdateChildren(depth, ChildType.All, ...)updates all children. Children already updated in step 6 are skipped viaalreadyUpdatedset. - Post-layout dimension check + gated climb — re-update dimensions if a child change could have altered them (always for a wrapping stack sized to its children: Ratio children are placed only in step 11 and move the siblings stacked after them, which changes the lines). If that changes the size, this element is placed again (an origin other than top-left reads its own size) and every child, ignored ones included, is laid out again against the new size; then, for a propagated climb, continue up to the parent only if this element's own measured size or position actually changed (see Upward Propagation).
Repeat visits of a child are cut down to placing it
Steps 6, 8 and 11 (and the post-children re-measure) visit the same child more than once, so a chain of k
nested content-sized stacks would cost 2^k layouts. Every child visit in UpdateChildren goes through
LayOutChild (ChildUpdates.cs): after a visit that changed no size or position inside the child, a later
visit in the same session (one outermost UpdateLayout; UpdateLayoutWithinSession continues it, the public
UpdateLayout starts a new one) only places the child again (TryPlaceInsteadOfLayingOutAgain). The result
must equal laying out every time: GraphicalUiElement.SkipRepeatedChildLayouts = false is the test hook that
does that, and LayoutRandomTreeSweepTests compares the two. The skip needs the same axis (xOrY, or a
settled visit of both axes, which also covers a one-axis request: a parent measures a Ratio child on one axis
before laying it out in full), the same parent size on the axes the child's units read, a Ratio size that
GetRatioWidth/GetRatioHeight still work out to the size the child has now, and a visit that placed the child
at its final size. Dropping any of them fails a sweep or a test.
Visits are recorded only where a child can be visited twice. UpdateLayoutWithinSession(mayBeLaidOutAgain) is true
for a child of a tracking parent, and a layout tracks its children when it was passed true, sizes from its children,
wraps, or has a Ratio-first pass (trackChildVisits into UpdateChildren). The public UpdateLayout passes false, so
a plain Regular or fixed-size container laid out once pays none of the bookkeeping. A new second pass over the
children needs to set trackChildVisits.
Deferred font realization (step 4.5)
Right after the parent-delegate early-out, before measuring, a node loads any font deferred while
layout was suspended (isFontDirty, set under IsAllLayoutSuspended). This is what makes a bare
UpdateLayout() realize deferred fonts. A font load normally lays out again when the text's measured
size changed; that call is suppressed here (SuppressLayoutFromFontChange) because this pass already
sizes the element. See the gum-property-assignment skill for the full cascade.
Renderable-reported size changes
A setter that changes what the renderable reports (texture size, aspect ratio, text measure,
descender) goes through ChangeRenderableAndUpdateLayout, which lays out only when a unit this
element uses reads a value that changed. Font loads get the same check in LoadFontFromProperties.
A new texture, source file or font setter that writes the renderable directly skips layout.
Circular Input Is Undefined
The engine rejects only the cycles between a parent and its child (IsSizeFollowingParentContentSize, GetChildLayoutType). A cycle through an intermediate element, a convergent cycle, or a wrapped text whose height follows its width has no defined result: it may need several layouts to settle, may never settle, and is not worth a rule per shape or a dependency-graph cycle detector. LayoutRandomTreeSweepTests.IllFormedSeedsNotHeld lists the sweep seeds that do this. The one guard is ToFiniteSize in .Dimensions.cs, which writes an infinite size as 0 so a divergent cycle cannot spread infinity into positions; it is a safety net, not a fix.
UpdateChildren Internals
Two-pass ordering for Ratio dependencies
When some children use Ratio width/height and siblings use complex units
(RelativeToChildren, PercentageOfOtherDimension, MaintainFileAspectRatio,
ScreenPixel, RelativeToMaxParentOrChildren), those complex-unit siblings must be
updated first. Ratio children need sibling sizes to compute remaining space.
Pass 1 (conditional): update children with DoesDimensionNeedUpdateFirstForRatio
units. Pass 2: update all remaining children.
A Ratio child is resized by siblings, not by its own subtree, so a depth-limited visit (a climb out of a
short subtree, such as hiding content) can resize it while stopping short of its descendants. LayOutChild
therefore lays a Ratio child out again to full depth, in a new session, when its size changed under a
limited depth. The branch for an element with no renderable (a Screen) does the same in LayOutScreenChild;
both ask NeedsFullDepthLayoutAfterSiblingsResizedIt.
shouldFlagAsUpdated
For Regular layout, children are flagged as updated to avoid redundant work.
For stacked layouts, children are not flagged — they need a second pass to
update positions in order (stacking depends on sibling order).
_cachedSiblingIndex
Set on each child (child._cachedSiblingIndex = i) in the iteration loop
before calling UpdateLayout. Used by GetWhatToStackAfter to avoid an
O(n) IndexOf call. Falls back to IndexOf if the cache is stale (element
not at expected position).
Stacking Position Pipeline
UpdatePosition → TryAdjustOffsetsByParentLayoutType → GetWhatToStackAfter
GetWhatToStackAfter
Finds the previous visible sibling and computes the offset to stack after it.
- Find sibling index — uses
_cachedSiblingIndex(O(1)) withIndexOffallback (O(n)). The cache is valid duringUpdateChildrenbut may be stale for individual property-change-triggered layouts. - Find previous visible sibling — walks backward from
thisIndexskipping invisible elements. - Determine wrap — if wrapping, increments
StackedRowOrColumnIndexand sumsStackedRowOrColumnDimensionsfor all previous rows/columns. - Compute offset — for non-wrapping: previous sibling's position + size +
StackSpacing. For wrapping: row/column dimension sum.
RefreshParentRowColumnDimensionForThis
Maintains parent.StackedRowOrColumnDimensions[rowOrColumnIndex] — the max
cross-axis dimension for each row (LeftToRight) or column (TopToBottom).
O(1) fast path: if this child's dimension >= stored max, just set it. This is the common case during sequential layout (e.g., populating a ListBox).
O(n) fallback: if this child's dimension < stored max, it may have been the max-holder and shrunk. Must rescan all siblings in the same row/column to find the true max.
The rescan stops at this child, so it is only right during the sequential pass;
calling it on one child afterwards drops later siblings from the max. In a
wrapping stack the row is the cross-axis parent for position, so a row-aligned
child placed before the row's largest member is fixed up by
RepositionChildrenAlignedInWrappedLines (position only, no row refresh) at the
end of UpdateChildren. It skips suspended children: they were not laid out in the
pass, so no line recorded them, and their own layout places them on resume.
An axis-only layout from a property setter (Height lays out XOrY.Y) also places the other
axis when that axis's size changed, since a width that is a percent of the height moves a
center or right origin. A parent laying out a child one axis at a time places it in full later,
so only the originating call does this.
Dirty State and Suspension
MakeDirty
Called when UpdateLayout is invoked on a suspended or invisible element.
Accumulates into currentDirtyState:
ParentUpdateType— OR'd together across multiple callsChildrenUpdateDepth— max of all callsXOrY— set to null if different axes were dirtied (means update both)
ResumeLayoutUpdateIfDirtyRecursive
Called when layout is resumed after suspension. ResumeLayout(recursive: true) first clears every descendant's
suspension (ClearLayoutSuspensionRecursive), so the first layout covers the subtree; resuming them one at a time
laid a parent out again per child (rows squared, #7239). Then it walks the tree:
- Clear
mIsLayoutSuspended - If
currentDirtyState != null, callUpdateLayoutwith accumulated state - Recurse into children
No double-update: the parent's UpdateLayout (step 2) calls
UpdateChildren, which calls each child's UpdateLayout, which clears that
child's currentDirtyState. When recursion (step 3) reaches that child, its
dirty state is already null — it skips the UpdateLayout call.
Visibility-deferred work is resolved on show
Layout skipped because an element or an ancestor was hidden is always resolved when it is shown, in any suspend mode and resume order; a layout clears a dirty record only when it covers its depth and axes, and resumeDescendantsOnResume makes a non-recursive resume walk hidden descendants (skipping children the user suspended).
EffectiveDirtyStateParentUpdateType
Adds all four IfParent* flags to currentDirtyState.ParentUpdateType. Each is checked against the real
parent when the update runs, and the climb passes the same flags up, so ancestors that stack or size from
children hear about a change skipped on a hidden element.
Upward Propagation
GetIfShouldCallUpdateOnParent
Returns true if:
- Parent dimensions depend on children (
GetIfDimensionsDependOnChildren) - Parent stacks children (any non-Regular
ChildrenLayout) - Any sibling uses
Ratiowidth/height
When true, the originating call delegates to the parent (flow step 3); propagated climbs above it are additionally size-gated (see below).
Upward propagation is incremental and size-gated
A change climbs one level so the parent can re-measure, then continues to the grandparent and beyond only while each level's own measured size or position keeps changing. When a level re-measures unchanged, propagation stops there — its siblings and ancestors are not relaid out. That is what keeps a change inside one item of an N-item stack from costing O(N-siblings).
The element that actually changed (the originating call) always notifies its
parent unconditionally, so the parent can re-measure; only the propagated
climbs above it are size-gated. The gateClimbOnSizeChange flag distinguishes
the two. Why the source can't gate itself:
An element's own size delta is not the same as its contribution to a content-sized or stacking parent. The clearest case is visibility: size is unchanged when an element is hidden or shown, but its contribution flips (full extent ↔ 0). Only the parent, by re-measuring, can tell whether the change matters. Gating at the source on the source's own size would silently drop visibility-driven (and add/remove) changes, because the parent would never re-measure.
RelativeToMaxParentOrChildren always propagates regardless of its own delta:
its size is the max of its content and its parent, so a content change can be
masked by a (stale) parent size while it still feeds the parent's size.
Visibility changes propagate through TWO paths
A visibility toggle is not one code path:
- Becoming invisible: the
Visiblesetter updates the parent directly (when the parent stacks / auto-grids / depends on children), separately fromUpdateLayout's climb. - Becoming visible: flows through
UpdateLayout's normal (originating) climb, unless the element is still suspended; then the setter updates the parent directly, as it does on hide (a Ratio sibling counts here too). The parent's layout skips its still-suspended children, so after a recursive suspend and a non-recursive resume, suspended siblings of the shown element keep stale positions until their ownResumeLayout.
Both rely on the parent re-measuring — see the contribution-vs-size trap above for why the parent, not the toggled element, is the source of truth.
Performance Patterns
| Optimization | What it avoids | Where |
_cachedSiblingIndex | O(n) IndexOf per child → O(n²) total | GetWhatToStackAfter |
RefreshParentRowColumn fast path | O(n) rescan per child → O(n²) total | RefreshParentRowColumnDimensionForThis |
UseFixedStackChildrenSize | Iterating all children in GetMaxCellHeight | UpdateLayout step 6, UpdateHeight |
xOrY parameter | Recalculating unchanged axis | Throughout |
childrenUpdateDepth | Unbounded recursion | UpdateChildren decrements per level |
alreadyUpdated set | Re-updating children measured in pre-pass | UpdateChildren |
LayOutChild repeat-visit skip | 2^depth layouts for nested content-sized stacks | UpdateChildren (ChildUpdates.cs) |
Diagnostic Counters
UpdateLayoutCallCount— total layout calls (incremented after parent propagation check)ChildrenUpdatingParentLayoutCalls— times a child triggered parent relayout
Verifying propagation (and a test-isolation caution)
UpdateLayoutCallCount deltas are how you assert propagation didn't over-fire:
build an N-item stack, make a change that shouldn't affect siblings, and assert
the delta stays flat as N grows rather than scaling. See the layout-call-count
tests in LayoutUnitTests.
If an engine change instead makes the RaylibGum draw-call-count tests fail,
suspect pre-existing test isolation before suspecting your change. Those tests
assert exact draw-call deltas and are sensitive to renderables leaked onto the
shared layer (an AddToManagers with no matching RemoveFromManagers); combined
with run-to-run test ordering that is flaky on a clean tree too. A layout change
can shift render batching just enough to change how often the latent flake trips —
confirm by running the suite repeatedly on the base branch before assuming you
caused it.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

