Spatial UI
Menus, HUDs, labels and settings panels that live in the world. UI is built from five widget entities — panel, text, button, toggle, slider — each a real entity with its own transform: move it with the gizmo, parent it like anything else, save it with the scene.
Widgets render on both XR headsets (point with the ray or gaze, click with trigger or pinch) and flat 3D experiences (hover and click with the mouse). Hover and press feedback is built in — you never script your own highlight. Name a theme on a menu's panel and it is styled as a whole.
The one sizing rule
Widget size is authored in metres on the component — never with transform scale. The widget's face is a texture rasterised for the authored size; scaling the entity stretches those texels into blur. To make a panel bigger, raise its width/height fields and it re-renders crisply.
Building a menu
- Create a UI Panel — the backdrop. A comfortable read is 1–2 m from the player, centred around eye height (y ≈ 1.2–1.6).
- Create Text, Button, Toggle, Slider entities and parent them under the panel. Place them with local transforms. Children always draw over their parent, from any angle, so local z is only for depth you want to see.
- Give each interactive widget an
actionId(empty means "use the entity's name"). - Attach one Behaviour to the panel. UI events fire on the widget's own entity first, then bubble up the parent chain — so the panel script hears every child widget and can switch on
actionId:
import { Behaviour, type UiInteractionEvent } from "@relu-interactives/spatial-ecs";
export class MenuController extends Behaviour {
onUiPress(event: UiInteractionEvent) {
switch (event.actionId) {
case "start-game":
// A button under this panel was clicked.
break;
case "quit":
break;
}
}
onUiToggle(event: UiInteractionEvent) {
if (event.actionId === "music") {
const on = event.value === true;
console.log("music enabled:", on);
}
}
onUiChange(event: UiInteractionEvent) {
if (event.actionId === "volume" && typeof event.value === "number") {
console.log("volume:", event.value);
}
}
}Bubbling — not broadcast — is what keeps two copies of the same menu prefab independent: each panel script hears only its own children.
The widgets
| Widget | Component | What it is |
|---|---|---|
| Panel | UIPanelComponent | The flat backdrop. Rounded corners, border, translucency, follow mode. |
| Text | UITextComponent | Wrapped, aligned text. fontSize is metres of glyph height. |
| Button | UIButtonComponent | Pressable. Fires onUiPress on release. |
| Toggle | UIToggleComponent | On/off switch. Fires onUiToggle; value persists with the scene. |
| Slider | UISliderComponent | Draggable value in [min, max]. Fires onUiChange. |
Images need no widget: parent an ordinary image entity under the panel. A transparent mesh under a widget draws with it, in front of that widget and behind the widget's own children.
Press semantics
A click is press, then release while still pointing at the same widget — sliding off before releasing cancels, exactly like every platform's buttons. While a press or slider drag is held, that hand cannot accidentally teleport (suppressed the same way grabbing suppresses it).
onUiChange streams while a slider is dragged (only on real value changes) and always fires once more with the final value on release.
Text sizing
fontSize is how tall the glyphs stand in the world, in metres — 0.035 reads like comfortable body text at arm's length, independent of the panel's texture density. Lines wrap automatically to the component's width; overflow past height is clamped with an ellipsis.
Themes
The quickest way to a finished look is a theme: name one on a panel and every widget under it is styled to match, with hover and press looks that move. Themes give the widgets their colours, type, corners, shadows and motion; you still choose sizes and positions.
import {
UIButtonComponent,
UIPanelComponent,
UITextComponent,
} from "@relu-interactives/spatial-ecs/components";
const menu = new UIPanelComponent({ width: 1.1, height: 0.8, theme: "holo" });
const title = new UITextComponent({ text: "Main menu", variant: "title", fontSize: 0.06 });
const play = new UIButtonComponent({ label: "Play", icon: "play-filled", variant: "primary" });| Theme | Look | Good for |
|---|---|---|
holo | Deep navy glass, bright top edge, orange main action, cyan details | Sports, arenas, VR games |
glass | Smoky translucent glass, white type, pills that rise toward you | Calm, premium menus over any scene |
minimal | White cards, near-black type, one blue accent | Training, education, showrooms |
neon | Night purple on a faint grid, magenta and cyan glow, condensed caps | Arcades, rhythm games, racers |
scifi | Cut corners, hairline cyan frames, scanlines, amber callouts, mono readouts | Shooters, space sims, cockpits |
fantasy | Grained wood framed in gold, parchment serif, bevelled corners | RPGs, card games, mythic worlds |
paper | Cream paper with grain, ink-brown serif, pen-line borders, red ink | Story games, puzzles, museums |
pixel | Square corners, chunky outlines, hard drop shadows, mono caps | Platformers, roguelikes, 8- and 16-bit |
cartoon | White bubbly cards, thick ink outlines, candy buttons that squash | Casual, party and kids' games |
terminal | Green phosphor on black glass, scanlines, outline buttons that light up | Hacking games, escape rooms, labs |
The nearest panel with a theme wins, so a whole menu takes its theme from the panel at its top. To see every theme side by side, run pnpm example:ui-themes in this repository and open http://127.0.0.1:4174 (?only=neon shows one).
Variants
Under a theme, each widget's variant says what part it plays.
| Widget | Variants |
|---|---|
| Panel | surface (a menu's body; the default at the top of a tree), card (the default inside another widget), inset (a sunken bar or well), hud (a small translucent plate), clear |
| Text | display, title, heading, body (default), caption, label (small, often caps), value (a big number), badge (a small pill) |
| Button | primary (the one main action), secondary (default), ghost, danger, tile (a large choice card), tab, icon (round) |
Toggles and sliders take the theme's colours. Text keeps its fontSize: a theme picks the face, weight and colour, never the size.
Give each screen one primary button. A row of choices is tile buttons, a row of sections is tab buttons in an inset panel, and the button that's chosen has selected: true.
States and motion
A themed button has its own look for hover, pressed, selected and disabled, and rises toward the viewer while pointed at. Set selected: true on the current tab or the picked card, and disabled: true on a button that can't be used yet: a disabled button takes no hover or press and fires nothing.
Hover and press never redraw anything: each state is drawn once and faded in over the face, and the lift and scale move the face, not the widget's hit area, so a rising button never slips out from under the ray.
Any button can have states without a theme, through its style:
import { UIButtonComponent } from "@relu-interactives/spatial-ecs/components";
const button = new UIButtonComponent({
label: "Start",
style: {
fill: { kind: "solid", color: "#1f6feb" },
radius: 1,
hover: { fill: { kind: "solid", color: "#388bfd" } },
pressed: { fill: { kind: "solid", color: "#1158c7" } },
motion: { lift: 0.008, scale: 1.04, pressScale: 0.97 },
},
});motion.lift is metres toward the viewer, scale the size while pointed at, pressScale while held, speed how quickly it gets there.
Changing a theme
Three ways, smallest first:
- Tokens. A theme's colours and fonts are tokens, and the panel's own
tokenswin over them.tokens: { accent: "#3ddc84" }recoloursholo's main actions, highlights and toggles at once. Every theme namesground,surface,surface2,card,line,ink,muted,faint,accent,accentHi,accentInk(text on the accent),accent2,danger,good,displayFamilyandtextFamily. SetfontDisplayorfontTextto a font file in the project to brand a theme's titles or body text. - A widget's
style. It wins over the theme field by field. A colour changed by hand (a button'sbackgroundColor, a text'scolor) wins too. - A theme file. A
.jsonfile in the project, named as the panel's theme:theme: "assets/ui/forest.json". Itextendsa built-in theme and changes any part of it, per variant:
{
"extends": "paper",
"label": "Forest journal",
"tokens": { "accent": "#3a7d44", "accentHi": "#4f9a5a", "surface": "#eef0dc" },
"panel": { "surface": { "corners": "cut", "radius": 0.02 } },
"button": {
"primary": { "radius": 1, "hover": { "shadows": [] } }
},
"text": { "title": { "text": { "family": "condensed", "weight": 800 } } },
"toggle": { "knob": "#fffaf0" }
}A theme file that can't be read leaves its panel unthemed and says why in the console.
Token colours at an opacity
Anywhere a token is used, [email protected] is its colour at 40% opacity, so a theme can draw a faint line or glow from the same accent: "[email protected]". A token may also hold another token: "line": "[email protected]".
Icons
A button's icon takes a built-in icon name, with no file to add:
import { UIButtonComponent } from "@relu-interactives/spatial-ecs/components";
const settings = new UIButtonComponent({ label: "", icon: "settings", variant: "icon" });
const solo = new UIButtonComponent({ label: "Solo", icon: "user", iconPosition: "top", variant: "tile" });With an empty label the icon fills the button. iconPosition is left (default), right, or top (above the label, for tiles). Icons take the label's colour.
There are about 200, from Tabler Icons (MIT), including play, pause, stop, next, replay, back, close, check, plus, minus, home, menu, settings, sliders, volume, mute, music, mic, mic-off, headset, lock, unlock, info, help, warning, user, users, friends, crown, chat, heart, like, trophy, medal, award, star, flag, target, flame, bolt, shield, sword, bow, bomb, skull, ghost, potion, backpack, chest, gift, coin, coins, gem, cart, shop, map, compass, pin, world, rocket, sparkles, wand, puzzle, dice, cards, ball, clock, timer, calendar, chart, gauge, level, book, quest, gamepad, keyboard, vr, camera and share. Solid versions end in -filled: play-filled, heart-filled, star-filled, trophy-filled, shield-filled, bolt-filled and more. UI_ICON_NAMES lists them all. An image or SVG file in the project works as before.
Styling
Every widget takes a style, which wins over its plain colour fields. Leave it out and the widget draws as it always has.
import { UIPanelComponent } from "@relu-interactives/spatial-ecs/components";
const panel = new UIPanelComponent({
width: 0.9,
height: 0.6,
tokens: { plate: "#1b2432", plateDeep: "#121824" },
style: {
fill: {
kind: "linear",
angle: 160,
stops: [
{ at: 0, color: "$plate" },
{ at: 1, color: "$plateDeep" },
],
},
radius: 0.036,
shadows: [{ x: 0, y: -0.02, blur: 0.06, color: "#00000099" }],
edge: { width: 0.0035, color: "#ffffff30" },
},
});| Field | What it does |
|---|---|
fill | solid, linear (angle in degrees, reads like CSS), radial, or image (cover, contain, fill, with an optional tint) |
border | Width in metres and a paint |
radius | One radius, or four: top-left, top-right, bottom-right, bottom-left |
shadows | Drop shadows, in metres, outside the shape only. They don't change what a pointer can hit |
edge | A thin highlight along the top inner edge |
opacity | 0–1. Multiplies down the widget tree, so fading a panel fades its menu, and a fade never redraws anything |
corners | round (default) or cut, which bevels each corner by its radius |
pattern | A texture over the fill, inside the shape: scanlines, grid, dots, stripes (with an angle) or noise, in a color, with spacing and width in metres |
text | font, family, weight, tracking, transform, paint, maxLines, shadow |
hover, pressed, selected, disabled | What changes in that state (buttons). See States and motion |
motion | lift, scale, pressScale, speed (buttons) |
Tokens
tokens on a panel name values for every widget under it, as $name in any colour or file field, the nearest panel winning. A theme therefore travels with a prefab, and one edit restyles a whole menu, redrawing only the widgets that use that token.
Fonts and images
style.text.font takes a font file in the project, and fill with kind: "image" or a button's icon takes an image or SVG. style.text.family names a font every device has, by feel: sans, serif, mono, rounded or condensed (or any CSS family list). It draws while font loads, and alone when there is no font. Files load on demand and the widget redraws when they arrive. Until then text uses a system face.
Variants
- Toggle
variant:switch(default),checkbox,radio. - Slider
variant:slider(default),progress,ring. The last two only show a value.readOnlydoes the same for a plain slider, andstepsnaps a dragged value.
Follow modes
follow: "world"(default) — the panel stays where you put it.follow: "billboard"— the panel yaw-rotates to face the player every frame at runtime (in the editor it holds still so you can work on it).
For a wrist menu, don't billboard — parent the panel under an XR Interactor's Left or Right slot entity (the same slots used for custom hand meshes). It then rides the hand like a watch.
Pause menus
UI keeps working while the game is paused, in a headset and with the mouse: widgets hover and press, and onUiPress fires as usual. See Pausing the Game.
Reading and driving widgets from scripts
Widget state is ordinary component data:
import { Behaviour } from "@relu-interactives/spatial-ecs";
import {
UISliderComponent,
UITextComponent,
} from "@relu-interactives/spatial-ecs/components";
export class ScoreHud extends Behaviour {
private score = 0;
addPoint() {
this.score += 1;
// This entity is the HUD text; editing the component re-renders it.
const text = this.world.getComponent(this.entityId, UITextComponent);
if (text) text.text = `Score: ${this.score}`;
}
readVolume(sliderEntityId: number): number {
const slider = this.world.getComponent(sliderEntityId, UISliderComponent);
return slider ? slider.value : 0;
}
}Style/text edits re-render the widget's texture on the next frame. Toggle and slider value are authored state — what you set in the editor is the state the experience starts with.
Event payload
Every UI hook receives the same shape:
import { Behaviour, type UiInteractionEvent } from "@relu-interactives/spatial-ecs";
export class Inspect extends Behaviour {
onUiPress(event: UiInteractionEvent) {
event.targetEntityId; // the widget that was activated
event.actionId; // its actionId, or its entity name
event.input; // the XR input source, or null for mouse clicks
event.value; // boolean (toggle) / number (slider); absent for presses
}
onUiHoverStart(event: UiInteractionEvent) {
// A ray or the mouse moved onto the widget. Two hands on one widget count
// as one hover. Vision Pro has no hover before a pinch.
console.log("hovering", event.targetEntityId);
}
}Renderers: uikit and canvas
Spatial UI has two renderers, picked per widget tree by the top panel's renderer:
renderer | Draws the tree with |
|---|---|
absent / "auto" | uikit in VR and mixed-reality projects (a scene with an XR Rig), canvas elsewhere |
"uikit" | @pmndrs/uikit: instanced panels and MSDF text, a few draw calls per menu |
"canvas" | one canvas texture and quad per widget: every style feature |
On a Quest 3 at 90 Hz, 200 widgets drew 672 calls and ran at about 38 fps on canvas; on uikit they drew 22 and held 90 fps.
uikit draws some looks approximately, in its own instanced panels (no extra draw calls):
- Shadows: three stacked translucent rounded layers, widest and faintest first, offset like the shadow.
- Edge highlights: a thin rim just inside the shape in the edge colour.
- Gradients: a vertical or horizontal one (within 15°) as 8 bands with matching rounded ends; a diagonal or radial one, or one on a shape whose corners are taller than a band (a pill button), as its middle colour. Gradient text uses its middle colour.
- Text shadows and glows: a copy of the text behind it, offset, in the shadow's colour (without the blur).
- Text that overflows is fitted as the canvas fits it: wrapped to the box's width, cut to the lines its height holds, the last ending in "…" ("..." when the font has no "…"), measured with the font atlas's own glyph widths. Nothing spills out of its box.
A tree that uses any of these stays on canvas, whatever renderer says: image fills, patterns, cut corners, checkbox toggles, ring sliders, characters the tree's font doesn't have, or a WebGPU renderer. Icons draw on uikit as a small texture per icon and colour (one draw call each). Of the built-in themes, holo, glass, minimal, pixel and cartoon draw on uikit; neon, scifi, fantasy, paper and terminal use patterns or cut corners and stay on canvas. Effects nobody can see (a transparent shadow or pattern, a zero-width edge) don't count. Ask why a tree is on canvas:
world.getUIPanelSystem()?.rendererOf(world, panelEntity);
// → { renderer: "canvas", reason: "shadows" }The same object is on the tree root's scene object as userData.__uiRenderer, for the editor.
Fonts on uikit: a project font file draws from the name.msdf.json atlas the editor writes beside it (fonts added before this release are converted when the project opens). Generic families use bundled faces: sans is Inter, serif Merriweather, mono Fira Code, rounded Nunito and condensed Roboto. The bundled faces cover ASCII only.
What the uikit renderer does for you:
- Live texts. uikit lays out a whole tree when any text changes. A text that changes three times within 90 frames (a score, a timer) moves to a small uikit root of its own, so ticking it never re-lays out its menu. It goes back after 300 frames unchanged. At most 24 at once.
- Layout budget. Tree layouts after a change run within
getUIPanelSystem().uikit.layoutBudgetMs(2 ms) a frame, the rest on the next frames; one always goes through. Colour, hover and value changes never wait. - Culling. uikit never frustum-culls its meshes, so trees out of view are hidden (
uikit.cull). Not in the editor. - Hidden and out-of-view trees cost nothing a frame: they catch up when they show.
- Values without layout. Slider fills scale and knobs slide by transform; hover lift and scale are transforms too.
Widgets keep their entities, transforms and invisible hit quads on uikit, so input, scripts, onUiPress and the editor behave the same.
Performance notes
- A widget's face redraws only when its style or content changes — an idle menu costs nothing per frame.
- Slider drags and toggle flips move geometry (the knob and fill quads), not pixels, so dragging never re-renders the texture.
pixelDensity(every widget) trades texture memory for sharpness: the default 1024 px/m is crisp at arm's length; raise it only for widgets the player inspects up close. It's squared: 1536 draws and uploads 2.25x the pixels of 1024, on every redraw.- A widget whose component hasn't changed since last frame is skipped before any style is worked out (0.22.0). On a Quest 3 that took 200 widgets from about 1.5 ms a frame to about 0.35 ms.
- Redraws are spread over frames: at most
maxRedrawsPerFrame(12) orredrawBudgetMs(4 ms) of them a frame, the rest on the next frames, so a screen change that retexts 60 widgets is no longer one long frame. Not in the editor, where an edit shows at once. - Set a widget's text only when its value changes, and update a timer or score a few times a second, not every frame: each change is a redraw and a texture upload.
- Disable menus that aren't showing: a disabled widget isn't drawn.
Draw order and blending
Widgets draw in a fixed order: within one UI tree, parents before children; between trees, back to front by plane distance. Widgets on one plane that are not parented to each other draw large before small, so parent them when the order matters.
Text and controls show from the front only. A panel keeps its back.
On a WebGPU project a translucent widget over a bright background looks a little duller than on WebGL, because WebGPU blends in linear light. Over dark backgrounds the two match. Opaque widgets are identical on both.

