# player-setup
Wiring a player into a scene the way a shared world requires: one
PlayerPrototype describing what each joining user becomes, instantiated per
peer by the engine, driven entirely through `scene.player`.
A subskill of `scenes` — open it with `agent_agent_skill { name = "scenes/player-setup" }`.
# validating
The whole job of checking a scene is right, in the order the steps pay off:
ask the engine what is already broken, read the data back, render the pass
that answers each question, judge motion over time and gameplay in play, look
at what a pixel costs, show the overlays for things with no appearance of
their own, run the world's tests, and do it twice.
Carries the rule a lit frame cannot give you — take the z-fighting pass over
every scene, because two surfaces at one depth look correct in every still and
shimmer the moment anything moves.
A subskill of `scenes` — open it with
`agent_skill { name = "scenes/validating" }`.
# agentSkill
A skill packages what an agent needs to do one job well: the instructions,
the assets and toolboxes the job runs through, and — for jobs with distinct
branches — subskills that go deeper.
Skills advertise themselves. Every registered skill's name and one-line
description rides the agent's tool responses, so an agent discovers what this
world knows how to do without being told to look. Invoking one returns the
instructions plus the exact identities and tool names the job needs.
## Shape
```
<name>.agentSkill/
skill.yaml # the manifest: description, when, checks, dependencies, order
instructions.md # the prose an agent receives on invoke
README.md # what this skill is, for a human reading the tree
.metadata # tags
<sub>.agentSkill/ # optional subskills, reachable as <name>/<sub>
```
## The manifest
```yaml
$schema: zero/agent-skill/v1
description: Making a character a person can actually play.
when: >
Reach for this when the player should look like something else, or when
you are about to build a camera and a body and wire them together by hand.
checks:
- check: Holding a movement key in play moves the body across the ground.
observe: Read its position before and after holding the key; the numbers differ.
- check: The body animates while it moves.
observe: A time-sampled collage from a camera outside the player, while the key is held.
dependencies:
- "@builtin::tools.scene"
- "@builtin::tools.scene.player"
- "@builtin::components.PlayerPrototype"
- "@builtin::docs.core.multiplayer"
order: [spawn-points, camera-rig]
```
`description` is the line the roster carries, and the whole basis on which a
skill is chosen. Name the job the skill makes a reader competent at, in the
outcome they are after — "getting a scene's player and view right", "making
content the engine will load". A reader scanning the roster is matching it
against the job in front of them, so the closer it reads to their own
sentence about that job, the sooner they open it.
`when` is the longer trigger — the situations that should send a reader here,
in the words they would use for their own task.
`checks` is what the reader is answerable for at the end, and it leads the
rendered skill, ahead of the procedure. Each entry pairs a **condition that
must hold** with **where it is seen**, and both halves are required — a
condition alone is satisfied by any glance, and the wrong vantage is how a
job passes while every one of its faults sits outside the frame. Write them
as observations someone else could repeat and disagree with: a number that
changed, a thing visible in a named shot, a count that came back as one.
A skill publishes only once it carries at least one.
`stages` models a skill whose passes run in order, when the order is
load-bearing. Each stage is `{ name, detail?, checks? }`, and a check that
sits in a stage is answered after that pass has run — which is the difference
between a criterion that means something and one that misleads. A skill with
no meaningful order leaves `stages` out and lists its checks flat; a skill
that has one may do both, and the flat checks then read as the final gate.
`verdicts` names the fixed set of outcomes a reader reports — at the end of
each stage when the skill has stages, and once at the end when it does not.
Each is `{ verdict, means }`: the word, and what reporting it asserts. Both
halves are required for the reason both halves of a check are. A verdict is a
check one level up, deciding a whole pass rather than one condition, and a
bare `refine` is a label each reader fills in privately — so two runs report
the same word about different states and nothing downstream can tell them
apart. Saying what it means settles the boundary in the skill instead of in
whoever happens to be reading it.
A check marked `perRun: true` is one whose content is written for the job at
hand: the manifest can say *keep a list of every feature this object must
have and answer against it*, but not what is on that list, because that is
per run. It renders with that instruction attached.
```yaml
verdicts:
- verdict: continue
means: Every check in the stage held, and the next stage can build on it.
- verdict: refine
means: A check failed on something this stage can still fix. Run it again.
- verdict: stop
means: A check failed on something an earlier stage decided. Go back to it.
stages:
- name: blockout
detail: Mass and proportion only.
checks:
- check: Every part on the identity list has a stand-in at roughly the right size.
observe: A capture beside the reference, at the same angle.
perRun: true
- name: material
checks:
- check: Metal reads as metal and cloth as cloth.
observe: The metallic and roughness passes, after the lighting stage has run.
```
`dependencies` is one flat list of asset **identities**: a toolbox, a single
tool, a guide, a component, a module, another skill. Each entry is resolved
when the skill is opened and reported with what it turned out to be, so a
skill never declares "this one is a toolbox" — the asset says so, and the
reader groups by that.
Identities are what make a skill portable. They pin like any other reference,
so installing a skill into another world brings the toolboxes and guides it
runs through along with it. A bare name (`scene`) or a guide path
(`core/multiplayer`) resolves to nothing and is refused before publish.
A toolbox entry lists the tools it carries, and a tool entry carries its own
signature, so the instructions never restate a call contract that can drift.
An identity this world lacks is reported as missing rather than dropped.
Write instructions that name the toolboxes and tools a job runs through, and
leave the call form to the reader — an agent may be holding the MCP tool
surface, the shell, or Luau, and the signatures are listed for it either way.
## Subskills
A `<sub>.agentSkill/` folder nested inside a skill is a subskill. It has the
same shape as its parent and is invoked as `parent/sub`.
Subskills are reachable only through their parent: they are absent from the
roster and from `skills.list`, and appear in the parent's invoke result. A
skill can therefore carry a dozen narrow procedures while costing the roster
one line.
`order` in the manifest names the subskills that lead. Any subskill it omits
still appears, sorted by name, after the ordered ones — so adding a subskill
folder is the only step needed to publish it.
## Publishing one
Make a skill and it is live: it joins the roster agents read and it opens by
name from the moment it exists. Edit its description and that is the line
agents see next.
A skill lives anywhere under `/zero/source/`. `asset.create` hands you a
valid one to fill in:
```luau
asset.create("agentSkill", "waveSpawning", { folder = "skills" })
```
A skill's scope — `builtin`, `library`, or `world` — comes from where it
lives rather than from anything it declares, so a world's own skill always
reads as the world's.
## Opening one
```
agent_skill {} -- the roster
agent_skill { name = "scenes" } -- one skill's instructions + deps
agent_skill { name = "scenes/player-setup" } -- a subskill
```
The same three through the toolbox — `skills.list`, `skills.invoke` — and
from Luau via `tools.use("skills", "invoke", "scenes")`. `asset.inspect` on a
skill ref returns the structured record all of them render.
Skills authored in a world are the world's own, and are labelled as world
content wherever they surface beside built-in ones.
## In the Inspector
Skill: what the skill is for and when it applies, how many checks and verdicts it declares, its stages, a link to each asset it depends on (and a problem for each that does not resolve), its subskills, and **Open** for instructions.md.
# PlayerPrototype
Marks the root of a player-setup subtree — the entity and children that define what a joining user becomes (avatar slot, spawn behaviour, controller). On awake it flips the entity to PrototypeOnly participation, so the prototype lives in the editor and drives spawning without being saved as a world entity itself; `kind` and `label` describe it for authoring surfaces. In edit mode it draws a cyan silhouette outline so the prototype root is easy to pick out, and surfaces its own setup-validation messages (missing camera, avatar slot, or wrong participation) on the component's error channel.
Location: `src/lua/lib/components/PlayerPrototype.component`
# scenes guide
Reference docs surfaced through `guides { path: "..." }` and `man scenes`.
The content lives in `guide.md`; this README is just the asset summary.
# camera
Author and manage the cameras in a scene: create one, list every camera, read its full parameters, change them, aim it, frame a subject, or make it the primary camera. A physical camera on the machine (a webcam, a phone camera) is `cameraInput`, covered by the `topics/camera-input` guide.
## Create & inspect
- **create** — spawn a camera entity at a position, with any starting parameters in one call: fov, near/far, priority, render layers, a follow target, a behavior, a `lookAt`, and `target` (render-to-texture — `true` or `{ width, height, name }` renders the camera offscreen instead of to the viewport). Returns the new camera's full parameter record.
- **list** — every camera in the scene, enumerated from the live ECS so a just-spawned, hidden, or runtime camera is never missed, sorted by descending priority, each row marking whether it is the on-screen (`active`) camera, whether it is the `player` camera (the one the PlayerPrototype uses), and its main/editor role.
- **get** — the full parameter record for one camera (position, rotation, fov, near, far, priority, render layers, debug channel, render target, behavior, follow). Defaults to the active/main camera when you name none.
## Modify
- **set** — change any of these camera parameters in one call: `fov`, `near`, `far`, `priority`, `debugPass` (the diagnostic view this camera renders, by name), `debugChannel` (the same as a raw numeric channel), `renderLayers` (the layer-name spec, e.g. `"all !ui"`), `behavior` (a `cameraBehavior`-tagged component), and `follow` (the entity the behavior tracks). Pass no camera to modify the active one. A camera's render target is set when it is created (`create` with `opts.target`).
- **lookAt** — aim a camera at a world position or at another entity.
- **frame** — position and aim a camera to frame a target entity from a distance and angle in one step.
- **bindToPlayer** — make the joining player use a camera in play by binding it to the scene's PlayerPrototype: it re-parents the camera into the prototype (so it is cloned with the player) and sets the prototype's `camera` role to it. Pair it with a static behavior (`set { behavior = "@builtin::controller.menu" }`) for a fixed PS1-style camera the player moves within, or a follow behavior (`orbital_follow`, `third_person_follow`, `first_person`, …) for a tracking one. A player-less scene has no prototype — there the rendering camera is simply the highest-priority one, ordered with `set { priority = N }`.
## Related surfaces
- Capturing an image from a specific camera is the `capture` toolbox (`capture` with a camera, or `oneshot`) — it renders any camera's authored pose offscreen without changing what is on screen.
- Putting geometry ON a render layer is the `renderLayer` toolbox (`renderLayer.set`); `renderLayer.camera` is the layer-system-side way to set a camera's include filter, the same field `camera.set { renderLayers = ... }` writes.
- The scene's primary camera is normally spawned for you from the scene's PlayerPrototype; `camera.create` adds additional cameras (a security view, a cutscene angle, a render-texture feed).
# capture
Render a screenshot of the scene from anywhere — an explicit position, a named camera station around an entity, a specific camera, or a mirror of the active viewport — and a grid of them in one image; or read back the frame the engine actually presented, exactly as the player saw it.
The picture of the machine's own camera (a webcam, a phone camera) is `cameraInput`, covered by the `topics/camera-input` guide; this toolbox photographs the scene.
Every source but `presented` and `window` (see [The presented frame](#the-presented-frame)) spawns an ephemeral offscreen camera, triggers one render, and returns the picture as an image value — returned from a tool, a probe or `execute`, it reaches you as a picture, with what the capture has to say about it (its size, the frame it is of, the cells of a grid) beside it. A PNG is written as well when you pass a `path`. The convenience wrappers render from a world-space position (with optional look-at), frame a target entity, mirror the active viewport camera including its layers, or render a specific camera by name from its exact authored pose and settings (`fromCamera`, with optional per-capture overrides that never touch the camera); they run as a background task that waits for the GPU readback and cleans up — which only works in play mode, since the task scheduler ticks there. The low-level oneshot spawns the camera, triggers one render, and returns the handles synchronously — the only path that works from edit mode, and the one the `capture` MCP tool is built on. A cleanup tool clears the capture output directory.
## Where a shot lands
A capture given a `path` writes the PNG there and says where those bytes
stand, beside the path it wrote: `durable` is true when the PNG is on the path
it names and the next session reads it back, and false when the play shadow
took it (live in this session and discarded on a guarded play-exit unless kept,
with `survivesRestart` saying whether a restart keeps it and `playShadow`
naming the routes that keep it) or when the path is in `/source/tmp/` scratch
(gone when the engine stops or restarts, with a `warning` opening `SCRATCH`).
Every capture carries it on the picture it returns as `durability`. Shooting
gameplay means shooting in play, which is exactly when a `/source` destination
is the shadow's, so this is the field that says whether a shot survives leaving
play — `vfs.promotePlayShadow(path)` keeps it with play still running.
## The presented frame
`source = "presented"` reads back the frame the engine presented to the
player instead of rendering one. Nothing is drawn for it: it is the frame the
viewport drew, copied out as it was finished, after the post chain, the
upscale, the display transform, the content UI and every post-scene pass, at
the size it was composed at. So it is the one capture whose temporal
antialiasing, motion blur, camera motion, auto exposure and render scale are
the real ones, and the source to verify any of them with. `source = "window"`
is the whole presented surface (the window, the browser canvas or the
headless framebuffer) with everything painted on the window: the editor's
chrome and every window-level UI pass. Where no Scene panel shows the
viewport, the two are the same image: the scene fills the window and the
editor's chrome is painted over it, and each such frame says so in its
`note` (a cell of a `presented` capture, a frame `renderer.presentedFrames`
returns) for as long as that chrome is on the window. Show the
Scene panel (the editor toolbox's `layout` tool) to read the game view alone.
`frames = n` (1-32) takes n presented frames, one every `interval` frames
(default 1: consecutive), at real gameplay speed, and lays them out as a grid
in the order they were presented. Each cell states what its frame was drawn
with: `frame` (the renderer's count, so consecutive frames carry consecutive
numbers), `rasterWidth` / `rasterHeight` (the size the scene rasterized at),
`compositeWidth` / `compositeHeight`, `renderScale` and `scaleMode`, `jitter`
(the projection's sub-pixel offset in raster pixels), `exposure` (what the
display transform multiplied the scene by) and `historyReset` (the viewport
camera's first frame, a cut, or a hand-over to another camera). A single frame
comes back at the size it was presented at; `width` / `height` resample it, or
size the sheet a grid is laid into.
A presented frame is drawn through the camera, layers, lens and chain that
drew the screen, so the options that aim, light or shape a rendered frame
(`camera`, `entity`, `position`, `viewpoint`, `fov`, `pass`, `renderLayers`,
`postProcessing`, `environment`, `mode = "collage"` and the collage axes) are
refused for it; aim the camera holding the viewport instead, or take an
offscreen capture. A source that renders refuses `frames` and `interval` the
same way, since they count presented frames. `deterministic` and `clearAir`
hold the clock and the air for the whole engine, so they reach the presented
frame too.
A diagnostic buffer of the viewport itself, under its real camera motion and
history, is read the same way: put the camera holding the viewport on that
pass (the camera toolbox's `set` with `debugPass = "motion_vectors"`) and take
`source = "presented"`. The viewport's velocity buffer is the frame's travel
against the frame before it, so a turning camera reads in it, where an
offscreen `pass = "motion_vectors"` holds the objects' own motion alone.
The `motion_vectors` picture is a visualization: each channel is the square
root of 100 times the stored displacement's size on its axis (R horizontal, G
vertical, B the length), the sign is dropped, and R reads 255 from
`width / 200` px of horizontal travel, G from `height / 200` px of vertical
travel (raster pixels). The rendering guide's "What the
`motion_vectors` picture encodes" states it in full.
The same frames, with their pixels as `TextureCpuHandle`s, come from
`renderer.presentedFrames({ scope = "viewport" | "window", frames, interval })`,
and `velocity = true` adds the viewport's velocity buffer from each frame as
numbers (`frame.velocity`, a `VelocityField`): each pixel's travel in pixels
per frame, x right and y down, signed and unclamped, read with
`field:at(x, y)`, `field:row(y)` and `field:region(rect)`.
## The feed
Every capture publishes the frame it made to `@builtin::tools.capture.feed`,
so a viewer can show the newest one without taking a shot of its own.
`Feed.latest()` is that frame: a `src` an image widget draws (the render
target's guid while the engine still holds it, the written path when the
capture produced a file), with the size, the source and the pass beside it.
`Feed.watch(fn)` calls `fn` as each new frame arrives. The editor's Capture
panel is built on it, and the `watch` layout puts that panel under the scene.
A viewer calls `Feed.shown()` to say it is drawing frames from the feed. From
then on the feed holds the newest capture's render target so the picture stays
up after the capture that made it is finished with it, and lets it go when a
later frame replaces it; `Feed.shown(false)` stops. With nobody drawing, a
capture's target is released the moment its capture is done, and nothing is
held.
## Viewpoints
A **viewpoint** names where the camera stands and which way is up in the image: `front`, `back`, `left`, `right`, `top`, `bottom`, `iso`. It replaces reverse-engineering a `{yaw, pitch}` pair, and names the seven stations that answer "is this built correctly".
`basis` says which axes the name is measured against, and it is **required** alongside a viewpoint when a subject is being framed:
- **`"local"`** — the subject's own axes. `front` is the side it faces however it is turned, and the frame is fitted to its own extents rather than to the world-axis box around them.
- **`"world"`** — the world axes. `front` is whatever faces world +Z.
For a crate turned 40 degrees those are different pictures, so the call says which one it wants. Framing a world position rather than an entity, both values mean the world axes and either is accepted.
## Passes
`pass` names **what** the frame holds, by name. `"final"` is the lit picture; a built-in diagnostic pass (`albedo`, `normal`, `depth`, `motion_vectors`, …) replaces the shaded image with the buffer behind it; and any capture **view** a render feature has published (`renderer.captureView.list()` enumerates them) is selectable by its own name. A name that is neither is refused against the list of what is registered.
The name carries two decisions: which channel the camera renders, and which render layers that channel is legible under. A diagnostic buffer is read flat, so the sky behind it and the post-process chain over it come off; a view that draws its own geometry declares the layers it needs and is rendered under them. Stating `renderLayers` answers that second question yourself, for the one call.
`passes` spreads the same vocabulary across the cells of a collage, and each cell reports the layers it was read under.
## Projection
`projection = "orthographic"` covers a fixed world-space height at every distance. Parallel edges stay parallel and two equal-size objects at different depths cover equal pixels, which is what makes it the projection to check a shape or compare sizes under — a perspective frame's convergence hides both. `orthoHeight` sets that height; omit it and it is fitted to what is being framed.
Any camera can be orthographic, not only a capture: it is a field on the `Camera` component. A capture through a camera the scene holds (`fromCamera`, `viewport`, and `source = "camera"`, `"screen"` or the scene camera) takes that camera's `projection` and `orthoHeight` with the rest of its lens, and its lighting `environment` with an `isolated` camera's background and ambient; a `projection` or `orthoHeight` stated for the call stands over the camera's.
## Which entity a capture framed
A capture names an entity, or a camera to render from, by its id or by its name.
A name exactly one entity carries means that entity. A name several entities
carry means none of them on its own, so the capture is refused, and the refusal
says how many entities carry it and names each by name and id; pass the id of
the one you mean. A player is drawn as its body, so a capture of a player
identity (an entity carrying `UserIdentity`, named `user`) frames the body its
`avatar` names. A player prototype is absent from the live scene while it
plays, so its name reaches no entity there: a capture of that name is refused,
and the refusal names each player spawned from the prototype, by its identity
and its body, with their ids.
Every cell of a capture aimed at an entity reports what it framed under
`subjects`: one `{ id, name }` per subject, carrying
`playerIdentity = { id, name }` when the picture is the body of the identity
the capture named.
## Isolate
Framing a subject fits the **frame** to it; it does not decide what is drawn in that
frame. Everything else standing there is still rendered — and a scene's default player
spawn sits at the world **origin**, which is exactly where a prop usually gets built, so
a tight shot of a new prop at the origin can come back showing the player instead.
`isolate = true` draws the subject without the other geometry. It changes exactly that — lighting, sky and post-process are untouched, so a final frame stays a final frame, and a flat read of the geometry is a `pass`. Excluded geometry still casts shadows onto the subject and still bounces light into it, the same as any render-layer exclusion. In a `setups` collage each cell shows the entity its own set-up frames alone, and a set-up can state `isolate` for its own cell; a set-up aimed from a position or a camera frames no entity and is refused when it is to be isolated.
## The tone the frame carries
Every capture reports `luma` on its cell record: the tone of the pixels it just
encoded, in code values on the 0-255 scale the image is delivered at.
```
luma = { pixels, min, max, mean, p1, p5, p50, p95, p99, span, spread, crushed, clipped }
```
`span` is `max - min` — the whole range, a single stray pixel included. `spread`
is `p95 - p5` — the range the body of the picture occupies, which is the reading
that answers whether a shot is legible. `crushed` and `clipped` are the shares of
the picture sitting at code 0 and at code 255.
A frame's mean cannot answer that question: half a picture at 40 and half at 200
carries the same mean as a flat field at 120, and only one of them has anything
in it. A subject can be modelled, shaded, lit and drawn and still arrive inside a
handful of code values, in which case the image looks like a wash and every other
field here reports success. `spread` is the number that says so.
The same reading is available anywhere pixels are: `cpu:tone()` on a
`TextureCpuHandle` — from `renderer.texture.readback(rtHandle)` on a capture
handle, from a render-to-texture camera's target, from a CPU canvas — and
`cpu:histogram()` under it, the per-code-value counts for luminance and for each
of the three channels, which every reading above is a sum over.
`cpu:histogram(x, y, w, h)` counts one rectangle of the picture alone, so a
reading per region of the frame — how much of each cell is dark, lit or a
given colour — is one call per region.
`cpu:flip(reference)` holds the picture against another of its size by NVIDIA
FLIP, the comparison a golden is judged by; `@builtin::modules.postMetrics`
carries it with the golden runner, the pixel metrics (banding, temporal
variance, halo overshoot, ring energy, hue drift) and the scopes, each
reading a presented frame or a capture result as it comes.
## The grade an offscreen frame carries
A capture spawns its own camera and renders offscreen, and the post-process
chain runs over that frame the way it runs over the viewport's — for a station,
for an orbit around an entity, for a named camera, for a render-to-texture
camera alike. Inside an effect, `engine.view_proj` / `engine.prev_view_proj` /
`engine.inv_view_proj` are the camera THAT render was drawn from and
`engine.resolution` is that target's own size, so a grade that reconstructs
world space from scene depth reconstructs against the station and lens the
capture asked for. That makes an offscreen capture an oracle for an authored
look: it photographs a chosen station and lens without taking the on-screen
camera away from whoever else is driving the scene, and moving that camera
somewhere else does not move the frame this one returns.
An offscreen render keeps no view history of its own, so `engine.prev_view_proj`
there holds that same matrix rather than the frame before it, and a pass taking
camera motion from the two reads none. On the viewport the pair is a frame
apart, so a camera's motion (and the blur and temporal reconstruction built on
it) is read from the presented frame: `source = "presented"`.
A render feature's passes reach an offscreen render the same way, against the
same camera — the `renderFeature` assetType README carries that half, including
`@frame.camera`, its own per-target camera input. `render(ctx)` itself runs once
a frame for the main viewport, so `ctx.viewport` is the window's size rather
than the captured target's; a feature sizes its scratch with `screen = true` and
lets the engine track the drawn target.
`postProcessing = false` takes the chain off the frame a capture returns, and
with it the film a render feature draws — the flare and grain, a short focus's
bokeh, the shutter's smear. It is a `Camera` property rather than a render
layer, so `renderLayers` does not reach it. A capture naming a diagnostic `pass`
drops the chain by default, so the buffer comes back as the value it encodes.
## Collage
`collage` renders a grid of frames into one image. What varies across its cells is what you pass — `setups` for a cell per whole camera set-up, `viewpoints` for a cell per view of one subject (or `"sides"` for all six), `passes` for a cell per render pass, `duration` for a cell per sample over time. A collage with no axis is refused rather than quietly sampling time.
`setups` is the shot list: each entry is written the way a single capture is aimed (`source`, `camera`, `entity`/`entities`, `position`, `lookAt`, `rotation`, `distance`, `angle`, `margin`, `viewpoint`, `basis`, `projection`, `orthoHeight`, `fov`, `near`, `far`), plus `label` to name the shot on the result, and a field an entry leaves out comes from the collage's own options. `setups` and `viewpoints` are one axis — both say where the camera stands — so a request names one of them; either crosses with `passes` into a 2D grid, a row per station and a column per pass.
The shot most of this exists for is one call: six sides of one object, each an orthographic elevation, nothing else in frame.
Authoring the cameras themselves — creating, listing, aiming, framing, and setting their parameters — is the `camera` toolbox.
# debug
Surface recent problems, inspect entity component state, and control the ambient debug-visualization overlay.
- **problems** — return the errors and warnings the engine has logged since your last call (contract violations, `awake`/`update` throws, auto-disabled components, unresolved requires, bridged renderer/asset errors). Advances a read-cursor, so repeated calls report only what is new. **When something you built does not behave, call this first.**
- **inspect** — component state for every entity matching a target (id, name, glob, proxy, or an array): script components as serialized public data, native ECS components as field values, or both — selected by `include`, filterable by `types`.
In the editor the overlay draws gizmos for the whole scene — mesh bounds, camera frustums, skeleton bones, physics colliders, icons for meshless entities (audio sources, cameras, lights), and mesh wireframes. It is ambient (no per-entity setup) and agent-driven:
- **set** — show or hide a category (`bounds`, `frustum`, `bones`, `colliders`, `icons`, `wireframe`), or `all`.
- **scope** — focus the overlay on specific entities (by name or id); call with nothing to clear the focus and draw for everything.
- **playSession** — show the overlay in play mode for a temporary, never-saved session, so bones/colliders/bounds stay visible on a running, animating scene.
- **state** — report which categories draw, the current scope, the play session, and the engine mode.
# entities guide
Reference docs surfaced through `guides { path: "..." }` and `man entities`.
The content lives in `guide.md`; this README is just the asset summary.
# assets
Find content and trace how it's used — search the project's assets, see what an entity is made of, and find who uses a given asset.
Search the whole asset index by substring and get every match grouped by category, without knowing where anything lives. Point at one entity, a list, or the whole scene and get back the unique set of asset references in use — materials, meshes, textures, bundles, and anything else a component field holds — each enriched with its identity, path, and the entities that use it. Or go the other way: name an asset and find every entity in the active layer that references it, down to the component and field.
# Camera
Manages viewport priority, render-to-texture, and capture. State is stored in the native `Camera` ECS component; the Rust camera system handles render scheduling and render targets.
Public fields: `fov`, `near`, `far`, `priority`, `textureHandle` (the guid of the texture the camera renders into; empty = main viewport), `renderLayers` (which render layers this camera draws — a space-separated spec of names, e.g. `"all"`, `"all !ui"`, or `"default sky"`; `ui`/`sky`/`debug`/`EditorUI` are built-in layers), `postProcessing` (whether this camera runs the post-process chain), `debugChannel`, plus the behavior slot below.
Methods: `:lookAt(target)` (entity id string OR `{x, y, z}` table), `:render()`, `:capture()`, `:setTargetTexture(tex?)` (a `renderer.texture.create` handle to render into, or nil for the viewport).
```luau
entity(id).component.add("Camera", { fov = 90, priority = 10 })
entity(id).component.get("Camera"):capture()
```
The scene's play-mode camera is reached as `layers.active.camera`, a handle that
reads and writes the fields above on whichever entity currently carries them.
`layers.active.camera.entity` is the entity ref for that camera and
`layers.active.camera.entityId` its id string, so a script that needs to attach
something to the camera — an `AudioListener`, a child entity — goes through the
ref:
```luau
local cam = layers.active.camera
cam.fov = 70 -- the camera's settings
cam.entity.component.add("AudioListener") -- the entity carrying them
```
## How the camera moves: `behavior` and `follow`
A `Camera` does not move itself. `behavior` names a component that does, and setting it attaches that component to this entity. Clearing it detaches whatever was attached.
```luau
local cam = entity(id).component.get("Camera")
cam.behavior = asset.ref("@builtin::controller.orbital_follow", "component")
cam.follow = playerBody
```
The attached behavior is an ordinary component on the camera's entity, so it is tuned the way any component is: read it with `component.get` and set its fields there. A `component.add` of the same type configures the instance the slot attached instead of adding a second one: the values it passes are written onto that instance and its proxy is returned. That add is the form a scene `build.luau` tunes the behavior with, because its values are saved with the scene and the loaded Camera's behavior takes them back. A key the component reads only as it is created (one of its `initKeys`, a private field) refuses the add and names the key.
```luau
cam.behavior = asset.ref("@builtin::controller.third_person_follow", "component")
local rig = entity(id).component.get("third_person_follow")
rig.cameraDistance = 6
-- the same, as an add of the type the slot attached
entity(id).component.add("third_person_follow", { cameraDistance = 6 })
```
`follow` is the standard slot every shipped behavior reads. Set the follow target on the **Camera**, not on the behavior, so swapping behaviors keeps it. A behavior that finds its own `follow` field empty falls back to this one, which is what lets a rig keep tracking the player across a behavior swap.
`followResolves` answers whether that slot names an entity that is live — `true` while it names a live one or names nothing at all, `false` once the target is despawned or the id names no entity. A rig whose target does not resolve holds its last pose, and this is the field that tells it from a rig posed correctly on a subject that has not moved. `camera.get` carries the same value beside `follow`, and a write naming an id with no entity behind it draws a warning where it lands.
```luau
cam.followResolves -- false once the followed entity is gone
tools.use("camera", "get", id).followResolves -- the same answer off the tool
```
The shipped behaviors live under `@builtin::controller.*`: `orbital_follow`, `third_person_follow`, `first_person`, `free`, `orbit`, `chase`, `isometric`, `rts`, `birds_eye`, `side_scroller`, `cinematic`, `menu`.
## Writing your own
Any component can be a camera behavior. Write one that moves its own entity and attach it the same way:
```luau
cam.behavior = asset.ref("MyChaseCam", "component")
```
`follow` lives on the Camera, so a behavior gets no property notification of its own when the target changes. Declare `onFollowChanged(newFollow, oldFollow)` to be told the moment it does — the Camera calls it on the component it attached, which is what lets a rig re-pose on the new subject at once. A behavior that reads `Camera.follow` on its own schedule declares nothing and is attached the same way.
```luau
typed function public:onFollowChanged(newFollow: any, oldFollow: any)
-- pose this entity against the new target
end
```
To make it appear in the discovery catalog alongside the shipped ones, declare the `cameraBehavior` tag in the component's `.metadata`:
```json
{ "tags": ["cameraBehavior"] }
```
The tag governs **discovery**, not attachment. A tagged component is listed by `layers.active.camera.behaviors` and is what tooling offers when something asks "which camera behaviors exist"; an untagged component attaches just as well and simply stays out of that list. Tag the ones you want other people (and agents) to find.
```luau
for name, ref in pairs(layers.active.camera.behaviors) do
print(name, ref.identity)
end
```
## Texture colour space
`textureColorSpace = "display"` applies the display transform when rendering into a texture. `"linear"` writes scene-linear values instead. `postProcessing` independently controls the effects chain in either mode. Floating-point targets retain values above one; normalized targets clamp to their representable range. The main viewport uses display encoding.
# multiplayer guide
Reference docs surfaced through `guides { path: "..." }` and `man multiplayer`.
The content lives in `guide.md`; this README is just the asset summary.
# entityOps
Operate on scene entities — spawn, instantiate content, change state,
swap, and navigate the hierarchy. Every tool resolves targets by entity
**name or id** (single, a list, or the records `scene.find` returns) or
by a **`scene.find` query** (`{ name = { "wheel" } }`,
`{ component = { "Light" } }`, `{ under = { "car" } }`) that names a
selection without looking it up first, and asset inputs by a name / path
/ identity string that the tool resolves and reports back canonically —
so the caller never needs to know an asset's exact identity up front.
Finding and reading entities is the `scene` toolbox (`scene.find`,
`scene.tree`, `scene.summary`); this toolbox is the operating surface.
## Spawn + instantiate
- **spawn** — spawn entities from a template: name the components they
carry and their field values, plus a transform. Authored (serializing)
components only. Pass a `{ defaults, items }` list to spawn MANY in one
call with shared defaults and per-item overrides — a six-walled room is
one call, not six — validated whole before any entity is created.
- **fromAsset** — instantiate an existing asset (bundle / avatar / mesh /
material / texture, or anything with an `:instantiate()`): resolves a
name/path/identity string, dispatches by category, and reports the
canonical asset it hit. Controls the live `link` and `synced` flags.
## State + hierarchy
- **modify** — delete / enable / disable / hide / show / temporary /
reparent / rename, over one or many entities.
- **swap** — replace an entity with another entity that already exists in
the scene (moves it into the target's slot).
- **addComponents** — attach component(s) with setup data to one or many
entities; `create` spawns missing ones.
- **removeComponents** — detach component(s) from one or many entities,
reporting per entity what was `removed` and what was `absent`.
- **component** — inspect a component TYPE's schema: its public fields
(name + type + current value), methods, and lifecycle hooks — so you
set fields that exist instead of guessing. Reach for it before
`addComponents` / `spawn`.
- **roots** — find the root ancestor of one or many entities.
## Transform + copy
- **transform** — move, rotate and scale: absolute sets, relative
offset / rotate / scaleBy, and grid snapping. With no ops it is a pure
read of the current transform.
- **duplicate** — copy entities, one at a time or as a numbered run
stepped along an accumulating `offset`.
## Addressing a set you built
Every tool here resolves targets by **query** as well as by name or id, so
a set can be operated on without retaining a single id. Tag the set as you
build it, then address it by that tag:
```lua
-- Build the set in one call, tagged.
entityOps.spawn({
defaults = { components = { Model = { model = "cube" } },
attributes = { group = "roomA" } },
items = { { name = "wall_n", position = { 0, 1, -2 } },
{ name = "wall_s", position = { 0, 1, 2 } } },
})
local set = { attribute = { name = "group", value = "roomA" } }
entityOps.transform(set, { offset = { 0, 5, 0 } }) -- move the whole set
renderLayer.set(set, "shell") -- re-layer the whole set
entityOps.modify(set, { delete = true }) -- remove the whole set
```
The tag is an ordinary entity attribute, so it persists with the scene and
is as much a part of the content as a name is.
To see what is already present rather than what you made, `scene.find`
with no search axis returns the whole live population, and
`include = { "transform", "componentValues", "attributes" }` annotates
each hit — one call, no follow-up per entity.
# wld
Manage the live world while you work — flip between edit and play, and compose additive scene layers.
Flip into play mode — which snapshots the edit state, then starts scripts and physics — and back to edit, which restores that snapshot and stops scripts; query the current mode any time. Load a scene as an additive layer alongside the current one, unload it, or show and hide layers without losing their entities. List the worlds saved on disk, and read the current world state: name, mode, active layer, and available scenes. To list the loaded scene layers or the scenes available to load, use `scene.loadedLayers` and `scene.list`.
Saving and loading scene snapshots is the `scene` toolbox (`scene.save` / `scene.load` / `scene.list`).
# scene
Work with the live scene across its whole lifecycle: start one from a
template, understand its structure, reshape its player, clean it, and set
it as the world's entry point.
## The player model
A scene is either **playerless** (`"none"`) or **spawns a player per
joining user** (`"spawns"`). The player is defined by a **PlayerPrototype**
subtree — a body (the avatar a joining user becomes) and a camera rig. Zero
is like Roblox here: the default character is a socket a joining player's
own avatar replaces, so **reuse the canonical player setup rather than
hand-rolling one** — a divergent player breaks multiplayer. `scene.summary`
and `scene.tree` always report the scene's player intent, so you can see a
scene's type without knowing this tool exists.
## Start a scene
- **create** — create a NEW scene from a typed template (`empty`, `flat`,
`player`, `menu`) and load it. Omit the template to get the catalog of
what each contains. `opts.startup = true` also makes it the world's entry
scene. The starting point is a choice, not a scene handed to you silently.
- **setStartup** — make the currently active scene the world's startup
scene, so it survives world reloads. No argument, no clear.
## Understand a scene
- **tree** — the entity hierarchy as an indented tree, led by a one-line
player-state header. The quick "what is the current structure" view.
- **find** — the single entity-discovery tool over the whole live
population. Search by `name`, `component`, or `attribute` (each a list),
scope by hierarchy or scene, and add projections with `include`:
`transform` (`position`, `rotation`, `eulerAngles`, `scale` as arrays,
read `position[1]`), `componentValues` (each component's live field
values), `attributes`, `scriptComponents`. Every match carries
`components` (the component names) without one. Returns
`{ matches, total, truncated, searchedAxes }`.
- **summary**: entity + root counts, the top-level rows (at most `limit`, 20
when omitted), the active camera, the **player** setup (intent + counts +
the verb to change it), and the world's **startup** scene. `under` scopes
the counts and rows to the subtrees of named entities, and `fields` keeps
only the named fields, so `{ fields = { "entityCount" } }` answers the count
alone.
- **list** — the SCENES you can load, so you find one by name instead of
guessing. `scope` filters `world` (default, this world's own scenes),
`library` (builtin `@builtin::` templates / demos / canonical setups),
or `all`; each entry says whether it is currently loaded / active.
- **loadedLayers** — the scene LAYERS composing the live scene right now:
the root scene plus any additive overlays (editor UI, effect passes),
each with its backing scene, status, visibility, and additive flag. A
layer whose load produced failures reads `status = "partial"`.
## See what a load did, and what a scene costs
- **observe** — what every load did and what each loaded scene costs.
`lastLoad` is the last load's report: what it produced, the root it
replaced and the overlays that went with it, the entity counts on each
side, the milliseconds each phase took, and every failure with the
entity, component or lifecycle hook it is about. `layers` counts what
the engine attributes to each layer, `cost` is each layer's per-frame
entrypoint tick summed across the window `window` reports.
- **whyPartial** — why a layer is not whole: the nearest cause from a
closed set, the engine's own words for it, and the full failure list.
The answer to "the scene loaded but something in it is missing".
- **cost** — which loaded scene is eating the frame time, ranked by what
each layer's entrypoint tick costs. A scene entrypoint's per-frame
`update` / `editorUpdate` runs on the scheduler rather than as a
component, so `profiler.scripts` does not list it; this does. Pass
`true` to open a fresh window, let frames pass, then call again.
## Reshape the player
- **player** — read the setup, flip the typed intent between `"spawns"` and
`"none"`, and reshape: `body` adopts an entity or an avatar asset ref,
`camera` wires an entity carrying a Camera, `behavior` sets the player
camera's behavior to any `cameraBehavior` component. `"none"` removes the
prototype and spawns; `"spawns"` authors the canonical setup when missing.
- **spawns** — the spawn POINTS: where joining players arrive, as opposed to
`player`, which decides whether they arrive at all and what they become. No
argument reports every PlayerSpawn with its transform, the prototype it
instantiates (and whether that reference still resolves), and its team /
role / maxPlayers / spawnPolicy / placement. `"add"` places one, `"set"`
reconfigures one (omitted fields keep their value), `"remove"` deletes one;
`opts.spawn` picks WHICH when the scene has several. A spawn's transform is
where a body lands and its forward axis is the heading it faces — the
edit-mode overlay draws that ring, arrow and standing capsule.
## Change the content
- **clean** — clear the scene down to a protected keep-set. By default only
the player setup survives (never orphaned); `keep` protects a `scene.find`
selection (e.g. `{ component = { "Light" } }`); `keepPlayer = false` wipes
the player too; `dryRun` previews. Only the active scene layer is touched.
- **remove** — delete entities by name, id, array, or a `scene.find` query,
subtree-deep. Removing the default floor is `scene.remove("ground")`.
- **save** — save a loaded scene back to its own `scene.json`; a no-arg call
reuses the last scene name.
- **load** — load a scene snapshot into the live world.
- **reload** — re-run a loaded scene's build after editing its entrypoint.
`load` of an already-loaded, unchanged scene is an idempotent no-op; this
rebuilds it, in edit mode. Omit the name to reload the active scene.
A rebuild saves the scene, as a write to `build.luau` does, so `scene.json`
holds what the reload built and the next play loads it. A library scene
(under `/libs/`) is rebuilt in the live scene alone.
- **replace** — replace a loaded scene's content with another scene's
content, keeping the target's identity. Supports `dryRun`.
## Maintenance
- **migrate_v6_to_v7** — convert a v6 scene's `scene.json` to the v7 format
in place. User-initiated only.
World mode (play/edit) and additive layers are `wld`; accepting or
rejecting play-mode changes is `sceneAuthoring`.
# assetType (asset type)
The `assetType` is the **type of types** — the meta-type that every
`<typename>.assetType/` folder is an instance of, including itself. A
`<typename>.assetType/` folder declares a new asset type called
`<typename>`: its on-disk shape, its identity rule, and the structural
contract instances of the type must satisfy.
This type is self-hosting. `assetType.assetType/` conforms to its own
schema — a `type.yaml` plus a `README.md` — so the type system is
defined in terms of itself rather than a hidden engine special-case
(the same way a C compiler is written in C). Every asset in the engine,
including each `.assetType` definition, now resolves to a registered
assetType: a `.material` resolves to `material.assetType`, and
`material.assetType` resolves to `assetType.assetType`, which resolves
to itself.
## Why it exists
Assets used to be mapped to their type *implicitly*, by matching the
folder suffix against a name-keyed registry. That match carried no
stored link: nothing on a `Foo.material` recorded *which*
`material.assetType` it was written against, so two worlds shipping a
same-named type could silently disagree. Making `assetType` a real,
resolvable asset closes that gap — the link from an asset to its type is
now an explicit reference pinned in the asset's `.refs` sidecar
(`via: "asset_type"`), exactly like every other dependency.
## Where it lives
- Source: `/zero/source/.../<typename>.assetType/`
- Identity: `<typename>` (the `.assetType` suffix strips from the
identity; the folder retains the suffix on disk).
- Folder shape:
- `type.yaml` — the structural spec the validator reads. **Required.**
- `README.md` — type-level documentation. **Required.**
- `about.yaml` — three short plain-language texts saying what the type
is for (see "Say what your type is for" below). Every built-in type
ships one.
- `behavior.luau` — optional behavior/scaffolding module.
- `template/` — optional canonical placeholder body the templater
copies into a new asset of the type.
- `<name>.module/` — optional shared code the type ships to **every
instance** of it, conventionally `shared.module/` (see below).
## Shared code its instances reach (`asset.containing` + `.modules`)
A type ships code every instance of it uses by declaring the modules in
its own `behavior.luau`, as a map of tracked `require`s:
```luau
-- inside <typename>.assetType/behavior.luau
M.modules = { shared = require(".shared") } -- the sibling shared.module/
```
An instance reaches it with one location-independent line:
```luau
-- inside any foo.<typename>/init.luau
local api = asset.containing(__FILE__).modules.shared
```
`__FILE__` is the chunk's own VFS path; `asset.containing` resolves the
calling asset, and `.modules.<name>` follows the instance's pinned
`typeRef` (the type's **guid**, recorded in the instance's `.refs` as
`via = "asset_type"`) to the module its type declares. Because
resolution follows that link rather than a category name, the same line
in an instance of a different type resolves to that type's module, and
identically-named modules in two types never collide. `asset.typeRef(target)`
reads that guid for any target; `asset.resolve(asset.typeRef(target))`
gives the full `AssetRef<assetType>`. See `assetTypes/README.md`
§ "Shared code: type-owned modules" for the full mechanism.
## How to create one
Authoring a new asset type is just creating a `<typename>.assetType/`
folder under `/zero/source/`. The engine registers `<typename>` as a
category **the moment the folder is written** — no engine restart, no
Rust change, and it works for built-in (`@builtin/assetTypes/`) and
user-defined types identically. Once `<typename>` is registered,
`<name>.<typename>/` folders are recognised as assets of that type and
resolve their `asset_type` link back to this definition.
Creating a `<name>.<typename>/` folder *before* its
`<typename>.assetType/` exists fails fast: the suffix has no registered
type, so the folder can't be a valid asset. Author the type first.
## Say what your type is for (`about.yaml`)
Every type carries a small `about.yaml` beside its `type.yaml`, and the README
you write for the type documents how to author an asset of it. Both are
required, and both are meant to be written as you make the type, while you know
what it is for. `about.yaml` answers three questions in plain words, one key
each:
```yaml
intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering."
function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text."
usage: "You choose it by name for your UI or your text, and the text appears in that typeface."
```
- **`intent`** is what the type is for in someone's game. Name the whole range
of things it covers, in the words a game maker would use for them.
- **`function`** is how it works today: what an asset of the type is made of and
what the engine does with it.
- **`usage`** is what a person or an agent does with one: how they pick it, place
it, call it, or hand it to something else.
A few habits keep it useful. Write about the type as a whole, so the text holds
for every asset of it, and leave out any one asset's name. Say what the type
does right now. Stay with words a game maker would say, and mention a file name
or a call only where a game maker would know it. The limits are in bytes:
`intent` 800, `function` 1500, `usage` 1200. Each is generous, and a few
sentences usually say it.
Why bother: agents working in a world read these three texts to learn what your
type is for, so they reach for it when it fits and use it the way you meant. People
searching find the type by what they want to make, and the three texts let them
tell at a glance whether it is the one they need.
`asset.create("assetType", name)` scaffolds the file with all three keys, and a
README whose first paragraph is a `[[describe]]` note. Each value starts with
`[[describe]]` followed by a note on what to write; replace the whole value with
your own words. A value or a README line that still starts with `[[describe]]`
counts as not written yet, which the push's check of each asset it carries against
its type reports, naming the file. A type you leave as it was is not asked, so
older types stand.
Many types at once, or one you would rather not write by hand: `services
describe` lists the types that lack these texts and what filling them costs, and
`{ mode = "all" }` writes them into the same files, where you edit them like
anything else you wrote.
Where the texts show up: `asset.inspect("<typename>", "assetType")` returns them
as `detail.about`, `assetTypeRef:getAbout()` returns them as a table with the
keys `intent`, `function` and `usage`, the type's `types/<typename>` guide page
ends with an "About this type" section holding them, and the Inspector's Type
section lists them at the top. The guide page is this README plus that section,
so a README that explains the type well and an `about.yaml` that says what it is
for read well together.
## Ask your assets to say what they are
A type can ask each of its assets to carry a description: a file, written by the
author or generated, that says what that asset is and what it is for. The people
and agents who find an asset read it to decide whether it fits, and the author
knows what it is for at the moment of making it.
**1. Declare the file with a `described` check.** This is the whole requirement:
```yaml
files:
required:
- path: "README.md" # any file name works
kind: "file"
content:
- { check: "described", message: "Say what this widget is for and where it goes." }
```
With that in place:
- An asset whose file is missing, empty, or still has a line starting with
`[[describe]]` does not meet the type's requirements. `asset.validate` names it,
`zm status` and `world.publishBlockers()` list it, and a push that carries it is
refused with `message`.
- `services describe` finds it (`mode = "find"` lists it and the price) and can
write the description for it (`mode = "all"`). It writes only this file.
For a YAML file that holds several texts, name the keys and their limits in bytes,
the way this type does for `about.yaml`:
```yaml
content:
- check: "described"
keys:
- { key: "intent", max_bytes: 800 }
- { key: "usage", max_bytes: 1200 }
message: "Write intent and usage."
```
`headings` names sections a Markdown file must have. `assetTypes/README.md` has the
full check.
**2. Optionally, steer what gets generated with a `describe:` block:**
```yaml
describe:
guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI."
examples:
- "<identity of an asset of this type whose description reads well>"
```
`guidance` says what a description of your type covers, and `examples` names assets
whose descriptions show the shape you want. Without the block, generation still
works from the general describing guide and the check's `message`.
An example is an asset of your type in the library whose description is a true,
written one, never a scaffold's placeholder, and never the asset being described.
When the library has none, leave `examples` empty rather than name one that is not.
A type whose assets the model cannot perceive (a sound it cannot hear, a motion it
cannot see) says so in `guidance`: the description comes only from what the asset's
own files state, such as its name and the `.metadata` where a generation service
records the prompt that made it, and when they state nothing the model answers
`cannot` with that reason. `services describe` then fails that one asset with the
reason and leaves its file as it was.
**3. Start the file unwritten in your template.** Put a heading and one line that
starts with `[[describe]]` and a short note on what to write, in
`template/<file>`, so a new asset starts unwritten rather than with text that only
looks written. Do not put example content in it: every new asset carries the
template verbatim, and the same text on many assets makes them impossible to tell
apart in search.
Types whose assets say what they are through their own content (a mesh, a texture,
a sound) leave this out: declare nothing and nothing is asked.
## The `behavior.luau` contract
`behavior.luau` is the type's code. It returns ONE table, and the keys below
are the ones the framework reads off it for EVERY type — the surface you get
by declaring them. Anything else on the table is your own: reachable by name
through `require("@builtin::assetTypes.assetType.shared.ref").loadTypeModule("<typename>")` for a
system that knows your type (`computeShader` publishes `dispatchKey` that
way), and never called by the framework.
```luau
local M = {}
M.ref = { ... } -- methods on every AssetRef of this type
M.modules = { ... } -- shared code the instances reach
M.global = {} -- reserved key; ship the empty table
function M.onCreate(name, opts) ... end
return M
```
### The tables
| Key | Shape | What the engine does with it |
|-----|-------|------------------------------|
| `M.ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every `AssetRef` of this type: `ref:name(...)`, with `self` the ref. This is how a type gives its instances an API. Two names in here are contracted — see below. |
| `M.modules` | `{ [name] = require(".sibling") }` | Shared code the type's instances reach through `asset.containing(__FILE__).modules.<name>`, resolved by the instance's pinned `typeRef` guid. See the section above. |
| `M.refShapes` | `{ [method] = "TypeName" }` | Declares the result type of a `M.ref` method so the LSP can check what a call site does with it. See the `M.refShapes` section below. |
| `M.events` | an events schema | The events an ASSET of this type fires, declared the way a component declares its own. Readers subscribe through `ref.events.<name>:connect(...)`; firing authority stays with the type. Keyed by the asset's guid, so every resolver of the same asset shares the signals and a re-resolved ref re-attaches to subscriptions already there. |
| `M.namePattern` | a Lua pattern string | The name shape `asset.create` enforces for instances of this type, replacing the default `^[A-Za-z][A-Za-z0-9_]*$`. |
| `M.global` | `{}` | Reserved. Ship the empty table. |
### The lifecycle hooks
Each is optional; a type that omits one costs nothing. The engine calls them:
| Hook | Signature | When it fires |
|------|-----------|---------------|
| `M.onCreate` | `(name, opts) -> { [filename] = contents }` | On `asset.create("<type>", name, opts)`. Returns the files that scaffold the new instance, as a map of relative path to contents; the framework writes them. The `opts` type annotation is the schema `asset.create` validates the caller's arguments against, so annotate it. |
| `M.onReplace` | `(dest, files) -> { [filename] = contents }` | On an `asset.create` that writes over an asset already at `dest`, after `onCreate`. Receives the files `onCreate` produced and returns the files to write, so a type that re-derives its content (a rig re-imported from its source file) can carry what an author added to the asset it replaces. Optional. |
| `M.onRegister` | `(self)` | Once per instance, the first time it registers: on `engine.onWorldLoaded` for instances already in the world, immediately on a live `asset.create`, and when an instance arrives after that sweep (installed, pulled, or synced from a peer). Guarded by the instance's path, so a double trigger never double-registers. An instance that leaves the runtime releases the guard, so one arriving at the same path again registers. This is what makes "write an asset into the world and it takes effect live" work for content that registers into a runtime registry. The `@builtin` library is excluded from the sweep. |
| `M.onChange` | `(ref, change)` | On every VFS write to a file INSIDE one of this type's instances. `change` is `{ path, asset, type, kind, origin }`: `kind` is `"edited"` or `"seeded"`, `origin` is `"local"` or `"remote"` (an importer runs on the originator only). **Filter on `change.path`**: the hook fires for any file under the folder, so act on the one you care about. It runs as its own task and may wait on what it reads: a `vfs.read` of bytes only the blob store holds (a binary file on the web build) fetches them. The writes to one asset reach the hook in the order they were made, each once the hook before it has finished. A re-entrancy guard suppresses writes back into the same asset routed inline from the hook, and a write the hook makes is routed on a later frame like any other, so the hook must be convergent on its own: diff the meaningful state and short-circuit while your own regeneration is in flight. |
| `M.onDelete` | `(ref)` | When an instance of this type leaves the runtime: it is deleted, or the engine swaps away from the world binding that held it. Its files are gone from `/zero/source` by then. A removal routed while the instance's `onChange` is waiting reaches `onDelete` once that hook, and every write queued behind it, has finished. On a swap the instance still exists in the world it belongs to, and a VFS write the hook makes reaches the world now bound. |
| `M.validate` | `(assetRef) -> { { code, message, severity? } }` | On `asset.validate`, after the structural `type.yaml` check, for the type's own SEMANTIC validation. `severity` defaults to `"error"`; error-severity problems flip `ok` to false, warnings do not. A hook that raises or returns a non-table is itself reported as a `validate.hook_failed` error. `world.push` runs this per user asset, so declaring it enforces your type's rules at publish time with no further wiring. |
### The two contracted `M.ref` names
Most `M.ref` methods are your type's own surface: name them what you like,
return what you like. Two are read by the engine and mean the same thing for
every type, so their shape is fixed:
- **`instantiate(self, target?, opts?) -> (root, idMap)`** — makes an instance
part of the scene. Defining it is the whole opt-in: `ref:canInstantiate()`
is true exactly when it exists. Its **return is a contract** — see the next
section.
- **`inspect(self) -> detail`** — the type-specific half of `asset.inspect`.
See its section below.
### Names a type cannot shadow
Some keys resolve on every `AssetRef` before per-type dispatch, so an `M.ref`
entry of the same name is never reached: `canInstantiate`, `getSource` /
`getBytes` / `getText`, `exists`, `deps`, `meta`, `runtime`, `events`,
`modules`, `typeRef`, and the residency flags `has_backing_asset`,
`has_runtime_changes`, `cpu_resident`, `gpu_resident`. These are the
behaviours every asset must expose identically, which is why they win.
### Reloading
A `behavior.luau` edit ripples to existing refs with no restart: dispatch
reads `mod.ref` fresh each time and `require`'s cache is re-run in place. A
type whose folder appears at runtime is picked up on the next dispatch —
negative results are not cached either.
## The names your type's assets hold (`references:`)
An asset that names another asset by a string depends on it: the named asset
travels with it into a pack or a pull, and a name nothing answers to is an
unresolved dependency `worldValidation` reports and the push gate refuses. The
engine reads `require(...)` and the asset lookups on its own; a name your type's
format or API carries anywhere else is one you declare, in `type.yaml`:
```yaml
references:
# A top-level key of this type's own files that holds a name (or a table of them).
keys:
- { key: "shader", type: "shader" }
# A call's argument, counting from 1, wherever the call is written.
args:
- { call: "g:node", position: 2, type: "procNode" }
# A field of the options table a call takes.
fields:
- { call: "fx.beam", field: "material", type: "material" }
```
`type` is the category the name resolves in, one of `asset.categories()`. An
argument declared once per category, at the same `call` and `position`, takes
the name from whichever category answers. A key or a field holds one category:
declared again with another `type`, it takes the later one. The block is
declared as the type registers, when the library or the world holding it is
laid into the VFS, so every reference table reads it whatever script has or has
not run. `asset.declareReferenceKey`, `asset.declareReferenceArg` and
`asset.declareReferenceField` declare the same things from a script, for a
surface that is no type's.
## What search does with your type (`indexing:`)
A type declares what search embeds for its instances. **This is not optional
and there is no useful default**: ZeroMind runs your declaration and adds
nothing of its own, so anything you do not point at is absent from the index —
silently, and for every instance of the type forever. Twenty types once shipped
with no `indexing:` block and every instance of them was unfindable.
A type whose instances are never searchable (a run record, a log) says so with
`indexing: none`; every other type declares a recipe.
A type without an `about.yaml` beside its `type.yaml` refuses every push that
carries it, whether or not the push edited the type. Texts in it that are not
written yet follow the rule every `described` file follows: they refuse the
push that edits, stages or commits the type.
Two words carry the whole thing, and they are the same two the search tool
exposes:
- **`identity`** — what an instance IS. For anything you can look at, that is
the picture (`content:` + `modality: image`, matched directly by a text
query). For everything else it is the authored text that says what it is.
- **`capability`** — what it DOES and how it is made. Code, settings, the
model-written summary of them.
A type with no behaviour has no `capability` entry. A type with nothing to look
at has no image. Leaving a slot empty is a statement; filling it with whatever
happens to be lying around is not.
The one you have to decide when authoring a type is: *for an instance of this,
what is the thing a person would recognise it by, and what is the thing it
does?* A texture answers "the image" and "its compression settings". A module
answers "its README" and "its code". Write those two answers into `indexing:`
and the rest follows.
Three specifics worth knowing before you write one:
- **`derive` is instructed by this type's own `README.md`.** A model reads an
instance's source and writes a description; what it embeds is the
description, not the source. It follows your README to know what it is
looking at, so a type whose README says what its instances are gets good
derivations for free. There is no prompt to name.
- **`derive` loses detail.** It keeps the main technique and drops secondary
ones. If the source is code you want searchable by its own vocabulary,
declare the same files a second time as `capability` with
`extractor: verbatim`. Two entries, same role, different failure modes.
- **Never `source: { field: name }`.** A filename is one or two words with no
usable embedding, and a corpus indexed that way answers "language runtime"
with `say_runtime_2.soundClip`.
`facets:` is the second stage: a `file:` embedded whole (`.metadata`, so keys
nobody declared still get indexed) plus computed keys that state a value for
every instance including `false` — the raw file can imply "not rigged" and can
never say it.
The full schema, every extractor and the facet sources are in
[`assetTypes/README.md`](../README.md); the scaffolded block with inline
guidance is in [`template/type.yaml`](template/type.yaml).
## A container whose contents work together (`system: true`)
A type that is a container can say its contents are one working whole by
declaring `system: true` at the top level of its `type.yaml`. `package` declares
it: the components, modules, scenes and tools a package ships are parts of one
system. The declaration is plain data, read from the decoded `type.yaml`
(`require("@builtin::assetTypes.assetType.shared.declaration").of("package").system`),
and a type that leaves it out is an ordinary type.
## What your type looks like (`preview:`)
A type declares how its instances are pictured, and the engine makes the
picture when something needs it: staging an instance whose `preview.png` is
missing or pictures content it no longer holds queues a render, a view that
shows the instance asks for one, and `ref:preview()` renders one on demand. An
edit renders nothing on its own. Each `preview.png` records the content it
pictured, which is how a stale one is told from a current one. The preview studio owns the light, the
backdrop, the framing and the camera, and nothing in the world reaches it, so
an instance pictures the same in every world. Declare one of four recipes:
| `kind` | The picture is | Your type provides |
|---|---|---|
| `instantiate` | the asset stood in the studio through its own `instantiate` | `ref.instantiate` |
| `image` | a file the instance holds, fitted to the frame, nothing rendered | `source.files`, the candidate files in order |
| `surface` | the asset painted on a builtin mesh | `mesh`, and `ref.previewMaterial(self) -> { material }` |
| `custom` | whatever `ref.preview(self, opts)` returns | `ref.preview` |
```yaml
preview:
kind: surface
mesh: sphere
```
A scene-instantiable type that declares nothing still answers `ref:preview()`
through its `instantiate`, but persists no picture: the declaration is what
makes the engine keep one. List `preview.png` among the type's files so an
instance may hold it.
The picture is findable only when `indexing.content` names it. The two are
separate statements, and neither is derived from the other:
```yaml
indexing:
content:
- role: identity
modality: image
source: { file: "preview.png" }
```
`@builtin::assetTypes.assetType.shared.previewRecipe` reads the declaration;
the scaffolded block with inline guidance is in
[`template/type.yaml`](template/type.yaml).
## Typing a result from the instance (`M.refShapes`)
Every method on `M.ref` is checked against the type its `--!return` names,
and every asset of the type gets the same one. That is right for most
methods and wrong for the ones whose result is shaped by the ASSET: a
method answering one entry per child folder, per row of a config, per
binding an input map declares. The widest true annotation for those is
`{ [string]: Thing }`, and an indexer accepts every key — so a caller's
typo reads as valid and nothing reports.
`M.refShapes` lets the type state the result per instance. Each entry is
`function(self) -> (typeExpression, source?)`: a Luau type expression for
THIS asset, and the module whose type vocabulary the expression uses.
Read the asset; never run it — stating a type must not take effect.
```lua
-- inputMap.assetType/behavior.luau — the shipped example.
-- `activate()` hands back one handle per control the map declares.
M.refShapes = {
activate = function(self): (string, string)
local names = {}
for _, control in ipairs(M.ref.controls(self)) do
table.insert(names, control.name .. ": Handle")
end
if #names == 0 then return "", "" end
return "{ " .. table.concat(names, ", ") .. " }",
"@builtin::modules.zinput.scheme"
end,
}
```
With it, `map.jump:onPressed(fn)` resolves and `map.noexisting` is
reported with the map's real controls. Without it, both pass silently.
### What the call site has to say
A per-instance type is matched by the asset's IDENTITY, so it applies only
where the reference the method is called on says WHICH asset. Two spellings
do:
```lua
-- a component field, whose declared default names the asset
public = { map = Field.assetRef("inputMap", "@builtin::inputMaps.default", Sync) }
local controls = public.map:activate() -- typed for THAT map
-- an annotation, naming category and identity
local m: AssetRef<"inputMap", "@builtin::inputMaps.default">
```
`asset.resolve("<identity>", "<category>")` carries the CATEGORY, so the
methods the category defines are checked on the result — but not which
asset it found, so a per-instance result keeps the category's declared
return. A reference that names no asset (`asset.resolve(someVariable)`, a
value passed in as a parameter) carries neither, and calls on it are
unchecked. That is the same rule everywhere: the checker states what the
code states, and a name computed at runtime states nothing.
### The result is a value, not a binding
The type belongs to the expression, so it travels the way any inferred type
travels. Indexing the call's result is checked; stashing it in a module
local and indexing it from another function is not, because the local's
declared type is what carries across — and `any` (or no annotation) carries
nothing:
```lua
-- checked: `d.greting` is reported
function awake()
local d = public.dialogue:lines()
d.greeting:say()
end
-- NOT checked: `lines` is a module local typed `any`
local lines: any = nil
function awake() lines = public.dialogue:lines() end
function start() lines.greting:say() end
```
Bind what you need at the call site and the names stay checked in both
places — the asset-derived type at the boundary, ordinary scoping after it:
```lua
local lineGreeting = nil
function awake()
local d = public.dialogue:lines()
lineGreeting = d.greeting -- `d.greting` is reported here
end
function start() lineGreeting:say() end
```
### When nothing is reported and you expected something
From a call site, a type that is correct and a type that was never published
look the same: no diagnostic either way.
`require("@builtin::assetTypes.assetType.shared.refShapes").published()` answers which it
is. It returns two maps — the category surfaces, and the per-asset results
keyed by identity and then by method:
```lua
local shapes = require("@builtin::assetTypes.assetType.shared.refShapes").published()
shapes.categories.dialogue
--> "{ lines: () -> any, lineNames: () -> { string } }"
shapes.returns.Shopkeeper.lines
--> "{ browsing: Line, farewell: Line, greeting: Line, wares: Line }"
```
An identity absent from `returns` was never published for, which is a
different thing from published-and-correct — and the reason to look here
rather than at the call site.
The answers are recomputed when an instance is written, so a control added
to a map reaches the checker with no restart. Only types that declare
`refShapes` are read per instance, and at most 64 assets of one type are —
past that the type keeps its declared return and the engine log names what
was dropped.
## The instantiate hook (`M.ref.instantiate`) — a contracted return
A type opts into becoming part of the scene by defining `instantiate` on its
`ref` table. That is the whole opt-in: `ref:canInstantiate()` is true exactly
when the hook exists, so consumers offer a scene path — an `Asset.source`
field, a viewport drop, a tool argument — by CAPABILITY rather than by a list
of type names.
Unlike `inspect`, this hook's **return is a contract**. A caller writes one
piece of code against every instantiable type, so what comes back cannot vary
by type:
```lua
-- behavior.luau
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
local M = {}
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts) -- IN: the base opts
-- ... compose whatever this type is, under `root`, NOW ...
return Instantiable.result(self, root, idMap) -- OUT: the contract
end,
}
return M
```
**IN.** `target` is an owning entity ref: the instance lands under (or, for a
hierarchy type, onto) that owner. With no target the type spawns a fresh root.
`position`, `rotation`, `scale`, `name` and `temporary` mean the same for every
type — `Instantiable.root` applies them to a root you mint, `Instantiable.place`
to one you adopt, so you never re-read the spec. Honour more opts of your own if
your type needs them, and document them in the hook's `--!arg` docs.
**OUT.** Return `(root, idMap)` through `Instantiable.result`:
- **`root`** — the composed root, as an `EntityRef`. Composition is
**synchronous**: everything your type builds is live when you return, so the
caller can parent to it and read its components in the same statement. Do not
defer the work to a component's `awake` and return an empty shell — a root
that is not live is refused.
- **`idMap`** — the `originalId -> runtimeId` map naming what you spawned, or
nil for a type with no addressable children (`result` normalises it to `{}`).
**A caller never receives nil.** A component that re-composes your asset on
every load keeps this map and passes it back in, which is how a cross-entity
reference into the composition survives a reload.
`AssetRef` runs every `instantiate` through `result` on the way out whether or
not your type called it, so returning something else fails at your own call
rather than handing a caller a nil root. Calling it yourself is still how you
say what you return, and running it twice changes nothing.
`@builtin::assetTypes.assetType.shared.instantiable`'s README is the full reference for both halves.
## The inspect hook (`M.ref.inspect`)
`asset.inspect(ref)` resolves `ref`, builds a common envelope shared by
every asset (`identity`, `name`, `guid`, `source`, `typeName`,
`typeDefinitionPath`, `scope`, `origin`, `description`, `tags`), then
calls the resolved type's own inspect hook — `M.ref.inspect(self)` on
`behavior.luau` — for the type-specific `detail`. The hook returns
*only* `detail`; the framework fills in everything else:
```lua
-- behavior.luau
local M = {}
M.ref = {
inspect = function(self)
-- self.path is the asset's own folder. Parse the asset's OWN
-- files — source text, a native payload header, its `.metadata`
-- — never runtime state (a live component instance, a GPU
-- upload, a compiled schema): inspect must work on an asset that
-- hasn't been compiled, uploaded, or registered yet.
return {
-- type-specific fields, whatever this type wants to surface
}
end,
}
return M
```
A type that omits `M.ref.inspect` yields the generic record: the
envelope alone, `detail = nil`. That's a valid, working state — not an
error — but it means agents calling `asset.inspect` /
`tools.use("assets","describe", ...)` on an instance of the type see
only identity and scope, none of what makes an instance of it
meaningful. Declaring the hook is what makes a type's instances
inspectable for what they actually are.
A hook that raises leaves `detail = nil` and sets `record.warning` to
the error text — `asset.inspect` itself never raises for a resolved
ref.
## Discovery
- `asset.list("assetType")` — every registered asset type.
- `asset.inspect("<typename>")` — the type's identity, source path, and
this README, plus its `about.yaml` texts as `detail.about`.
- `asset.resolve("<typename>", "assetType")` — the `<typename>.assetType`
asset itself (used by the validator to find the type's `type.yaml`).
## Related
- `assetTypes/README.md` — the full `type.yaml` schema and validator
rules.
- `@builtin::assetTypes.assetType.shared.instantiable` — the instantiation contract's shared
implementation, both halves.
- Every other `*.assetType/` here — the concrete types built on this
meta-type.
## The Inspector a type ships
Every type names the file its Inspector sections come from with `inspector: { type: "inspector.luau" }` in its type.yaml. `asset.create("assetType", name)` scaffolds the block and an `inspector.luau` whose Contents section lists an asset's files, built from `ctx.parts`. `asset.validate` on a type that names none reports `assetType.inspector_required` (an error for a `@builtin` type the engine's library authors; a warning for a world's own, and for one the library carries by reference, which the world that published it answers for), and one whose file does not load `assetType.inspector_invalid`.
## In the Inspector
Type: what the type.yaml declares (suffix, container, primary files, the settings and inspector blocks), whether the type ships a behavior, how many instances it has, and **Open** for its files. Schema: the settings every instance carries, as read-only typed controls at their defaults (a type whose schema is per instance says where it is declared). Instances: a link to each of the first 20 assets of the type, and how many there are when there are more.
# scene.player
The scene's player setup, in one tool.
```lua
scene.player() -- report: intent + prototypes (body/camera wiring) + spawns
scene.player("none") -- playerless scene; removes every PlayerPrototype + PlayerSpawn
scene.player("spawns") -- player per joining user; authors the default setup if missing
scene.player("spawns", { body = "@builtin::avatars.minimal_player" }) -- swap the avatar
scene.player("spawns", { behavior = "@builtin::controller.first_person" }) -- first-person
scene.player("spawns", { camera = "my_cam" }) -- wire an existing camera entity
```
The intent is typed: `"spawns"` or `"none"`. `"spawns"` on a scene with
no PlayerPrototype authors the canonical setup — humanoid body,
third-person camera (OwnerOnly), a spawn at the origin — the same shape a
fresh scene ships and the `player` template produces. `"none"` strips the
player machinery entirely.
A `roles` table (second argument) reshapes the player and implies
`"spawns"`:
- `body` — an entity name/id to adopt, **or** an avatar asset ref
(`@builtin::avatars.minimal_player`) that repoints the body's avatar. A
joining user's own avatar replaces this body socket, so reuse the
canonical setup rather than hand-rolling one.
- `camera` — an entity carrying a Camera component; moved under the
prototype and scoped OwnerOnly so each joining user gets their own view.
- `behavior` — any `cameraBehavior` component (built-in or authored) set
on the player camera's `Camera.behavior`.
- `prototype` — picks one when the scene has several.
Setting anything saves the scene.
The report names the root scene layer's `intent` and `scene` path, and lists
every PlayerPrototype and PlayerSpawn the loaded layers hold. In play the
scene holds each authored prototype as the captured template a joining player
is cloned from; the report lists it through the spawn that names it, with
`template = true`. With no scene loaded as the root layer the report carries
`unloaded` in place of `intent` and `scene`, saying so and how to load one,
and the setters refuse until a scene is loaded.
The behavior is attached to the player camera's entity as a component of its own type, so it is tuned there: `component.get("<its type>")` on the camera entity and set its fields. A `component.add` of that type writes its values onto the attached instance instead of adding a second one.
# inputSim
Every simulated input, across every device a player might hold. Drive the
world as a keyboard-and-mouse player, as a phone, or as someone with a
controller — and read back what actually reached the game.
## Why all three, always
A world checked only from a keyboard is a world whose keyboard experience
is the only one anybody verified. That is how a game ships playable on a
desktop and dead on a phone: not because the touch path was written badly,
but because nothing ever drove it.
So this toolbox covers the three classes symmetrically, and `device` makes
a desktop session present as any of them.
## Driving the game: actions
A game reads its input through the controls its input maps declare —
`move`, `jump`, `sprint`. `action` drives one by name with the value the
game should read, which is how a test or an agent plays a game: the same
call works whatever device the player would hold, and nothing about a
device — which key a map binds, where the pointer is — has to be worked out.
```lua
tools.use("inputSim", "bindings") -- the live controls and their kinds
tools.use("inputSim", "action", "jump") -- tap a button
tools.use("inputSim", "action", "move", { 0, 1 }, 2) -- walk forward for 2 s
tools.use("inputSim", "action", "sprint", true, nil, true) -- hold until `release`
tools.use("inputSim", "fired") -- reported under class "driven"
```
A button takes `true`, a 1-D axis a number, a 2-D axis `{ x, y }`. The
value joins the control like another device: its shaping applies, its
press and release fire, and a context or a suppression that stands the
control down stands it down too. `release` lets go of every driven control.
The device verbs below prove the devices themselves: that a key, a pad or
the touch overlay reaches the control a player would press it for.
## The loop
```lua
tools.use("inputSim", "device", "touch") -- present as a phone
tools.use("inputSim", "bindings") -- what controls are live?
tools.use("inputSim", "layout") -- what is on screen?
tools.use("inputSim", "tapButton", "Jump") -- tap it where a player would
tools.use("inputSim", "fired") -- did it reach the game?
```
`bindings` first, always. Nothing is live until a component activates an
input map, so an empty list means no awake component asked for input —
which is a different problem from a control that fires and does nothing.
`fired` is what turns a simulated input into an assertion. A capture can
look identical whether or not the input landed; this cannot. Its `count` is
the number of engine frames the control was active, so a tap that holds a
button across two frames reads 2 for one press. To count presses, subscribe
with `control:onPressed`.
## One argument shape
Every verb here takes its arguments POSITIONALLY, in one order across the
whole toolbox: **what** first — the button, key, stick, trigger, label or
contact id — then **where** as flat `x, y` (or `dx, dy`), then **how long**
in seconds or **how far spread** in frames, then **which pad slot**. Every
optional argument trails. No verb wraps its arguments in an options table,
so a verb's shape is known from having called its neighbour.
```lua
tools.use("inputSim", "click", 0, 400, 300) -- what, where
tools.use("inputSim", "mouseDown", 0) -- the same what
tools.use("inputSim", "touch", 400, 300, 0.5) -- where, how long
tools.use("inputSim", "padStick", "left", 0, -1) -- what, where
```
Every surface that names arguments resolves those names against the same
positional list, so one call is written four ways and reaches the same
slots: `click(0, 400, 300)` in Luau, `{ button = 0, x = 400, y = 300 }`
through `tools.use`, `args` over `use_tool`, and `--button 0 --x 400 --y
300` in the shell. A verb whose every argument is optional takes `{}` for
"no arguments at all", and a name the verb does not declare is refused with
the ones it does.
## Who the input is for
What this toolbox simulates is the game's input: a key, click, motion, wheel
or touch reaches the scene alone. It reaches the scene whatever a person at
the window has focused — a panel they clicked, a terminal they are typing a
message into — and it reaches no UI widget, so a run driving the game never
types into the person's panel and the person's typing never stands the run
down. Every key, pointer and touch verb takes a trailing `target`:
`"game"`, the default, or `"ui"`, which reaches the UI the way a person's
device does. Driving a UI by its elements — clicking a button, typing into a
field — is the `gui` toolbox's work.
```lua
tools.use("inputSim", "key", "KeyW", 1) -- walks the player
tools.use("inputSim", "key", "KeyA", nil, "ui") -- types into the focused field
```
A mouse button is written either way, index or name: `0` / `"left"`,
`1` / `"right"`, `2` / `"middle"` — the same pair `Zin.state.mouseButtonDown`
reads. A pad button is always a canonical position name (`"south"`,
`"dpad_up"`, …), because a pad has no index a player could recognise.
## Where a point is measured from
`mouseMove` and `click` take their point in physical pixels, measured in
the space the input's receiver reads positions in, so `target` decides it.
With `target` `"game"` (the default) the point is in the space `capture`
reports: the scene's own pixels, measured from the top-left of the picture
a capture returns. That is the space `Zin.state.get().mouse_position` reads
a pointer back in and the space `worldToScreen` answers in, so a point read
off any of the three is a point the other two take.
```lua
tools.use("inputSim", "mouseMove", 300, 200)
Zin.state.get().mouse_position -- 300, 200
```
The window can hold the scene inside a rect with editor chrome above and
to the left of it; the offset is those two verbs' to carry, not the
caller's.
With `target` `"ui"` the point is on the window: the space every UI widget
is recorded in, wherever its screen draws (the window itself, or the
picture a Scene panel presents). A widget's `gui.bounds` rect is in logical
points, and times `ui.pixelRatio()` it is the point to aim at:
```lua
local b = tools.use("gui", "bounds", "play-button")
local r = ui.pixelRatio()
tools.use("inputSim", "click", 0, b.centerX * r, b.centerY * r, nil, "ui")
```
`gui.clickElement` does the same by id and refuses a widget the last frame
did not draw where its rect claims, so it is the call for pressing a named
button.
A `macro`'s ops are those same verbs, so an absolute point written for one
is the point the other takes.
`touch`, `touchDown` and `touchMove` place their contact on the window.
`camera.viewData().viewport` states where the scene's rect sits on that
window.
## Keyboard and mouse
| Tool | What it does |
|---|---|
| `key` | Tap a key — down, optional hold, up |
| `keyDown` / `keyUp` | Hold and release |
| `click` | A full click, optionally at a point |
| `mouseDown` / `mouseUp` | Hold and release a button |
| `mouseMove` | Move the cursor to a point; the delta is what look bindings read |
| `mouseMoveBy` | Move the pointer by a motion, over `steps` frames — repeat it to hold a look axis |
| `scroll` | Turn the wheel |
| `lockPointer` | Lock or release the pointer — mouse-look is usually gated on it |
`keyDown` and `mouseDown` hold until something releases them, and a hold
outlives the call that made it — including a driver task that was cancelled
mid-press. `held` says what is down; `release` puts all of it down at once.
## Touch
| Tool | What it does |
|---|---|
| `touch` | A whole tap at a point |
| `touchDown` / `touchMove` / `touchUp` | One finger, by contact id — several at once |
| `stick` | Push the on-screen movement stick |
| `drag` | Drag across the look zone, spread over frames |
| `pinch` | Pinch or spread two fingers |
| `tapButton` | Tap an on-screen button **by the label a player reads** |
`tapButton` aims at the button's real centre and raises when no live button
carries that label, listing the ones that do. That is deliberate: a tap
that silently lands on nothing looks exactly like a control that works.
## Gamepad
| Tool | What it does |
|---|---|
| `pad` / `padOff` | Connect or disconnect a simulated pad |
| `padPress` | Press a button — down, optional hold, up |
| `padDown` / `padUp` | Hold and release |
| `padStick` | Push a thumbstick |
| `padTrigger` | Squeeze a trigger to an analog travel |
Buttons are named by POSITION, never by the letter printed on them:
`south`, `east`, `west`, `north`, `left_shoulder`, `right_shoulder`,
`left_trigger`, `right_trigger`, `left_stick`, `right_stick`, `select`,
`start`, `guide`, `dpad_up`, `dpad_down`, `dpad_left`, `dpad_right`. The
same call works whatever pad is connected.
The name passed to `pad` decides which legends a prompt draws, so
connecting `"Sony DualSense Wireless Controller"` is how a scheme's
PlayStation prompts get checked.
## Reading back
| Tool | What it answers |
|---|---|
| `device` | Which class the session presents as — and forces one |
| `bindings` | Which controls are live, and which map contributed each |
| `layout` | What the on-screen controls are actually drawing |
| `fired` | Which controls were active since last asked, for how many engine frames, and from which device |
| `held` | What the session is holding down right now, across every device |
`layout` is how a phantom control is caught: a label on screen that no
entry in `bindings` explains is a button nothing consumes.
`held` is how a leftover hold is caught: keys, mouse buttons, fingers, the
stick and connected pads in one answer, with `atRest` true when the session
holds nothing. A control that keeps firing after a take ended reads here as
the key that is still down, so recovering from it is a `release` rather than
a guess at what was pressed.
## Replaying a sequence
A run of events worth repeating becomes a `.inputMacro` asset, so the
same sequence drives the same world on every later check.
| Tool | What it does |
|---|---|
| `recordMacro` | Capture real input for `duration` seconds |
| `saveMacro` | Write an event list to a `.inputMacro` asset |
| `macro` | Play an event list back through the input surface |
| `listMacros` | Every `.inputMacro` asset in the project |
An event is `{ t, op, arg }`. `op` names one of the verbs above that drives
input and `arg` carries that verb's arguments — the value itself when the
verb takes one, a table keyed by the verb's parameter names when it takes
several — so every device class a verb reaches is a device class a macro
reaches. A `touchDown` event's `arg.id` is the name its contact goes under,
and the `touchMove` and `touchUp` events carrying that `id` drive it.
```lua
tools.use("inputSim", "macro", {
{ t = 0.0, op = "pad" },
{ t = 0.4, op = "padDown", arg = "south" },
{ t = 0.6, op = "padUp", arg = "south" },
{ t = 0.8, op = "touchDown", arg = { x = 714, y = 984, id = 1 } },
{ t = 1.2, op = "touchUp", arg = 1 },
})
```
`recordMacro` reads what every device is HOLDING each frame — keys, mouse
buttons, pad buttons, the pad itself, fingers on the glass — and what each
one is MEASURING every `sampleInterval` seconds — mouse motion, the wheel,
thumbsticks, triggers, a sliding contact.
`release` is the reset between takes — it lifts every contact, drops the
on-screen stick, releases every held key and mouse button, and disconnects
every connected pad, so one take never leaks a held control into the next.
It reports how many of each it let go, and `held` reads the same set before
or after.
# camera.bindToPlayer
Make the joining player use this camera in play by binding it to the active scene's PlayerPrototype: it re-parents the camera into the prototype subtree (so it is cloned with the player on spawn), sets the prototype's `camera` role to it, and detaches + disables any displaced camera (parked idle, not deleted). Pair it with a static behavior (`@builtin::controller.menu`) for a fixed PS1-style camera the player moves within, or a follow behavior for a tracking one. A player-less scene has no prototype — there the rendering camera is simply the highest-priority one.
# controller.side_scroller
Side-scroller camera controller. Fixed-offset camera that follows a target from the side (classic 2.5D perspective). Maintains a constant position relative to the target and looks slightly ahead.
Public fields: `target`, `centerX`, `centerY`, `centerZ` (fallback), `offsetX`, `offsetY`, `offsetZ` (camera offset from target), `lookAheadX`, `lookAheadY`, `lookAheadZ` (look-at offset from target).
Controls: none — follows the target automatically.
```luau
entity(id).component.add("controller.side_scroller", { target = "player", offsetX = -8, offsetY = 3 })
```
# controller.first_person
First-person camera controller. Positions the camera at an entity's location (+ eye-height offset) and rotates with mouse look.
It resolves its follow target in this order: its own `target` field, then `Camera.follow` when `target` is empty, then the static `posX/posY/posZ` when neither is set. `Camera.follow` is the standard slot every behavior reads, so a first-person camera selected through `Camera.behavior` tracks whatever `Camera.follow` points at — the correct source for a player camera, whose body id is minted fresh per spawned clone and cannot be authored onto the behavior ahead of time.
Public fields: `target` (entity id to follow, empty = use `Camera.follow`, then `posX/Y/Z`), `posX`, `posY`, `posZ`, `offsetX`, `offsetY` (eye height above target origin), `offsetZ`, `sensitivity`, `minPitch`, `maxPitch`.
Controls: pointer lock to rotate (yaw + pitch), which the standard scheme
takes while the world runs. With the cursor handed back, an RMB drag rotates
too — for as long as nothing else in the world binds the right button.
```luau
-- Track the Camera's follow target (set Camera.follow, no id authored here):
entity(id).component.add("controller.first_person", { offsetY = 1.6 })
-- Or a static camera at a fixed position:
entity(id).component.add("controller.first_person", { posX = 0, posY = 1.6, posZ = 3 })
```
# camera.set
Change one or more camera parameters in a single call: `fov`, `near`, `far`, `priority`, `debugChannel`, `renderLayers` (a layer-name spec like `"all !ui"`), `behavior` (a `cameraBehavior`-tagged component), and `follow` (the entity the behavior tracks). Pass no camera to change the active one.
# animation toolbox
Test-play animation clips on skinned bodies. `animation.play` is the quick way
to see a `.animation` clip on a character without authoring a component: it
resolves the clip and the entity, finds the SkinnedModel to drive, plays the
clip through the canonical AnimGraph, and tears everything down when the window
ends.
```lua
animation.play("A_Walk_F_Masc", "hero") -- play once, auto-cleanup
animation.play("Idle", "hero", { offset = "5s" }) -- wait 5s, then play
animation.play("Wave", "hero", { loop = true, duration = 8 }) -- loop for 8s
```
It plays while the world runs (play mode), the same as any component-driven
animation. Durable playback belongs on a `ClipPlayer` component; this tool is for
throwaway testing and leaves no component behind.
On a body that already animates (a ClipPlayer, the character controller) the clip
overrides for the window and the body's own animation resumes untouched
afterwards — the tool reuses the running graph and restores its output on cleanup.
# inputAuthor
Write control schemes whose every control already carries keyboard,
gamepad and touch.
## Why a toolbox for this
A binding must cover all three devices — that rule is what stops a world
shipping playable on a desktop and dead on a phone. A rule like that only
survives if obeying it is cheap; otherwise authors reach for a canonical
name that half-fits, or bind the keyboard and mean to come back.
So the catalog fills in the common controls. Ask for `jump` and get Space,
the south face button, and a lower-right touch button, already complete.
Ask for six controls and get a whole scheme in one call.
```lua
tools.use("inputAuthor", "map", "shooter",
{ "move", "look", "attack", "aim", "reload", "jump" })
```
Where each control lands is a judgement about the device rather than a
translation of the keyboard binding: `sprint` is a stick click on a pad
because that is where a thumb already rests, and a lower-right button on
touch for the same reason. `aim` is a trigger, not a face button.
## Overriding
A control is either a catalog name or a table naming it with overrides:
```lua
tools.use("inputAuthor", "map", "racer", {
"move",
"brake",
-- a sprint, under the name this game calls it
{ name = "boost", from = "sprint", label = "Nitro" },
{ name = "horn", -- unknown: supply all three
kind = "button",
kbm = '{ B.key("KeyH") }',
gamepad = '{ B.padButton("north") }',
touch = '{ B.touchButton({ zone = "right-lower" }) }' },
})
```
`from` is for the common case where a game's control IS a canonical one
under its own name — a racer's boost is a sprint, a shooter's fire is an
attack. It keeps the control named what the game calls it without retyping
three bindings.
A name the catalog does not know, and that does not say what it is based
on, needs all three classes from you. It cannot guess where a control
nobody has named before belongs on a pad or a phone screen, and guessing
would produce exactly the half-right layout this whole model exists to
prevent.
Nothing is written until every control resolves, so a scheme with one
unknown control names it rather than leaving half a map on disk.
## Tools
| Tool | What it does |
|---|---|
| `map` | Write a scheme: the map folder and every control it declares |
| `control` | Add one control to a scheme that already exists |
| `catalog` | List the controls that come pre-filled, and what each is bound to |
| `check` | Report every problem across a scheme's controls, without activating it |
`check` reports all faults at once and activates nothing, so a scheme can
be inspected before a world runs it. To drive the result on each device,
use the `inputSim` toolbox.
# appearance
Change how entities look across a whole hierarchy in one call — hand it a material, a mesh, or a shader and a scope, and it finds the right entities and fields and applies it.
The common situation is that you have a material and a rough idea of where the thing lives, and want the assignment done across the whole subtree at once. Batch-assign a material (by name or ref) to every material field under a scope, swap the mesh on the Model / SkinnedModel entities under a root, or swap a material's shader while preserving its texture links and property values by canonical role.
Targeting is schema-driven: for the material and shader operations, each targeted entity's components are enumerated and every component — builtin or user-authored — that declares a public material asset-ref field participates. The scope is one entity, a list, or the whole scene by default; options can stop at the first match or filter candidates by name pattern. This is the hierarchy-aware assignment layer — creating materials and editing registry-wide properties live on the lower-level `Material` surface, and per-ref edits live on the resolved asset refs themselves.
# wld.play
Enter play mode. First auto-snapshots the current edit state so returning to edit can restore it, then starts scripts and physics so the scene runs live. This is the counterpart to returning to edit — play the scene to see it in motion, then rewind to the pre-play snapshot.
# third_person_follow
Over-the-shoulder camera. The rig hangs off a shoulder pivot beside the follow target and sits back along the heading it looks down, so framing is authored as offsets in space. The offset is measured in the camera's own frame, so the subject holds the same spot on screen whichever way it turns.
The rig owns that heading. Binding a follow target aims it along the subject's facing, and look input turns it from there — the subject's facing is never read again. That is what makes the camera steerable for a character who turns to face where it is walking: hold "forward" and the character walks the line the camera looks down, instead of chasing a heading that moves as it turns.
The facing a bind reads comes from the body's own declaration of which way it faces (`Locomotion.forward`), so the rig lands behind a `+Z`-forward Synty body and a `-Z`-forward glTF body alike. A target that declares nothing falls back to its transform forward.
Public fields: `follow`, `shoulderOffset` (x across the frame, y up it, z along the heading), `verticalArmLength`, `cameraSide` (0 = left shoulder, 1 = right), `cameraDistance`, `minDistance`, `maxDistance`, `aimYaw` (the world heading the camera looks along, in radians about +Y from world +Z) and `aimPitch` (how far it tilts off level), `damping` (per-axis time constants in seconds), `cameraRadius` (radius of the pull-in sweep; `0` turns the pull-in off), `cameraIgnore` (entities whose colliders the pull-in passes through), `sensitivity`, `invertY` (off by default: pushing the mouse forward looks UP; on pitches the other way), `zoomSpeed`, `minPitch`, `maxPitch`.
Writing any framing field re-poses the rig immediately with damping bypassed, so edit mode shows the framing play mode will produce.
`follow` falls back to the `Camera.follow` slot when it is empty, so a rig selected through `Camera.behavior` tracks whatever that camera already follows.
Controls: mouse to look (play mode requests pointer lock, so no button is held), scroll to adjust `cameraDistance`.
## The control scheme
`inputMap` is the scheme the rig answers to. It reads two controls from it, each on its own:
- `look` — turns `aimYaw` and `aimPitch`.
- `zoom` — steps `cameraDistance`.
A map declaring only one of the two gives the rig that one and keeps the other where it is; the rig logs which control the map left out, and names the map. A field naming no map leaves the rig answering nothing, and logs that too. Point `inputMap` at a world's own map to rebind looking and zooming without touching this component.
**Repointing it on a live rig takes on the next frame.** The map the rig was holding is stood down — its controls leave the live set and its touch buttons leave the screen — and the map named here is taken up in its place:
```luau
entity(rigId).component.get("third_person_follow").inputMap = asset.resolve("mygame.input.cinema", "inputMap")
```
Assigning the map the rig already holds changes nothing, so re-stating the scheme leaves the live set where it is. While gameplay is paused the rig holds no map at all — the editor's camera has the controls — and it takes whatever `inputMap` names when play resumes.
```luau
local cam = entity(id).component.get("Camera")
cam.behavior = asset.ref("@builtin::controller.third_person_follow", "component")
entity(id).component.get("controller.third_person_follow").cameraDistance = 3
```
## The camera pulls in when a collider is in the way
Each frame the rig sweeps a sphere of `cameraRadius` from the point it aims at out to where its framing puts the camera, and stands the camera where the sphere first meets a collider. Every collider in the world stops that sweep, whether or not anything draws it: an invisible walk bound (a `BoxCollider` with no `Model`), a trigger volume and a solid wall all pull the camera in alike. The follow subject is the one entity the sweep passes by default.
So a camera that snaps in close to the player, or collapses onto it, while nothing visible stands behind the player is meeting a collider nobody can see. Two fields settle it:
- `cameraIgnore` lists the entities whose colliders the camera sees through. Name the walk bounds and gameplay volumes there and the sweep passes them as it passes the subject, while walls the player can see still pull the camera in. Each entry is an entity (or its id), and it is the collider's own entity that is listed.
- `cameraRadius = 0` turns the pull-in off: the camera stands where its framing puts it, through every collider.
```luau
local rig = entity(camId).component.get("controller.third_person_follow")
rig.cameraIgnore = { entity.find("NorthBound"), entity.find("SouthBound") }
-- or drop the pull-in entirely
rig.cameraRadius = 0
```
## Attach through `Camera.behavior`
The Camera owns the behavior slot, so assigning the rig there is what lets the Camera tell it when `follow` changes. A rig added straight onto the entity with `component.add` still poses, but the Camera does not know about it and a `follow` assigned afterwards will not reach it.
Assigning the slot attaches the rig to the camera's entity, so it is tuned on that instance: `component.get("third_person_follow")` and set its fields. A `component.add("third_person_follow", { ... })` after the assignment, in a scene `build.luau` or anywhere else, writes its values onto the instance the slot attached and returns it, so the Camera keeps the one rig it knows about. In a `build.luau` that add is the way to tune the rig: its values are saved with the scene and the loaded rig holds them.
## Player cameras: leave `follow` unset
Entering play drops and respawns `PlayerPrototype` subtrees, so the body is recreated with a NEW entity id. A `follow` authored on the rig keeps pointing at the original, which is no longer live, and the camera freezes at its last pose instead of tracking the player.
For a player camera, set the target on the **Camera** and leave the rig's own `follow` empty:
```luau
entity(rigId).component.get("Camera").follow = body -- PlayerPrototype rebinds this on every spawn
```
`PlayerPrototype` refreshes `Camera.follow` to the live body each time it clones, and the rig reads that slot whenever its own `follow` is empty. Set the rig's `follow` only for a camera that watches a fixed, non-respawning subject.
# PlayerSpawn
A world entity that spawns players from a prototype. It carries the fields describing how spawning happens: which `prototype` to instantiate, the `team` and `role` assigned to spawned players, a `maxPlayers` cap (0 = unbounded), the `spawnPolicy` (how many players spawn from this point), and the `placement` (where a spawned player is positioned). The entity's own transform is the spawn point when `placement` is `at_spawn_transform`. In edit mode it draws an orange silhouette outline at the spawn point and surfaces its own setup-validation messages (missing or mis-targeted prototype) on the component's error channel.
Location: `src/lua/lib/components/PlayerSpawn.component`
# camera.lookAt
Aim a camera at a world position or at another entity. Pass a single target to aim the active camera, or a camera plus a target to aim a specific one.
# topics/input guide
Reference docs surfaced through `guides { path: "..." }` and `man topics/input`.
The content lives in `guide.md`; this README is just the asset summary.
# camera.frame
Position and aim a camera to frame a target entity in one step: place the camera at a distance from the target on a yaw/pitch angle, then look at it.
# zinput
zinput is the engine's Luau-side input framework and the **only** public
Luau input API. It sits on top of the internal `__zero_input.*` FFI
(snapshot, events, frameId, pointer-lock, simulate\*) and builds the
control model above it in pure Luau: control assets grouped into maps, the
live set of activated maps and its per-frame dispatch, per-device-class
binding evaluation, the on-screen touch overlay, gesture recognisers, and
the tick coordinator that advances all of it.
The top-level module re-exports every submodule under a single table and
owns the tick coordinator (`Zin.tick`) plus the unified handle namespace
for `Zin.disconnect`.
## The control model
A control is a `<name>.inputBinding/` folder inside a `<name>.inputMap/`
folder. It carries a `label`, a `kind` (`button` / `axis1` / `axis2`), and
a binding for each of the three device classes — `kbm`, `gamepad`, `touch`.
A class set to `false` is a deliberate refusal.
Nothing is live until something activates a map. A world activates the map
it needs and subscribes to the controls it uses:
```luau
public = {
inputMap = Field.assetRef("inputMap", "@builtin::inputMaps.default", NoSync, "The controls this component reads."),
speed = Field.number(5, NoSync, "World units per second at full deflection."),
jumps = Field.number(0, NoSync, "How many times the jump control was pressed."),
}
local controls
function awake()
controls = public.inputMap:activate()
controls.move:onInput(function(v, dt, active)
if not active then return end
local p = public.entity.position
local step = public.speed * dt
public.entity.position = { p.x + v.x * step, p.y, p.z - v.y * step }
end)
controls.jump:onPressed(function() public.jumps += 1 end)
end
function onDestroy()
public.inputMap:deactivate(controls)
end
```
What `activate` returned is this holder's claim on the map, and handing it
back to `deactivate` disconnects the subscriptions made through it while
the map stays live for whoever else holds it. Every activation reads the
map's binding children again, so a control edited since it came up reaches
the running set and the holders already standing on it.
Several maps are live at once and compose: the player's surface is the
union of them, so picking up a gun adds Fire beside the movement stick and
dropping it takes away Fire alone. A map declares the `group` its controls
belong to and the groups it `suppresses` while live, which is how a car
stands walking down without owning the walk map. `Zin.scheme` holds the
live set and runs the dispatch.
`man topics/input` is the full walkthrough.
## Exports
Subsystems (re-exported from the corresponding submodule):
- `M.scheme` — the live set of activated maps and their per-frame dispatch.
- `M.bindings` — binding constructors, evaluators, and the legend formatter.
- `M.state` — per-frame snapshot reads plus held-time and synthetic repeat.
- `M.events` — frame-event readers and `on`/`off` edge subscriptions.
- `M.input` — `onBegan` / `onEnded` / `onChanged` / `onTextInput` listeners
and `lastInputType()`.
- `M.context` — the input context stack.
- `M.chords` — sequence and simultaneous recognisers.
- `M.gestures` — tap / double-tap / long-press / swipe / pinch / pan
recognisers.
- `M.touch` — per-finger contacts and `touch.*` listeners.
- `M.surface` — touch-vs-kbm device-class classification.
- `M.gamepad` — connected pads, family, and button legends.
- `M.virtual` — the per-tick virtual-control store on-screen controls write.
- `M.touchControls` — the on-screen touch overlay (stick, drag-look zone,
buttons) and the API that adds a control while a world runs.
- `M.emulation` — the map-driven key-emulation floor.
- `M.pointer` — pointer-lock mutations.
- `M.back`: Back, claims a world holds while Back means something to it,
and `press` to issue one. The engine routes each press to the topmost
dismissible overlay, else the most recent claim, else the platform's own
default (an Android app moves to the background).
- `M.test` — synchronous test-input helpers.
- `M.controllers` — `free` / `orbit` / `fps` controller factories.
- `M.profile` — binding profiles, saved as JSON and loadable from
`@builtin::profiles.<name>`.
- `M.rebind` — interactive binding-capture sessions.
- `M.conflicts` — the binding-collision reverse index.
- `M.autoTick` — the opt-in per-frame tick worker.
- `M.utils` — pure helpers.
- `M.actions` / `M.axes` / `M.map` — the name-registered action, axis and
map registry. A control asset replaced them; each carries its own
`--!deprecated` message naming the replacement.
Tick coordinator:
- `M.tick(dt: number?)` — advance every stateful subsystem.
- `M.lastTickAt() -> number` / `M.lastTickFrameId() -> number` — test/debug accessors.
- `M._resetTickGuard()` / `M._resetLiveArmed()` — test-only.
Handles:
- `M.disconnect(handle: number) -> boolean` — accepts any Zin handle (input listener OR action handler) and routes to the right `disconnect`.
Constants:
- `M.VERSION` — the library version string.
- `M.SPEC` — the VFS path of the architecture spec.
- `M.ROADMAP` — the VFS path of the roadmap document.
## Raw state
`Zin.state` and `Zin.events` are the snapshot and event layer that
bindings evaluate against — the layer the emulation floor, rebind capture,
and dev tooling operate on directly. Gameplay code subscribes to controls;
polling `Zin.state.keyDown` from a world makes that world keyboard-only and
draws the `engine-raw-key-poll` diagnostic at author time.
## Notes
- `Zin.tick(dt)` is the single hub that advances every stateful subsystem
each frame. Stateless features (state / events / utils / bindings /
context) work without ticking; the live binding dispatch, axes, chords,
subscriptions, held-time, repeat, and rebind are dormant until something
ticks.
- The first real input read arms the input system on its own: it starts
`Zin.autoTick`, so dispatch, the touch overlay and the emulation floor
advance with no host component and no explicit tick call. A host script
component can still call `Zin.tick(dt)` from its `update(dt)` hook, and
`Zin.autoTick.start()` remains available directly; both stay idempotent
alongside the self-arming path. `Zin.test` engagement suppresses the
arming so suites keep explicit control over tick cadence.
- Same-frame re-tick dedup: `__zero_input.events()` is non-draining, so
running the observe-and-dispatch pipeline twice in one engine frame would
double-fire subscribers. The frame-id guard in `M.tick` and the autoTick
worker keeps this from happening.
- The handle namespace is unified: every handle from `Zin.input.on*` and
`Zin.actions.bind` is drawn from a single counter, and `Zin.disconnect`
routes any of them to the correct `disconnect`. `Zin.input.disconnect`
and `Zin.actions.disconnect` are also wired to the unified dispatcher.
- Library users can either grab the whole table
(`require("@builtin::modules.zinput")`) or pull one submodule
(`require("@builtin::modules.zinput.state")`).
- `__zero_input` is an internal namespace — reachable from Luau but hidden
from `/docs/api/`; production game code goes through Zin.
# orbital_follow
Three-ring orbit camera. Framing is authored as three rings around the follow target — a bottom, a centre and a top, each with a `height` above the target's origin and a `radius` out from its axis. Vertical look slides the camera along the spline through those rings; horizontal look orbits around them. The shape of the orbit is geometry you can see and edit rather than a pair of pitch limits you cannot.
Public fields: `follow`, `ringBottom` / `ringCenter` / `ringTop` (each `{ height, radius }`), `verticalAxis` (0 at the bottom ring, 1 at the top), `horizontalAxis` (the world heading the camera looks along, in radians about +Y from world +Z), `radiusScale`, `aimHeight` (the aim point above the target's origin), `damping` (per-axis time constants in seconds), `cameraRadius` (radius of the pull-in sweep; `0` turns the pull-in off), `cameraIgnore` (entities whose colliders the pull-in passes through), `sensitivity`, `invertY` (off by default: pushing the mouse forward looks UP, drawing the camera toward the bottom ring; on pitches the other way), `zoomSpeed`, `minRadiusScale`, `maxRadiusScale`.
The rig owns that heading. Binding a follow target aims it along the subject's facing, so the shot opens from behind whoever the camera is told to follow, and look input turns it from there — the subject's facing is never read again. That is what makes the camera steerable for a character who turns to face where it is walking: hold "forward" and the character walks the line the camera looks down, instead of chasing a heading that moves as it turns.
The default rings frame a roughly 1.8 m humanoid standing at its origin: the centre ring sits above head height at the widest radius for a resting shot from behind and slightly above, the bottom ring drops to knee height and pulls in to look up, and the top ring climbs and tightens for a near-overhead look down.
Writing any framing field re-poses the rig immediately with damping bypassed, so editing a ring moves the camera to the shot that ring describes.
`follow` falls back to the `Camera.follow` slot when it is empty, so a rig selected through `Camera.behavior` tracks whatever that camera already follows.
Controls: mouse to orbit and to slide along the rings (play mode requests pointer lock, so no button is held), scroll to scale the ring radii.
```luau
local cam = entity(id).component.get("Camera")
cam.behavior = asset.ref("@builtin::controller.orbital_follow", "component")
entity(id).component.get("controller.orbital_follow").ringCenter = { height = 2.6, radius = 6 }
```
## The camera pulls in when a collider is in the way
Each frame the rig sweeps a sphere of `cameraRadius` from the point it aims at out to where its framing puts the camera, and stands the camera where the sphere first meets a collider. Every collider in the world stops that sweep, whether or not anything draws it: an invisible walk bound (a `BoxCollider` with no `Model`), a trigger volume and a solid wall all pull the camera in alike. The follow subject is the one entity the sweep passes by default.
So a camera that snaps in close to the player, or collapses onto it, while nothing visible stands behind the player is meeting a collider nobody can see. Two fields settle it:
- `cameraIgnore` lists the entities whose colliders the camera sees through. Name the walk bounds and gameplay volumes there and the sweep passes them as it passes the subject, while walls the player can see still pull the camera in. Each entry is an entity (or its id), and it is the collider's own entity that is listed.
- `cameraRadius = 0` turns the pull-in off: the camera stands where its framing puts it, through every collider.
```luau
local rig = entity(camId).component.get("controller.orbital_follow")
rig.cameraIgnore = { entity.find("NorthBound"), entity.find("SouthBound") }
-- or drop the pull-in entirely
rig.cameraRadius = 0
```
## Attach through `Camera.behavior`
The Camera owns the behavior slot, so assigning the rig there is what lets the Camera tell it when `follow` changes. A rig added straight onto the entity with `component.add` still poses, but the Camera does not know about it and a `follow` assigned afterwards will not reach it.
## Player cameras: leave `follow` unset
Entering play drops and respawns `PlayerPrototype` subtrees, so the body is recreated with a NEW entity id. A `follow` authored on the rig keeps pointing at the original, which is no longer live, and the camera freezes at its last pose instead of tracking the player.
For a player camera, set the target on the **Camera** and leave the rig's own `follow` empty:
```luau
entity(rigId).component.get("Camera").follow = body -- PlayerPrototype rebinds this on every spawn
```
`PlayerPrototype` refreshes `Camera.follow` to the live body each time it clones, and the rig reads that slot whenever its own `follow` is empty. Set the rig's `follow` only for a camera that watches a fixed, non-respawning subject.
# Component (asset type)
A component is a reusable behavior + data unit attached to an entity.
The component file declares public fields, methods, and lifecycle
callbacks; the engine instantiates one per attachment and drives its
hooks every frame. Components are the primary unit of gameplay code —
movement, AI, animations, UI panels, network sync, and per-entity state
all live here.
## When to use one
- You need per-entity state that survives across frames.
- You need per-entity behavior driven by engine lifecycle hooks
(`start`, `update`, `destroy`).
- You want to expose configurable fields to designers / `entity.spawn`
callers / scenes without code changes.
If you need a global service that outlives any entity, use a `.service`
instead. If you need a stateless pure-function library, use a `.module`.
## Where it lives
- Source: `/zero/source/.../<Name>.component/`
- Identity: `<Name>` (the `.component` suffix strips from the
identity, but the folder retains the suffix on disk).
- Folder shape:
- `init.luau` (or `init.lua`) — declares the component. **Required.**
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
The structural contract is enforced by `asset.validate` against this
type's `type.yaml`.
## How to create one
Always start with the scaffold — it guarantees the folder shape
matches `type.yaml` from the moment it's on disk:
```luau
asset.create("component", "<Name>")
-- Creates: /zero/source/<Name>.component/
-- init.luau (canonical declare + public block + hooks stubbed)
-- README.md (instance README template)
```
After scaffolding, edit `init.luau` to fill in the actual fields and
behaviour. The component registers as soon as the file is written —
hot-reload is automatic; no engine restart required.
## How it operates
1. **Registration.** Writing `init.luau` into a `.component/` folder
indexes the asset, mints a guid (in the `.meta` sidecar), and
surfaces the type to the engine's component registry. Same-frame
visible to `entity.component.add`.
2. **Attachment.** `entity(id).component.add(name, data)` (or the
batch form `tools.use("entityOps", "addComponents", targets,
{ [name] = data })`) attaches an instance.
The `data` table's fields override the component's declared
defaults; omitted fields take the declared default. The `data`
values are copied into `public.*` BEFORE `awake()` runs.
3. **Lifecycle.** The hooks run in this order:
- `awake()` — same frame as attach, immediately after the data
copy. Initialise state, set up native bridges, register with
other systems. Other components on the same entity may not have
awoken yet.
- `start()` — the next frame. Every component on the entity has
completed `awake()` by then, so cross-component setup is safe
here.
- `update(dt)` — same frame as `start()`, then every frame after,
for as long as the gameplay clock is running. `fixedUpdate(dt)`
runs beside it on the fixed timestep; `editorUpdate(dt)` runs
while the clock is held. Which of them ticks is decided by
`engine.mode` AND `engine.paused` together — see **Per-frame
hooks and the two axes** below, and `man modes`.
- `onDestroy()` — when the component is removed via
`component.remove` or when the owning entity is despawned.
Release resources, drop native ECS components.
For the full list (`onEnable`, `onDisable`, `fixedUpdate`,
`editorUpdate`, `onPropertyChanged`, `onAssetReload`,
`onModuleReload`,
`onBeforeSave`, …) and the timing details, **read `man components`
— that is the canonical lifecycle reference. Generic component
patterns (declare blocks, public fields, sync, ECS bindings,
typed methods) all live there.**
4. **Public surface.** Fields declared in `public` are inspectable,
editable in the inspector, and persist with the entity. Methods are
declared on that same table with a colon —
`typed function public:method(args)` — and every one of them takes
the component ref as `self`, so a caller invokes it with a colon
too: `entity(id).component.get(name):method(args)`. That is the one
calling convention a component ref answers to: the reflection
methods `ref:fields()` / `ref:getField(name)` /
`ref:setField(name, value)` take the same spelling. A function the
chunk declares at file scope (`function helper()`) is the
component's own, reachable from its hooks under its bare name;
`public` is what the ref carries.
5. **Settings and the Inspector card.** `type.yaml` names the component's
settings schema as `settings: { schema: { instance: "init.luau",
export: "public" } }`: the `public` table IS the schema, and its values
live on each entity the component is on, so `asset.schema(componentRef)`
answers the Field descriptors and no values file exists. On an entity
the Inspector shows the component as a card whose generic `settings`
section edits those fields as typed controls, each edit checked against
the schema and written to the live component as one undoable operation.
`type.yaml` also names `inspector: { instance: "inspector.luau" }`: a
component that ships an `inspector.luau` beside its `init.luau` shapes
its card — the file returns `{ sections, replace, order }` (see
`assetTypes/README.md`, "`inspector:`"), each section's `build(ctx)`
reading `ctx.component` (the live component) and `ctx.selection.id` (the
entity). `SceneModule.component/inspector.luau` replaces `settings` with
the bound module's declared inputs.
6. **Events.** An `events` block declares typed moments the component
fires from inside — `events = { onHit = Event({ dmg =
Field.number(0, NoSync) }) }`. The owner fires with
`events.onHit:fire({ dmg = 10 })`; outside code subscribes through
the proxy's subscribe-only facade,
`entity(id).component.get(name).events.onHit:connect(fn)`
(`:once` / `:wait` too). Pass `Sync` as the event's second argument
to replicate a fire to other peers. Events let one component react
to another's moments without polling. Full reference: **`man
components`**, Events section.
7. **Hot reload.** Editing `init.luau` reloads the component
definition; live instances are reconciled with the new declaration
in-place, and each crosses one lifecycle boundary: `onDestroy()`
ends the running life, then `awake()` and `start()` construct the
one that replaces it, and `update()` resumes on the next frame.
`public` and `private` values carry across; module-level `local`s
belong to the chunk, so the new life starts with them at their
initial values and its `awake`/`start` are what fill them in.
Whatever the old life handed elsewhere — a subscription, a shared
registration, a spawned entity — is released in `onDestroy`, the
call that pairs with the construction about to run. An edit that
leaves the source byte-identical crosses no boundary at all.
A field carries its value across when something stated it: a key of
the `data` table the instance was attached with (a scene record's
data is that table), or a write made since. Every other field takes
the edited source's declared default, so changing a default reaches
every instance that left the field to it. An instance that states
its own value for a field whose default the edit changed keeps that
value, and the reload logs a `[HotReload]` warning naming the field,
the entity, the value kept and both defaults.
## Discovery
- `asset.list("component")` — every registered component (engine +
world + libraries).
- `asset.inspect("<name>")` — identity, scope, public fields,
lifecycle methods, source path, and this type README. `detail`
carries the component's declared `fields`, `methods`, and `events`,
parsed from its source — `tools.use("assets","describe", "<name>")`
renders it as markdown, so a component's events are visible without
opening its source.
- `ls /zero/source/<Name>.component` lists the files the folder holds.
- `entity(id).component.list()` — components attached to an entity.
## Per-frame hooks and the two axes
`engine.mode` (`"edit"` / `"play"`) and `engine.paused` (the gameplay
clock) are independent, and the per-frame hooks read them separately:
- `update(dt)` / `fixedUpdate(dt)` tick while **the gameplay clock is
running** — whichever mode the engine is in.
- `editorUpdate(dt)` ticks while **the clock is held** — because the
mode is `edit`, or because play is paused — and also alongside
`update` whenever edit is running.
Which gives four states, and this table is the contract:
| `engine.mode` | `engine.paused` | hooks that tick |
|---|---|---|
| `edit` | `true` | `editorUpdate` |
| `edit` | `false` | `update`, `fixedUpdate`, `editorUpdate` |
| `play` | `false` | `update`, `fixedUpdate` |
| `play` | `true` | `editorUpdate` |
Entering edit sets `paused = true` and entering play sets it back to
`false`, so a session that never writes `engine.paused` only ever sees
rows 1 and 3 — which is where the shorthand "`update` is the play tick,
`editorUpdate` is the edit tick" comes from. It is the two default rows
of a four-row table, not the rule.
**Row 2 is the one that surprises.** With `engine.paused = false` in
edit — set by hand, or by a tool that advances the gameplay clock to
sample it, such as a `capture.collage` given a `duration` — `update` and `editorUpdate`
both fire, once each, every frame. A component that declares both and
routes them to one body therefore runs that body **twice per frame**:
```luau
local function drive(dt) ... end
function update(dt) drive(dt) end
function editorUpdate(dt) drive(dt) end -- twice per frame in row 2
```
Nothing reports the doubling; it reads as an animation running at twice
its intended speed. To get exactly one tick per frame in every row, ask
which axis you meant and answer it in the body:
```luau
function update(dt) drive(dt) end
function editorUpdate(dt) if engine.paused then drive(dt) end end
```
A scene `entrypoint.luau` declaring the same two hook names is dispatched
by the scene loader, not by this table: there `update` needs play AND
running, `editorUpdate` needs edit, and play-paused ticks neither. Read
`man scenes` before carrying a component's rule to an entrypoint.
## Authoring conventions
- Annotate public fields with `--!desc` so the inspector + LSP show
documentation alongside the field name.
- Declare lifecycle hooks (`start`, `update`, `destroy`) explicitly
rather than relying on engine defaults — readers can see at a glance
what runs when.
- Keep `update(dt)` cheap — it runs every frame per instance. Move
heavy work to `start`, to a service, or behind a job (`man jobs`).
- For multi-entity batching, prefer
`tools.use("entityOps", "addComponents", targets, components)` over
a loop of `entity(id).component.add` — it takes many targets and
many components in one call.
## Common pitfalls
- **Naming.** The component identity is the folder stem with
`.component` stripped (e.g. `<Spinner>.component/` → identity
`Spinner`). Don't repeat the suffix in the identity passed to
`component.add`.
- **`init.lua` vs `init.luau`.** Either is accepted (it's a
`one_of_group: "entrypoint"`), but `.luau` is canonical. Mixing both
in one folder is invalid.
- **`update` in edit mode.** It runs whenever the gameplay clock is
running, and entering edit stops that clock — so `update` is idle in
a freshly-entered edit session and ticks again the moment anything
sets `engine.paused = false`. Use `tools.use("wld", "play")` to test
update logic under the mode it ships in; `tools.use("wld", "edit")`
to return. See **Per-frame hooks and the two axes** above.
- **Renaming.** Renaming the folder changes the identity. Update
every `component.add(<oldname>, ...)` call and the scene JSON
entries that reference it.
## Related types
- `.module` — pure-function library, no per-entity state.
- `.service` — globally-scoped behavior, no per-entity state.
- `.preset` — a captured component configuration, replayable into
`component.add` without re-typing fields.
- `.bundle` — entity hierarchies that may carry component attachments
as part of the bundle.
## In the Inspector
Fields: its execution order, hooks, and how many methods and events it declares, then the fields its `public` table declares as read-only typed controls holding their defaults, with **Check** and **Open** for its entry file. Instances: a link to every entity carrying it. What its card shows on an entity comes from the component's own `inspector.luau`.
# guide
A guide is a single-file documentation asset: a `<name>.guide/` folder whose body is `guide.md`, surfaced through the `guides` MCP tool, the `man` shell builtin and the Docs panel. Drop one anywhere under `/zero/source/`, a `.package` included, and it shows beside the built-in guides.
## In the Inspector
Guide: the guide's word count, its headings, and **Open in Docs**, which opens it in the Docs panel.
# camera.create
Spawn a new camera entity at a position, with any starting parameters — fov, near/far, priority, render layers, a follow target, a behavior, a look-at, or a render-to-texture setup — in one call. The scene's primary camera comes from the PlayerPrototype; use this for additional cameras (a security view, a cutscene angle, a render-texture feed). Returns the new camera's full parameter record.
# camera.get
The full parameter record for one camera — position, rotation, fov, near, far, priority, render-layer spec, debug channel, render target, behavior, and follow — plus whether it is the active and/or player camera. Defaults to the active/main camera when none is named.
# camera.list
Every camera in the scene, enumerated from the live ECS so a just-spawned, hidden, or runtime camera is never missed, sorted by descending priority. Each row marks whether it is the on-screen (`active`) camera, whether it is the `player` camera (the one the PlayerPrototype uses), and its main/editor role.
# camera shared
Cross-tool helpers for the `camera` toolbox — camera resolution (by name/id/proxy, defaulting to the active camera), live-ECS camera enumeration, the parameter snapshot every tool reads or returns, PlayerPrototype and prototype-camera lookup, and flexible position parsing. Referenced only by the `camera` toolbox's own tools.
# Toolbox (asset type)
A toolbox is a namespace folder that groups related `.tool/` children
plus shared helpers. Toolboxes are the addressing layer for tools —
every tool's identity is `<toolbox>.<name>`, so the toolbox name
appears in every callsite. Toolboxes also own a `shared.module/`
helper module that the toolbox's tools `require(".shared")` for
common utilities (result envelopes, validators, formatters).
## When to use one
- You have two or more related tools that belong together (an `anim`
toolbox with `play` / `stop` / `list`; an `assets` toolbox with
`compose` / `validate`).
- You need a shared helper module exclusively used by a tool set.
- You want a clean dot-namespaced identity for your tools
(`my_tools.foo`, `my_tools.bar`).
If you only have one tool and no shared helpers, you still need a
toolbox — it's the required parent.
## Where it lives
- Source: `/zero/source/.../<Name>.toolbox/`
- Identity: `<Name>` (the `.toolbox` suffix strips).
- Folder shape (container-style — open child set):
- `README.md` — instance documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
- `shared.module/` — optional shared helper module
(`init.luau` + `README.md`).
- `<x>.tool/` — any number of `.tool/` children.
The validator permits unlisted children (`allow_unlisted: true`) so
tool subfolders don't need to be declared per-name.
## How to create one
```luau
tools.createToolbox({ name = "<Name>", description = "..." })
-- or the generic scaffold:
asset.create("toolbox", "<Name>")
-- Creates: /zero/source/<Name>.toolbox/
-- README.md (instance README template)
-- shared.module/ (ok / fail result-envelope constructors)
-- `folder` places it in a subfolder of /source; `into` nests it in a
-- resolved `.package`:
asset.create("toolbox", "<Name>", { folder = "tools" })
```
Then add tools under it:
```luau
local box = asset.resolve("<Name>.toolbox")
asset.create("tool", "<toolName>", { into = box })
```
## How it operates
1. **Registration.** Writing into a `.toolbox/` folder indexes the
toolbox. It becomes the parent namespace for any `.tool/`
children.
2. **Tool identity composition.** Each child `.tool/`'s identity is
`<toolbox>.<tool>`. Listing the toolbox's tools enumerates the
children.
3. **Shared helpers.** Tools inside the toolbox pull
`shared.module/` in via `require(".shared")` (relative require
from the tool's `init.luau`).
4. **Hot reload.** Editing `shared.module/init.luau` reloads every
tool in the toolbox (they all `require` it). Editing the toolbox
folder structure (adding / removing tools) reflects in
`tools.list` immediately.
## Discovery
- `asset.list("toolbox")` — every registered toolbox.
- `asset.inspect("<name>")` — child tools, source, this type
README.
- `ls /zero/source/<Name>.toolbox` lists the files the folder holds.
- `tools.list()` — every tool across every toolbox.
## Authoring conventions
- **Per-tool implementation lives in each `<x>.tool/init.luau`.**
The tool's full function body — argument validation, the call
into engine APIs, the return value — goes in `init.luau` with
`--!desc` / `--!arg` / `--!return` / `--!example` annotations
above the function. **Every exported function is declared
`typed function`** — the keyword compiles to the runtime argument
check, so a plain `function` accepts any input and reports success
on garbage. Do NOT make `init.luau` a one-line forwarder onto a
function defined in `shared.module/`.
- Keep `shared.module/` thin: result envelope constructors
(`shared.ok(value, formatted)`, `shared.fail(message, exitCode)`),
argument validators, common formatters — anything genuinely used
by more than one tool. Per-tool logic does NOT belong here.
- Group by domain, not by surface — `assets` toolbox holds asset
operations, `entity` toolbox holds entity operations. Tools that
feel unrelated probably want different toolboxes.
- Document the toolbox's surface in `README.md` — what problem space
it covers, who calls into it, any shared invariants.
## Common pitfalls
- **Missing parent toolbox.** Tools cannot exist outside a toolbox.
Always scaffold the toolbox first.
- **Cross-toolbox shared.** Each toolbox has its own
`shared.module/`. Don't try to share helpers across toolboxes; if
you need cross-toolbox helpers, factor them into a standalone
`.module`.
- **Toolbox identity.** Strip the `.toolbox` suffix in identity
references (`my_tools`, not `my_tools.toolbox`).
## Related types
- `.tool` — the required child(ren) of a toolbox.
- `.module` — for cross-toolbox utilities.
## In the Inspector
Tools: how many tools the box holds, whether it ships a shared module, what each tool does, and a link to each tool.
# capture.cleanup
Clears every file from the capture output directory, removing the PNGs left behind by earlier captures. Safe to call when the directory is missing or already empty.
# collage
A grid of frames in one image.
One picture that answers a question no single frame can: what does this look like
from every side, what does this frame look like under each diagnostic pass, what
moved over the last three seconds, which of these twenty shots is the shot.
## The axis is always stated
A collage varies one thing across its cells, and the argument you pass is what
that thing is:
| Argument | One cell per |
|----------|--------------|
| `setups` | whole camera set-up — a shot list, each entry aimed the way a single capture is |
| `viewpoints` | named view of one subject — a list, `"front top left"`, or `"sides"` for all six |
| `passes` | render pass — `final`, `albedo`, `normal`, `depth`, `motion_vectors`, or any content-registered capture view |
| `duration` | sample, spread across that many seconds of gameplay |
`setups` and `viewpoints` are one axis — both say where the camera stands — so a
request names one of them.
Naming a station axis **and** `passes` lays out a 2D grid: a row per station, a
column per pass. Reading across a row is one set-up under every pass; reading
down a column is one pass from every set-up.
A collage with no axis is refused, naming all of them. It does not fall back to
time — a silent time default is exactly what taught callers that a collage could
only ever be time, so nobody looked for a grid of views.
`duration` cannot combine with `setups`, `viewpoints` or `passes`. A cell that
differs both in what it looks at and in when it was taken answers neither
question; take one collage per axis.
## The shot list
Each entry of `setups` is written the way a single capture is aimed — `source`,
`camera`, `entity`/`entities`, `position`, `lookAt`, `rotation`, `distance`,
`angle`, `margin`, `viewpoint`, `basis`, `projection`, `orthoHeight`, `fov`,
`near`, `far` — plus `label` to name the shot on the result. A field an entry
leaves out comes from the collage's own options, so a shot list writes down only
what makes each shot differ:
```lua
zero capture collage --setups '[
{ "position": [-14.6, 1.35, 4.5], "lookAt": [-16.3, 1.1, 1.6], "fov": 28, "label": "doorway" },
{ "position": [8, 3, 12], "lookAt": [0, 1, 0], "fov": 50, "label": "wide" },
{ "entity": "hero", "viewpoint": "front", "basis": "local", "label": "closeup" }
]'
```
Three stations, three lenses, three subjects, one instant, one picture — which is
the comparison a framing pass is made of. A key outside that vocabulary is
refused where it was written, so a misspelled `fov` names itself instead of
quietly framing a shot nobody asked for.
## Reading the result
The grid shape is worked out from the number of cells — pass `grid` (`"3x2"`) to
state it, and it is an error rather than a silent crop if it cannot hold them.
Every cell comes back labelled in `cells`, with its `label`, the `viewpoint`
and/or `pass` that made it differ, the `eye` it was rendered from and the lens it
was rendered through. A grid is meant to be readable from the response, not
guessable from the pictures. Only a time collage reports the window it covered —
a station or pass grid samples one instant, and reporting a span for it would
invite reading the difference between cells as motion.
## Aiming it
Exactly as a single capture is aimed: `entity` (with `viewpoint` and `basis`, or
`angle` and `distance`), `position` with `lookAt`, `camera`, or nothing at all
for the main scene camera. `projection`, `orthoHeight`, `isolate`,
`renderLayers`, `fov`, `width` and `height` all mean what they mean for one
frame, and apply to every cell a set-up of its own does not override.
The shot most of this exists for is one call:
```lua
zero capture collage --entity crate --viewpoints sides --basis local \
--projection orthographic --isolate
```
Six sides of one object, each an orthographic elevation, nothing else in frame.
# feed
The newest frame a capture produced on this engine, and who is watching for it.
Every capture core publishes here. `latest()` is that frame: a `src` an image
widget draws (the render target's guid while the engine still holds it, the
written path when the capture produced a file), with the size, the source and
the pass beside it. `watch(fn)` calls `fn` as each new frame arrives, and
`unwatch(token)` drops the subscription.
`shown()` says a viewer is drawing frames from the feed. From then on the feed
holds the newest capture's render target so the picture stays up after the
capture that made it is finished with it, and lets it go when a later frame
replaces it; `shown(false)` stops. With nobody drawing, a capture's target is
released the moment its capture is done.
The release path asks `retains(rtHandle)` before destroying a target, which is
how a held frame survives its own capture. `capture.shared.releaseFrame` is the
one place that asks.
# capture.fromCamera
Render the scene from a specific named camera's authored pose and settings, returning the picture as an image value (and writing a PNG as well when a `path` is given). By default it uses the camera's exact world-space pose plus its whole lens (fov/near/far, and the projection it builds with the orthoHeight an orthographic camera covers), its diagnostic debugChannel, its post-process setting, its lighting environment (an isolated camera's background and ambient with it) and the scene layers it draws: the camera's own `renderLayers` with the editor's chrome (`EditorUI`) and the authoring overlays (`debug`) taken off, since those are drawn for whoever is editing rather than by that camera into the world. So the frame is precisely what that camera draws of the scene, without changing what is on screen. Pass overrides (`renderLayers`, `debugChannel`, `fov`, `near`, `far`, `projection`, `orthoHeight`, `width`, `height`) to change any of those for the one capture without touching the camera; `renderLayers = "all"` is how the overlays are captured on purpose.
# capture.fromEntity
Renders a screenshot orbiting a target entity. The camera position is computed from a distance and a yaw/pitch angle relative to the entity's world position, with an optional offset applied before framing and a configurable field of view and output size. Returns the picture as an image value, and writes a PNG as well when a `path` is given; fails when the entity is missing or its position can't be read. Runs as a background task that waits for the GPU readback, so it works in play mode.
# capture.fromPosition
Renders a screenshot from an explicit world-space camera position and returns the picture as an image value. Aim it with a look-at target (defaulting to the origin) or a quaternion rotation that takes precedence, and set field of view, output size, and near/far clip planes. A PNG is written as well when a `path` is given. It spawns an ephemeral camera, triggers one render, reads the frame back, and despawns the camera automatically — running as a background task that waits for the readback, so it works in play mode.
# isolate
Show the subject without the other geometry drawn, then put everything back.
A prop inside a built scene is behind whatever stands in front of it. The
render-layer system already expresses "draw only these" — an entity is a member
of layers, a camera renders a filter over them — but it does not remember what
it displaced, so every caller wanting one clean shot of one thing hand-rolls the
same record, swap and restore. This is that, once, with the restore guaranteed.
## What it changes
Exactly one thing: the other geometry is not drawn.
Sky, post-process and UI are left exactly as the capture's own render-layer spec
stated them, so a final frame stays a final frame. A caller who wants the
geometry read flat — no lighting, no atmosphere — asks for a **pass**
(`pass = "albedo"`, `pass = "normal"`), which is what passes are for.
## What it does not change
Excluded geometry still **casts shadows** onto the subject and still bounces
light into it. Lights are not filtered by render layer at all, and the layer mask
drives object culling and the geometry passes rather than the shadow passes. This
is the render-layer system's deliberate behaviour — a wall stays out of the shot
while it still exists for lighting, shadows and physics — so a shadow with no
visible caster in an isolated capture is the system working, not a bug.
## The layer
One reserved layer name, `captureIsolate`, reused by every isolated capture.
Membership is a 32-bit mask with six reserved bits. A layer minted per call would
exhaust the namespace in twenty-six captures and leave a trail of empty layers
that `renderLayer.list` would show forever.
## Restoring
`begin` records each affected entity's membership before moving anything, so the
token describes the whole subtree even if the move fails part-way. `restore`
puts every entity back to the layers it carried — and an entity that carried
**no** explicit membership ends with none, rather than an explicit `default` that
looks identical in a picture and different in the data.
`restore` is safe to call twice and safe on a token whose subjects have since
despawned, which is what lets a caller restore unconditionally on every exit
path: success, failure, and once around a whole collage grid rather than between
its cells.
# capture.oneshot
The low-level one-shot capture primitive. Spawns an ephemeral offscreen camera configured from a source — the viewport, an entity (or several), a world-space position, or a UI window — triggers a single render, and returns the camera and render-target handles synchronously so the caller drives the readback and cleanup itself. This synchronous shape is the only capture path that works from edit mode, where the background-task scheduler the convenience wrappers rely on does not tick.
When framing an entity, omitting the distance auto-fits the camera to the union world-space bounds of the target(s), so the subject is guaranteed fully in frame at any scale — a small prop and a large building both fill the shot. Because the data drives the camera, an empty result is a real signal that the geometry or material is wrong rather than a framing mistake; a distance can be passed to force a fixed orbit radius, and an angle sets only the viewing direction. Further options select the debug visualization channel, toggle which layers (scene, sky, post-process, UI) render, and set field of view, clip planes, and output size. The returned camera is left disabled so it can be re-triggered to produce additional frames on the same target, as when stitching a collage.
# shared Module
Cross-tool helpers for the `capture` toolbox. Every tool inside this
toolbox can pull these in with `require(".shared")`.
## Purpose
This module holds the small set of helpers that more than one tool in
the toolbox needs — typically the `ok(value, formatted?)` /
`fail(message, exitCode?)` constructors that produce the canonical
`captureToolResult` shape, plus any toolbox-wide parsers,
validators, or shared state. Keep it focused: per-tool implementation
stays inside each `<x>.tool/init.luau` (with its own `--!desc` /
`--!arg` / `--!return` / `--!example` annotations).
## Usage
```luau
local shared = require(".shared")
function M.someTool(...)
if not ok then
return shared.fail("reason", 1)
end
return shared.ok(value, "")
end
```
## Exports
See `init.luau` for the full export surface. Typical exports include
`shared.ok(value, formatted?)` and `shared.fail(message, exitCode?)`
for building the toolbox's standard result envelope.
# subject
What a capture of an entity is a picture of. Every path that frames or isolates
an entity (`fromEntity`, `oneshot`, a `setups` or `viewpoints` collage,
`isolate`) resolves the name, id or proxy it was given here, so they agree on
which entity a name means.
## A player is drawn as its body
A player identity (an entity carrying `UserIdentity`) is the registry anchor a
connected user is known by. The player is drawn as the body its `avatar` names,
a standalone entity at the scene root, so a capture of an identity frames and
isolates that body.
In play, a player prototype's spawn turns the prototype's copy into the joining
user's identity under the prototype's own name and stands the body it names at
the spawn point. A capture of the name an author gave their player prototype
therefore frames the player's body in play, and the prototype's subtree in
edit.
## What a refusal names
`describe(target, via)` is the phrase a framing refusal uses for each subject it
looked at: the entity's name and id with the number of descendants it holds,
and the player identity it is the body of when it was reached through one, or,
for a player identity with no live body bound, that the body is missing.
| Function | Returns |
|----------|---------|
| `resolve(t)` | the entity a capture pictures for a name, id or proxy (nil when none matches), and the player identity it was reached through |
| `bodyOf(target)` | the live body a player identity is drawn as, or nil |
| `isPlayerIdentity(target)` | whether the entity carries `UserIdentity` |
| `describe(target, via)` | the refusal phrase for one resolved subject |
# viewpoints
The named camera stations a capture can be taken from, and the rule that decides
what a name like `front` means.
A **viewpoint** is a direction with an image-up: where the camera stands relative
to what it is looking at, and which way is up in the resulting picture. Naming
one replaces reverse-engineering a `{yaw, pitch}` pair, and names the seven
stations that answer "is this built correctly" — the six sides and the corner.
| Viewpoint | Sees |
|-----------|------|
| `front` | the side the subject faces |
| `back` | the opposite side |
| `right` | the subject's right |
| `left` | the subject's left |
| `top` | plan view, the subject's front toward the top of the image |
| `bottom` | the underside |
| `iso` | the corner view where all three axes project equally |
An entity faces its local -Z, so the camera that sees its front sits on its +Z.
`top` and `bottom` take their image-up from the subject's forward axis, because
world up is undefined when you are looking straight down it — that is what puts
the subject's front at the top of a plan view instead of leaving the roll to
whatever the yaw happened to be.
## Basis
`basis` says which axes the name is measured against, and it has **no default**:
- **`"local"`** — the subject's own axes. `front` is the side the subject faces,
whichever way it is turned, and the frame is fitted to the subject's own
extents (`entity:orientedBounds()`).
- **`"world"`** — the world axes. `front` is the side facing world +Z, whatever
the subject is doing.
For a crate turned 40 degrees these are different pictures, so the caller states
which one it wants. A default would mean one call site's `front` is the crate's
front and another's is the world's, and the difference only shows up in the
image. With no subject to take axes from — a capture framed on a world position
rather than an entity — both values mean the world axes, and both are accepted.
## Orthographic size
`orthoHeightFor` answers the question an orthographic frame asks that a
perspective one does not: how big is the frame? A perspective camera backs off
until the subject fits; an orthographic camera does not converge, so its size is
decided by the subject alone — project the bounds' eight corners onto the
camera's up and right axes and take whichever needs more room.
Its `half` extents and `axes` must be stated in the same frame. A resolved
viewpoint carries both: `frame` axes to use with local-frame extents, and its
world axes to use with world extents.
# capture.viewport
Renders a screenshot mirroring the active viewport. It mirrors the on-screen camera through the shared capture core, so the frame carries that camera's pose, its lens (`fov`, clip planes and the projection it builds), the lighting environment it states (an `isolated` camera's background and ambient) and the layers it draws the screen with, the editor's own overlays included, so the image matches what's on screen. The raster is the viewport's own pixel size, the size `getViewportSize()` reports. Returns the picture as an image value, and writes a PNG as well when a `path` is given; fails when no active viewport camera exists.
Its one argument is a path to also write the PNG to, or a table overriding any of that for one capture: `width` / `height` for a raster of some other size, `renderLayers` for the frame under a different layer spec — `"all !EditorUI !debug"` is the frame without the editor's chrome over it — and `postProcessing` to take it with the grade off.
```lua
tools.use("capture", "viewport", "/source/tmp/capture/shot.png")
tools.use("capture", "viewport", { path = "/source/tmp/capture/clean.png",
renderLayers = "all !EditorUI !debug" })
tools.use("capture", "viewport", { width = 960, height = 540 })
```
# debug.inspect
Inspect entity component state — script components, native ECS components,
or both — for every entity matching the target.
```lua
debug.inspect("player")
debug.inspect("lamp", { include = "ecs" })
debug.inspect("enemy_*", { types = { "Health" }, limit = 5 })
```
The target is an entity id, a name, an entity proxy, or an array of them.
A name resolves to **every** matching entity (names are not unique; globs
like `enemy_*` work), an id to itself.
Options:
```lua
{
include = "all", -- "script" | "ecs" | "all" (default)
types = nil, -- restrict to these component types; full identity
-- or leaf name ("Camera" matches
-- "@builtin::components.Camera")
limit = 10, -- cap on matches
}
```
Returns:
```lua
{
query = { target, count },
matches = {
{
id = "ent_...",
name = string?,
script = { [componentType] = data }, -- serialized public data
ecs = { [componentName] = fields }, -- native component fields
},
...
},
}
```
`script` data is the serialized form (entity refs as id strings, asset refs
as `{ __ref, name, type }` envelopes) produced by the `component_snapshot`
module; `ecs` is `ecs.snapshot` per entity. For live gameplay reads and
writes, use `entity(id).component.get` / `getAll` — the data those return
is the running component's proxy, not a snapshot.
# debug.playSession
Show or hide the debug overlay during play mode.
```lua
debug.playSession(enabled?)
```
- `enabled` — `true` (default) to show the overlay in play, `false` to hide it.
Returns `{ playSession = boolean }`.
Edit mode always shows the overlay; play mode shows it only while this session is
on — the way to watch bones, colliders, or bounds on a running, animating scene
(bones only move once the scene is unpaused). The flag lives in memory only and
is never saved, so debug visibility can never be permanently toggled on by
accident; it resets on engine restart.
# debug.problems
Surface the recent errors and warnings the caller has not read yet.
```lua
debug.problems()
```
Non-crashing failures — a contract violation, a component `awake`/`update`
throw, a component auto-disabled after erroring, an unresolved require, a
bridged renderer or asset error — land in the engine's log ring but do not
surface in `execute` results unless you happened to ask for them at the right
level in the call where they occurred. `debug.problems` reads them back out.
**When something you built does not behave, call this first.** The engine has
usually already logged the reason.
Each call advances a read-cursor and returns the problems logged since the
previous call, **oldest first** — so the root-cause error (the `awake()` throw
that disabled a component) reads ahead of the cascade it triggered. Repeated
calls report only what is new.
```lua
debug.problems({
level = "warn", -- minimum severity: "warn" (default) or "error"
limit = 50, -- cap on entries returned (default 50)
all = false, -- true: recent problems regardless of the cursor, cursor untouched
peek = false, -- true: read the next batch without advancing the cursor
})
```
Returns:
```lua
{
problems = { -- oldest first
{ seq, level, type, message, timestamp },
...
},
shown = number, -- #problems
truncated = boolean, -- more unread problems remain past `limit`
cursor = number, -- read-cursor after this call
counts = { errors, warnings }, -- lifetime totals (survive ring eviction)
}
```
`all = true` gives a one-shot overview of the most recent problems without
disturbing the drain cursor. `peek = true` previews the next batch and leaves
it unread for the next call.
The full log ring — every level, searchable, countable, filterable by the
script or entity that logged a line — is the `logs` toolbox, whose `search`,
`tail`, `errors` and `summary` tools read it. Reach for those when you need
more than the unread problems: a specific message, a specific entity, a
specific minute, or the lines that led up to a failure. The same ring is also
readable directly from Luau through the `logs` global, and as plain files at
`/zero/runtime/logs/engine`, `/zero/runtime/logs/errors` and
`/zero/runtime/logs/script` when a grep for a message you can name is
shorter than a query.
This tool is the read-cursor view over the warn/error slice of it.
# debug.scope
Focus the debug overlay on specific entities, or clear the focus.
```lua
debug.scope(target?)
```
- `target` — a name or `ent_` id, an array of them, or the `{ id = ... }`
records `scene.findAll` returns. Names resolve to every matching entity. Omit (or
pass an empty list) to clear the focus and draw for every entity again.
Returns `{ scoped = { ids }, count = number }`, the scope after the change.
Every enabled category honours the scope, so the overlay focuses on the chosen
objects — hierarchy bounds, for instance, draw one box per scoped part instead of
one union box per top-level object. The scope lives in memory only and is never
saved.
# debug.set
Show or hide a debug-visualization overlay category.
```lua
debug.set(category, enabled?)
```
- `category` — a category name (`bounds`, `frustum`, `bones`, `colliders`,
`icons`, `wireframe`), or `"all"` for every category.
- `enabled` — `true` (default) to show the category, `false` to hide it.
Returns `{ [category] = boolean }`, the category state after the change (every
category when `"all"` is passed). Errors on an unknown category name, listing the
known ones.
The overlay is ambient editor tooling drawn for the whole scene; this only flips
which categories draw. `bounds`, `bones`, `colliders`, and `wireframe` are off by
default (heavier per-mesh overlays); `frustum` and `icons` are on.
# shared Module
Cross-tool helpers for the `debug` toolbox. Every tool inside this
toolbox can pull these in with `require(".shared")`.
## Purpose
This module holds the small set of helpers that more than one tool in
the toolbox needs — typically the `ok(value, formatted?)` /
`fail(message, exitCode?)` constructors that produce the canonical
`debugToolResult` shape, plus any toolbox-wide parsers,
validators, or shared state. Keep it focused: per-tool implementation
stays inside each `<x>.tool/init.luau` (with its own `--!desc` /
`--!arg` / `--!return` / `--!example` annotations).
## Usage
```luau
local shared = require(".shared")
function M.someTool(...)
if not ok then
return shared.fail("reason", 1)
end
return shared.ok(value, "")
end
```
## Exports
See `init.luau` for the full export surface. Typical exports include
`shared.ok(value, formatted?)` and `shared.fail(message, exitCode?)`
for building the toolbox's standard result envelope.
# debug.state
Report the current debug-visualization state.
```lua
debug.state()
```
Returns:
```lua
{
categories = { [name] = boolean }, -- which categories draw
scope = { ids }, -- focused entity ids (empty = all)
count = number, -- #scope
playSession = boolean, -- play-mode overlay session on?
mode = string, -- engine mode ("edit" / "play")
}
```
A read-only snapshot of what `debug.set`, `debug.scope`, and `debug.playSession`
have configured — the state the ambient overlay draws from this frame.
# backfillSearchMeta
Re-derive the search `.metadata` for existing assets whose type records facet
data there — a bundle's component set and humanoid classification, an
animation's humanoid classification.
New and edited assets get this from their type's `onChange` hook. Assets minted
before the deriver existed carry no `.metadata.components` / `.metadata.humanoid`,
so their search facets read a false negative (an unrecorded asset looks the same
as one that genuinely lacks the trait). Run this once to populate them.
```lua
tools.use("assets", "backfillSearchMeta", {}) -- bundle + animation
tools.use("assets", "backfillSearchMeta", { types = { "bundle" } })
```
Idempotent: re-running recomputes the same values. Only assets whose type
exposes a `reindexSearchMeta` ref method are touched; everything else is counted
as scanned and left alone. Returns `{ total, byType = { <type> = { scanned,
reindexed } } }`.
# assets.describe
Agent-facing inspect surface. Resolves `assetName` the same way
`assets.find` results resolve, calls `asset.inspect` for the structured
record, and renders it to markdown via `modules/asset_inspect_render`.
Pairs with `assets.find` (find -> describe).
Named `describe` — never `inspect` — so it is never confused with the
`asset.inspect` code API (one letter apart is a trap).
# assets.fetchInUse
Fetch the unique set of asset references in use on the targeted entities — materials, meshes, textures, bundles, and every other category a component field can hold. It scans each entity's components, walking their public data recursively for asset references, dedupes by identity, and reports each reference enriched with its identity and on-disk path plus the entities that use it. Target one entity, a list of entities, or the whole scene; roots are scanned through their children. The one-call inventory of what a piece of content is made of.
# assets.find
Project-wide asset search by substring — "find anything with 'car' in it", without knowing where anything lives. It combs the entire asset index in one call and returns every matching identity grouped by category, optionally restricted to a single category. Matching is case-insensitive and literal.
# assets.fromEntity
Capture everything an entity is carrying at **runtime** as durable assets, and
repoint the entity at them.
A procedural mesh (`renderer.mesh.create`) has no asset behind it, so anything
keyed to that geometry — a GI bake, a saved scene — is session-only: reload and
the mesh regenerates with a fresh identity, and the bake is gone.
`assets.fromEntity` freezes every live runtime resource an entity's components
hold — across the whole hierarchy, every resource field — into persistent assets
in one call, and rewrites each field to point at the durable asset. Persistent
references (already assets) are left untouched.
Resource fields are discovered generically from each component's registered
schema, so any component carrying runtime content participates — it reifies
**all** of an entity's runtime content, not one hard-coded type. A runtime
resource shared across several fields is reified once and every field is
repointed at the one asset.
Reify in **edit mode** to make content durable — in play mode the new assets land
in the ephemeral runtime store.
```
assets.fromEntity() -- freeze every runtime resource in the scene
assets.fromEntity("cornellRoom") -- freeze the cornellRoom hierarchy
assets.fromEntity(nil, { dryRun = true }) -- report what would be reified, write nothing
```
Returns `{ reified, skipped, failed }`. The single-resource primitive is
`assets.new`.
# assets.generatePreviews
Queue a render of the missing or stale `preview.png` for every world asset whose type declares a `preview:` recipe in its `type.yaml` — the batch pass that brings an existing world up to the previews-carry-the-description contract. Each asset is pictured by its type's recipe (a material on a sphere, a shader on the shader ball, a texture as its own pixels, anything scene-instantiable stood in the preview studio) and the picture is persisted inside the asset folder, where it syncs, publishes, drives image-based search, and gives browsers a thumbnail. The call itself only scans and enqueues, so it returns in seconds regardless of world size; the renders drain serially on the preview work queue in the background — poll `assets.previewStatus` until `pending` reaches 0. Re-running the tool is safe at any point: assets whose preview is current, one that records the content the asset holds now, are skipped unless `force` re-renders them, so an interrupted backfill resumes where it left off. `root` narrows the pass to a path prefix. Empty leftover `README.md` files inside visited assets are removed — an empty file can never sync, so each one otherwise re-enters the outgoing queue on every boot.
# assets.new
Persist a **live runtime GPU resource** — a mesh or texture handle from
`renderer.mesh.create` / `renderer.texture.create`, which has no asset behind
it — into a durable, guid-anchored asset.
A runtime resource lives only on the GPU: nothing references it by a stable
identity, so anything keyed to it (a GI bake, a saved scene, a material slot) is
session-only and regenerates with a fresh identity on the next reload.
`assets.new` reads the resource back from the GPU, encodes it, and writes a real
asset via `asset.create`, so it survives a reload.
`asset.create` itself is disk-only — it writes supplied bytes or pixels and never
reads the GPU back. So for raw in-hand geometry or pixels, call
`asset.create(<type>, name, data)` directly; `assets.new` is the tool for
freezing a resource that only exists as a live handle.
Reify in **edit mode** to make content durable — in play mode the asset lands in
the ephemeral runtime store.
```
local h = renderer.mesh.create({ positions = p, indices = i })
assets.new(h, "tree") -- persist the runtime mesh
assets.new({ guid = meshGuid, category = "mesh" }, "terrain")
```
Reifiable categories: `mesh`, `texture`. See `assets.fromEntity` to reify every
runtime resource an entity carries in one call.
# assets.previewStatus
Read the preview work queue — the serial drain that renders every queued `preview.png` (from `generatePreviews` backfills, from staging an asset whose preview is missing or stale, and from views that ask for a picture). Returns how many renders are still pending, which asset is rendering right now, the session's completed/failed totals, and the most recent failure records. Poll it after `generatePreviews` until `pending` reaches 0 and `active` is empty; a non-empty `failures` list names each asset that could not render and why.
While `pending` is above 0 and nothing renders, `held` names what the queue is waiting for: the engine in play mode (the queue renders in edit) or a render device being rebuilt after a loss. A render that cannot finish does not wait: when the render device is abandoned, a subject draws nothing, or the drain rendering it ends part way, the entry moves to `failures` with the reason, and the `zm push` refusal for an asset that needs its preview.png says where the queue stands on it. `activeFrames` counts the engine frames the batch under way has run, which tells a slow batch from one that is not moving, and `drainer` is the handle of the task draining the queue (`task.status(drainer)` reads it). Reading the status starts a drain when work is queued and none is running.
# assets.reconcileReferenceNames
Write the current name of every moved reference into the world sources that still spell an old one. A source records the guid of each asset it references, so when an asset sits at another path the reference keeps resolving to it and nothing breaks; the source's stored text still spells the old name, and a notice names the source each time the world becomes ready. This call writes the name the asset has now. It changes no behaviour: every reference resolves to the same asset before and after. Each write is an edit of that source, synced to the world like any other. Only the author's sources are written: the world's own files and installed assets the author has modified, never `/source/deps/` or an installed asset still as it was published. `dryRun` lists what would change and writes nothing; `paths` narrows the call to those sources.
# reify
Shared helper for the assets toolbox: turn a **live runtime GPU resource** into a
persistent asset.
A resource made with `renderer.mesh.create` / `renderer.texture.create` lives
only on the GPU — no asset, no stable identity. This module reads it back from
the GPU, encodes it into the engine-native payload, and writes a real asset via
`asset.create` (the GPU→CPU→encode→create path `asset.create` does not do on its
own, since it is disk-only).
The reify recipes are a table keyed by asset category, so a new resource category
is one entry rather than a code fork. Current recipes: `mesh` (ZMSH via
`renderer.mesh.readback`) and `texture` (ZTEX via `renderer.texture.readback`).
Consumed by `assets.new` (one resource) and `assets.fromEntity` (every runtime
resource an entity carries). Not an agent-facing tool.
# assets.typeBehavior
What an asset of this TYPE can do: the operations every ref of it answers to
(`ref:method(...)`), the lifecycle hooks it runs, and whether it can become an
entity in a scene.
Knowing a type exists is not the same as knowing what it gives you. A type that
already evaluates, instantiates, validates and recompiles itself is scaffolding
to build inside. This is how you see that before deciding to write your own.
Pairs with `assets.typeDoc` for the prose and `assets.types` for the list.
# assets.typeDoc
One asset type's own documentation — what it IS, the shape of its folder, how it
is authored, and what it does for you.
A type's README says things no signature can: which file is the source, what
regenerates when you write it, what the type handles so you do not have to. Read
it before building anything that resembles what the type describes; that is the
moment a project turns into a few lines.
`assets.types` finds the name to pass here. `assets.typeBehavior` gives the
operations the type answers to.
# assets.types
Every KIND of asset this engine can make — the scaffolding available to build
inside.
Three different questions, three different surfaces, and only one of them was
answerable before this tool:
- `search_tools` — what OPERATIONS can I call?
- `assets.find` — what CONTENT already exists?
- `assets.types` — what KINDS of thing can I make?
The third is the one that decides whether a job is a few lines inside an
existing system or a system written from scratch. An agent that checks only the
first two can survey exhaustively, find nothing that matches, and reasonably
conclude it must build from nothing — while a type shaped for exactly that job
sits registered and unmentioned.
Each row carries the type's name, the `asset.create` call that makes one, the
lead line of its own README, and whether it declares `instantiate` — the
contract `entityOps.fromAsset` dispatches through, and therefore whether the
type can become an entity in a scene.
# assets.users
Find every entity in the active layer that uses a given asset. Name the asset as a word — the project is combed case-insensitively and the first match is used — or pass an asset reference you already hold. Every entity's component data is scanned recursively, and each use site is reported with the entity, component, and field it lives in.
# entityOps.addComponents
Attach component(s) — with their setup data — to one or many entities
in a single call, creating the entities first when asked.
```lua
entityOps.addComponents("crate", { Physics = { kind = "dynamic" } })
entityOps.addComponents({ "crate_1", "crate_2" }, { "Physics", "Audio" })
entityOps.addComponents("spinner", { Rotator = { speed = 2 } }, { create = true })
```
Targets are entity **names or ids** (arrays and `scene.find` results
pipe straight in). Components are a name, an array of names, or a
`{ Name = dataTable }` map carrying each component's setup data — names
accept the leaf (`"Physics"`), the full identity
(`"@builtin::components.Physics"`), or a VFS path, resolved before
anything mutates.
`create = true` spawns a fresh root entity for any string target that
matches nothing, so one call both creates the entity and gives it its
setup. Returns one `{ id, name, added, created? }` record per entity.
# entityOps.component
Inspect a component **type** so you set fields that exist instead of
guessing. Reports the component's public fields (name + type + current
value), its callable methods, its lifecycle hooks, and its asset-ref
fields.
```lua
entityOps.component("Camera") -- fields, methods, hooks + default values
entityOps.component("Model", { on = "my_prop" }) -- actual values on that entity
entityOps.component("@builtin::components.Light")
```
Resolves the component by name / identity / VFS path. Pass `on` (an
entity name or id that carries the component) and every field's `value`
is that entity's **actual** value, read off its live component proxy;
omit `on` and each `value` is the **declared default**, as written in the
component's source.
A live value keeps its shape: a number reads back as a number, a vector or
struct as its plain table. A field that resolves on read reports the identity
of what it points at — an asset (`resource` / `assetRef`) as a
`{ __ref, identity, name, type }` envelope whose `identity` you hand straight
back to `addComponents`, an `entityRef` as the entity id. A field whose live value could not be read
carries an `error` instead of a value, so a value that failed to read is
never mistaken for the default.
```lua
-- on a wall carrying a mesh and a custom material
entityOps.component("Model", { on = "wall_north" })
-- fields: model = { __ref = "336f4feb-…", identity = "@builtin::meshes.cube", name = "cube", type = "mesh" }
-- material = { __ref = "99d699e9-…", identity = "@user::materials.brick", name = "brick", type = "material" }
```
Returns `{ identity, description, builtin, executionOrder, hooks,
fields, methods, assetFields, source }`. Reach for it before
`entityOps.addComponents` / `entityOps.spawn` to learn the exact field
names and value shapes — the fix for setting fields a component doesn't
have.
To inspect the components + values on an *entity* (rather than a
component type's schema), use `debug.inspect`.
# entityOps.duplicate
Copy entities that already exist — one duplicate, or a numbered run of
them spread along an axis.
```lua
entityOps.duplicate("crate")
entityOps.duplicate("crate", { count = 5, offset = { 2, 0, 0 } })
entityOps.duplicate("pillar", { count = 4, offset = { 0, 3, 0 }, name = "pillar_%d" })
entityOps.duplicate({ name = { "tree" } }, { offset = { 10, 0, 0 } })
```
Targets take a name or id, a list of them, `scene.find` records, or a
**query** resolved for you — so everything matching `{ name = { "tree" } }`
is copied without looking the entities up first.
`count` makes that many copies of **each** source. It must be a whole
number of at least 1.
`offset` is a world-space `{x,y,z}` step that **accumulates**: copy 1 sits
one offset from the source, copy 2 sits two, copy 3 sits three. Every copy
is placed relative to the **source**, so a run spreads evenly instead of
compounding rounding from copy to copy.
`name` names each copy, and a `%d` in it becomes the copy's 1-based index
— `"pillar_%d"` yields `pillar_1`, `pillar_2`, … Without a `name`, copies
are named after their source (`crate_copy`, or `crate_copy_1`,
`crate_copy_2`, … for a run).
Copies carry the source's render layer.
An option key outside the documented set is an error that names it and
lists the accepted keys, so a mistyped `conut` is reported instead of
returning copies that quietly ignored it.
Every call returns the resulting
`{ id, name, position, localPosition, rotation, localRotation, eulerAngles, scale, parent }`
per copy, in creation order — the copy and the read are the same call.
# entityOps.fromAsset
Instantiate an existing asset into the scene — **resolution-first**: pass
a name / path / identity string, the tool resolves it and reports the
canonical asset it hit, so you never need to know the exact identity up
front.
```lua
entityOps.fromAsset("@builtin::avatars.humanoid")
entityOps.fromAsset("oak_chest", { type = "bundle", position = {2, 0, 0} })
entityOps.fromAsset("gold", { type = "material" })
entityOps.fromAsset("/zero/source/generated/meshes/a_statue.bundle", { link = false })
```
Dispatch by resolved category:
- **bundle / avatar** — instantiated via its own `:instantiate()`. `link`
(default true) keeps the live Asset-component link so the source drives
the hierarchy; `link = false` bakes the hierarchy into the scene.
- **mesh** — a renderable (Model + mesh Collider).
- **material** — a sphere carrying the material.
- **texture** — a plane sampling the texture (through a fresh unlit
material, so it never rewrites another preview).
- **anything else** — instantiated through its own `:instantiate()` when
it has one, else a legible error.
`type` limits the asset search to one category (avoids name clashes).
`position` / `rotation` / `scale` place it; `synced` replicates gameplay
edits to peers. Returns `{ id, name, resolved = { category, identity,
path } }` — `resolved` is the canonical asset your string hit.
To spawn from hand-named components instead of an existing asset, use
`entityOps.spawn`.
# entityOps.modify
Change entity state — one tool for delete / enable / disable / hide /
show / temporary / reparent / rename, over one or many entities resolved
by **name or id**.
```lua
entityOps.modify("debug_probe", { hidden = true })
entityOps.modify({ "probe_a", "probe_b" }, { delete = true })
entityOps.modify("old_character", { enabled = "toggle" })
entityOps.modify("hat", { parent = "player_head" })
```
Ops: `delete` (removes the whole subtree; wins over everything else),
`enabled`, `hidden`, `temporary` (booleans, `"toggle"` flips the current
state), `parent` / `unparent` (with `keepWorldTransform`, default true),
and `rename` (single target only).
Returns one `{ id, name, applied }` record per target. `scene.find`
results pipe straight in as targets.
# entityOps.removeComponents
Detach component(s) from one or many entities — the counterpart to
`entityOps.addComponents`.
```lua
entityOps.removeComponents("lamp", "Light")
entityOps.removeComponents({ "crate_1", "crate_2" }, { "Physics", "Audio" })
entityOps.removeComponents({ component = { "Light" } }, "Light")
entityOps.removeComponents("lamp", "light") -- partial name, resolved
```
Targets take a name or id, a list of them, `scene.find` records, or a
**query** resolved for you — so a component is stripped from everything
carrying it without naming a single entity.
Component names match loosely: the leaf (`"Light"`), the full identity
(`"@builtin::components.Light"`), a VFS path, or a case-insensitive
partial. The response reports the **canonical** name it resolved to, so a
half-remembered name both works and teaches you the real one.
A name that could mean several components is an error listing the
candidates rather than a guess, and a name matching nothing is an error
too — nothing is silently skipped.
Every entity comes back as `{ id, name, removed, absent }`:
- `removed` — components it carried and lost.
- `absent` — components it never had, so nothing happened for them.
That split makes a call which changed nothing visible, instead of letting
it read like a success.
# entityOps.roots
Find the root ancestor of one or many entities — walks each up its
parent chain to the top-level entity.
```lua
entityOps.roots("player_hand")
entityOps.roots({ "wheel_fl", "wheel_fr" })
```
Targets are entity names or ids (a single one, an array, or `scene.find`
records). Returns one `{ target, targetName, root, rootName, depth }`
per target; an entity that is already a root reports itself with
`depth = 0`.
# entityOps shared
Cross-tool helpers for the `entityOps` toolbox — the pieces more than
one of its tools reuse.
- **Entity resolution** — `resolveEntity` / `resolveTargets` / `toList`
turn a name / id / proxy / `scene.find` record (single or a list) into
live entity proxies, raising a legible error on anything that doesn't
match.
- **Subtree removal** — `collectDescendants` / `despawnSubtree` remove an
entity and its whole subtree, raising rather than leaving a half-removed
tree behind.
- **Slot capture** — `captureSlot` snapshots the parent + local transform
+ name + sync flag an entity occupies, so a replacement can take its
exact place.
- **Asset resolution** — `resolveAsset` turns a caller's name / path /
identity string (or an already-resolved AssetRef) into a resolved
asset, reporting the canonical identity/path it hit, optionally limited
to one asset category.
Tools are thin wrappers over these; the helpers call the engine APIs.
# entityOps.spawn
Spawn entities from a template — you name the components they carry and
their field values, plus a transform.
## Many entities in ONE call
Pass a `{ defaults, items }` list: `defaults` holds what every entity
shares, each `items` entry overrides only what differs. A six-walled room
is one call, not six.
```lua
entityOps.spawn({
defaults = { components = { Model = { model = "cube" }, BoxCollider = {} },
scale = { 4, 3, 0.2 } },
items = {
{ name = "wall_n", position = { 0, 1.5, -2 } },
{ name = "wall_s", position = { 0, 1.5, 2 } },
{ name = "wall_e", position = { 2, 1.5, 0 }, rotation = { 0, 90, 0 } },
{ name = "wall_w", position = {-2, 1.5, 0 }, rotation = { 0, 90, 0 } },
},
})
```
- A per-item key wins over the matching `defaults` key.
- `components` merges **per component**: an item naming `Model` replaces
only that entry and keeps the shared `Collider`.
- Every item is validated **before any entity is created** — a typo in the
last entry fails the whole call rather than leaving a half-built scene.
- An unrecognised key is an error naming the accepted set, at the top
level, in `defaults`, and in an item alike.
- Returns one `{ id, name, components }` record per item, in item order.
## One entity
```lua
entityOps.spawn(
{ Model = { model = "cube" }, BoxCollider = {} },
{ position = {0, 1, 0} })
entityOps.spawn(
{ Light = { kind = "point", intensity = 5 } },
{ name = "lamp", position = {0, 3, 0} })
entityOps.spawn({}, { name = "group" }) -- bare entity, no components
```
Components is a `{ [ComponentName] = { field = value } }` map. Each is an
**authored** component (leaf name like `"Model"`, a full identity, or a
VFS path) added with its data so it **serializes** — native ECS
components are intentionally not exposed here, so you never author
something that renders at runtime but vanishes on save.
Transform: `position` `{x,y,z}`; `rotation` a `{x,y,z,w}` quaternion or
`{pitch,yaw,roll}` euler degrees; `scale` a number or `{x,y,z}`. Also
`temporary`, `hidden`, `synced` (replicate gameplay edits to peers), and
`attributes`.
Returns `{ id, name, components }` with the component leaf names added.
To instantiate an existing **asset** (a bundle / avatar / mesh /
material / texture) rather than hand-name components, use
`entityOps.fromAsset`.
# entityOps.swap
Replace one entity with another entity that **already exists in the
scene**. The replacement is moved into the target's slot — same parent,
local position and rotation, the target's scale (`keepScale = false`
opts out) and name (`keepName = false` opts out) — and the target is
removed with its whole subtree.
```lua
entityOps.swap("DefaultBody", "my_knight")
entityOps.swap("placeholder_car", "sports_car", { keepName = false })
entityOps.swap("DefaultBody", "my_knight", { dryRun = true })
```
Both arguments are entity names or ids. `dryRun = true` reports what
would move and what would be removed without mutating.
To replace an entity with a content **asset** (a bundle/mesh/…) rather
than another scene entity, use `entityOps.fromAsset` (spawn) or
`appearance.replaceWithContent` (in-place slot swap).
# entityOps.transform
Move, rotate and scale entities that already exist — over one or many
entities.
```lua
entityOps.transform("lamp", { position = { 0, 3, 0 } })
entityOps.transform({ "wall_n", "wall_s" }, { offset = { 0, 2, 0 } })
entityOps.transform({ name = { "wall" } }, { offset = { 0, 2, 0 } })
entityOps.transform("crate", { rotation = { 0, 45, 0 }, scale = 2 })
entityOps.transform("lamp") -- no ops: a pure read
```
Targets take a name or id, a list of them, `scene.find` records, or a
**query** resolved for you — so you can move everything matching
`{ name = { "wall" } }` without looking the entities up first.
**Absolute** ops carry their space in the name: `position` / `rotation`
are world, `localPosition` / `localRotation` are parent-relative, `scale`
is a number or `{x,y,z}`.
**Relative** ops are `offset` (position delta), `rotate` (applied on top
of the current rotation) and `scaleBy` (multiplier). `space` —
`"world"` (default) or `"local"` — governs these.
`snap` quantizes the resulting position to grid steps.
Rotations take a `{x,y,z,w}` quaternion or `{pitch,yaw,roll}` euler
degrees, the same forms `entityOps.spawn` accepts.
Absolute and relative forms of one channel are exclusive — passing
`position` and `offset` together is an error rather than a silent
precedence rule.
An option key outside the documented set is an error that names it and
lists the accepted keys, so a mistyped `positon` is reported instead of
returning a successful-looking read of an entity that never moved.
Per-entity values in one call:
```lua
entityOps.transform({
{ target = "wall_n", position = { 0, 1, -5 }, rotation = { 0, 0, 0 } },
{ target = "wall_e", position = { 5, 1, 0 }, rotation = { 0, 90, 0 } },
})
```
Every record is validated and resolved before any of them is applied, so
a bad entry fails the whole call rather than moving its siblings and
leaving itself behind.
Every call returns the resulting
`{ id, name, position, localPosition, rotation, localRotation, eulerAngles, scale, parent }`
per entity — the mutation and the read are the same call.
# wld.edit
Return the engine to edit mode. Restores the edit state that was auto-snapshotted on the previous transition into play, and stops script and physics execution so the scene sits still for authoring. This is the counterpart to entering play — the round trip lets you run a scene, then rewind to exactly the state it had before it started.
# wld.hideLayer
Hide a loaded scene layer by name. The layer's entities stay in the world and keep their state — only their rendering stops. Showing the layer again makes them visible without a reload, while unloading despawns them entirely. Useful for toggling optional overlays such as a UI or debug layer on and off cheaply.
# wld.info
Read the current world's high-level state in one call: the bound world name, whether it is in edit or play mode, the active scene layer, and the list of saved scene snapshots in the live world. A quick orientation snapshot for deciding what to do next without querying each piece separately.
# wld.listWorlds
List the worlds persisted on disk under the local worlds directory. Returns the name of each stored world, giving a quick inventory of what has been saved locally.
# wld.loadLayer
Load a scene as an additive layer alongside the current scene, composing its entities on top of what is already live rather than replacing it. An optional origin offset positions the loaded content in world space, and the layer can be marked persistent or given an explicit name so it can be hidden, shown, or unloaded later.
# wld.mode
Report the engine's current mode. Returns `"edit"`, where scripts and physics are paused for authoring, or `"play"`, where they run. Use it to branch on the current state before flipping modes.
# wld.promoteAndSwitch
Promote the source-file edits made during play (the play-shadow set — what accepting the "edits" group promotes), then switch the engine to the requested mode, in one call. Replaces the changes() / acceptChanges("edits") / wld.edit()-or-wld.play() sequence for the edit-and-retest loop. Entity changes stay in the sceneAuthoring review flow: a flip to edit with unaccepted entity changes stops at the leave-play safeguard.
# shared Module
Cross-tool helpers for the `wld` toolbox. Every tool inside this
toolbox can pull these in with `require(".shared")`.
## Purpose
This module holds the small set of helpers that more than one tool in
the toolbox needs — typically the `ok(value, formatted?)` /
`fail(message, exitCode?)` constructors that produce the canonical
`wldToolResult` shape, plus any toolbox-wide parsers,
validators, or shared state. Keep it focused: per-tool implementation
stays inside each `<x>.tool/init.luau` (with its own `--!desc` /
`--!arg` / `--!return` / `--!example` annotations).
## Usage
```luau
local shared = require(".shared")
function M.someTool(...)
if not ok then
return shared.fail("reason", 1)
end
return shared.ok(value, "")
end
```
## Exports
See `init.luau` for the full export surface. Typical exports include
`shared.ok(value, formatted?)` and `shared.fail(message, exitCode?)`
for building the toolbox's standard result envelope.
# wld.showLayer
Show a previously hidden scene layer, restoring the rendering of its entities. The counterpart to hiding a layer — since hiding leaves the entities in the world, showing brings them back into view instantly with no reload.
# wld.unloadLayer
Unload an additive scene layer by name, despawning its entities entirely and removing its contribution from the composed scene. This fully releases the layer's content; to keep the entities alive but stop drawing them, hide the layer instead.
# scene.clean
Clear the active scene down to a protected keep-set.
```lua
scene.clean() -- keep only the player setup
scene.clean({ keep = { component = { "Light" } } }) -- also keep lighting
scene.clean({ keepPlayer = false }) -- full empty
scene.clean({ dryRun = true }) -- preview, no changes
```
By default only the player setup survives (every `PlayerPrototype` subtree and
every `PlayerSpawn`), so a clean never orphans the player. `keep` protects a
CATEGORY of entities — a `scene.find` query on `component` / `attribute` /
`tag` / `under` — not a single named entity.
A clean is a LIVE mutation only: it does not write the saved `scene.json`, so
`scene.revert` undoes it and `scene.save` commits it. If the scene has unsaved
edits, clean refuses (to avoid folding its removals into work no revert could
restore) — save or revert those edits first. There is no confirm/force flag.
The guard does not apply while play mode runs unpaused.
Returns `{ removed, kept, intent }`, plus a `warning` when the clean left the
scene with no lights.
# scene.cost
Which loaded scene is costing the frame time. Ranks every loaded layer by what its entrypoint's `update` / `editorUpdate` costs, timed where the tick runs and attributed to the layer that owns it — the answer to "the scene is slow and the profiler's script rows do not account for it", because a scene entrypoint's per-frame tick is not a component and does not appear among them. `totalMs` is a sum across the window since the last reset (or engine start) and `avgMs` is the per-tick cost, which is the per-frame cost for a tick that runs every frame. Answers in edit mode as well as play.
# scene.create
Create a NEW scene from a template and load it.
```lua
scene.create("sandbox") -- returns the template catalog
scene.create("level_1", "flat") -- ground + lighting, no player
scene.create("arena", "player") -- ground + lighting + default player
scene.create("title", "menu", { startup = true }) -- a menu scene the world opens into
```
`template` is typed: `"empty"` (blank canvas), `"flat"` (ground + lighting, no
player), `"player"` (ground + lighting + the canonical reusable player a joining
user's avatar replaces — prefer this over hand-rolling a player), `"menu"`
(lighting only, no ground, no player). Omit the template to get the catalog of
templates and what each contains; an unknown value errors with the valid
choices. Pass `opts.startup = true` to also make the new scene the world's
startup scene.
The scene is minted as a fresh asset and loaded. Returns
`{ scene, template, contains, startup? }`, or `{ templates }` when the template
is omitted.
# scene.find
The single entity-discovery tool. It reads the flat live population, so
it reaches **runtime clones, temporary entities, and detached roots** —
the entities a hierarchy walk from a scene root silently misses.
Pick a search axis (each a **list**, so many candidates resolve in one
call):
```lua
scene.find({ name = { "muzzle", "flash" } }) -- name terms (substring by default)
scene.find({ component = { "Light", "Camera" } }) -- entities carrying any of these
scene.find({ attribute = { name = "team", value = "red" } })
```
Multiple axes = union; each hit reports **which** criterion matched, so
you learn the right wording.
Modifiers:
- `substring` (default `true`) — case-insensitive name-part matching, so
`"muzzle"` reaches `muzzle_light_ent_620d…`. Set `false` for exact.
- `includeInternal` (default `false`) — entities marked internal are excluded
unless you opt in.
- `roots` — top-level entities only. `maxDepth` — cap the hierarchy depth.
- `under` — only descendants of these entities (by name or id).
`ancestorsOf` — only ancestors of these.
- `additive` (default `false`) — search only the active scene, or set
`true` to also search loaded overlay (additive) scenes.
- `limit` — cap the returned matches; `total` still reports the full count.
## Projections — `include`
By default a hit says *which* entity matched. `include` makes the query
answer the question outright, so you inspect a set in **one call**
instead of querying and then interrogating each entity:
```lua
scene.find({ under = { "room" }, include = { "transform", "componentValues" } })
```
| Projection | Adds to every match |
|---|---|
| `transform` | `position = { x, y, z }` (world), `rotation = { x, y, z, w }` (world quaternion), `eulerAngles = { x, y, z }` (degrees), `scale = { x, y, z }` (local), each an **array** |
| `componentValues` | `componentValues`: each component's **live** field values, keyed by component name |
| `attributes` | `attributes`: the entity's attributes as `{ name = value }` |
| `scriptComponents` | `scriptComponents`: every script-component instance the live entity carries, as `{ type, identity, instance }` |
The `transform` vectors are arrays, the vector shape the scene and
entityOps tools take and report, so a projected `position` passes
straight to `entityOps.transform`. Read them by index:
```lua
local hit = scene.find({ name = { "crate" }, include = { "transform" } }).matches[1]
local x, y, z = hit.position[1], hit.position[2], hit.position[3]
-- entity(hit.id).position holds the same value keyed x, y, z
```
Every match already carries `components`, the **names** of its
components, without `include`; their live values are the
`componentValues` projection. Nothing else is added unless `include`
names it. An unrecognised projection is an error listing the accepted
ones and naming the one to write instead (`include = { "components" }`
points at `componentValues` and `scriptComponents`, `"position"` at
`transform`). Projections read the **live** entity, so a component
added in the same frame reports its values here even though the entity
census has not caught up.
Returns `{ matches, total, truncated, searchedAxes }`, each match a
`{ id, name, parent, depth, components, layer, matched }` with the FULL
canonical id and name, plus whatever `include` asked for.
## Writing the query under its parameter name
`scene.find`'s one parameter is named `query`, so the search can also
be written under that name. Fields written beside the `query` table
join it, and both calls below search the same:
```lua
scene.find({ query = { name = { "ground" } }, include = { "transform" } })
scene.find({ name = { "ground" }, include = { "transform" } })
```
A field written both inside `query` and beside it is refused, naming
the field.
This replaces the old `find`, `findAll`, and `findByComponent`.
# scene.list
List the scene snapshots available in the current world.
```lua
scene.list()
```
Returns the array of scene-snapshot names registered in the live world.
# scene.load
Load a scene snapshot into the live world.
```lua
scene.load("main")
```
Loads via `layers.load(name)` and records `name` as the toolbox's last
scene name, so a subsequent no-arg `scene.save()` persists back to the
same snapshot. Returns `{ loaded = name }`.
# scene.loadedLayers
The scene LAYERS loaded into the live world right now.
```lua
scene.loadedLayers()
```
Reports the root scene plus any additive overlays (editor UI, effect passes)
currently loaded — one record per layer with its `name`, backing `scene`,
`status`, `visible`, whether it is `additive`, and whether it is the `root`.
This lists loaded LAYERS (the runtime state), not the scenes available to load —
for that use `scene.list`. Returns `{ LoadedLayer }`.
# scene.migrate_v6_to_v7
Converts a v6 scene's `scene.json` to the v7 format, in place and user-initiated only — the migration never runs automatically. v6 scenes carry top-level `player{}` and `camera{}` object blocks; v7 replaces both with a single top-level string `player` intent, either `"spawns"` or `"none"`, decided from the v6 `player.required_in_play` flag. On `"spawns"` it injects the final-shape `PlayerSetups`/`Spawns` structure that mirrors the `scene.assetType` template — a `DefaultSocialPlayer` prototype with a child body carrying the avatar asset and an owner-scoped camera rig, and a `DefaultSpawn` pointing back at it — with injected ids derived from the scene folder so no two converted scenes collide. Every existing entity, the lighting, and the `format` are preserved untouched. It also scans the sibling `entrypoint.luau` for references to the removed player/camera flow and returns the flagged call sites for review without ever rewriting the Luau. It is idempotent and safe: a scene already at version 7 or higher is skipped, and a scene with a missing, too-new, or invalid version is reported as an error without being mutated. Reach for it to bring an old scene onto the current player system.
# scene.observe
What every scene load did, and what each loaded scene costs. One read carrying the last load's report — what it produced, the root it replaced and the overlays that went with it, the entity counts on each side, how long each phase took, and every failure it produced with the entity, component or lifecycle hook it is about — plus a per-layer inventory of what the engine attributes to each layer and the per-frame cost of each layer's entrypoint tick. Recorded at each load's own completion point and read lazily, so nothing is measured per frame beyond the tick timings themselves. Answers in edit mode as well as play mode.
# scene.reload
Re-run a loaded scene's build.
```lua
scene.reload() -- the active root scene
scene.reload("main") -- a named scene
```
`scene.load` of a scene that is already loaded and unchanged is an
idempotent no-op, so editing an entrypoint and loading it again rebuilds
nothing. This unloads and re-loads the layer in place, running the
entrypoint's build again — in edit mode, so iterating on a build script
does not mean flipping to play and back through the play shadow.
A rebuild saves the scene, the way a write to `build.luau` does: `scene.json`
holds what the reload built, so the next play loads it, and unsaved edits in
the scene are saved with it. A library scene (under `/libs/`) is rebuilt in
the live scene alone, and its files stay as the library states them.
Returns `{ reloaded = <name>, built = true, content = n, editorOnly = n,
saved = bool }` once the layer has been rebuilt (`saved` is false for a
library scene), `{ reloaded = <name>, built = false, reason, message }` when
the build did not run, or `{ error = "..." }` when no matching layer is
loaded.
# scene.remove
Remove entities from the active scene.
```lua
scene.remove("ground") -- delete the default floor
scene.remove({ "probe_a", "probe_b" }) -- several by name/id
scene.remove({ component = { "PointLight" } }) -- every entity with that component
```
Targets are entity NAMES or ids, arrays of them, `scene.find` records, or a
`scene.find` query — so you delete a selection without looking it up first. Each
target is removed with its whole subtree.
A remove is a LIVE edit of the scene: `scene.revert` undoes it, and
`scene.save` writes it into the scene's `scene.json`, which is the file
`zm add` stages and `zm commit` records. To clear a scene while keeping the
player setup, use `scene.clean` instead.
Returns `removed`, one `{ id, name }` record per removed target, and
`playerHint` when a target was part of the player setup.
# scene.replace
Replace a loaded scene's **content** with another scene's content. The
target scene keeps its identity (guid, name, place in the world); its
files — `scene.json`, `entrypoint.luau`, everything else in the scene
folder — become copies of the source's, and the scene reloads so the
world reflects the swap immediately.
```lua
scene.replace("@builtin::scenes.test_arena")
scene.replace("my_template", { dryRun = true })
scene.replace("my_template", { scene = "hud_overlay" })
```
Targets the active scene unless `opts.scene` names another loaded
scene. Target content files the source doesn't have are removed;
identity sidecars are untouched. `dryRun = true` reports exactly which
files would be written and removed, plus the entities the source
declares, without touching anything.
# scene.revert
Discard a scene's unsaved edits and restore its saved `scene.json`.
```lua
scene.revert() -- undo unsaved edits on the active scene
scene.revert("main") -- revert the loaded scene named 'main'
```
The undo for `scene.clean` / `scene.remove` and any edit-mode change, and the
counterpart to `scene.save`. Every edit since the last save lives in the
scene's dirty overlay until you commit it; this throws that overlay away and
respawns the scene from its saved state.
Because the dirty overlay belongs to the scene ASSET (not the runtime layer), a
revert works whether or not the scene is currently loaded — pass a `name` to
revert a specific scene, or omit it for the active one. This reverts only the
edit-mode dirty overlay; it is not the play-mode baseline restore.
Returns `{ scene, discarded }` — `discarded` is true when unsaved edits were
thrown away, false when the scene was already clean.
# scene.save
Save the loaded scene named `name` back to its own `scene.json`.
```lua
scene.save() -- the last-used scene name (initially "main")
scene.save("main")
```
Resolves the scene by name via `layers.find` and saves that scene — saving
scene A never writes scene B. Errors when no scene by that name is loaded.
Returns `{ scene = name }`.
# scene.setStartup
Make the currently active scene the world's startup scene.
```lua
scene.setStartup() -- pin the active scene as the world's entry point
```
Takes no arguments: it pins whatever scene is live now as the scene the world
auto-loads every time it loads, so after building or loading a scene you call
this to make it stick across world reloads. There is no clear/unset — a world
with no startup scene has no scene context and every script fails, so that is
not a valid choice.
The current startup scene shows in `scene.summary`. Returns `{ scene }` — the
name of the scene now set as the world startup.
# scene.toolbox shared module
Cross-tool sharing for the `scene.*` toolbox: the hierarchy snapshot core
(`snapshot`, `findAll`, `leaf`) that backs tree / findAll /
findByComponent / summary, and the last-scene-name state that save / load
share. Tools call these functions; the functions call engine APIs.
# scene.spawns
The scene's spawn points. `scene.player` decides whether a scene spawns
players and what they become; this decides **where they arrive** — the
PlayerSpawn entities themselves.
```lua
tools.use("scene", "spawns") -- report every spawn
tools.use("scene", "spawns", "add", { position = { 12, 0, -4 } })
tools.use("scene", "spawns", "set", { spawn = "DefaultSpawn", rotation = { 0, 90, 0 } })
tools.use("scene", "spawns", "remove", { spawn = "RedSpawn" })
```
## What a spawn decides
- **Its transform** — where a joining player's body lands while `placement`
is `at_spawn_transform`, and its forward axis is the direction they face.
The edit-mode debug overlay draws that as a ring, a heading arrow and a
standing capsule, so a spawn is visible where it stands.
- **Its prototype** — which PlayerPrototype subtree gets instantiated for the
joining user. A spawn whose prototype is unset or no longer resolves cannot
spawn anyone; the report says so (`prototypeResolves`) and the overlay draws
it red. In play the scene holds the prototype as the captured template each
joining player is cloned from, and the spawn's prototype resolves to that
template.
- **team / role / maxPlayers / spawnPolicy** — the PlayerSpawn component's own
fields, carried onto the players it spawns.
## Picking a spawn
`opts.spawn` names the spawn to act on, by name or id. With one spawn in the
scene it is implied; with several it is required, and an unmatched name is an
error listing what the scene has. On `"add"` the same field names the new
entity instead.
New spawns are parented alongside the spawns already in the scene (else under
the scene's `Spawns` container), so spawn points stay collected in one place.
Mutating saves the scene.
# scene.summary
High-level "what's in the scene" report, and the call that counts the entities
in the scene or in one group of it.
```lua
scene.summary()
scene.summary({ limit = 0 })
scene.summary({ under = "level_1", limit = 5 })
scene.summary({ under = "level_1", fields = { "entityCount" } })
```
Returns `{ entityCount, rootCount, roots, truncated, more?, under?,
activeCamera, player, startupScene }`: the visible entity count, the
top-level rows (with their hierarchy fields), the active camera id, the
player setup with the verb that changes it, and the world's startup scene.
`roots` carries at most `limit` rows, 20 when the call names none. `limit = 0`
answers the counts, camera, player and startup scene alone, the read to make
when the rows are not the question. `rootCount` is always the full count, and
`truncated` with `more` says when rows were left out. An answer to a call naming
neither `limit` nor `fields` carries `narrowWith`, the options that shorten it.
`under` names entities (an id, a name, a proxy, or an array of them) and scopes
the report to what is beneath them: `entityCount` counts their descendants and
`roots` holds their children. A reference that names no entity is refused by
name. `includeInternal = true` counts entities marked internal too.
`fields` keeps only the named fields of the answer: `{ fields = { "entityCount" } }`
answers the count alone, the cheapest read to repeat while a scene changes. A
name no answer carries is refused, and the refusal lists the fields.
For the full structure, `scene.tree` renders the hierarchy itself, and
`scene.find { roots = true }` lists every root.
# scene.tree
Render the entity hierarchy as an indented tree — the quick "what is the
current structure" view.
```lua
scene.tree() -- the whole active world, 4 levels
scene.tree("player") -- just the player subtree(s)
scene.tree(nil, { depth = 2 }) -- roots + their direct children
```
Each line shows the entity's name and its component types; children nest
under their parent. Anything deeper than `depth` (or beyond the node
budget) is summarized as an explicit `… +N below` count instead of being
silently dropped.
Options:
```lua
{
depth = 4, -- levels to expand (1 = just the roots)
components = true, -- annotate each entity with its component types
includeInternal = false, -- include entities marked internal (and their subtrees)
limit = 500, -- node budget
}
```
Returns:
```lua
{
text = string, -- the rendered tree (print this)
roots = { { id, name, components?, childCount, children?, omitted? } },
total = number, -- entities in scope (full subtrees)
shown = number, -- nodes rendered
truncated = boolean, -- depth or budget cut something
}
```
The target is an entity id, a name (every matching entity), a proxy, or an
array of them; omit it for the whole world from its roots. Children sort by
name, so repeated calls give stable output.
# scene.whyPartial
Answer why a loaded layer is not whole. Returns the nearest cause from a closed set — `loaderRaised`, `entrypointCompileFailed`, `entrypointBodyRaised`, `entrypointRaised`, `buildRaised`, `entityFailed`, `parentMissing`, `parentRefused`, `parentAbandoned`, `componentUnresolved`, `componentRefused`, `subscriberRaised`, `updateRaised` — with the engine's own words for it and the full list of failures, each naming the entity, component identity or lifecycle hook it is about. A layer that produced everything its scene declared reports `ok = true` and no reason.
# profiler
Find where the frame time goes — autonomously, in any scenario, without a human reading a graph.
The engine's raw profiling surface is flat (`getProfilingDataTable`, `getLuauVmDataTable`, `profiler.stopCapture`). These tools compose it into the honest, self-accounting hierarchy a profiler should give you: every node shows its **self** time (own cost, excluding children), its **total**, call count, and share of the frame; the frame time no schedule covers shows as an explicit **present / idle** (vsync) bucket instead of vanishing; and each heavy component's `update(dt)` is attributed down to the exact **component + entity** so the cost lands on something you can open and fix.
The intended call site is the `use_tool` MCP surface — `use_tool { toolbox = "profiler", tool = "...", args = [...] }`.
## The tools
- **`summary`** — the engine's own one-line performance summary, the string that rides a tool response. A *different measurement* from everything below: this is the published smoothed frame, while the rest report the profiler's effective frame time (wall clock minus the cost of the call doing the asking). Read it when you want the figure other callers are being told; read `frame` when you want to know where the time goes.
- **`frame`** — the full attributed tree (self / total / calls / % per node). The deep view; read from the top row down.
- **`hotspots`** — a flat, ranked list of the costliest nodes by self time. The fast "what's slow" triage.
- **`scripts`** — per-component `update(dt)` attribution: last / avg / max / calls, by `component @ entity`. The "which of *my* content is slow" view.
- **`record`** — start / stop / status a background recording that spans a play session. Play across as many turns as you like, then stop to get avg / p50 / p90 / p99 / max frametime and the **spike-cluster distribution**. The path for "it hitches while I play", which a single live frame can't catch.
- **`ring`** + **`retro`** — the latency-immune path. `ring on` keeps an always-recording history of the last N seconds; `retro` reads it back AFTER the fact. Because the data is historical, it does not matter that a tool call lands seconds after the spike — the flaw that makes `frame`/live sampling unreliable for an agent (which can't control when its calls land).
- **`watch`** + **`hits`** — the conditional path. `watch <ceilingMs>` arms a frame-time watchdog that either records every bad frame (review with `hits`) or pauses gameplay the instant one hits (freeze + inspect with `retro`). Runs in the engine's per-frame hook, so it catches stalls an agent poll would miss.
- **`gpu`** — GPU pass timings from timestamp queries, label-aggregated (`compute.<shader>`, `scene.*`, `post.<effect>`, `feature.*`). The other side of the frame: when the CPU tree shows everything under **present / idle**, the frame is GPU-bound and this is the view that says which passes the GPU spends it on.
Everything an agent reads is on **effective** frame time — wall-clock minus the agent's own injected `execute` cost — so your profiling and authoring calls never masquerade as game hitches. Spike reports are **distributions** (every spike frame grouped by its dominant hotspot), so one capture shows the whole picture rather than a single anecdotal worst frame. The ring and watchdog are **editor-profile only** and off until enabled, so a shipped runtime never pays for them.
## The autonomous loop
1. `hotspots` or `frame` — baseline, what's expensive now (best when the scene is steady; live sampling races the ~seconds of tool-call latency).
2. For anything that hitches: `ring on` → play / test → `retro` — latency-immune, and the clustered distribution of every spike. Or `watch <ceilingMs>` in `pause` mode to freeze the exact bad frame.
3. `scripts` — attribute script cost to the component + entity.
4. Fix, then `retro` / `record` again and `compare`.
Every read tool accepts a recording label as its `source` — including a `retro` or `hits` snapshot — so anything you can see live you can also drill into for a recorded window's clusters, worst, or typical frame.
# renderDiagnostics module
Publishes the `overdraw` and `zfighting` capture views, so `capture pass=<name>`
resolves to them. Requiring the module registers both.
```luau
local diagnostics = require("@builtin::systems.renderDiagnostics.renderDiagnostics")
diagnostics.register() -- idempotent; already done by the require
diagnostics.unregister() -- withdraw both views and drop their features
```
Registration is cheap and permanent: each view's passes are gated to the debug
channel the registration hands out, so they are skipped for every camera that is
not a capture selecting that view. The feature that draws a view is created the
first time it is selected, through the registration's `ensure`.
`renderer.captureView.list()` enumerates every registered view, and the package
readme has what each colour band means.
# diagnostics
Ask the engine what's wrong with a scene — triage broken materials, missing assets, and component errors before guessing.
Three read-only inspectors over the active world's canonical state: the current component and entity errors (all of them, or narrowed to one entity), an at-a-glance summary of the scene (entity count, component-type breakdown, error count, cameras, culling stats), and a validation pass that checks scene integrity — broken materials, missing model assets, entity errors. Nothing here mutates the scene; it only reports.
# worldValidation
Validate a world's authored content — the cargo-check equivalent for scenes, scripts, and assets — and report what's broken.
Run a full pass over the world plus every imported library, or narrow it: the world's own content only (everything under source except the libraries), every imported library, or one named library. Generate a report with structured filter and format options — scope, minimum severity, category, code, path pattern, source, placeholder inclusion, a problem limit, and a render format (human, markdown, JSON, or summary) — and optionally write it to a file. Or ask for just the one-line health summary with no problem list. Each pass returns the validation report alongside a one-line summary.
# topics/rendering guide
Reference docs surfaced through `guides { path: "..." }` and `man topics/rendering`.
The content lives in `guide.md`; this README is just the asset summary.
# tests
Run the engine test suite from inside a live engine and triage the results — the baseline-then-regression loop, without leaving the session.
List every registered test suite (optionally with test counts) to see exactly what the runner and CI will execute. Run everything, one suite, or a subset — each suite runs through its own cooperative coroutine so multi-frame tests yield correctly — and get back structured results plus Markdown and JSON reports written to the VFS. Compare two JSON reports to surface the failures that are new since the baseline, which is how you catch regressions a change introduced. The lower-level framework for authoring suites lives in the test module and the `testSuite` asset type.
# yaml.module
YAML decode + encode for authored engine content. Pure Luau, no engine
dependencies — a general parsing library, not data-system plumbing.
```luau
local Yaml = require("@builtin::modules.yaml")
local doc = Yaml.decode(vfs.read(path))
vfs.write(path, Yaml.encode(doc))
```
## Supported subset
- Block mappings (`key: value`) and block sequences (`- item`), nested
to any depth.
- Compact sequence-of-mapping entries (`- path: x` / ` kind: y`).
- Flow collections — `{ a: 1, b: 2 }` and `[1, 2, 3]` — single line.
- Plain scalars with type inference: `~` / `null` → nil, `true` /
`false` → boolean, numeric literals → number, everything else →
string.
- Single- and double-quoted strings (`''` escapes a literal quote
inside a single-quoted string; `\n` `\t` `\r` `\\` `\"` inside a
double-quoted one). A quote opens a quoted scalar where a scalar
begins — after `key:`, after a `- ` entry marker, or inside a flow
collection — so a plain scalar carries an apostrophe as data
(`note: the world's rules`). Quoted keys are read in flow mappings.
- `#` comments — honored outside quotes, so a `#` inside a quoted
string is kept as data.
- Literal (`|`) and folded (`>`) block scalars — the bare indicators
only. A block scalar's content is literal text: quotes (balanced or
not), `#`, `key: value` and `---` inside it are data.
- An optional leading `---` document marker.
## Loud-error contract
Constructs outside the subset above raise instead of misparsing:
anchors/aliases (`&`, `*`), tags (`!`), directives (`%`),
multi-document streams (a second `---`), block-scalar
chomping/indentation indicators (`|-`, `|+`, `>-`, `|2`, ...), tab
indentation, and inconsistent indentation (both block structure and
block-scalar bodies). Every error carries the offending line number
(`yaml: line N: ...`), so a bad config points straight at the line to
fix.
Tab indentation is rejected everywhere — including block-scalar body
lines whose leading whitespace contains a tab. A tab after the first
non-space character of a line is content and passes through.
## API
- `Yaml.decode(text: string): any` — decode a YAML document into a
Luau value (table, scalar, or nil for an empty document). Raises on
malformed input or an unsupported construct.
- `Yaml.decodeWithComments(text: string): (any, boolean)` — decode as
`decode` does, and report whether the text carries a comment by the
decoder's own rule: a `#` at a line's start or after whitespace, outside
a quoted scalar and outside a block scalar. Re-encoding the value drops
such comments, so an editor that writes a document back reads this first.
- `Yaml.encode(value: table): string` — encode a Luau table as YAML
(block style, two-space indent, alphabetically sorted keys). Raises
on values YAML can't represent (functions, userdata, non-string
mapping keys).
A top-level empty table encodes to an empty document, which decodes
back to `nil` (the YAML empty-document ambiguity).
# interfaces
The screen-building skill: author a UI as a styled widget tree the way you
write HTML and CSS, register it, and then see it and drive it through the `gui`
toolbox rather than reasoning about the tree.
Covers the layout and paint model, entrance and idle animation, callbacks that
fire in play mode, and the build → capture → play → iterate loop that gets a
screen from blank to built.
# debugging
Finding out **when** something went wrong in a running world.
The job this skill covers is not "what is the current value" — the current
value is downstream of the moment that matters. It is: attach an instrument to
running code, keep working, and be told the instant the thing happens.
It exists because the reflex it replaces does not work. Running something,
waiting, and taking a capture aims at a moment you cannot see: seconds pass
between the call and the frame, and adding a wait only moves the guess. Polling
is the same guess with more steps.
Covers: probing a function call, a source line, or a value; using a condition
to name the moment rather than every step toward it; reading the state a value
was taken in before trusting the value; and cancelling what you armed.
The trap it spends the most words on is the expensive one — a right value read
in the wrong world, where the match already ended or the scene already swapped,
nothing announced it, and every number afterwards means something else.
# assetType runtime
The machinery that reads a `<typename>.assetType/behavior.luau` and turns its
declarations into live behaviour.
A `behavior.luau` is a table of declarations — `ref` methods, `modules` shared
code, an `events` schema, a `namePattern`, `refShapes`, and the `onCreate` /
`onRegister` / `onChange` / `onDelete` / `validate` / `settingsDefaults` /
`settingsCorrections` hooks. None of it runs itself. This is the code that
runs it, and it lives here because reading a type's declarations is the
**assetType type's own behaviour** — the same way `material.assetType` owns
what a `.material` does.
## Sub-modules
| Module | Reads | Responsibility |
|---|---|---|
| `ref.module` | `ref`, `modules` | Builds every `AssetRef` envelope, attaches the shared metatable, and dispatches per-type methods and shared modules onto it. Also owns edit-mode write-behind persistence. |
| `create.module` | `onCreate`, `namePattern`, `validate` | Backs `asset.create`: resolves the type, checks the name against its pattern, runs `onCreate` (or clones `template/`), and writes the instance. `validate.module` beside it checks a creation `opts` table against the type's `createSchema`. Before running `onCreate`, resolves the type's settings chain (below) and hands the result to the hook as `opts.settings`. |
| `settings.module` | `settings`, `settingsDefaults`, `settingsCorrections` | A type's declared settings schema and where its values live (`type.yaml`'s `settings:` block). `Settings.resolveForCreate` layers the schema's own defaults, the type's own `settingsDefaults(name, opts, asked)` hook (a DEFAULT the schema can't express — a name-derived convention, a fact read off a payload the caller handed it, a value following a field `asked` shows a higher layer naming; any later layer overrides it), the Preset Manager, an importer's settings, the caller's `settings` table, then the type's own `settingsCorrections(values, name, opts)` hook (a CROSS-FIELD CONSTRAINT the schema can't express, applied last over the fully merged values). A correction over a default/preset/importer value lands silently; a correction that would override what the caller's own `settings` table explicitly asked for refuses the creation instead, naming the field and why. Neither hook is ever handed a table to mutate; each returns what it wants changed (`settingsCorrections` may also return a `{ [field]: reason }` table for that refusal message). `Settings.cloneValues` deep-copies a values table — `create.module` hands `onCreate` a copy, never the table it stamps. `Settings.valuesOf` / `writeValues` read and write an asset's own values file. |
| `typeYaml.module` | `type.yaml` | The folder a type lives in and its parsed `type.yaml`, decoded once per content version of the file. `settings.module` and `inspector.module` read their blocks through it. `about` / `aboutAt` read a type's `about.yaml` (`intent`, `function`, `usage`), leaving out any key that is empty or still starts with `[[describe]]`; `aboutRows` and `aboutMarkdown` lay the texts out for the Inspector and the `types/<name>` guide. |
| `inspector.module` | `type.yaml`'s `inspector:` block | Which inspector a type declares for its assets (`inspector: { type: ... }` or `{ instance: ... }`), and the declaration that file returns — the sections it adds, the generic ones it replaces, and their order — or the problem that kept it from loading. |
| `onRegister.module` | `onRegister` | Fires an instance's once-only registration hook — on arrival, on world load, and for `@builtin` library instances. |
| `changeDispatch.module` | `onChange`, `onDelete`, `refShapes` | Routes a VFS source write or a folder delete to the enclosing typed asset's type hooks. |
| `refShapes.module` | `refShapes`, `ref` | Publishes what every `AssetRef<category>` answers to, so a member read on an asset-typed value is checked against that category's real surface. |
| `events.module` | `events` | The per-asset event runtime behind `ref.events`. |
| `instantiable.module` | `ref.instantiate` | The instantiation contract an asset type opts into: `root` stands the root entity, `place` applies the base placement opts to one the type adopted, and `result` shapes the `(root, idMap)` every `instantiate` returns. Also registers the `sceneInstantiable` field-constraint validator. |
| `declaration.module` | `type.yaml` | The type's decoded declaration, read once and held until a write inside an `.assetType` folder; what every question about a type as a whole reads. |
| `previewRecipe.module` | `type.yaml` `preview:` | How an instance's `preview.png` is produced: which of the four recipes (`instantiate`, `image`, `surface`, `custom`) the type declares, and what that recipe needs. |
## Reaching it
```luau
local rt = require("@builtin::assetTypes.assetType.shared")
rt.ref.loadTypeBehavior("material")
```
Fields resolve lazily. The prelude requires the sub-modules directly, in
dependency order (`ref`, then `changeDispatch`, `onRegister.install()`,
`refShapes.install()`) — a table that required all six on load would take that
ordering away from it.