Skip to main content

@engine/ui — the in-canvas UI toolkit

Rendered from corpus/wiki/engine-ui.md · updated 2026-11-03

This page is generated from the project corpus and rewritten on every docs build. Edit the source in corpus/, not here.

@engine/ui (at engine/ui/) is the retained-mode, in-canvas widget toolkit shared by Farm, Citadel and MateQuest — it grew out of the "all GUI in-game" push (no DOM chrome), and those three clients draw their HUDs through it. Hollow does not use it: its client depends on @engine/core + @hollow/sim-core only, and its research surfaces are their own thing.

Three games consume it, so it may never import a game, and it must work under three different palettes (engine + Farm = EDG32, Citadel = Apollo-46, MateQuest = Resurrect-64). That single constraint explains most of the design below.

Text — the UNSCII font stack (2026-07-14)​

The text stack renders a bitmap pixel font baked to an atlas at boot — no font file is loaded at runtime, no platform font is measured, so the bake is byte-identical on every machine.

  • Source: UNSCII by Viznut — public domain. The .hex sources are vendored at engine/ui/vendor/ and converted ONCE into committed TypeScript glyph tables by tools/hex-to-glyphs.ts.
    • ⚠️ Do not vendor unscii-16-full.* — it is Unifont-derived and GPL. The base unscii-8 / unscii-16 files used here are outside that carve-out. See vendor/LICENSE.md.
  • Two sizes: BODY_FONT (unscii-8, an 8×8 cell — the default) and DISPLAY_FONT (unscii-16, 8×16). drawText/layoutText/measureText take an optional { font }.
  • Coverage is printable ASCII only (0x20–0x7e). Anything outside it renders as the ? fallback box — so no emoji, no ✕, no · in an in-canvas label. Use ASCII (X, -).
  • Glyphs are white/alpha masks, tinted by the caller. No colour ever enters the font path (the repo-wide palette guard forbids a hex literal here anyway).

This replaced a hand-coded 5×7 ASCII font that read as a debug font. The old font was 5px wide; UNSCII is 8px — see the reflow trap below, which is the whole story of that migration.

Icons — palette-agnostic shade-ramp masks​

Icons live in engine/ui/src/icon/: 34 glyphs at 16×16 covering Citadel's build bar (22 buildings + 5 tools) and goods strip (7 goods).

  • An icon stores SHADE INDICES, never colours (./1/2/3 = transparent/dark/mid/light). The consumer supplies a 3-colour ramp from its own palette at draw time. That is what lets ONE icon set render Apollo in Citadel and EDG32 in Farm without the engine knowing either palette.
  • Tinting mechanism: the renderer's textured-quad path takes exactly ONE colour per quad (no per-pixel tint exists in either backend). So each icon bakes to three pixel-disjoint 1-bit masks (one per shade) and draws as three stacked tinted quads. Disjoint ⇒ draw order is irrelevant, and no renderer change was needed.
  • The bake is pure + deterministic; a malformed recipe throws at import, not at draw.

The authoring rule (do not skip — this is the expensive lesson)​

Never author or edit an icon without looking at it:

npx tsx engine/ui/tools/icon-sheet.ts [nameFilter]

Citadel's building art was authored blind as ASCII pixel recipes, shipped unreadable, and had to be rebuilt from scratch as 3D meshes (see citadel-rendering.md). The first icon pass repeated it exactly: authored blind at 12×12, the "wheat" glyph rendered as mush and the "hammer" as a slab on a stick. Rendering them and looking is the loop; 16×16 exists because 12×12 demonstrably could not carry a readable silhouette and two shade bands for grain/flour/bread.

The reflow trap (read before changing ANY text metric)​

Changing the font changes every layout that consumed it. The 5×7 → UNSCII migration surfaced four bugs, and not one was caught by a unit test — every one needed a browser. They share a shape: something was positioned by a constant or a guess instead of by the laid-out rect.

  1. Fixed pixel widths sized to the old font. Farm's hotbar/inventory slots, tooltip wrap width, observer/slate/event-feed column widths all had constants tuned to a ~6px advance. All had to grow.

  2. A magic placement fraction. Farm's DOM seed <input> was positioned at panel.height * 0.52 — "just below the midpoint". The panel got taller, and the input collided with the Randomize button. Fixed by having the canvas row reserve an empty slot and positioning the input onto that node's rect.

  3. A container smaller than its own padding. The slate's stock-bar track is 5px tall, but containers default to the theme padding (6px) — so the bar's fill was laid out at track.y + 6, i.e. entirely below its own track, printing on the caption beneath it. Any container shorter than the theme padding needs an explicit padding: 0.

  4. A node that reserved a text line where a sprite gets drawn. Farm's hotbar drew a 26px item sprite over an empty label("") — one text line tall — so the art spilled onto the item's own caption. A node that a sprite is painted over must reserve the sprite's box.

  5. A multi-line label/button measured as one giant line. layout.ts textSize() once measured WIDTH with measureText (which counts \n as a glyph — the whole string as a single line) while measuring HEIGHT with layoutText. So an N-line label/button (e.g. a 6-line observer farmer row, or the wrapped weather forecast) measured ~N× too wide, and align:"stretch" dragged its whole column wider (the "Farmers panel exceeds width" report — the right column probed at 485px vs a ~374px fix). Fixed 2026-07-23: width now uses layoutText(text).width (the widest resulting line). Lesson: any node whose intrinsic size comes from text with \n must measure per-line, not with measureText (which is single-line by contract — see its doc).

Labels do not wrap unless you ask them to. label(text, { maxWidth }) wraps; without it a label is one unwrapped line that will run straight off a fixed-width panel. Any label carrying dynamic, sim-authored text inside a pinned-width panel needs maxWidth — OR pre-wrap/pre-truncate the string yourself with explicit \n (what the observer/event-feed rows do), which now measures correctly.

