# Scene (asset type)
A scene is a saved, loadable snapshot of an entity scenegraph inside a
world: the entity hierarchy, transforms, components, lighting, and a
declared `player` intent, plus an auto-discovered startup script. A scene
is the unit of "level" or "screen" — a title screen, a lobby, a gameplay
area, and an end-of-game summary each get their own scene.
Scenes load as **layers**. One root scene is active at a time; additional
scenes can load additively as overlays on top of it. Each scene owns its
own multiplayer relay room. Switching scenes is a local call: the client
that makes it leaves the old scene's room and joins the new scene's room.
## When to use one
- You want a savable, re-loadable snapshot of an entity scenegraph plus
its lighting and player setup.
- You want a runnable starting state for a level or screen.
- You want a scenes-as-data flow: `layers.load("lobby")`, edit live, then
`layers.active:save()` to publish the edits back to the scene.
For a reusable entity assembly (a prop, a vehicle, a UI panel) that many
scenes spawn into themselves, use a `.bundle`. A scene is a whole-world
snapshot; a bundle is one prefab that lives inside scenes.
## Folder shape
A scene asset is a folder ending in `.scene`. Its identity is the folder
name with the suffix stripped (`Lobby.scene` → `Lobby`).
- `scene.json` — the scenegraph: `entities[]`, lighting, and the
top-level `player` intent. **Required.** Written by the engine — a build,
a save, a human dragging something in. Not hand-edited.
- `build.luau` — what the scene is made of, written as code. Runs while you
author; saving bakes its result into `scene.json` (see Building a scene).
- `entrypoint.luau`: the startup script. **Required.** Auto-discovered as a
sibling of `scene.json`; define lifecycle callbacks here (see The entrypoint).
- `<name>.<type>/` — an asset the build makes, authored here by `build.asset`
(see The assets a build makes), alongside `.build.assets`, which records
which `build.luau` produced each of them.
- `prefabs/` — optional subfolder for scene-local bundles.
- `scripts/` — optional subfolder for scene-local Luau helpers, required
from `entrypoint.luau`.
- `README.md`: notes about THIS scene: what it shows or plays and what it
is for. **Required.** The general scene model lives here, in
`guides { path: "types/scene" }`.
- `.metadata`: **Required.**
`scene.json` is version 7. It carries `"format": "scene"`,
`"version": 7`, an `entities[]` array, and a top-level `"player"` string
intent.
## The `player` intent
Every scene declares how it handles players with a top-level `player`
field in `scene.json`:
- `"spawns"` — the scene carries an authored player setup, and the engine
spawns a player for each connecting user from it. This is the default
for a freshly created scene.
- `"none"` — the scene spawns no player and authors no camera. Author your
own Camera entity for the view (menus, UI-only screens, cinematics).
### How `"spawns"` works
A `"spawns"` scene authors two things in `scene.json`:
1. A **PlayerPrototype** — an entity carrying the `PlayerPrototype`
component, whose `body` field names a child entity (the body). The
body carries an avatar (an `Asset` pointing at an avatar, e.g.
`@builtin::avatars.humanoid`). A `CameraRig` child carries a `Camera`
with a camera behavior (e.g. `orbital_follow`). The prototype root is
authored `PrototypeOnly` so it exists as a clonable template.
2. A **PlayerSpawn** — an entity carrying the `PlayerSpawn` component,
whose `prototype` field names the PlayerPrototype to instantiate and
whose transform is where players appear.
The scaffolded scene groups these under two organizing entities,
`PlayerSetups` (holding the prototype) and `Spawns` (holding the spawn),
so the authoring tree stays legible.
On each user join — entering play, and each subsequent connect — the
engine runs the spawn for that user:
- It clones the PlayerPrototype subtree.
- The clone root becomes the user's **internal identity** — a registry-only
entity named `user` carrying the `UserIdentity` component. The identity
is the anchor for who the player is; it has no world presence.
- The body named by `PlayerPrototype.body` is adopted as the user's
**avatar** — their visible presence in the world — and placed at the
PlayerSpawn's world transform. Move the PlayerSpawn (or drag it in the
editor) to set where players appear.
- The `CameraRig`'s Camera follows the bound avatar.
The player prototype is live in edit mode so you can see and adjust it. In
play mode it is deactivated and marked internal — it stays a clonable source while
each user gets their own clone.
### Reaching the live player
The player surface lives on the root scene's registry,
`layers.active.players`:
- `players.localPlayer` — this client's player, a curated handle.
- `players.localReady` — `true` once the local player's avatar is bound
(or the scene opted its avatar out).
- `players:list()` / `players:count()` — the players connected in this
scene's room.
- `players:get(userId)` — a connected player by account id.
- `players:ownerOf(avatar)` — the player whose body is a given avatar.
A player handle is a data record about who the player is, plus a link to
their body:
- `player.avatar` — the body's entity ref. Act on the body through it
(`player.avatar.position`, raycasts, rig access).
- `player.isLocal` — whether this client owns the player.
- `player.ready` — whether a live avatar is bound.
- `player.userId` / `player.identity` / `player.displayName` — the
player's account identity.
- `player.avatar = ref` — bind a live body entity as the player's body
(assign nil to clear). To use a `.bundle` / `.avatar` asset, spawn it
into the world first, then bind the resulting entity.
The player's identity entity is the internal anchor; the handle exposes the
body (`player.avatar`) and the player's data, and reaching for
`.entity` / `.id` / `.component` raises with a redirect to `player.avatar`.
## Building a scene
`build.luau` declares what the scene holds. It is ordinary engine code —
`entity.spawn`, `component.add`, transform writes, `for` loops, a `require`
of a module that computes a layout — and what it creates is what ends up in
the scene.
```lua
function content()
for i = 0, 4 do
local crate = entity.spawn("crate")
crate.localPosition = { i * 2, 0.5, 0 }
crate.component.add("Model", { model = asset.resolve("cube", "mesh") })
end
end
```
The build runs while you author, in **edit** mode, and what it created lands in
the live scene. Saving the scene bakes it into `scene.json`, which is what makes
the entities durable content: a human can select and inspect them, they
replicate, and they are there when the world opens without `build.luau` running
at all. Play mode never runs it — in play the entities load from `scene.json`
like anything else the scene holds.
**Editing the file rebuilds the scene in place.** Writing `build.luau` is the
signal; there is nothing to reload, and the rebuild saves. An entity keeps the
id it had, so a reference to it — a spawn naming a prototype, another entity's
component naming this one — survives every rebuild. Add a crate to the loop and
the other four do not move.
A write through `write_file`, `edit_file` or the engine's `bash` answers once
the rebuild it started has finished, so what the rebuild landed and kept comes
back on that answer as a notice, whose `message` is the report's summary line:
```
[info] a write to build.luau rebuilt the scene { content="6", scene="scenes.main",
editorOnly="1", kept="1", message="build.luau against the scene: kept 1 value on
1 entity (crate_3); ..." }
```
A rebuild still running when the write's wait ends is named under the answer's
`startedWork`, and its notice arrives on a later call.
An edit saved while a rebuild is still running is an edit to code that rebuild
has already read, so it gets a rebuild of its own once that one finishes, and
says which it was:
```
[info] a write to build.luau arrived during a rebuild and was rebuilt after it
{ content="7", scene="scenes.main", editorOnly="1" }
```
Several edits saved during the same rebuild get the one run after it, which
reads the file as it stands then.
A scene that declares a build also runs it when it **loads** in edit, so the
scene shows what the code says now, including an edit made while the world was
closed. A load whose `.build.state` records the current script reads
`scene.json` as the build and runs nothing. When the load does run it, a
world's own scene saves the result, unless the scene holds unsaved edits: those
stay the author's to keep or discard, and the file write waits for their save.
A library scene (one under `/libs/`, the `@builtin` library included) is read
by its load: the build lands in the live scene and its files stay as the
library states them. Play reads `scene.json`, so it comes up without that build
until `:build()` saves it.
### The two surfaces
- `content()` — the scene's own entities. Present in play.
- `editorOnly()` — entities present while authoring and absent in play. They
carry the `EditorOnly` participation the runtime deactivates and hides when
play begins, and they are baked too, so a collaborator opening the world sees
the same ones. Anything an author needs to see and a player does not goes here
— an alignment guide, a spacing marker, a debug volume.
Both are optional. A scene with neither has no build.
### What a rebuild touches
Only the entities the build itself placed. Anything a human dragged in, or a
tool placed directly, is invisible to a rebuild and never moved or removed.
Within what it owns, the build is authoritative: an entity the code stopped
emitting is despawned, a component it stopped adding is removed.
A plain rebuild keeps a hand edit to an entity the build placed: a value
`build.luau` states the way the last build stated it is left as the scene holds
it, so a move, a rename, an attribute, the active flag, the lifecycle mode, the
replication scope or a component field changed since survives the rebuild, the
one a write starts included. To see every such edit,
ask the build for its report:
```lua
local report = layers.active.asset:build({ save = false })
print(report.message) -- opens with one line counting all four lists
```
On a scene already holding what the build states it leaves nothing to save,
and it answers `kept` (hand edits to entities the build placed), `driven`
(fields another component writes at runtime, such as a sky orienting the sun),
`handAdded` (components and attributes added by hand to built entities) and
`handPlaced` (entities no build placed). An entity's render layer and its
`hide()` switch are runtime state no build sets, so the lists leave them out;
the answer states what the scene holds on both for the entities a build
placed instead, in `renderLayers` (`{ entity, name, layer }`) and `hidden`
(`{ entity, name }`), and its message counts them ("render layer set on 3
(...); hidden by hide() 0"). It also names the scene it compared: `client` is
the client of the world it ran in (`user`, or a sub-client's id), since every
client holds its own live scene, and `unsaved` lists the edits that scene held
beyond the saved `scene.json` (the entries `sceneAuthoring.changes` lists), so
an empty `unsaved` makes the report a statement about `scene.json`. To land
`build.luau`'s values over the kept ones:
```lua
layers.active.asset:build({ restate = true })
```
A restate writes exactly the values `kept` names, so the scene's diff after one
is the report. To bring a `handPlaced` entity into the build, delete the
hand-made one and save the scene, then write it into `build.luau`: the write
rebuilds at once in every client and the writing client saves its rebuild, so
a delete left unsaved in another client can come back. A hand-made entity
still standing under a name the build now places is reported with
`builtTwin`, a second copy beside the build's, and the message names the
calls that settle it. The message also compares the report against
`scene.json` as saved: it names each unsaved edit and what it changed, and any
entity whose live state differs from the scene's files with no unsaved edit
behind it (a write this client has not taken), with the calls that take that
client back to `scene.json` before anything saves from it.
`guides { path: "core/scenes-as-code" }`, "What a rebuild touches", gives the
shape of every entry and how `driven` and `restate` meet.
The build writes its own name and each entity's place in the hierarchy onto the
entity, and `scene.json` records that pair beside the entity's name and
transform — which is why a rebuild after a reload, in a later session, lands on
exactly the entities it placed the first time without anything having been
remembered.
### When the file did not change
`:build()` runs the build against what it resolves right now — for the case
where something the builder *reads* changed and the file did not: a module it
requires, an asset it resolves. After a write it is unnecessary; the write has
already run it.
```lua
layers.active.asset:build() -- rebuild and save
layers.active.asset:build({ save = false })
```
It answers with how many entities each surface placed —
`{ content = 6, editorOnly = 1 }` — and with nil for a scene that has no
`build.luau`. Called while a build for that scene is already running, it returns
at once with `{ inFlight = true, scene, trigger, startedBy, message }` naming
that build instead of starting a second one; `inFlight` is what tells the two
answers apart.
An operation the bake cannot hold is **refused** rather than applied. A build
accepts what its records carry: entity lifecycle, transforms, hierarchy, names,
visibility, active state, participation mode, network scope, attributes, and
components with their public data. Anything else raises while the build runs,
naming the operation and the build it answered to, instead of leaving the scene
depending on something no reload brings back. When that happens the previous
build stays exactly as it was. A runtime resource a build needs — a mesh it
generates, a texture it writes — is made as an asset instead, below. Everything
else a refusal names goes outside the builder, or into a component the builder
attaches, which runs at play.
### The assets a build makes
`build.asset(type, name, produce)` makes an asset the build's content names — a
mesh a lathe produces, a texture a pattern writes. `produce` takes nothing and
returns the creation parameters `asset.create` takes for that type; the call
returns the asset's `AssetRef`, which is what a component field holds.
```lua
function content()
local tower = build.asset("mesh", "tower", function()
local positions, indices = lathe(profile, 16)
return { positions = positions, indices = indices }
end)
entity.spawn("tower").component.add("Model", { model = tower })
end
```
The asset is authored inside the scene's own folder — `Lobby.scene/tower.mesh`
— and the scene records which `build.luau` produced it in `.build.assets`. So
`produce` runs when the build script changed and never otherwise: a reload
re-runs the build and reuses the asset, while editing the profile re-authors
`tower.mesh` **in place**, keeping its path and its guid. That is what holds the
reference — `scene.json` names assets by guid.
For a part of a scene that several scenes place — or that one scene places many
times with different settings — see `guides { path: "types/sceneModule" }`,
which is the same idea with declared `inputs` a placement sets.
`guides { path: "core/scenes-as-code" }` covers both.
## The entrypoint
`entrypoint.luau` is the scene's **runtime** — what happens while the game is
being played. What the scene *is* comes from `build.luau` above; nothing here
has to construct it.
`entrypoint.luau` is auto-discovered as a sibling of `scene.json`. The
loader runs it in a fresh environment and folds its top-level
`function name(...)` declarations into the matching scene lifecycle event.
Define the callbacks the scene needs — the recognised set:
- `onLoad()` — the scene loaded in **play** mode. Gameplay-start hook,
runs on every connected client.
- `onHostLoad()` — the scene loaded in **play** mode, on the client that
owns the scene's synced content (the relay room creator; offline and
single-player count as host). Fires once. Entities spawned here — and
anywhere downstream — become synced automatically, so this is where
shared world content is spawned: it runs on exactly one peer, and every
other peer receives the entities from the relay snapshot.
- `onEditLoad()` — the scene loaded in **edit** mode. Custom per-scene
authoring tools. Writing this file while the scene is loaded in edit mode
reloads its layer, so the new `onEditLoad` runs after the previous load's
`onUnload`.
- `onUnload()` — before the scene's entities are torn down. Extra cleanup;
engine-managed teardown (entity despawn, resource release) runs
separately.
- `update(dt)` — per frame in play mode, while the gameplay clock
runs.
- `editorUpdate(dt)` — per frame in edit mode, running or paused.
Play-paused ticks neither hook. The scene loader partitions these
strictly on mode; a component's hooks of the same name read
`engine.paused` instead, so the two rules differ — `man components`
has that table.
- `localPlayerReady(player)` — once the local player's avatar is ready.
Gameplay wiring for the local player: attach state, bind UI, swap the
avatar. The avatar is already placed at the PlayerSpawn, so this is for
behavior, not positioning.
- `playerJoined(player)` — a remote player joined this scene's room. Use
for per-player UI (nameplates, greetings). The local player arrives
through `localPlayerReady`.
- `playerLeft(eid)` — a remote player left this scene's room. Receives the
departed entity's id (the entity is already despawned).
Each scene's entrypoint runs in its own environment, so two scenes can
declare the same top-level names without clashing. Keep each callback
short; push per-scene logic into `scripts/` modules and `require` them.
## Layers
Scenes load through the `layers` namespace.
- `layers.load(ref, opts?)` — load a scene. `ref` is a scene AssetRef or
identity string. Without `opts.additive`, this is a **root** load: it
replaces the current root scene. `opts`:
- `additive` — load as an overlay alongside the current root instead of
replacing it.
- `persistent` — keep an additive overlay mounted across mode flips and
root swaps.
- `origin` — a `{x, y, z}` world offset for the overlay's entities.
- `deferred` — spread the entity spawn across frames (for
thousand-entity scenes); the load signals complete only once the
scene has settled.
- `layers.active` — the current root scene proxy (nil before any load).
- `layers.list()` — every loaded layer (root + additive overlays).
- `layers.find(ref)` / `layers.is_loaded(ref)` — look up a loaded layer by
ref.
- `layers.onLoad(cb)` / `layers.onUnload(cb)` / `layers.onBeforeLoad(cb)` —
subscribe to every scene load / unload (distinct from a scene proxy's
own `:on_load` / `:on_unload`, which fire only for that scene).
A root scene carries the `players`, `camera`, and `settings` surfaces;
additive overlays inherit the root's players and lighting and do not carry
their own.
### The scene proxy
`layers.active` (and `layers.find` / `layers.list` entries) returns a
scene proxy:
- Fields: `.guid` (canonical identity), `.name`, `.path`, `.asset`,
`.additive`, `.visible`, `.state` (`"loading"` → `"loaded"` → `"ready"`
→ `"unloading"`), `.ready`, `.players`, `.camera`, `.settings`,
`.entrypoint`.
- `.camera` — a proxy over the scene's primary camera entity; read and
write the live Camera component through it, and
`.camera.behaviors._list()` enumerates the available camera behaviors.
- `:save(opts?)` — publish the live scenegraph to canonical `scene.json`
(see Saving). A convenience that forwards to the scene ASSET's `save`
(`self.asset:save(opts)`): the proxy is the runtime view and owns nothing
on disk, so persistence lives on the asset.
- `:reload()`: unload and reload the same scene (a runtime respawn). A scene
with a `build.luau` runs its build again and saves the scene, so `scene.json`
holds what the reload built and the next play loads it; a library scene's
rebuild lands in the live scene alone.
- `:clearDirty()` — discard unsaved edits and respawn from canonical.
Forwards to the scene asset's `discard` (`self.asset:discard(opts)`).
- `:sceneAsset()` — the durable `AssetRef<scene>` this live layer maps to.
- `:promoteDirty()` / `:writeDirty()` / `:hasDirty()` — manage the dirty
overlay directly.
- `:unload()` — despawn the layer and free its slot.
- `:onReady(cb)` — fire once the scene reaches `ready` (latched: a late
subscriber fires immediately).
## Multiplayer & relay rooms
Every scene has its own relay room, keyed by the world guid, the boot
profile, the mode, and the scene guid. Switching scenes with
`layers.load` runs a room transition — leave the old room, tear down,
join the destination scene's room — all on the client that made the call.
Teardown of the old scene never leaks to peers in the new one.
In play mode connected to a relay, the scene's entities are
host-authoritative: only the room creator instantiates them (marked
synced), and every joiner receives them from the relay snapshot rather
than spawning their own. This is why shared world content belongs in
`onHostLoad` — spawning it in `onLoad` would run on every peer and
duplicate it. Each player's own avatar spawns per-user from the
PlayerSpawn on every client.
Edit mode and offline boots spawn locally and never auto-sync.
## Loading and saving
**Loading** — `layers.load(ref)` for a root scene:
1. Despawns the current root scene's non-persistent entities.
2. Instantiates the entities from `scene.json` (including the player
prototype and spawn for a `"spawns"` scene).
3. Applies lighting and sky.
4. Runs `entrypoint.luau` and fires lifecycle callbacks as their events
occur.
**Saving** — persistence lives on the scene ASSET. `sceneRef:save()`
writes the scene's current state back to canonical `scene.json`; when the
scene is loaded it captures the live scenegraph, and when it is not loaded
it promotes the pending dirty overlay. `layers.active:save()` is the
convenience form — it forwards to the active layer's mapped asset
(`layers.active.asset:save()`). Writing canonical is the only path that
does so: edit ↔ play cycles never save, so hitting play to test never
overwrites the scene. Between saves, live edits accumulate in a per-scene
dirty overlay that the loader merges on top of canonical.
`sceneRef:discard()` throws the overlay away and restores the saved state
— deleting the overlay, and respawning the live layer when the scene is
loaded. It works whether or not the scene is loaded, because the overlay
belongs to the asset, not the runtime layer. `layers.active:clearDirty()`
forwards here. Saves capture entity data, not the entrypoint script —
edits to `entrypoint.luau` and `scripts/` are always preserved.
`opts.to` on `save`/`discard` targets a different scene ("save as"),
taking either a bare name (`"level_2"`) or a full VFS path.
**What a record states.** A component's record in `scene.json` holds the
fields that instance's configuration states: the keys of the table it was
added with (a `build.luau` call's own init table, or the record it was
loaded from) and every field written since, through code, a tool or the
inspector. A field nothing set stays out of the record and takes the
component's declared default each time the scene loads, so changing that
default reaches every entity that left the field to it. To have an entity
follow the default again, remove the field from its record. A field set on a
live entity after its record was made is a change the scene review names
(`sceneAuthoring.changes` lists it as `+ Type.field = value`), and accepting it
writes the field into the record. A stored
value cannot be told apart from one an author chose, so a stored value
loads and saves as it is, and a hot reload that changes a default one of
them shadows names it. A stored field the component no longer declares is named by a
`[component.add]` warning when the record loads and left out of the next
save.
## Lighting
Lights are ordinary entities: a directional light, an ambient light, and
a sky are entities carrying `Light` / `ProceduralSky` components in
`scene.json`. Author, move, and tune them like any other entity. If a
scene is missing any of {directional light, ambient light, sky}, the
loader adds a temporary default for the absent one so a scene never loads
dark or skyless; the defaults are never saved into the scene.
Scene-level lighting state that is not an entity — clear color and sky
descriptor — lives under `layers.active.settings.lighting` (`clear_color`,
`sky`); writing those fields updates the engine live.
## Modes
Scenes load in both edit and play mode (see `man modes`). The mode
governs behavior:
- An entrypoint's `update(dt)` runs in play while the gameplay clock
runs, and its `editorUpdate(dt)` runs in edit. A component's hooks of
the same name follow the clock rather than the mode — `man
components` has the four states that produces.
- Player prototypes are live in edit and deactivated + internal in play,
where each user instead gets a clone. `EditorOnly` entities follow the
same edit-live / play-internal toggle.
- `onLoad` / `onHostLoad` fire on a play-mode load; `onEditLoad` fires on
an edit-mode load.
## How to create one
```luau
asset.create("scene", "<Name>")
-- Creates /zero/source/<Name>.scene/ with:
-- build.luau where this scene's content is written. A new one starts
-- with the sun / ambient / sky lighting and the "spawns"
-- player setup, commented for editing — everything else the
-- scene comes to hold is written here too.
-- scene.json what that code produces, baked.
-- entrypoint.luau commented lifecycle-callback stubs.
```
A freshly created scene has a player with a following camera on the first press
of play. It carries no ground, so the first thing to author is what the player
stands on — a `content()` line away in `build.luau`.
## Discovery
- `asset.list("scene")` — every registered scene.
- `asset.inspect("<name>")` — entity count, lighting summary, source path,
and this type README.
## Authoring conventions
- Keep static layout in `scene.json` — geometry, lights, props, the player
prototype and spawn.
- Keep dynamic setup in `entrypoint.luau` lifecycle callbacks — event
listeners, gameplay state, services attached to spawned entities.
- Spawn shared, synced world content from `onHostLoad`; spawn each
player's own gameplay wiring from `localPlayerReady`.
- Set the world's startup scene in `/.world_settings` — that is the scene
the world boots into.
- Y is up; -Z is forward.
- Renaming the folder changes the scene's identity. References to the
scene are recorded against the scene itself, so renaming or moving it
does not break them.
## Related types
- `.bundle` — reusable entity hierarchies that scenes spawn into
themselves.
- `.service`: a declarative content generator a scene can draw on.
- `.world_settings` — picks the startup scene and world-level renderer /
physics options.
## In the Inspector
Selecting a scene opens its **Scene** section, read from `scene.json` without loading the scene: how many entities it holds, how many of them are roots (and their names), how players join and the file's format version when it states them, and whether the scene has edits not yet saved.
# lookdev (bundle)
The reference subject a lighting preview is photographed on: a grey ground,
a white diffuse sphere, a chrome sphere and an 18% grey card standing behind
them. The diffuse sphere shows the light's direction, colour and softness, the
chrome sphere reflects the sky and the light sources, and the grey card reads
the exposure. Five entities under one root, built from builtin meshes and
materials.
A type whose pictures show what an asset does to a scene names it as its
preview `subject` (a scene setup's preview, for one); the asset is applied to
the world while the subject is photographed.
```lua
asset.resolve("@builtin::preview.subjects.lookdev", "bundle"):instantiate(nil, { position = { 0, 0, 0 } })
```
# Model
Loads and displays a 3D mesh on an entity. Disabling the component hides the mesh. Supports procedural meshes (`cube`, `sphere`, ...), model files, and remote URLs. Tint and outline are shader effects applied to the mesh.
**Material lives on this component.** There is no standalone `Material` component — a material only renders where there is a mesh to render it on, so the `material` field is part of Model (and SkinnedModel). Set it at add time or assign the field later; properties are registry-wide.
Public fields: `model`, `material` (`AssetRef<material>`), `tintR/G/B`, `tintBlend`, `outlineR/G/B`, `outlineIntensity`, `outlineOccluded` (`"hide"`, the default, hides the rim where geometry stands in front of the mesh; `"dashed"` draws it there in dashes, the `occluded` choice of `@builtin::modules.outline`).
Methods: `:setTint(color, blend?)` (color: `{r, g, b}` array or `{r=, g=, b=}` map), `:clearTint()`, `:setOutline(color, intensity?)`, `:clearOutline()`, `:setMaterialProperty(prop, value)`, `:getMaterialProperty(prop)`, `:getMaterialPropertyNames()`.
```luau
entity(id).component.add("Model", { model = "cube", material = "gold" })
entity(id).component.get("Model").material = "checkerboard" -- swap material
entity(id).component.get("Model"):setTint({1, 0, 0}, 0.5)
entity(id).component.get("Model"):setMaterialProperty("roughness", 0.2)
```
**Tint is synced.** Every `tint*` field replicates, so `:setTint` is the colour every participant sees. A colour that changes every frame on many entities (a stress map, a heat map, a damage flash, per instance colour) belongs in an instance-data lane instead: wear `@builtin::materials.instance_color` (or `instance_color_unlit`) and write `renderer.instanceData.set(id, 2, r, g, b, coverage)`, which replicates nothing and costs about a twentieth of a tint write. `guides { path = "topics/rendering-instance-data" }` has the lane layout.
# lighting
Scene-lighting base capability: ambient + directional ("sun") light and procedural-sky setup with modify-or-spawn, read-merge-write semantics, plus clear color, and the per-frame reads of the resolved lights. Identity is the component, never the entity name: the sun is the `Light` the renderer's snapshot names as the directional holder, the ambient is the light-role component of kind "ambient", and the sky is the entity carrying a sky-role component. Name-based lookup, word resolution, and sky-material orchestration (presets, material swap) live in the `lighting` toolbox.
`sun` and `ambient` configuration patch the scene's resolved sun / ambient light components, spawning a carrying entity when the scene has none. A partial update (e.g. only `intensity`) reads the component's current fields first and merges the given fields on top, so unspecified fields keep their authored values instead of resetting to a default. `sky` writes the sky entity's ProceduralSky component the same way — any of its fields, plus `enabled = false` to remove the sky component.
## Types
- `SunOpts` — `{ direction?, color?, intensity?, castsShadows? }`.
- `AmbientOpts` — `{ color?, intensity? }`.
- `ProceduralSkyOpts` — ProceduralSky component fields, plus `enabled = false` to remove the sky.
- `SetupOpts` — `{ sun?, ambient?, sky?, clearColor? }`.
- `SetupResult` — `{ sun?, ambient?, sky? }`, the entity ids each provided section resolved to.
- `Sun` — `{ direction, color, intensity, castsShadows, entityId? }`.
- `Ambient` — `{ color, intensity, entityId? }`.
- `LightRow` — one punctual light as the renderer resolved it.
## Exports
Writes — each takes the opts above and answers with the entity the light resolved to:
- `M.setSun(opts: SunOpts) -> string` — set the scene's sun, returning its entity id.
- `M.setAmbient(opts: AmbientOpts) -> string` — set the scene's ambient term, returning its entity id.
- `M.applySetup(opts: SetupOpts) -> SetupResult` — apply a lighting setup in one call. All fields optional — only provided fields change. `clearColor` is `{r, g, b}`.
- `M.setProbeVolume(key: string, volume)` / `M.removeProbeVolume(key: string)` — publish or retract a baked irradiance probe volume.
Reads — each takes no arguments, and answers from the resolved lighting state at a cost independent of scene size:
- `M.sun() -> Sun` — the sun the frame is shaded by.
- `M.ambient() -> Ambient` — the ambient term the frame is shaded by.
- `M.lightRows() -> { LightRow }` — every punctual light the renderer resolved this frame.
Identity:
- `M.lightKind(componentType: string, component: any?) -> string?` — the kind a light-role component names.
- `M.lightOfKind(entityId: string, kind: string) -> any` — the light-role component of that kind on one entity.
## Usage
```luau
local lighting = require("@builtin::modules.api.engine.lighting")
lighting.setSun({ direction = { 0.3, -1, 0.2 }, intensity = 2.0 })
lighting.setAmbient({ intensity = 0.3 })
lighting.applySetup({
sun = { direction = { 0.3, -1, 0.2 }, intensity = 2.0 },
ambient = { intensity = 0.3 },
sky = { timeOfDay = 14 },
})
local sun = lighting.sun()
print(sun.intensity, sun.entityId)
```
A reader takes no arguments and a setter takes the opts table, so `lighting.sun(opts)` is refused with the name of the call that applies it.
# IKLookAt
Turns a character's spine, neck, and head toward a target so it watches
something as it moves.
```luau
guard.component.add("IKLookAt", { target = playerRef, clampAngle = 80 })
```
## Fields
- `target` — an `EntityRef`. Nil leaves the pose alone.
- `rootBone`, `tipBone` — an explicit chain, for a rig with no canonical spine
roles. Absent, the spine-to-head run is resolved from roles.
- `axisX` / `axisY` / `axisZ` — the head's local forward, default `+Z`. Naming
the wrong axis is the classic way to get a mangled pose: the solver faithfully
points the axis you named, however strange the result.
- `bodyWeight` — the share of the turn taken by the bones below the head. 0
turns the head alone; higher brings the torso round with it.
- `clampAngle` — the largest total turn, in degrees. This is what stops a
character wringing its neck round to follow something behind it.
- `weight` — blends against the incoming animation; 0 is an exact pass-through.
## Checking it
```luau
guard.component.get("IKLookAt"):lookState()
-- { ready, status, boneCount, clamped, clampAngle, bodyWeight, weight, error }
```
`clamped` is the field worth watching: it distinguishes "watching the target"
from "turned as far as allowed and still facing away", which look identical in
a screenshot.
# Standard Default
The baseline PBR surface — a neutral white base colour (`1.0, 1.0, 1.0`), half roughness (`0.5`), non-metallic (`0.0`), wired with the full standard texture set (base colour, normal, roughness-metallic, emissive, occlusion) and the `_NORMALMAP` / `_OCCLUSIONMAP` keywords enabled. Opaque, back-face culled, instanced, in the opaque queue (`2000`). Built on `@builtin::shaders.pbr`. This is the starting point most materials copy and retint.
## Inputs
- `colors.base_color` (`1.0, 1.0, 1.0`) — the albedo tint over the base colour texture.
- `floats.roughness` (`0.5`) / `floats.metallic` (`0.0`) — dielectric, mid-gloss default.
- `floats.normal_strength` (`1.0`) / `floats.ao_strength` (`1.0`) — normal-map and occlusion intensity.
- `textures.normal_texture` / `textures.roughness_metallic_texture` / `textures.occlusion_texture` — the PBR map slots, seeded with neutral defaults.
# characterController system
Self-contained character controller + locomotion package. Install on any
entity to give it a third-person camera, WASD ground movement, and
skeletal animation driven by a Locomotion blend space — without
hand-wiring the underlying components. The player's controls drive the
character once it is bound as the local player's body
(`layers.active.players.localPlayer.avatar = entity(id)`); any other
character moves on what writes its `CharacterController` input bus.
## Layout
```
systems/characterController/
characterController.module/ -- public API (install / uninstall / preset)
init.luau -- surface used by tools and custom code
physics.module/ -- raycast helpers (ground / walls / ceiling)
movement.module/ -- velocity integration + collision resolve
data.module/ -- default config presets (standard, platformer, ...)
presets/ -- (Task 16) shipped controller + animation
-- presets (synty, default humanoid, ...)
files/ -- (Task 17) bundled assets pulled in by
-- the shipped presets (synty rig, anims)
demo/ -- (Task 20) showcase scene exercising the
-- install -> tweak -> preset loop
tools/characterController.toolbox/
-- user-facing tools (install, uninstall,
-- apply-preset). Lives here until runtime
-- VFS-driven toolbox discovery lands
-- (see #1220); the colocated
-- `.toolbox/` is the long-term home.
documentation/ -- long-form reference
01-overview.md -- what the package is, when to use it
02-install.md -- characterController.install(id, opts)
-- recipe and the components it touches
03-presets.md -- shipped presets and how to author your own
04-customize.md -- overriding components, swapping the
-- camera, custom blend spaces
```
## Flow
```
┌────────────────────┐
user / agent ──┤ characterController│
│ .toolbox │
└────────────────────┘
│
▼
┌──────────────────────┐
custom code ──────┤ characterController │── install /
(require) │ .module (API) │ uninstall / preset
└──────────────────────┘
│
▼
┌────────────────────────┐
│ CharacterController │
│ + Locomotion │
│ + MovementState │
│ + AnimDebug │
│ (+ third-person cam) │
└────────────────────────┘
│
▼
WASD-driven character with animation
on any entity, no hand wiring required.
```
`characterController.install(entity, opts)` is the only thing most callers
need — it adds the controller, the locomotion graph, the movement-state
mirror, and (optionally) a third-person camera child. The package is
self-contained: it depends only on standard utility modules and on the
animation graph engine, never on game-specific code.
## Documentation
- [`documentation/01-overview.md`](documentation/01-overview.md) — what
this package is and when to reach for it.
- [`documentation/02-install.md`](documentation/02-install.md) — the
`characterController.install(id, opts)` recipe.
- [`documentation/03-presets.md`](documentation/03-presets.md) —
shipped presets (synty, default humanoid) and authoring your own.
- [`documentation/04-customize.md`](documentation/04-customize.md) —
overriding components, swapping the camera, custom blend spaces.
# Error Text
A 3D "ERROR" text model used as the visible fallback when an asset fails to
load — spawned in place of missing geometry so a broken reference is obvious
in-scene instead of silently invisible. Decomposed from `ERRORText.fbx` into
this bundle (mesh + material + texture + entity template).
## Composition
- Root `error_text` → `Sketchfab_model` → the `ERRORText.fbx` node hierarchy.
- Carries the extruded "ERROR" letter mesh, its material, and texture as
private subassets.
## Usage
Spawned automatically by the engine as the placeholder for an unresolved
asset; can also be spawned directly to test the fallback path.
# Plastic White
A clean white plastic — a non-metallic PBR surface with a pure white base colour (`1.0, 1.0, 1.0`) and mid roughness (`0.5`) for a soft dielectric sheen. Built on `@builtin::shaders.pbr`. Opaque, back-face culled, queue `2000`.
## Inputs
- `colors.base_color` (`1.0, 1.0, 1.0`) — the white plastic tint.
- `floats.roughness` (`0.5`) — soft, semi-glossy highlight.
- `floats.metallic` (`0.0`) — dielectric (non-metal) response.
- `floats.emissive` (`0.0`) — no self-illumination.
# Asset
Promote the bundle's spawned children from temporary to permanent scene state and remove the Asset component, "baking" the bundle's contents directly into the owning scene. Subsequent saves persist the baked entities verbatim and stop replaying the bundle template.
Location: `src/lua/lib/components/Asset.component`
# lamp_post (bundle)
A lamp post: a slim post, a lit head sitting on top of it, and the point light
it casts. Four entities under one root — `post`, `head` and `glow` — built from
builtin meshes and materials, so the bundle carries no geometry of its own.
Its foot sits at `y = 0` and it stands 2.53 units tall, so placing it at a
position on the ground puts it on the ground.
```lua
asset.resolve("@builtin::bundles.lamp_post", "bundle"):instantiate(nil, {
position = { 4, 0, 2 },
rotation = { 0, 30, 0 },
scale = 1.2,
})
```
## What it is for
It is the prop a starting scene places to show what placing an asset does: one
call brings a whole hierarchy in as the scene's own entities, and the `Light`
riding along shows that a bundle carries behaviour and not only shape.
Reach for it whenever a scene needs a light source that reads as an object
rather than as a floating value.
# ClipPlayer
Plays one `.animation` clip on the skinned body it is attached to, through the
canonical AnimGraph. The graph retargets the clip from its source rig onto the
body's rig and drives the body's bone entities each frame, so any humanoid clip
plays on any humanoid body. It is the single-clip case of the animation
contract: build a one-clip graph on start, then advance and apply it each frame.
Attach it to the same entity as the skinned mesh. The body's rig comes from its
`Skeleton`; the clip's source rig from the clip itself (or `sourceRig`). All the
retarget and pose machinery lives in the graph — this component only configures
the clip and ticks it.
```luau
entity.find("hero").component.add("ClipPlayer", { clip = "A_Walk_F_Masc" })
```
Public fields: `clip` (the `.animation` to play), `sourceRig` (the clip's source
rig; empty resolves from the clip), `looping`, `speed`, `playing` and
`startedAt`.
## Playing in phase on every peer
`startedAt` is a session time (`multiplayer.sessionTime()`, seconds on the
timeline every participant of a session reads alike). Set, the playhead sits at
`(sessionTime - startedAt) * speed` on every frame: wrapped by a looping clip,
held at the end by one that plays once, and held at the start before
`startedAt` arrives. The playhead follows the session clock on every frame the
component updates, whatever the engine's time scale. While the engine is
paused the component does not update and the playhead holds; on resume it is
placed in phase again. The field replicates like the others, so every peer that
holds the component plays the clip at the same clip time, within the session
clock's accuracy (`multiplayer.sessionClock().accuracyMs`). Choose a start a
little in the future so the value reaches every peer before the clip begins:
```luau
local player = entity.find("dancer").component.get("ClipPlayer")
player.startedAt = multiplayer.sessionTime() + 0.5
```
Unset, the clip advances from wherever its playhead is, by each frame's time.
## Faces: blend-shape tracks
A clip can carry blend-shape (morph target) weight tracks beside its bones, one
per shape, addressed by the shape's name: an imported glTF keeps its `weights`
animations and an imported FBX its blend-shape curves. ClipPlayer plays those
tracks on the meshes of the body that carry shapes of those names, so a smile,
a blink or a set of visemes plays like any other clip. Attached to a mesh with
blend shapes and no skin (a face mesh), it plays the clip's weight tracks alone:
```luau
entity.find("face").component.add("ClipPlayer", {
clip = asset.resolve("Smile", "animation"),
looping = true,
})
```
`skeleton.clipShapes(bytes)` names the shapes a clip drives. To play a face
clip over a body clip, layer it on the body's graph with a shape mask
(`AnimGraph.Layer` with `AnimGraph.shapeMask(layout, "face")`) or use
`AnimOverlay` with `region = "face"`; the animation guide's "Faces" section
covers both.
# 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`
# 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.
# 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`
# scene runtime
What a `.scene` folder does when it is loaded, saved, built, or swapped.
A `<name>.scene/` carries `scene.json` (the entity arrangement), an optional
`build.luau` (the code author's half), an optional `entrypoint.luau`, and a
`scene_dirty/` overlay of unsaved edits. Reading, composing and writing all
four is the scene type's own behaviour, so it lives in the type.
## Sub-modules
| Module | Responsibility |
|---|---|
| `loader.module` | Reads scene.json v6 and v7, refuses versions it does not know, composes canonical + dirty overlay, spawns the entities, and runs the entrypoint. |
| `saver.module` | Persists scene state as a delta overlay against the canonical file, promotes that overlay on save, and answers which edits are still pending. |
| `build.module` | Runs a `build.luau` inside an entity capture scope and composes what it spawned into scene records. |
| `observe.module` | The read side — the per-scene counts and costs `layers` and `loader` write. |
| `swapOrchestrator.module` | Drives multiplayer room transitions and the scene-swap gate, so a local swap does not leak despawns to peers in the old room. |
## Reaching it
```luau
local rt = require("@builtin::assetTypes.scene.shared")
rt.saver.hasPendingSceneEdits(layers.active.name)
```
Fields resolve lazily. The prelude installs `swapOrchestrator` and starts
`saver`'s dirty writer in a fixed order, which a table that required all five
on load would take away from it.
# assetType (asset type)
An asset type says what a kind of asset is: the files an asset of the kind is
made of, the code that gives it behaviour, the interface a person uses to work
with it, and how it is found, pictured and checked. A `<typename>.assetType/`
folder declares a type called `<typename>`, and every `<name>.<typename>/`
folder is an asset of it. `assetType` is itself a type, so a type is an asset
like any other: it is created, versioned, installed and contributed the same way.
## Making a type
`asset.create("assetType", "<typename>")` scaffolds a type. The type registers
the moment its folder is written, anywhere under `/zero/source/`, and from then
on `<name>.<typename>/` folders are its assets. An asset of a type that is not
registered yet is not an asset, so make the type first.
A type folder is a root: `~.x` in any file inside it names the type's own `x`,
wherever the type is installed. Keep the type's whole implementation inside its
folder and reach it that way.
What a type folder must hold is set by this type's own `type.yaml`, the same way
every type's `type.yaml` sets what its assets hold. `asset.validate` on a type
reports anything missing, and the scaffold produces a folder that passes.
## What sets your type's schema (`type.yaml`)
`type.yaml` is the structural contract every asset of the type is checked
against. The keys below are the ones the engine reads; a key not listed here is
ignored.
| Key | What it controls |
|---|---|
| `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. |
| `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. |
| `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. |
| `is_container` | Whether the suffix stays in the identities of what the asset holds. |
| `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. |
| `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. |
| `is_text_default` | Whether the asset's files are text unless stated otherwise. |
| `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. |
| `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. |
| `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. |
| `files: { required, optional }` | The files an asset holds (below). |
| `allow_unlisted` | `false` reports every file the type does not declare. |
| `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. |
| `settings:` | Typed per-asset settings (below). |
| `inspector:` | The interface people use for the type and its assets (below). |
| `preview:` | How an asset is pictured (below). |
| `references:` | Names of other assets the type's files carry (below). |
| `indexing:` | What search reads for each asset (below). |
| `describe:` | How a missing description is generated (below). |
### The files an asset holds
Each entry under `files.required` or `files.optional` is
`{ path, kind: file | folder, one_of_group?, content? }`. `*` in a path matches
within one segment. Entries that share a `one_of_group` are satisfied by any one
of them. `content` lists checks on the file's bytes:
| Check | Passes when |
|---|---|
| `non_empty` | the file has content |
| `json_field { key, type?, non_empty?, accept? }` | the JSON holds the key (a dotted path) with that shape |
| `yaml_field { key, type?, non_empty?, accept? }` | the same for YAML |
| `described { keys?, headings?, message? }` | the file says what the asset is (see "Ask your assets to say what they are") |
Each check takes a `message`, which is what the author is told when it fails.
### Settings
`settings: { values, schema: { type | instance, export? } }` gives every asset
typed settings. `values` names the file an asset's values live in; `schema.type`
declares one schema for the whole type, and `schema.instance` names a file each
asset declares its own in. `asset.create` writes the resolved values, and a write
to the values file reaches `onChange` with what changed.
## The human side (`inspector.luau`)
A type is used by people through its Inspector, and without one the type is
usable only from code. The Inspector is the type's interface for a person: for a
procedural graph it is the graph editor, for a kit it is the tracking view of
what the kit holds and what is still missing. Writing it is part of writing the
type.
`inspector: { type, instance? }` in `type.yaml` names the files. `type` is the
interface for the type itself and for its assets; `instance` names a file an
asset may ship to add its own. Each returns:
```luau
return {
sections = { { id = "graph", title = "Graph", build = function(ctx) ... end } },
replace = { contents = { ... } }, -- replace a default section by id
order = { "graph", "contents" }, -- section order
}
```
`build(ctx)` receives the asset and builds the section. A section's `title`, and
the text its rows carry, is a string or an `i18n.text` value read from a catalog
(`i18n.text("inspectors.mesh.title")`), which follows the editor's language. `asset.create("assetType",
...)` scaffolds a working `inspector.luau` to start from. `asset.validate` on a
type that names no inspector, or names one that does not load, reports it.
## Say what your type is for (`about.yaml`)
Every type carries an `about.yaml` that says what the type is for, in three
plain-language texts:
```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, in the words a game maker uses. Up to 800 bytes.
- **`function`** is how it works today: what an asset of it is made of and what the engine does with it. Up to 1500 bytes.
- **`usage`** is what a person or an agent does with one. Up to 1200 bytes.
Write about the type as a whole, not one asset of it, and say what it does now.
Agents read these texts to learn when to reach for the type and how; people
searching find the type by them. The scaffold starts each text with
`[[describe]]` and a note on what to write; a text that still starts that way
counts as not written. `services describe` can write them.
They show up in `asset.inspect` as `detail.about`, in
`assetTypeRef:getAbout()`, at the end of the type's `types/<typename>` guide,
and at the top of the type's Inspector.
## Ask your assets to say what they are
A type can require each asset to carry a description: a file, written by the
author or generated, saying what the asset is and what it is for. Declare it with
a `described` check:
```yaml
files:
required:
- path: "README.md"
kind: "file"
content:
- { check: "described", message: "Say what this widget is for and where it goes." }
```
A file that is missing, empty or still has a line starting with `[[describe]]`
fails the check, and so does a YAML file whose named `keys` are missing or over
their `max_bytes`, or a Markdown file missing a named heading. `asset.validate`
names the asset, and a push that carries it is refused with `message`.
`services describe` finds such assets and writes their descriptions.
`describe:` steers what is generated:
```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>"
```
An example is an asset of your type whose description is a true, written one,
never a placeholder and never the asset being described; with none, leave
`examples` empty. A type whose assets the model cannot perceive (a sound, a
motion) says so in `guidance`, and the description is drawn only from what the
asset's own files state.
Start the file unwritten in your `template/`: a heading and one line starting
with `[[describe]]`, never example content, which every new asset would carry
verbatim. A type whose assets say what they are through their own content (a
mesh, a texture) declares no check.
## The type's code (`behavior.luau`)
`behavior.luau` returns one table. These are the keys the engine reads from it;
anything else on the table is the type's own.
### What the type's assets can do
| Key | Shape | What the engine does with it |
|---|---|---|
| `ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every asset of the type: `ref:name(...)`. |
| `modules` | `{ [name] = require(".x") }` | Code the type's assets reach with `asset.containing(__FILE__).modules.<name>`. |
| `events` | an events schema | Events an asset fires. Readers subscribe through `ref.events.<name>:connect(...)`; the type fires them. |
| `refShapes` | `{ [method] = function(self) -> (typeExpr, source?) }` | The result type of a `ref` method for one particular asset (below). |
| `namePattern` | a Lua pattern | The names `asset.create` accepts for the type's assets. Default `^[A-Za-z][A-Za-z0-9_]*$`. |
| `derive` | `{ output, module, compute, fingerprint, matches?, required?, timeout? }` | A file computed from the asset when it is committed; a `required` one holds the commit until it lands. |
Some `ref` names mean the same for every type, and the engine calls them:
- **`instantiate(self, target?, opts?) -> (root, idMap)`**: puts the asset in a scene. Defining it is what makes the type scene-instantiable. Its return is a contract (below).
- **`inspect(self) -> detail`**: what `asset.inspect` reports for the asset beyond the common record (below).
- **`preview(self, opts)`**: renders the asset's picture; it wins over the type's `preview:` recipe.
- **`previewMaterial(self) -> { material }`**: the material a `surface` preview paints.
- **`saveDefinition(self)`**: writes the asset's in-memory edits back to its files in edit mode.
Some names are answered for every asset before the type is asked, so a `ref`
entry of the same name is never reached: `getSource`, `getBytes`, `getText`,
`exists`, `deps`, `canInstantiate`, `canPreview`, `preview` (which calls yours
when you define one), `meta`, `runtime`, `events`, `typeRef`, `modules`, and the
residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`,
`gpu_resident`.
### When the engine calls the type
| Hook | Signature | When it runs |
|---|---|---|
| `onCreate` | `(name, opts) -> { [path] = contents }` | On `asset.create`. Returns the files of the new asset, laid over the type's `template/`. Annotate `opts`: its type is the schema `asset.create` checks the caller's arguments against. A `""` key writes a single loose file. |
| `onReplace` | `(dest, files) -> files` | On an `asset.create` over an asset already at `dest`, after `onCreate`, so what the author added can be carried into the replacement. |
| `onRegister` | `(self)` | Once per asset, when it first registers: when the world loads, on a live `asset.create`, and when an asset arrives later (installed, pulled, synced). This is what makes an asset take effect the moment it is written. |
| `onChange` | `(ref, change)` | On every write to a file inside an asset of the type. `change` is `{ path, asset, type, kind, origin }`, plus `settings` and `settingsChanged` for a write to the settings values file; `kind` is `edited` or `seeded`, `origin` is `local` or `remote`. Filter on `change.path`. Writes to one asset arrive in order, each after the hook for the one before has finished, and the hook may wait on what it reads. A write the hook makes inside its own asset arrives later like any other, so keep the hook convergent. |
| `onDependencyChange` | `(ref, change)` | When a module the asset's code requires is re-run, or a name the asset carries starts resolving. `change.kind` is `dependency`. |
| `onDelete` | `(ref)` | When an asset of the type leaves the world: deleted, or the world it is in is swapped away. |
| `validate` | `(ref) -> { { code, message, severity?, path? } }` | On `asset.validate`, after the `type.yaml` checks, for the type's own rules. `severity` defaults to `error`. Runs on every push, so a type's rules hold at publish. A hook that fails reports `validate.hook_failed`. |
### Settings hooks
| Hook | When it runs |
|---|---|
| `settingsDefaults(name, opts, asked) -> table` | Once per `asset.create`, for values the schema's defaults do not give. |
| `settingsCorrections(values, name, opts) -> (corrections?, reasons?)` | On every settings write. A correction to a field the writer named refuses the write, giving the reason. |
| `settingsDerivedDefaults(values, explicit, changed)` | On a settings write, for fields derived from others. |
| `normalizeSettings(values, stored?)` | On every read and write, to map an earlier spelling of a field to the current one. |
| `settingsHealed(values, stored)` | On a read, to repair stored values. |
| `settingsSchemaProblem(schema, ref) -> string?` | When an asset's own schema is read; a returned string refuses the schema. |
`creationInputs` (`{ [opt] = true | selectorOpt }`) names `asset.create` options
that are inputs to the type rather than settings.
### Reloading
An edit to `behavior.luau` reaches existing assets with no restart.
## How an asset is pictured (`preview:`)
| `kind` | The picture is | The type provides |
|---|---|---|
| `instantiate` | the asset placed in the preview studio through its `instantiate` | `ref.instantiate` |
| `image` | a file the asset holds, fitted to the frame | `source: { files }`, the candidate files in order |
| `surface` | the asset painted on a mesh | `mesh`, and `ref.previewMaterial` |
| `custom` | whatever `ref.preview` returns | `ref.preview` |
```yaml
preview:
kind: surface
mesh: sphere
```
`angle: [yaw, pitch]` turns the camera. The studio owns the light, the backdrop
and the framing, so an asset pictures the same in every world. A type with no
`preview:` that defines `instantiate` still answers `ref:preview()`.
A picture is rendered when something asks to view it (the editor showing the
asset, `ref:preview()`), when previews are generated on request
(`assets.generatePreviews`), and when the asset is staged. An edit alone
renders nothing. The picture records what it was made
from, so a stale one is told from a current one.
## The names your type's assets hold (`references:`)
Where your type's own format or API carries the name of another asset, declare
it here:
```yaml
references:
keys: # a top-level key of the type's files that holds a name, or a table of them
- { key: "shader", type: "shader" }
args: # an argument of a call, counting from 1
- { call: "g:node", position: 2, type: "procNode" }
fields: # a field of the options table a call takes
- { call: "fx.beam", field: "material", type: "material" }
```
`type` is the category the name resolves in. `asset.declareReferenceKey`,
`asset.declareReferenceArg` and `asset.declareReferenceField` declare the same
from a script.
## What search reads (`indexing:`)
`indexing:` is how assets are found. Search reaches an asset only through what
its type's `indexing:` names, and adds nothing of its own. That includes you: an
asset indexed badly is one you cannot find later, when you are making something
else and need it. A type whose assets are never looked for says `indexing: none`.
```yaml
indexing:
data: # text, read from the asset's files
- role: identity
extractor: verbatim
source: { file: "README.md" }
- role: interface
extractor: symbols
source: { files: ["init.luau"] }
- role: implementation
extractor: verbatim
source: { files: ["init.luau"] }
content: # the picture
- role: identity
modality: image
source: { file: "preview.png" }
facets: # what a query filters and re-ranks by
file: ".metadata"
rigged: { type: bool, from: { components: { contains: SkinnedModel } } }
roughness: { type: number, filter: range, from: { file: "mat.yaml", field: "floats.roughness" } }
```
**Roles.** Each `data` and `content` entry has a `role`, and a query matches in
two slots:
- **`identity`**: what an asset is. For anything you look at, the picture; for anything else, the text that says what it is.
- **`capability`**: what it does and how it is made. `interface` (the signatures or shape a caller uses) and `implementation` (the body) both count as capability, and a type with code usually declares both.
Ask what a person would recognise an asset of the type by, and what it does, and
point each role at the file that says it. For text, that is the asset's
description: the file your template starts with a `[[describe]]` block, which the
author writes or `services describe` fills in (see "Ask your assets to say what
they are").
**`data`.** `extractor: verbatim` embeds a file's text as it is; `symbols` embeds
the declared signatures of code. `source` is `{ file }` or `{ files: [...] }`.
Never index a file name (`source: { field: name }`): one
or two words carry nothing to match.
**`content`.** `modality: image` embeds the picture itself, so a text query
matches what the asset looks like. A type whose assets are looked at makes the
picture its identity.
**`facets`.** What a query narrows and re-ranks the matches by. `file` is embedded
whole, so keys nobody declared in it are still found. Each further key is
computed for every asset and states a value for every one, including `false`: a
file can imply "not rigged" but never say it, and a query separates rigged from
unrigged only because the unrigged ones say `rigged: false`. A key is
`{ type: bool | number | enum, filter?: range, from }`, where `from` is
`{ file, field }` (a field of one of the asset's files, dotted for nesting),
`{ metadata: key }`, or `{ components: { contains | any_outside } }` (what the
asset's entities carry).
## What blocks a push
A push checks every asset it carries against its type. These refuse it:
- a required file that is missing, a `content` check that fails, a `described` file not written yet;
- an error from the type's `validate`.
Unlisted files and warnings do not. A `described` file blocks only a push that
changes the asset. When a push is refused, the message names each asset and what
it lacks. `world.publishBlockers()` and `zm status` read the same list without
pushing.
## Typing a result from the asset (`refShapes`)
A `ref` method whose result depends on the asset (one entry per child folder, per
row of a config, per control a map declares) can only be annotated as
`{ [string]: Thing }`, which accepts any key. `refShapes` states the result for
each asset instead: a function returning a Luau type expression for that asset,
and the module whose types the expression uses. Read the asset; never run it.
```lua
-- inputMap.assetType/behavior.luau
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)` is checked and `map.noexisting` is reported.
A per-asset type applies where the call site names which asset: a component
field whose default names it, or an annotation `AssetRef<"inputMap", "<identity>">`.
`asset.resolve(name, category)` carries only the category, and a name computed
at runtime carries nothing, so calls on those keep the declared return. The type
belongs to the call's result: index it there, or bind what you need from it
there, and the names stay checked.
`require("@builtin::assetTypes.assetType.shared.refShapes").published()` shows
what was published: `categories` (each type's method surface) and `returns`
(per-asset results by identity, then method). An identity missing from
`returns` was never published. Results are recomputed when an asset is written;
at most 64 assets of one type are read.
## Putting an asset in a scene (`ref.instantiate`)
A caller writes one piece of code against every instantiable type, so what
`instantiate` returns is fixed:
```lua
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts)
-- compose the asset under `root`, now
return Instantiable.result(self, root, idMap)
end,
}
```
**In.** `target` is the entity the asset lands under, or onto for a hierarchy
type; with none, the type spawns a new root. `position`, `rotation` (three
numbers in degrees, or a quaternion), `scale`, `name` and `temporary` mean the
same for every type: `Instantiable.root` applies them to a root you make,
`Instantiable.place` to one you adopt. Document any options of your own in the
hook's `--!arg` docs.
**Out.** `(root, idMap)`. `root` is the composed root, live when you return:
build synchronously, never defer to a component's `awake`. `idMap` maps each
original id to the spawned one, so a component that composes the asset again on
every load can pass it back in and keep references into the composition. Every
call goes through `Instantiable.result`, which refuses a root that is not live
and turns a missing `idMap` into `{}`.
## Inspecting an asset (`ref.inspect`)
`asset.inspect(ref)` builds a record every asset shares (`identity`, `name`,
`guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`,
`description`, `tags`), then calls `ref.inspect(self)` for the type's own
`detail`:
```lua
M.ref = {
inspect = function(self)
-- read the asset's own files, never runtime state: inspect works on an asset
-- that has not been compiled, uploaded or registered
return { --[[ what makes this asset what it is ]] }
end,
}
```
Without it, the record is the shared part alone, and an agent inspecting the
asset learns nothing of what it is. A hook that raises leaves `detail` empty and
sets `record.warning`.
## Discovery
- `asset.list("assetType")`: every registered type.
- `asset.inspect("<typename>")`: the type, its README and its `about.yaml` texts.
- `asset.resolve("<typename>", "assetType")`: the type itself.
# Bundle (asset type)
A bundle is a composable, spawnable entity assembly— a saved entity
hierarchy plus its components, sub-assets (meshes, textures,
animations, materials, sub-bundles), and any nested data, packaged
into a single addressable identity. Bundles are the engine's "prefab"
primitive.
There are **two ways** to bring a bundle into a scene — and the
difference matters enormously for scene saving and live editing. See
"How to spawn" below before you write anything.
If you want one snapshot of a whole world / level, use a `.scene`.
## Where it lives
- Source: `/zero/source/.../<Name>.bundle/`
- Identity: `<Name>` (the `.bundle` suffix strips for use in
identities, but the on-disk folder keeps the suffix).
- Folder shape (container type — open child set):
- `entity_template` — JSON of the entity hierarchy + components.
**Required.**
- `.metadata`: optional.
- Anything else: meshes / textures / materials / animations /
sub-bundles. Validator allows arbitrary additional files
(`allow_unlisted: true`).
## How to create one
Two paths, depending on whether you have an in-scene hierarchy or are
authoring from scratch:
```luau
-- From an existing in-scene entity: composes the given entity tree into a bundle.
local bundle = asset.create("bundle", "<Name>", { entity = entityRef })
-- Or scaffold an empty bundle, then update it from an entity:
local bundleRef = asset.create("bundle", "<Name>")
bundleRef:update(entityId)
```
## How to spawn
### 1. `Asset` component — live-linked (the canonical way)
**This is the primary way to put a bundle into a scene that survives
saving as an asset reference.** Spawn an empty entity, attach the
`Asset` component, point it at the bundle:
```luau
local car = entity.spawn("car_1")
car.component.add("Asset", { source = "<bundleIdentity>" })
```
What you get:
- The bundle's hierarchy spawns as **temporary** children under the
owning entity. They're real, addressable runtime entities, but
they are NOT serialized into `scene.json` on save, only the Asset component and its entity is saved.
- **Live editing of the bundle is supported.** When you edit
anything inside the `.bundle/` (entity_template, meshes,
materials, sub-bundles, components), every entity in the world
carrying that `Asset` component automatically tears down its
spawned children and rebuilds them from the new template — same
frame, no restart, no manual reload. The `onAssetReload` hook in
`Asset.component/init.luau` drives this.
- **Per-instance overrides survive across reloads.** Move a spawned
child, rename it, add/remove components on it, edit a component's
public state — the changes land in the Asset's `public.diff` (a
sparse delta keyed by the child's `original_id`) at save time and
are replayed by `bundleRef:instantiate()` on next load. The bundle stays
a single source of truth; per-spot tweaks ride on top.
- **Stable child ids across reloads.** `public.idMap` records the
`original_id → runtimeId` assignment on first spawn; on every
subsequent spawn the same mapping is reused so cross-entity
references (e.g. `SkinnedModel.skeletonRoot = "ent_xxx"`) stay
valid.
### 2. `bundleRef:instantiate` — baked, no live link
Resolve the bundle and instantiate it onto an entity — this spawns the
children **without** the live-link plumbing the `Asset` component
provides:
```luau
local car = entity.spawn("car_1")
asset.resolve("<Name>", "bundle"):instantiate(car)
```
What you get — and the trade-offs:
- The children spawn as **regular** (non-temporary) entities. On the
next `layers.active:save()`, the entire spawned hierarchy is serialized into
`scene.json` verbatim.
- **No live link to the bundle.** Editing the `.bundle/` after the
fact has no effect on already-spawned hierarchies. The bundle was
effectively consumed at spawn time.
- Scene-save / restore round-trip works the same as for any other
hand-authored entity tree.
Use this path when you want a one-shot expansion of the bundle into
permanent scene state (e.g. you're populating a scene's static
layout from a parametric bundle and don't want a live link).
You can convert a live-linked instance into a baked one explicitly
via `Asset:bakeIntoScene()` — this drops the `Asset` component and
promotes the temporary children to permanent scene entities.
## How it operates
1. **Registration.** Writing into a `.bundle/` folder indexes the
asset with the container-category restore plumbing.
2. **Inner refs.** Component fields that reference assets inside the
bundle use the `__ref` shape (`{ "__ref": "<guid>", "name": "...",
"type": "..." }`). The asset registry resolves them at spawn
time.
3. **Identity.** The `.bundle` suffix is stripped, so a bundle
resolves as `<Name>` (`asset.resolve("<Name>", "bundle")`); the
type argument tells it apart from any `<Name>` of another type.
4. **Hot reload.** Saving `entity_template` (or any file in the
bundle directory) fires the engine's per-asset content-changed
hook, which calls `onAssetReload("source")` on every entity
whose `Asset` component points at the bundle. Each carrier
despawns its children and re-instantiates against the new
template — typically next frame.
## Discovery
- `asset.list("bundle")` — every registered bundle.
- `asset.inspect("<name>")` — sub-asset catalog, source, this type
README.
- `ls /zero/source/<Name>.bundle` lists the files the folder holds.
## Parts and slots
A bundle can be an object assembled from parts, and a part that fills one. A
child carrying a `Slot` component is a named place another part fills (its
`kind`, the `tags` a part must carry, a `default` part, and where the part
attaches: that child's transform). A bundle whose root carries a `Part`
component is a part, and its `fits` names the slot kinds it fits. An
`Assembly` on the root holds what fills each slot by path (`wheel_fl`,
`engine/turbo`, a part's own slots nesting under the slot it fills), and
resolves, swaps and explains them at runtime:
```luau
local car = entity.spawn("car")
car.component.add("Asset", { source = "Buggy" }) -- a bundle with slots and an Assembly at its root
local asm = car.component.get("Assembly")
asm:configure({ wheel_fl = "SportWheel", engine = { part = "V8", turbo = "Turbo" } })
asm:fill("wheel_fl", "OffroadWheel") -- rebuilds that wheel alone
print(asm:fits("wheel_fl", "V8")) -- false, and why
```
The configuration is saved with the scene and synced; the parts are runtime
children rebuilt from it. `guides { path: "topics/assemblies" }` covers the
whole family.
## Authoring conventions
- Prefer `bundle:update()` or `asset.create("bundle", "<name>", { entity = ref })` over hand-authoring `entity_template`. The
in-scene composer wires `__ref` shapes correctly and pulls in every
transitively-needed asset.
- Keep bundles focused — one prefab per bundle. If you have a "vehicle
+ driver + sound" assembly, split into three bundles and reference
them from a scene rather than packing all three into one bundle.
- Name child entities meaningfully — bundle interiors are
inspectable, and stable IDs let other tooling (`entity_template`
edits, animation hooks) find them.
- Sub-bundles compose: a bundle's `entity_template` can `__ref` a
child `.bundle/`. The asset registry resolves them transitively.
## Common pitfalls
- **Confusing the two spawn paths.** `Asset` component = live link,
reference-only scene save. `bundleRef:instantiate()` directly = baked,
full hierarchy in `scene.json`.
- **Copying JSON between bundles.** A copied `entity_template` does not
bring the assets it references along with it; re-compose from a
live scene rather than copy-pasting JSON.
- **Live editing only fires for live-linked carriers.** Already-baked
entities don't update when you edit the source bundle.
## Related types
- `Asset.component` — the canonical mount point for a live-linked
bundle. See its README for the `idMap` / `diff` machinery in
detail.
- `.scene` — owns a whole world's worth of entities; spawns bundles
into itself via `Asset` components on per-spot entities.
## In the Inspector
Selecting a bundle opens its **Contents** section, from the bundle's inspect detail: the template's node count, its root, the component types attached across it, a table of each renderable node's mesh and material, and a link to each of those meshes and materials.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Texture
Managed texture asset. `data.ztex` is the encoded payload the renderer uploads; compression settings live in `settings.yaml` (`texRef:setSettings({ ... })` to change one).
# 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`, `onDestroy`).
- You want to expose configurable fields to designers / `entity.spawn`
callers / scenes without code changes.
If you need a stateless pure-function library, use a `.module`. If you
need to generate content declaratively, use a `.service`; compute work
belongs in a `.computeShader`.
## 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 once per physics step, straight after it, with the step's
`dt`, so a frame can run it several times or not at all;
`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`, `onDestroy`) 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 `.computeShader`, 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. References
to the component are recorded against the component itself, so
renaming or moving it does not break them.
## Related types
- `.module` — pure-function library, no per-entity state.
- `.service`: a declarative content generator, 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`.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Texture
Managed texture asset. `data.ztex` is the encoded payload the renderer uploads; compression settings live in `settings.yaml` (`texRef:setSettings({ ... })` to change one).
# Texture
Managed texture asset. `data.ztex` is the encoded payload the renderer uploads; compression settings live in `settings.yaml` (`texRef:setSettings({ ... })` to change one).
# Texture
Managed texture asset. `data.ztex` is the encoded payload the renderer uploads; compression settings live in `settings.yaml` (`texRef:setSettings({ ... })` to change one).
# Texture
Managed texture asset. `data.ztex` is the encoded payload the renderer uploads; compression settings live in `settings.yaml` (`texRef:setSettings({ ... })` to change one).
# Texture
Managed texture asset. `data.ztex` is the encoded payload the renderer uploads; compression settings live in `settings.yaml` (`texRef:setSettings({ ... })` to change one).
# Module (asset type)
A module is a reusable, stateless (or globally-stateful) Luau library
that other code pulls in with `require()`. Modules are the unit of
factored-out logic in a world: helpers, math libraries, format
parsers, registries, shared algorithms.
## When to use one
- You have logic you want to share across multiple components,
services, scenes, or tools.
- You have a registry, lookup table, or shared cache that callers all
read from / write to.
- You want a stable API surface (`M.fn`) other code can depend on.
If the logic is bound to one entity, use a `.component`. If you want a
named UI of fields rather than functions, use a `.preset`.
## Where it lives
- Source: `/zero/source/.../<name>.module/`
- Identity: the source path with `/` written as `.` and each segment's
type suffix dropped — `/zero/source/demo/beats.module` is
`demo.beats`, and `/zero/source/kit.package/beats.module` is
`kit.beats`, the container's name kept and its `.package` suffix
gone. `asset.create` returns this string, `asset.resolve(...).identity`
reads it back, and the `require` forms below write it as
`<identity>`.
- Folder shape:
- `init.luau` (or `init.lua`) — module body. **Required.** Returns
a table (conventionally named `M`).
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
```luau
asset.create("module", "<name>")
-- Creates: /zero/source/<name>.module/
-- init.luau (canonical `local M = {} … return M`)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source, and that subfolder
-- leads the identity: `{ folder = "lib" }` produces `lib.<name>`.
-- `into` authors it inside a resolved container (a package, a toolbox),
-- whose own identity leads the same way:
asset.create("module", "<name>", { folder = "lib" })
asset.create("module", "<name>", { into = asset.resolve("myPkg.package") })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.module/` folder
indexes the asset and registers the module path with the resolver.
2. **Loading.** The first `require("<identity>")` runs
the file's body and caches the returned table. Subsequent requires
from anywhere return the **same table** — this is the
shared-state lever for "module-local" registries. The body runs in
an environment of the module's own: a name it declares without
`local` is readable by the module's own functions and by no other
script, so an export reaches its callers through the returned table
and nothing else. Requiring a component's folder runs its chunk the
same way, once, and its `update`, `start` and `public` stay in that
environment; a component runs on an entity through
`entity(id).component.add(name)`.
3. **Hot reload.** Editing the file re-runs the module body and folds
what it returns into the table already loaded, so that table keeps
its identity: a caller that captured it with `require` reads the new
source's functions and values through the reference it already
holds, and a later `require` returns that same table. A key the new
source drops goes away; a key something set at runtime stays. The
body's own `local`s start again from their initial values, so state
that must outlive an edit lives in `modules.state()`
(`guides { path: "core/scripting-and-tasks" }`).
4. **Identity resolution.** A module is reached by its `<identity>`,
and where the caller lives decides which spelling of it resolves.
For a module in a **world**, from a caller in that same world —
another module, a component, a scene entrypoint, or an `execute`
chunk:
- `require("<identity>")` — the identity on its own, resolved
against the caller's own root. It carries every folder segment,
so a module created with `{ folder = "demo" }` is
`require("demo.beats")`.
- `require("@root::<identity>")` — the same root-relative
resolution, written out.
- `require(".sibling")` — a module in the same folder, by its bare
name; `..name` steps up one folder, `...name` two.
Logs, stack traces and hot-reload notices name that same module
`@local.source.<identity>` — its key under the world source root.
The `<identity>` tail of that key is the form above, so a trace
reading `@local.source.demo.beats` is `require("demo.beats")`.
For a module in a **library** — content under
`/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's
root from anywhere: `require("@builtin::modules.transform")`.
Mounting a world as a library moves its files under such a root and
flips the caller root to `@<lib>::`, which is what keeps the
root-relative forms above resolving across the move.
## Discovery
- `asset.list("module")` — every registered module.
- `asset.inspect("<name>")` — public functions, source path, this
type README.
- `ls /zero/source/<name>.module` lists the files the folder holds.
## Authoring conventions
- Return a single `M` table from `init.luau`. Top-level statements
with side effects run on first require — useful for one-time
initialization, dangerous if they touch the engine before it's
ready.
- Write exported functions as `typed function`, not `function`: the
argument types are enforced at the call and the checker knows the
signature, so a caller's mistake is reported where they made it.
- Annotate exported functions with `--!desc` / `--!arg` / `--!return`
/ `--!example` so the LSP, `tools.list`, and `asset.inspect`
surface them. A function with no `--!desc` is reachable only by
someone already reading this file.
- Declare a VALUE with `Field.<kind>(default, mode, description)`, and
a table whose members are reached through a metatable with
`--!members <TypeName>` — the latter gives the surface its accepted
member set, its type, and its documentation from one table. See
`guides { path: "core/authoring" }` for all four rules and
`modules/api/engine/entity.module/members.module` for a worked
member table.
- Keep module state in module-local upvalues or in `modules.state()`.
A name the body declares without `local` lives in the module's
environment, which every run of the module shares: a function the
previous run left in place reads what the reload assigned. Module-locals start again from their
initial values with each hot reload; the table `modules.state()`
returns is the same table on both sides of every reload.
- Prefer focused modules over kitchen-sink modules. If two halves of a
module have no shared state, split them.
## Common pitfalls
- **Cyclic requires.** A `require` chain that loops will return the
partial table (the half built before the cycle was detected).
Design for one-way dependencies.
- **Engine-time side effects.** Don't `entity.spawn` at module
top-level — the engine may not be ready. Expose an `M.init` and
call it from a scene entrypoint.
- **Hot-reload + module-local cache.** A module that caches
expensive computation in upvalues loses that cache on reload —
fine for dev, but be aware in performance work.
- **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical.
- **Writing one while play runs.** A `/source` write made while play is
running lands on the play shadow, and a guarded play-exit discards it
unless it is kept. One `.module` write shadows `init.luau`, the
`README.md` and the `.metadata` together.
`vfs.write(path, bytes, { durable = true })` skips the shadow, and
`vfs.promotePlayShadow` keeps what is already on it — the `core/vfs`
guide has the model and what each route costs.
## Related types
- `.component` — for entity-bound state + lifecycle hooks.
- `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider.
- `.tool` — for a single agent-callable function with a YAML schema.
- `.package` — to group several modules + components + scenes into
one shippable folder.
## In the Inspector
Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
# Material (asset type)
A material is a named, configured instance of a `.shader`. The shader
defines the surface look (lighting model, available property fields,
texture slots); the material picks values for those fields and a
shader to bind to. Renderable entities reference materials, not
shaders, so the same geometry can wear different materials and the
same material can be reused across many entities.
Entities sharing one material can still differ in a value: every drawn
object carries four `vec4` lanes of its own that a surface shader reads
as `input.shader_data[lane]` and `renderer.instanceData.set` writes. Use
that for a dissolve at its own progress per subject, a hit flash at its
own age, a fill level per instance — a material per entity is for when
the LOOK differs, not when a number does.
> New to how a material relates to its shader, its textures, and the live GPU
> material behind it? Read `core/resource-model` first. It also covers the
> difference between an authored `.material` asset (this type) and a runtime GPU
> material made with `renderer.material.create`.
## When to use one
- You want a named surface configuration an entity wears by referencing it
from its `Model` component (`material = "@.../<Name>"`).
- You want runtime property tweaks (`asset.resolve(ref):setProperty(...)`) to
affect every entity using the material at once.
- You want to publish a curated look (`Gold`, `RedGlow`,
`BrickWall`) other authors can reuse without re-typing shader
bindings.
If you need a brand-new lighting model or a custom visual effect, you
need a `.shader` first; the material wraps it.
## Where it lives
- Source: `/zero/source/.../<Name>.material/`
- Identity: `<Name>` (the `.material` suffix strips).
- Folder shape:
- `mat.yaml` — canonical material spec (shader + property values).
**Required.**
- `README.md` / `.metadata` — optional prose + tags, indexed when an
author writes real ones.
- `textures/` — optional folder for embedded textures. Validator
allows the folder; its interior is unrestricted.
- `shaders/` — optional folder for a co-located custom shader.
Same rule.
## How to create one
```luau
asset.create("material", "<Name>")
-- Creates: /zero/source/<Name>.material/
-- mat.yaml (shader binding + property scaffold)
-- `folder` places it in a subfolder of /source instead of the root:
asset.create("material", "<Name>", { folder = "materials" })
```
Pass the shader and initial values through `asset.create`, then tune with
`setProperty` and keep what you tuned with `saveDefinition`:
```luau
local mat = asset.create("material", "<Name>", { shader = "@builtin::shaders.pbr" })
mat:setProperty("base_color", { 0.8, 0.6, 0.1, 1 })
mat:setProperty("roughness", 0.3)
mat:saveDefinition() -- writes the tuned values into mat.yaml
```
This mints the `.material` asset and returns a handle you tune with
`setProperty`. A set is a runtime change: it reaches the GPU material and every
entity wearing it, and `saveDefinition` is the call that writes it into
`mat.yaml`, so a property driven every frame costs no file write and leaves the
authored file as its author wrote it. A purely runtime `asset.create` lives only
for the session.
For an ephemeral, runtime-only GPU material that is not an asset at all, use
`renderer.material.create` instead (see `core/resource-model`).
## How it operates
1. **Property reflection.** The bound shader's uniform struct fields
become the material's configurable properties — no manual property
declarations needed.
2. **Property values.** `mat.yaml` groups values by type, each block
keyed by the shader's field names: `properties:` holds scalars and
colors/vectors, `ints:` holds integer-typed fields, `bools:` holds
boolean-typed fields, and `textures:` holds texture slots. Omitted
fields take the shader's default. A scalar is a bare number
(`roughness: 0.5`); a color or vector is an array
(`base_color: [1, 1, 1, 1]`). `shader:` is the shader's identity
string. This is the shape every material the engine writes uses. A
`saveDefinition` writes the changed values into the file where they
already stand and leaves the rest of it — its comments, the order of
its keys and blocks, the spelling of its literals, untouched.
3. **Render state.** `render:` holds how the mesh is drawn rather than
what the shader reads: `blend` (the equation the fragment composites
with, also spelled `type`), `cull`, `depth_write`, `depth_compare`,
`topology` and `queue` (the draw order, a whole number: `2000` opaque,
`3000` transparent, `4000` overlay). The `.shader` type README's "The
render block" section lists every value each key takes, and
`asset.create`'s `render` argument takes the same keys and values.
4. **Application.** An entity wears a material by referencing it from its
`Model` component (`material = "@.../<Name>"`). Materials affect every entity
that references them; runtime `asset.resolve(ref):setProperty(...)` changes
propagate to all of them immediately, and last until the next mode change
unless `saveDefinition` writes them into `mat.yaml`.
5. **Texture binding.** Texture slots accept `color:r,g,b,a` for
solid colors, `default:white` / `default:black` / `default:normal` for the
engine's own fallback texels, `@builtin::textures.<name>` for builtins,
`path/to/image.png` for file textures, or a render-target handle
for camera renders. The GPU texture cache reads the `color:` and
`default:` forms from the string itself, so a slot written in one names no
asset and carries nothing with the material when it travels; every other
form names a texture asset the slot depends on.
A texture in `base_color_texture` is multiplied by `base_color`: every
built-in surface shader declaring both draws the texture's colour times
`base_color`, channel by channel. Under the default white `base_color` the
texture shows as itself, and a coloured `base_color` tints it. The two
read a colour differently: `base_color` is linear, and the slot reads its
texels as sRGB-encoded, a `color:` value's included, the way it reads an
image. A colour stated in both places is therefore multiplied by a darker
copy of itself: `color:0.62,0.14,0.05,1` in the slot decodes to
`0.34, 0.017, 0.0039`, so beside `base_color` `0.62, 0.14, 0.05` the
surface draws `0.21, 0.0024, 0.0002`, far darker than either. State a
solid colour once, as `base_color`, and leave the slot at its default
white.
6. **Hot reload.** Editing `mat.yaml` repacks the GPU uniform buffer
on the next frame; visible immediately.
**Properties that follow a named value.** `values:` binds a property to a
named value of the entity wearing the material (`values.set(entity, name,
v)`, the `topics/values` guide): `property: valueName`, or
`property: { value: "name", scale: s, offset: o }`, and the property draws
`value * scale + offset` on each entity holding the value, read on the draw.
A boolean reads as 1 or 0, and a number fills every channel of a colour or
vector property. The wearer's own value is read, else its nearest
ancestor's, so a lamp mesh under a car lights from the car's `brake`; a
wearer holding none draws the material's own value. A scalar, vector,
colour or bool property binds (at most 32 per material); a texture slot
does not. `asset.create("material", name, { values = { ... } })` and
`renderer.material.create({ ..., values = { ... } }, key)` take the same
map.
```yaml
values:
emissive_intensity: { value: "brake", scale: 3 }
```
7. **Inspector.** `type.yaml` names `inspector: { type: "inspector.luau" }`,
and `inspector.luau` declares the material's sections beside the generic
ones: `shader` (the bound shader, swappable), `properties` (each shader
field as its typed control) and `textures` (each texture slot as an asset
chip). They read the material through `mat:getShaderRef()` (the bound
shader's ref, `~` expanded) and `mat:getTextures()` (slot name →
`{ ref, name }`: the bound texture's guid and the id the material names
it by). An edit there is an authoring write: `mat:writeProperty(name,
value)` and `mat:writeTexture(slot, texture)` write the value into
`mat.yaml` (and drop the session's own value for it, so the material
reads what the file holds), and `setShader` rewrites the file; inside an
undo operation each file write is recorded, so undo puts `mat.yaml` back.
`setProperty` / `setTexture` stay runtime writes that last until the next
mode change.
## Discovery
- `asset.list("material")` — every registered material.
- `asset.inspect("<name>")` — shader binding, property values,
source path, this type README.
- `ls /zero/source/<Name>.material` lists the files the folder holds.
- `asset.resolve("<name>"):getProperties()` — the property fields exposed by
the bound shader, each at the value it currently holds: what `mat.yaml`
authored until something writes to the material, and the written value from
then on, whichever call wrote it. That is the value the surface is drawn
with. Read them back rather than guessing names; which fields exist comes
from the shader.
- `asset.resolve("<name>"):getDefinition()` — the authored `mat.yaml` bytes,
the value the material rests at.
- `asset.resolve("<name>"):getShader()` — the shader the material binds.
## Authoring conventions
- Use lowercase, descriptive names (`brushed_steel`, `red_glow`,
`tarmac_wet`). Avoid shader-name suffixes in the material name —
the binding lives in `mat.yaml::shader`.
- Drive every property the shader exposes; defaults are a fallback,
not a contract for which fields exist.
- Embed textures alongside the material (`textures/` subfolder) when
they're used only by this material; reference shared textures from
`@builtin::textures.*` or a library.
## Common pitfalls
- **Property names must match the shader's uniform struct exactly**
(case-sensitive). Misnamed properties silently get the shader's
default.
- **`base_color_texture` multiplies `base_color`.** A `color:` texture holding
the same value as `base_color` multiplies the colour by its own
sRGB-decoded value, so the surface renders far darker than the value
written. Write a solid colour as `base_color` alone.
- **Broken shaders break the material.** A material whose shader has a
parse error renders as the magenta checkerboard. Inspect the shader
first if the material looks wrong.
- **`setProperty` targets the material, not the entity.** Changes affect
every entity that references the material.
- **`setProperty` is a runtime change.** It reaches the GPU, not the file:
call `saveDefinition` to write the current values into `mat.yaml`. For a
per-entity override that no other entity sees, give the entity its own copy
with `Model:applySessionMaterial(renderer.material.create(...))`.
- **Renaming the folder changes the identity.** A `Model` component or
other reference to the material is recorded against the material
itself, so renaming or moving it does not break them.
## Related types
- `.shader` — defines what properties exist; required before a
material can bind to it.
- `.preset` — captures a component configuration; conceptually
similar to a material, but for components instead of shaders.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
# AnimDebug
Demo component for inspecting character-controller animation state during the character controller demo.
# CharacterController
Kinematic mover. Integrates velocity against gravity, walls, ceilings and
ground, and writes the result to the entity's position every frame.
## Driving it
The character moves on a public input bus: `inputX`, `inputZ`,
`inputJump` and `inputJumpHeld`. Each frame the controller reads the bus, moves on what it found,
and then refills it for the next frame.
**Only the local player's body answers the player's controls.** The character
the local player is bound to (`layers.active.players.localPlayer.avatar`)
refills its bus from the `move` axis and the `sprint` / `jump` actions of its
input map, so the map drives it whenever nothing else does. Every other
character holds no map and refills its bus with no movement: an NPC, a
mannequin, a preview or another player's body stands where it is until
something writes its bus. The player's spawn binds the body for you; to hand
the controls to a character you made, bind it:
```luau
layers.active.players.localPlayer.avatar = entity(bodyId)
```
The character takes the map up on the frame after the bind and gives it back
when the binding moves to another body.
Anything else takes the character over by writing those three fields from its
own `update()` — an AI brain, a networked peer, a replay, or gameplay code
that wants the character committed during an attack. The write works from
**any** `executionOrder`, because the refill happens after the read: whatever
is in the bus when the controller next reads it is what the character does.
On the local player's body the controller fills the bus from the map once
more just before the read, so a press moves the body on the frame it
arrives, and that fill takes only the fields nothing has written since the
last refill. A write counts whatever value it carries
(`ref:fieldWrites(name)`), so a writer that holds the body still by writing
no movement and the jump let go keeps it still through every press.
- A writer ahead of the controller (`executionOrder` below `-100`) is acted on
the same frame.
- A writer behind it is acted on the next frame.
- A writer that writes some of the fields leaves the others to the map: one
that steers with `inputX` / `inputZ` alone leaves the jump to the player's
jump control, which jumps on the frame it is pressed.
- Stop writing, and the character stops one frame later; on the local
player's body the map has it back instead.
- Pausing gameplay empties the bus, so a character frozen mid-stride stands
where it was paused and a writer that had it committed says so again.
`inputX` / `inputZ` are a world-space velocity in units per second, the walk
the character is asked for: the controller takes its walk toward them at its
`acceleration` and `braking` (see "Movement feel" below), so scale them
yourself rather than expecting `moveSpeed` to. `inputJump` asks for one jump
and the next update consumes it. `inputJumpHeld` says the jump control is
held: write it `true` on every frame the jump is held, and a jump asked for
with it is cut short when it stops (with `minJumpHeight` above 0), on the
step it takes off when it stopped while the request waited in the
`jumpBuffer`; a jump asked for without it rises its full height.
A component that walks the character due north, whatever the input map says:
```lua
-- Northbound.component/init.luau
declare { executionOrder = 50 } -- anywhere works; 50 runs after the controller
public = {
speed = Field.number(4.0, Sync),
}
function update(_dt: number)
local cc = public.entity.component.get("CharacterController")
if cc == nil then return end
cc.inputX = 0
cc.inputZ = -public.speed
end
```
`WASDInput` is the same pattern shipped as a component: it reads an input map
of its own and writes the bus of whatever component `targetComponent` names,
which is how a mover that reads no controls of its own gets driven. On a
CharacterController — which reads `move`, `sprint` and `jump` from its own
`inputMap` — a WASDInput writes the bus every frame at its own `speed`, and
that is the speed the character walks at. `CharacterController.install` adds
one when `input = true` asks for it.
## The control scheme
`inputMap` is the scheme the character answers to. It reads three controls from it, each on its own:
- `move` — an axis2, projected against the active viewport camera so "forward" is into the screen. The camera turns for the frame in its look phase, before the controller reads it, so a look that turns the camera turns the walk on the same frame.
- `sprint` — held, multiplies `moveSpeed` by `sprintMultiplier`.
- `jump` — pressed, asks for one jump.
A map declaring only some of the three drives the character with those: a scheme with no `sprint` holds one gait, a scheme with no `jump` stays on the ground. The character logs which controls the map left out and names the map, so a game with three verbs ships a three-control scheme. A field naming no map leaves the character answering nothing, and logs that too.
**Repointing it on a live character takes on the next frame.** The map the character 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(bodyId).component.get("CharacterController").inputMap = asset.resolve("mygame.input.run", "inputMap")
```
Assigning the map the character already holds changes nothing, so re-stating the scheme leaves the live set where it is. While gameplay is paused the character holds no map at all (the editor's camera has the controls), and it takes whatever `inputMap` names when play resumes. A character that is not the local player's body holds no map either, and takes whatever `inputMap` names when it is bound as that body.
## Movement feel
How the character starts, stops, turns, jumps and falls is set by its feel
fields. The same settings drive the package's character module
(`CharacterController.attach` / `Velocity.resolve`), through one set of rules
(`movement.feel` of `characterController.module`).
On the ground:
- `acceleration` (m/s², default 20) is how fast the walk speeds up toward the
walk asked for. At 20 a 2.5 m/s walk is reached in 0.125 s and a 7 m/s
sprint in 0.35 s.
- `braking` (m/s², default 30) is how fast it slows: to a stop when nothing is
asked, down to a slower walk, and away from a heading the request turned
from. A turn sheds the old heading at `braking` while it builds the new one
at `acceleration`, and a reversal at speed brakes to a stop before it speeds
up the other way, rather than flipping in a frame.
- Either at 0 reaches the walk asked for on the frame it is asked, which is
how the `instant` preset keeps a character that answers with no ramp.
- The walk is the character's own, on top of what carries it: on a belt or a
moving deck it speeds up relative to the surface; on a slope it follows the
ground. `velocityX` / `velocityZ` read the ramp as it happens, so
`Locomotion` blends its gait from the speed the body really moves at, and a
networked peer sees the motion the owner simulated.
The jump:
- `jumpHeight` (m) and `jumpApexTime` (s) state a jump directly: with both, a
full jump rises exactly `jumpHeight` and tops out `jumpApexTime` after
take-off, at any frame rate. `jumpHeight` alone rises that high against the
character's gravity; `jumpApexTime` alone takes off at `jumpForce` and tops
out that long after. At 0 (the default) a jump takes off at `jumpForce` m/s
against the character's gravity.
- `minJumpHeight` (m) above 0 makes the jump control's release cut the jump
short. Let go at take-off, it rises `minJumpHeight`; let go during the rise,
it rises `minJumpHeight` above where it was when let go; held to the top, it
rises the full height. A real tap holds the control a few frames, and a fast
jump has risen some way by then: a `minJumpHeight` of 0.8 m on a jump taking
off at 8.3 m/s gives a 0.05 s tap a hop near 1.3 m. Set `minJumpHeight`
below the hop a tap should give; the presets set it so. On the local player's body the input
map's `jump` control holds it (keyboard, gamepad and touch alike); a writer
of the bus holds it with `inputJumpHeld`, and the module with
`CharacterController.jump(id)` until `CharacterController.releaseJump(id)`.
- `fallGravityMultiplier` (default 1) scales gravity while the character falls,
from the top of a jump or off a ledge: above 1 a jump rises floaty and comes
down fast, below 1 it drifts down.
- `maxFallSpeed` (m/s) above 0 caps the fall.
- One request is one jump. `inputJump = true` (or one press of `jump`) spends
one jump, and `jumpCount` counts it. A character with `maxJumps = 2` jumps
once on the request and keeps its second jump for the next request it gets
in the air. Landing gives every jump back.
- `coyoteTime` (s) is how long after walking off the ground the first jump is
still the jump from the ground. Past it that jump counts as spent, so with
`maxJumps = 2` a request in the air takes the air jump, as it does after a
jump from the ground.
- `jumpBuffer` (s) keeps a request made in the air with no jump left, which
jumps the moment the character lands; the jump it takes closes the buffer.
A tap made just before landing takes off as a tap: with `minJumpHeight` set
it gives the short hop.
- In the air the velocity across the ground carries on and turns toward the
walk the bus asks for at `airControlFactor * 10` of the way a second. A run
held through a jump keeps its speed, so a 5 m/s running jump of about a
second covers about 5 m; letting go of the stick slows the character the
same way, and a new heading takes over gradually. The higher the factor the
faster it answers: at 6 or more it takes the asked-for walk within one 60 Hz
frame, and at 0 it keeps the take-off velocity untouched.
Four presets set every feel field at once. Apply one to a character, or name
it in `CharacterController.install(id, { preset = "weighty" })`:
```luau
preset.apply("@builtin::systems.characterController.presets.weighty",
{ entity = id, component = "CharacterController" })
```
| Preset | Ground | Jump |
|--------|--------|------|
| `instant` | no ramp: starts, stops and turns the frame it is asked | `jumpForce` against gravity, full height however it is pressed, no fall scaling or cap |
| `responsive` | 40 m/s² up, 50 m/s² braking: quick and crisp | 1.3 m in 0.38 s, let go at take-off 0.25 m, falls at 1.6x, capped at 20 m/s |
| `weighty` | 6 m/s² up, 6 m/s² braking: a heavy body that commits to its heading | 0.8 m in 0.36 s, full height every press, falls at 2x, capped at 25 m/s, little air control |
| `floaty` | 25 m/s² up, 15 m/s² braking: light, slides a little into stops | 2.5 m in 0.6 s, let go at take-off 0.3 m, drifts down at 0.6x, capped at 6 m/s, strong air control |
Each field can be set on its own afterwards, on top of a preset:
```luau
local cc = entity(id).component.get("CharacterController")
cc.jumpHeight, cc.jumpApexTime = 1.5, 0.45 -- a full jump: 1.5 m, top at 0.45 s
cc.minJumpHeight = 0.4 -- let go at take-off: 0.4 m
cc.fallGravityMultiplier = 1.8 -- comes down faster than it went up
```
## Stairs and steps
A grounded character walks up a riser or curb no taller than `stepHeight`
and down a drop no deeper than it. The capsule lands on the next tread in
the frame it reaches it and keeps that exact height, so the walls, the
ground and every query see the character where it stands.
What the player sees climbs smoothly: the character's direct children that
hold no collider and no physics body, with none below them (the body mesh, a
name label) are drawn
shifted back by the riser and close on the capsule as a critically damped
spring of `stepSmoothing` seconds (default `0.1`: about three fifths of a
step in that time, nine tenths in twice it). A rise or drop the ground's
slope accounts for, on a ramp or a hill, is drawn as it happens; a
character placed by something else (a teleport, a respawn) is drawn where it
was placed. `stepSmoothing = 0` draws the body on the capsule every frame.
The character's module (`characterController.update`) smooths its steps by
the same rule, through `movement.stepSmoothing`.
## Platforms, belts and the contact filter
The character meets the surfaces content declares on colliders the way a
rigid body does. Its ground, wall and ceiling queries are cast for the
character's own entity as their mover (`Physics.raycast(..., { mover = id })`
and the same option on the shape casts), so the contact rules the physics
step applies to bodies apply to it too:
- **One-way platforms.** A collider whose `oneWay` points up holds the
character from above only: it jumps up through the platform from below and
lands on top of it, and walks through its sides.
- **Dropping through.** `Physics.passThrough(character)` drops it through the
one-way colliders it stands on (or, with a second argument, only those that
entity owns). It falls through under its own gravity and meets each again
once it is clear of it.
```luau
Physics.passThrough(player) -- drop through what it stands on
Physics.passThrough(player, platform) -- drop through this platform alone
```
- **Moving surfaces.** Standing on a collider whose `surfaceVelocity` moves (a
conveyor belt, a treadmill, an escalator) carries the character at that
velocity on top of its own walk. It keeps the carry as momentum when it
jumps or walks off, and air control (`airControlFactor`) takes it back
toward the walk it asks for.
- **Moving bodies.** Standing on a body that itself moves or turns (a lift, a
moving platform, a turntable, a raft, a ship's deck, a train car) carries
the character with it: each frame the point under its feet goes where the
body took it, and the character turns with the body's turn about up, with
its own walk on top. It rises and descends with a lift without leaving the
ground, and keeps the body's motion at its feet as momentum when it jumps or
walks off. In the air it goes on moving with that motion until it lands, the
way a crate thrown off the deck does: air control (`airControlFactor`) steers
its walk relative to it, so a jump in place on a moving deck comes down on
the spot it left, and a wall it meets in the air stops the part of it the wall
is in the way of. A kinematic body a script moves (`localPosition` writes,
`Physics.setVelocity`), a dynamic body the simulation moves and a transform
something animates all carry it alike. The body is read where the frame
draws it (`Physics.drawnPose`), and the character is seated on the ground as
drawn, so the two stay in step on screen at any frame rate and physics tick
rate. A body a script moves after this component's `update` (an
`executionOrder` above -100, or a task) carries the character on the next
frame. The momentum a kinematic body or an animated transform leaves the
character with is how fast it carried the feet over the last tenth of a
second (and at least the last six frames), however the frames fell against
the physics ticks, and a body that vanishes from under the character
leaves it the same. A character something else moves (a teleport, a
respawn, a script writing its position) rides nothing until it stands on
a body again. A move faster than 150 m/s over the frame
(`StatedWalk.TELEPORT_SPEED`) places it: it stands where it was put at
rest, with none of the fall, jump, walk or carry it had where it was taken
from. A slower move carries it (a room-scale step in XR, a script pushing
it along), and its fall and walk go on; writing back the position it
already stands at moves it nowhere. In a multiplayer session the
character states its pose relative to the kinematic or dynamic body it
rides, and through a jump off it until it lands (`multiplayer.setPoseFrame`,
read back with `multiplayer.poseFrame`): every other peer draws it on that
body where that peer draws the body, so a rider on another peer's moving
deck holds its spot there on every screen.
```luau
local lift = entity.spawn("lift")
lift.component.add("BoxCollider", { half = { 1.5, 0.1, 1.5 } })
lift.component.add("Physics", { kind = "kinematic" })
Physics.setVelocity(lift.id, 0, 1, 0) -- the character on it rides up
Physics.setAngularVelocity(lift.id, 0, 1, 0) -- and turns with it
```
- **The contact filter.** Give the character a collider with a `contactTag`
(a trigger capsule is enough) and `Physics.setContactFilter` answers its
pairs: a collider whose tag the filter answers `"ignore"` or `"sensor"`
with the character's tag is one the character walks through.
```luau
player.component.add("CapsuleCollider", { isTrigger = true, contactTag = "player" })
Physics.setContactFilter("player", "ghostWall", "ignore")
```
## Launching, knockback and momentum
Give the character speed it did not choose (a launch pad, a spring, a
knockback from a hit, a rope let go of, a respawn that sends it off) with
`setVelocity` or `addVelocity` on its controller, in m/s in world space. The
same verbs on `Physics` reach it too, so `Physics.setVelocity(player, ...)`,
`Physics.addVelocity(player, ...)` and `Physics.getVelocity(player)` work on a
character as on a rigid body. A character holds no mass, so an impulse is
given as the change of speed it makes (`addVelocity`), and
`Physics.applyImpulse` moves it nowhere and says so in the log.
```luau
local cc = entity(player).component.get("CharacterController")
cc:addVelocity(0, 14, 0) -- a jump pad: straight up, 10 m high at 9.81 m/s²
cc:setVelocity(6, 10, 0) -- a launch pad: thrown up and along +X
cc:addVelocity(away.x * 8, 4, away.z * 8) -- knockback away from a hit
Physics.addVelocity(player, 0, 14, 0) -- the same through Physics
local v = cc:getVelocity() -- { x, y, z }, world space
```
`setVelocity` replaces the velocity the character has; `addVelocity` adds to
it (to its walk, its fall and any motion kept from a body it left). Called
several times before the character's next frame, `setVelocity` calls replace
one another and `addVelocity` calls add up, on top of the last `setVelocity`.
Either takes effect on the character's next frame, after anything that
placed it this frame, so a respawn onto a launch pad launches. Each takes
`(x, y, z)`, a `vector` or a table `{ x, y, z }`, and answers `true`.
The controller carries the velocity on through its own movement, the way it
carries a jump or the motion of a platform it leaves:
- **Standing, with no speed up**, the part across the ground is the
character's walk: `braking` slows it to a stop (or to the walk its input asks
for), so 6 m/s with a `braking` of 5 slides 3.6 m. Walls stop it a skin short
of their face and slide it along them, and a dynamic body in the way is
pushed as a walk pushes it.
- **With any speed up**, it leaves the ground on that frame and reads
`grounded` false until it lands. No jump is spent, and the jump it could
have taken from the ground in `coyoteTime` is gone, so a character with
`maxJumps = 2` has its air jump and one with 1 has none. It rises and falls
under its gravity (a launch rises its full height whether the jump control
is held or let go), a ceiling stops the rise, and on a moving body it adds
the body's motion as it leaves, as a jump does.
- **In the air**, the speed across the ground it was given flies on: air
control (`airControlFactor`) steers only the walk the input asks for, on top
of it, as it does over the motion kept from a platform. A wall met in the air
stops the part of it the wall is in the way of.
- **Landing**, what is left of it becomes the walk, and `braking` slows it on
the ground.
The movement is integrated exactly for each part of a frame, so a launch rises
the same height and lands the same distance away at 30 and at 120 frames a
second, within the step of the frame it lands on. On a body the character
stands on, the velocity is relative to that body. In a multiplayer session the
peer that moves the character applies it (the owner of a player's body, or
the peer it is bound to) and every other peer sees the motion through the
character's replication. On another peer's replica both calls leave the velocity
as it is and answer `false` (`Physics.setVelocity` and `Physics.addVelocity`
say so once in the log), so a hit landed on another player's body is sent to
the peer that moves it (a `Sync` event or `multiplayer.send`) and given there.
## Other characters
Characters meet one another as solid bodies. Every entity carrying a
`CharacterController` is an upright capsule of its `radius` and `height` to
every other character's wall pass (`physics.characters`), so two characters
walking into each other stop a skin apart, a character meeting another off
centre slides around it, and `blocked` reads true while a walk presses into
another character. The same holds for the local player, an NPC and another
player's body.
A character is a body while its entity is active and its controller enabled:
one set inactive (`entity(id):setActive(false)`) or with its controller
disabled (`enabled = false`) lets the others walk through it until it is
switched back on.
The push rule:
- A walk never moves another character. Each peer moves only the characters
it owns, against where it sees the others, so two players' bodies meet on
both peers' screens.
- Two characters that overlap (placed into one another, two spawned at one
point, a body the network shows a frame late) move apart at up to 2 m/s
each, each taking half of the overlap, and never through a wall. A pair
pressed together stands still a skin apart.
- A character gives way to no body moving into it: the one walking in is the
one stopped, on the peer that moves it, so a player walking into a standing
one never drives it along, however late each peer sees the other.
- Only bodies sharing some height meet: a character jumping over another
passes above it, and one coming down onto another's head is moved off it to
the side.
Which characters pass through which is the contact filter's to say, by each
character's `contactTag` (`"character"` unless content names another):
```luau
Physics.setContactFilter("character", "character", "ignore") -- nobody blocks anybody
ghost.component.get("CharacterController").contactTag = "ghost"
Physics.setContactFilter("ghost", "character", "ignore") -- the ghost walks through people
Physics.setContactFilter("redTeam", "redTeam", "ignore") -- teammates pass, foes block
```
## Triggers, pickups and the bodies it walks into
The character holds no rigid body: it states its capsule (`Physics.setWaterVolume`),
`height` tall and `radius` round, standing on its feet. That capsule is how
the rest of the world meets it:
- **Triggers and pickups.** A trigger collider hears the character enter and
leave it as it hears a body (`Physics.onTrigger(zone, fn)`, with `other`
the character's entity), and a listener on the character
(`Physics.onTrigger(character, fn)`) hears every trigger it goes through.
Every engine the character exists in hears it, the remote players' bodies
included, so a zone counted on each peer counts every player. A trigger on
an entity beneath the character (a sensor it carries) rides with it and
does not hear it.
- **Water.** `Physics.onWater` hears it go in and out of the water and
`Physics.immersion` reads how deep it stands.
- **Pushing.** A dynamic body the walk runs into is pushed along the walk:
the walk stops at it as at a wall, and the body is given the impulse that
brings its speed along the walk up to the walk's, with at most `pushForce`
newtons (400 by default) behind it. On level ground a body moves once
`pushForce` passes its friction coefficient times its weight, so at the
default a 5 kg crate goes along at the walk with the character behind it and
a 500 kg one stands like a wall. `pushForce = 0` makes every body a wall.
- **Bodies moving into it.** A body that moves into the character puts it
back outside, as a wall that moved into it does.
```luau
local player = layers.active.players.localPlayer.avatar
Physics.onTrigger(coin, function(e)
if e.kind == "enter" and e.other == player.id then collect(coin) end
end)
player.component.get("CharacterController").pushForce = 150 -- a weaker shove
```
## Telemetry
These read back what the mover did on the frame just simulated:
- `grounded` — standing on ground no steeper than `maxSlopeAngle`.
- `falling` — in the air and descending.
- `sliding` — on ground too steep to stand on, being carried down it.
- `blocked` — the character asked to move horizontally and the wall pass left
it with none of that movement: pressed into a wall, or wedged where two
surfaces meet. This is what tells a character standing still apart from one
whose walk is being refused.
- `slopeAngle` — the angle, in degrees, of the ground under it.
- `velocityX` / `velocityY` / `velocityZ` / `horizontalSpeed` — its velocity,
across the frame it stands in (`frame`). `getVelocity()` reads it in world
space, with any velocity given since its last frame.
- `jumpCount`: jumps used since it last landed. Walking off a ledge counts
the jump from the ground as used once `coyoteTime` has passed.
## Standing still
A character standing on the ground with nothing asking it to move rests: it
takes no movement step and writes none of its fields, so a crowd of idle
characters costs little more than the check each one makes that nothing has
reached it. It takes its step again on the frame anything does: a write to its
input bus or any of its fields, its feet moved by something else, the ground
or the body it rides moving or changing (taken away, switched off, passed
through, its surface set moving), a collider coming to overlap it, another
character moving within reach, the gravity at its feet changing, or its being
bound as the local player's body. Entities spawned and despawned elsewhere in
the world leave it resting. Telemetry reads what it read on the frame it came
to rest.
`stats()` reads how its frames went:
```luau
local s = entity(id).component.get("CharacterController"):stats()
print(s.resting, s.stepFrames, s.restFrames)
```
# Locomotion
Blend-space-driven locomotion for entities running the
characterController package. Feeds a single 2D blend space (strafe-angle
on X, speed on Y) with idle / walk-{F,L,R,B} / run-{F,L,R,B} / sprintF
clips from the character's own walk.
The walk is what the character's `CharacterController` states each frame it
moves it: its walk across what it stands on, so a body carried by a conveyor,
a moving deck or a lift while it stands still plays its idle, and the walk it
is asked for. The body turns toward the walk it is asked for at whatever speed
it asks (a light stick push, a walk into a wall the walls refuse), and with
none asked toward its velocity once that is faster than `moveDeadzone`. A
body that carries neither a `MovementState` nor a `CharacterController` reads
the walk the nearest of its ancestors with a `CharacterController` states, so
a body parented under a root a controller walks idles on a conveyor and turns
toward a wall it is asked to walk into, as that root does. On a frame nothing
states the walk (another peer's avatar the sync moves, a body a script moves)
the velocity is measured: from the entity's `MovementState`, or its
`CharacterController` without one, against its parent; and on a body that
carries neither, from its position in the world, so a body parented under the
root an NPC's brain and navigation move walks and faces with that root.
The strafe angle is the signed angle from the body's facing to
its velocity, positive toward the body's right (`forward x up`): the R
clips sit at +90, the L clips at -90 and the B clips at 180. Each
clip's point sits at the speed the clip carries this body at: its
retarget bake measures how fast the ground passes under the
stance foot on this body's legs, so the feet move with the ground at
whatever speed the body moves. A clip that plays without a measured
speed sits at its gait's `walkSpeed` / `runSpeed` / `sprintSpeed`.
Pair on the same entity (or a parent of) a `SkinnedModel`. The
component creates the AnimGraph, polls for the SkinnedModel child
once start() has run, registers the clips as blend-space points and
plays the graph. `update()` damps speed + angle and writes them to
the active blend space each frame.
Once every clip has bound, the component hands the graph to the engine
(`AnimGraph:runNatively`): the engine reads the walk the mover states, or
measures the root's velocity from its position, turns the body as above, damps the speed and angle and evaluates
the blend space every frame, and the component's `update` is held. A body
the sync moves (another peer's avatar), an NPC and the local player's own
body all walk with no script running for their pose. The component takes
the graph back when one of its fields changes or another component changes
the graph (a layer spliced over it), and runs it in script while the graph
holds a node the engine does not run, a clip that drives blend shapes, or
its velocity is read from a `CharacterController` without a `MovementState`.
`component.get("Locomotion"):stats()` reads
`{ native, handle?, frames?, refusal?, motion, space }`: where the graph runs,
why not in the engine when it does not, whether the velocity is the walk the
mover stated (`motion = "stated"`) or a measured one (`"measured"`), and
whether a measured velocity is the body's motion against its parent
(`space = "local"`) or in the world (`"world"`).
## Facing in multiplayer
The body's facing is the rotation of its anchor, the child of the root that
holds the skinned body, and only the peer that owns the body turns it. The
component names that child with `multiplayer.syncChildPose`, so its local
pose travels with the synced root: every other peer draws the facing the
owner states, a short delay behind on the timeline the root is drawn on, at
join, after the body stops and through a turn in place alike (a script that
turns the anchor on the owner's peer is drawn turned everywhere). On a peer
that draws it so, `multiplayer.childPoseFromOwner(anchor)` reads true and the
component, in script or in the engine, reads its strafe angle from that
facing and leaves the anchor's rotation as the owner states it.
## Jumping, falling and landing
`jumpAnim`, `fallAnim` and `landAnim` are the air poses: the take-off and
rise, the fall, and the landing. With any of them set (the `synty` preset sets
all three, and the built-in humanoid avatar uses it) the blend space and those
clips sit under one Mixer, and the body moves between four states by the
motion of its root:
- **ground**: the locomotion blend plays.
- **rise**: the body is off the ground and moving up faster than 1 m/s. The
take-off clip plays from its start.
- **fall**: the body is off the ground and moving down faster than 1 m/s (a
walk off a ledge), or its rise has stopped. The fall clip loops.
- **land**: the ground is under the body again. The landing clip plays from its
start and fades into the locomotion blend over `landTime` seconds.
The body is off the ground while nothing stands within 5 cm below its feet
across its footprint. The footprint is the disc its `CharacterController`
stands on, its `radius` less its `skinWidth` (0.25 m without one), and the
5 cm are counted from the ground the feet stand a `skinWidth` above, so a body
standing on the edge of a ledge, or with a wide skin, reads the ground its
controller stands on. A sphere of the footprint's radius is swept down past
the colliders the character carries, far enough to reach an edge at the rim
of the footprint, and the surface it meets counts where the sphere touched it.
A change of the controller's `radius` or `skinWidth` reaches the sweep on the
next frame (the controller calls `footingChanged()`). A body on nothing that
moves neither up nor down (a preview, a mannequin) keeps the locomotion blend.
Each pose's weight moves toward its state's at
`1 / airBlendTime` a second. A slot left nil, or whose clip failed to bind, is
stood in for: the take-off by the fall, the fall by the take-off, and the
landing by the locomotion blend. A clip that failed to bind keeps the graph in
script, and `stats().refusal` names the clip.
The engine runs the air states with the rest of the graph, so the local
player, an NPC and another player's body the sync moves all jump, fall and
land the same way with no script running for their pose.
```luau
local loco = entity(id).component.get("Locomotion")
loco.jumpAnim = asset.resolve("A_Jump_Running_Masc", "animation")
loco.landTime = 0.2
```
# MovementState
Component that exposes movement state for controller-driven animation and gameplay consumers.
# characterController
Physics-based character controller — capsule movement with
ground / wall / ceiling detection. A kinematic controller using
raycasts for collision; handles gravity, jumping, slope traversal,
step climbing, wall sliding, coyote time, and riding the bodies it stands on
(`physics.platform`). The
module owns a per-entity registry; attach once, call `move` / `jump`
each frame, then drive a per-frame `update(dt)`. The
`install` / `uninstall` / `preset` surface wires up the standard set
of components (CharacterController + Locomotion + MovementState +
optional WASDInput and third-person camera child) in one call.
Require it to use the surface:
```luau
local CharacterController = require("@builtin::systems.characterController.characterController")
```
## Exports
- `CC.attach(entityId: string, userConfig: Config?)` — register an entity, merge user overrides over `Defaults.standard`.
- `CC.detach(entityId: string)` — drop the registry entry.
- `CC.move(entityId: string, direction: Vec3)` — set per-frame world-space movement input (`y` is ignored).
- `CC.jump(entityId: string)` — request a jump; honours coyote time and jump buffer.
- `CC.getState(entityId: string) -> State` — snapshot copy of grounded / falling / velocity / etc.
- `CC.getVelocity(entityId: string) -> (number, number, number)` — current `vx, vy, vz`, with any velocity given since the last update; for an entity carrying the `CharacterController` component, that component's.
- `CC.setVelocity(entityId: string, x: number | Vec3 | vector, y: number?, z: number?) -> boolean` — replace the character's velocity (m/s, world space): a launch pad, a knockback. Standing with no speed up it is walk `braking` slows; with speed up it leaves the ground and flies, air control steering only the walk asked for on top of it, and on landing what is left is braked. Takes effect on the next update, after a placement.
- `CC.addVelocity(entityId: string, x: number | Vec3 | vector, y: number?, z: number?) -> boolean` — add to the character's velocity, an impulse as the change of speed it makes; calls before the next update add up. Both reach a body this module moves (`attach`) and one carrying the `CharacterController` component (`install`), answer false on another peer's replica, and raise for an entity with neither.
- `CC.setGravity(entityId: string, gravity: number)` — update gravity at runtime.
- `CC.setMaxSlope(entityId: string, degrees: number)` — update max walkable slope angle.
- `CC.setConfig(entityId: string, key: string, value: any)` — update a single config key.
- `CC.getConfig(entityId: string) -> Config` — config copy.
- `CC.update(entityId: string, dt: number)` — advance one frame (resolve movement, write position, tick state machine). `dt` is clamped to 0.1. A body something else placed elsewhere since the last update (a teleport, a respawn, a script writing its position), faster than `StatedWalk.TELEPORT_SPEED` (150 m/s), starts from where it was put at rest; one carried slower keeps its motion.
- `CC.isAttached(entityId: string) -> boolean` — whether the entity has a registration.
- `CC.install(entityId: string, opts: InstallOpts?) -> InstallResult` — high-level wire-up (components + optional camera / mesh / WASDInput).
- `CC.uninstall(entityId: string) -> UninstallResult` — remove everything `install` added.
- `CC.preset(entityId: string, presetName: string) -> PresetResult` — apply a preset to an already-installed character in place.
Types:
- `Vec3 = { x: number, y: number, z: number }`
- `Config = { height?, radius?, maxSlopeAngle?, stepHeight?, gravity?, jumpForce?, coyoteTime?, jumpBuffer?, maxJumps?, airControlFactor?, groundSnapDistance?, stepSmoothing?, skinWidth?, moveSpeed? }`
- `State = { grounded, falling, sliding, wallContact, wallNormal, velocity, groundNormal, slopeAngle, jumpCount, timeSinceGrounded, timeSinceWallContact, onMovingPlatform, platformEntity? }`
- `BundleRef = { guid?, __ref?, identity?, path?, name? }`
- `InstallOpts = { preset?, camera?, input?, mesh?, overrides? }`
- `InstallResult = { entityId, cameraId?, meshHostId? }`
- `UninstallResult = { entityId, despawned }`
- `PresetResult = { entityId, preset, applied }`
## Usage
```luau
local CharacterController = require("@builtin::systems.characterController.characterController")
-- Low-level: manual attach + per-frame drive.
CharacterController.attach(entityId, { gravity = -15, jumpForce = 7 })
CharacterController.move(entityId, { x = 1, y = 0, z = 0 })
CharacterController.update(entityId, dt)
-- High-level: one-call wire-up.
CharacterController.install(entityId, {
preset = "humanoid_default",
camera = true,
overrides = { jumpForce = 8 },
})
```
## Notes
- `attach` merges user config over `Defaults.standard`; passing
unknown keys is allowed (they survive into the config table).
- `update` clamps `dt` to 0.1s to prevent capsule tunnelling on
lag spikes.
- `getState` and `getConfig` return shallow copies — mutating the
result does not affect the controller. The returned `velocity` /
`wallNormal` / `groundNormal` are also shallow copies.
- `install` is idempotent per component — re-running on an already
wired entity adds nothing new. `uninstall` removes the components
and any third-person-camera child that targets this entity.
- `preset` mutates fields in place and never adds or removes
components — call `install` first.