Pointer gestures that end off-canvas — cancelPointer()​

Every host listens for pointer events on the canvas. A press released outside it therefore never produces a pointerUp — and pointerUp was the only thing that cleared the dispatcher's active node and restored the pressed leaf's resting state. The widget stayed rendering as pressed for the rest of the session. blur() does not help (it moves focus, not press state), and pointerMove deliberately refuses to disturb the active node.

dispatcher.cancelPointer() abandons an in-flight press without activating anything. Call it from a window-level mouseup whose target is outside the canvas, and from blur — the two ways a gesture can end where the canvas cannot see it. It is idempotent.

  • A cancel is not a click: onActivate / toggle never fire.
  • The node returns to "normal", never "hover" — the pointer is not over it.
  • A drag in flight still gets its "end" event, carrying cancelled: true, reported at the press origin (where the pointer actually went is unknowable by definition). A handler that commits a value on "end" should check that flag.

Four games, four answers — converged 2026-09-19 (sweep-03). The divergence was the real lesson; the end state is:

gameapproach
Hollowcanvas.setPointerCapture(e.pointerId) on pointerdown (render3d/camera-input.ts) — the browser routes the release back to the canvas wherever it lands. Never was vulnerable.
Farmwindow mouseup/blur → cancelPointer() on every registered root (ui/canvas/ui-host.ts)
Citadelthe same, across all seven canvas UI roots (main/input.ts)
MateQuestthe same (main.ts) — fixed first, 2026-09-19, and the shape the others converged on

Farm and Citadel previously replayed the outside release as a real pointerUp(x, y, btn) at whatever coordinates the outside event mapped to — or, on blur, which carries no coordinates at all, at a remembered last-pointer-position. cancelPointer() needs no coordinates, which is why it deletes that bookkeeping.

Two host-level flags survive the convergence and must not be "tidied" away. uiPressActive decides whether the capture-phase handlers should stopImmediatePropagation() to block the world during a live UI gesture; uiGestureWasUI suppresses the canvas click that fires on the common ancestor of the mousedown/mouseup targets after a UI-owned press. The dispatcher has no notion of "should the host block the world" or "a click is about to fire" — both are DOM-event concerns owned by the host, not press state owned by the dispatcher.

Pointer capture was considered for Farm and Citadel and rejected (sweep-03), so do not re-propose it without new information. Hollow's capture is one narrow, single-purpose 3D-camera listener. Citadel's input.ts interleaves seven named UI dispatchers with right-button camera pan and road/wall placement drag, all keyed off e.button and clientX/Y; migrating means a mouse-event → pointer-event rewrite across all of it, and capture changes button semantics — a captured element keeps receiving events for that pointer id regardless of which button is down. For a new pointer path, still prefer capture; cancelPointer() is for the mouse-event paths that already exist.

Accessibility​

An icon-only button still passes its text label as the accessible name — the a11y mirror (src/a11y/mirror.ts) always mirrors text, never icons. Do not "optimise away" a button's label because the icon replaced it visually.

Custom-draw escape hatch (all raw-draw folded into the tree)​

custom(draw, layout) (src/widget/node.ts) is a layout-participating, non-interactive leaf whose draw(surface, rect, alpha) runs during renderTree in tree order under inherited opacity — the escape hatch for raw-quad/sprite draws that have no widget kind. Paired with LayoutProps.overlay (an out-of-flow child that fills its parent's inner box without shifting siblings) it also folds on-top passes into a panel's subtree. As of 2026-07-23 all six one-time raw-draw sites are folded: wealth-graph, and via overlay nodes slate-billboard/hotbar/inventory; plus pip-farm-marker (Farm, createPipFarmMarker() — draws absolute screen-space, rect vestigial) and Citadel minimap (node()/setFrame() — draws at its laid-out rect origin; clicks stay separate via trySeek, since a custom node is non-interactive). There is no longer any bespoke drawX(surface, …) pass beside renderTree in either render loop.

Immediate mode (optional, 2026-11-03)​

createImmediateUi() (immediate/) lets a screen describe itself every frame (if (ui.button("buy", "Buy")) …) over the same retained nodes, layout, renderer and a11y mirror. Nodes are cached per key, so focus, presses and mirror ids survive frames. A key unseen for evictAfter frames (default 60) is dropped, and clicks arrive one frame late. No screen uses it today. Retained is the default (decisions.md → UI — retained by default, immediate mode optional). The cost and the comparison are measured on mathquest-ui.md.

Known gap — no grid/tabular layout, and that is still the right call​

villager-panel.ts was audited + fixed (width: 200→288) for the wider font on 2026-07-22. No known text-metric gaps remain.

The toolkit is flexbox-lite: row/column/grow, no grid and no constraint solver. Adding a grid was the last open item of the 2026-07-22 improvements backlog, which was closed on 2026-09-19 with it deliberately unbuilt. Its own rule was "add a grid layout prop when a panel needs it, not before", and re-checked against the code, none does.

The nearest thing to a table is Farm's relationship matrix, and it is fine: relationship-matrix.ts builds a 21×21 trust grid as a column box of row boxes of label cells — ordinary primitives, no by-hand pixel math. Columns line up because every cell is a single initial in a fixed-width bitmap font, so every cell measures the same.

That last sentence is the trigger condition. The alignment is a property of the content, not of the layout engine. Build the grid prop when a panel needs columns to align across rows whose cells have different intrinsic widths — a real table with varying-length values. At that point independent row boxes stop working and no amount of gap tuning will save it. Until then a grid prop would be a speculative abstraction with one hypothetical consumer, which is what the backlog told us not to build.