# 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`.
# 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 } })
```
# 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.
# quickGeometry
Model a scene in Luau with three.js-shaped code. A `build.luau` or a `.sceneModule` builds `Group`s and `Mesh`es from geometry constructors and materials; at the end of the build the tree is stored in the scene as data, drawn by one `Generator`, and nothing runs per frame.
A bare box reads as a placeholder. Every geometry takes **modifiers** that turn it into a modelled shape: round its edges, taper it, bend it, drill it, smooth it, or build it from a profile or cross-sections. A build whose parts are mostly bare boxes and planes logs a warning that names them.
## Using it
The nouns are globals in a scene's `build.luau` and a `.sceneModule`'s entry script: `sceneNouns` and `quickLighting` join both scripts' contexts, so the engine binds their exports when it loads the script, and the language server knows the same names.
```luau
function content()
local paint = MeshStandardMaterial({ color = "#b0332f", metalness = 0.45, roughness = 0.28 })
local steel = MeshStandardMaterial({ color = "#aab2ba", metalness = 1, roughness = 0.25 })
local body = Mesh(BoxGeometry(1, 1, 1):round(0.14), paint, "rounded_box")
body.position:set(0, 0.8, 0)
local block = Mesh(BoxGeometry(1.1, 1.1, 1.1):subtract(CylinderGeometry(0.3, 0.3, 2, 24)), steel, "drilled_block")
block.position:set(1.5, 0.8, 0)
local hull = Mesh(LoftGeometry({
{ shape = EllipseShape(0.45, 0.28), z = -1.2, scale = 0.25 },
{ shape = EllipseShape(0.45, 0.28), z = -0.55, scale = 0.95 },
{ shape = EllipseShape(0.45, 0.28), z = 0.4, scale = 1.0 },
{ shape = EllipseShape(0.45, 0.28), z = 1.2, scale = 0.3, offset = { y = -0.06 } },
}), paint, "hull")
hull.position:set(3.2, 0.8, 0)
end
```
The same code works in a `.sceneModule`'s builder, where `inputs` declare what a placement may set.
A module joins those contexts with `--!context sceneBuild sceneModule` in its leading comment block, the way these two do. A world's own module joins the same way, and its exports become globals in every build script beside the nouns. A name that starts with `_` stays inside its module. A module that exports `_beginRun` and `_finish` has them called around every run of a build. The `script_context` module's README covers contexts in full.
## Parts
- `Group(name)` holds other objects. `Mesh(geometry, material, name)` draws a geometry.
- `object.position`, `object.rotation` (Euler angles in radians, XYZ) and `object.scale` take `.x`, `.y`, `.z` and the vector methods `set`, `setScalar`, `copy`, `add`, `sub`, `multiplyScalar`, `clone` and `toArray`; calls chain.
- `parent:add(a, b, ...)` nests objects under another, and their poses are then in the parent's frame; an object added elsewhere moves. `parent:remove(a, ...)` takes them out, and a removed object is not drawn until it is added again. `object.parent` and `object.children` hold the tree.
- `object.visible = false` leaves the object and everything under it out of the scene. `object.userData` is a table for your own values.
- `object:lookAt(x, y, z)` or `object:lookAt(Vector3)` turns the object so its +Z axis points at a point in its parent's frame; the object's position and the point are numbers.
- `object:clone(recursive)` copies the object, its pose, components and (unless `recursive` is false) what is under it; the copy shares the geometry and material and is placed like a new `Mesh`. `object:traverse(fn)` calls `fn` on the object and everything under it, and `object:getObjectByName(name)` finds one.
- `object:addComponent(type, data)` puts an engine component on the entity a part becomes (`Physics`, a collider, a `Joint`). A part whose pose follows a formula is drawn as an instance and takes none.
- An object that never moves and carries a component becomes an entity named for it, with its parent and local pose; one that never moves and carries none is folded into the object above it. A moving object's leaves are drawn as instances.
## Geometry
| Constructor | Shape |
|-------------|-------|
| `BoxGeometry(width, height, depth)` | box |
| `CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded)` | cylinder; a cone when one radius is 0 |
| `ConeGeometry(radius, height, radialSegments, heightSegments, openEnded)` | cone with its apex up |
| `SphereGeometry(radius, widthSegments, heightSegments)` | UV sphere |
| `TorusGeometry(radius, tube, radialSegments, tubularSegments, arc)` | torus |
| `TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q)` | torus knot |
| `CapsuleGeometry(radius, length, capSegments, radialSegments)` | capsule |
| `PlaneGeometry(width, height, widthSegments, heightSegments)` | flat rectangle |
| `CircleGeometry(radius, segments)` | flat disc |
| `RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength)` | flat annulus |
| `TetrahedronGeometry`, `OctahedronGeometry`, `IcosahedronGeometry`, `DodecahedronGeometry` `(radius, detail)` | regular polyhedra; `detail` above 0 rounds them toward a sphere |
| `LatheGeometry(points, segments)` | a profile of `{ x = radius, y }` points revolved around Y |
| `ExtrudeGeometry(shape, { depth, curveSegments })` | an outline extruded along +Z |
| `ShapeGeometry(shape, curveSegments)` | a flat, filled outline |
| `TubeGeometry(path, tubularSegments, radius, radialSegments, closed)` | a circle swept along a curve |
| `LoftGeometry(sections, { caps })` | a surface through cross-sections along Z |
| `BufferGeometry()` | a mesh from your own arrays |
| `mergeGeometries(list)` | several geometries as one |
Every geometry also takes `translate(x, y, z)`, `rotateX/Y/Z(angle)` and `scale(x, y, z)`, which move it.
### Outlines and curves
`Shape()` records an outline with `moveTo`, `lineTo`, `quadraticCurveTo`, `bezierCurveTo` and `absarc`. `EllipseShape(rx, ry, segments)` and `RoundedRectShape(width, height, radius, segments)` return ready outlines. `CatmullRomCurve3(points, closed)` and `HelixCurve(radius, turns, height)` return curves for `TubeGeometry`.
### Loft
`LoftGeometry` takes sections in order, each `{ shape, z, scale?, offset? }`: an outline, where along Z it stands, a scale (a number or `{ x, y }`) and a move (`{ x, y }`). `caps = false` leaves the ends open. A body, a hull, a fuselage or a bottle is a loft.
### Custom arrays
```luau
local triangle = BufferGeometry()
triangle:setAttribute("position", Float32BufferAttribute({ 0, 0, 0, 1, 0, 0, 0, 1, 0 }, 3))
```
`setAttribute` takes `position`, `normal` and `uv`; `setIndex(list)` gives triangle indices; without normals they are computed and shared across triangles (`computeVertexNormals()`).
## Modifiers
A modifier changes the shape in its own frame, before `translate`/`rotate`/`scale` move it, and modifiers stack in the order called.
| Modifier | Effect |
|----------|--------|
| `:round(radius, segments)` | round every edge with that radius |
| `:bevel(width, segments, angle)` | round only edges sharper than `angle` degrees; `width` is how far it reaches onto each face |
| `:subdivide(levels, mode)` | split every triangle into four, `levels` 1 to 3 times; `"loop"` (default) also smooths, `"linear"` only adds points |
| `:smooth()` | one round of Loop smoothing |
| `:taper(amount, axis)` | scale the cross-section by `1 - amount * d` at distance `d` along `axis` (`"y"` by default) |
| `:twist(angle, axis)` | turn the shape about `axis` by `angle` radians per metre along it |
| `:bend(curvature, axis)` | curve it along `axis`; `curvature` is 1 over the bend's radius in metres |
| `:subtract(other)`, `:union(other)`, `:intersect(other)` | combine with another closed solid, which stands where it was moved to |
`subtract`, `union` and `intersect` take one shape and one shape; merge parts after combining. Both must be closed solids (a box, cylinder, sphere, torus, capsule or polyhedron, or a bevelled or smoothed one).
## Materials
`MeshStandardMaterial({ color, roughness, metalness, emissive, emissiveIntensity, opacity, side })` and `MeshBasicMaterial({ color, opacity, side })`. A colour is a `Color`, a hex string (`"#a3141b"`), a number (`0xa3141b`), a name (`"red"`) or `{ r, g, b }`; hex colours are sRGB. `side = "double"` draws both faces; an `opacity` below 1 blends.
## Math
`Vector3`, `Color` and `MathUtils` come from the same module as the other nouns and are described in the [math](math.module/README.md) module's README: vector methods and operators, colours from hex, names and HSL, and clamp, lerp, smoothstep and a seeded random.
```luau
MathUtils.setSeed(3)
for i = 1, 12 do
local post = Mesh(CylinderGeometry(0.05, 0.05, 1):round(0.01),
MeshStandardMaterial({ color = Color():setHSL(i / 12, 0.5, 0.5) }), "post" .. i)
post.position:set(i * 0.5, 0.5, MathUtils.randFloatSpread(0.2))
end
```
## Motion
Write a pose as a formula of `Time` (seconds) and the `Expr` functions `sin`, `cos`, `sqrt`, `atan2`, `abs`, `min`, `max`, `mod` and `floor`, with `+ - * / ^`:
```luau
local angle = Time * 6.28
piston.position.y = 1.74 * Expr.cos(angle) + Expr.sqrt(32 - 3 * Expr.sin(angle) ^ 2)
crank.rotation.z = -angle
```
The formula is stored with the scene and runs on the device each frame; children follow their parent's motion.
## Lighting
```luau
Lighting({ background = "#0c0f12", environment = 1, sun = { color = "#fff1dc", intensity = 1.6, position = { 18, 30, 22 } } })
PostProcessing({ exposure = 0.9, toneMapping = "aces", bloom = { threshold = 1.05, intensity = 0.55 } })
```
A scene setup places a whole lighting composition as one asset. The V8Dyno scene places `studioLighting`, a studio backdrop, a warm key light and a sky light that lights the model from the backdrop:
```luau
asset.resolve("@builtin::systems.quickGeometry.studioLighting", "sceneSetup"):instantiate(nil, { name = "lighting" })
```
## Where it lives
Each build ends by spawning one entity named `model` with a `Generator` on the `ModelGraph` graph in this package. The tree is the Generator's `objects` and `channels` inputs, stored in `scene.json`; the shapes are made by the nodes of the `shape` nodebox and the modifiers by procgen's `geometry.*` nodes. Names that two parts share get a numeric suffix.
# 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.
# 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`
# generator
The parts of the `Generator` component (`@builtin::systems.procgen.Generator`).
The component makes one context table per instance, `gen`, holding its
`public` and `private` surface, and calls this module with it. Each part
installs its state and operations on `gen`:
- `realized`: What a Generator has realized and from which graph: the entities, populations, meshes, materials and volumes it stands, tracked per output, and the retirement that keeps an output's earlier realization standing until its replacement lands.
- `translated`: A Generator's translated outputs: the states they stand as, the bounds it publishes for them, the frames play of a held output, and the clock a translated output is presented at.
- `cook`: Cooking a Generator's graph: the outputs it resolves, the node and frame caches a cook reads and fills, the cook's own state and costs, the world values a graph follows, the pacing of a cook on a worker, the inputs a cook takes, the evaluation of one output, and the per-node placement the `playback` report reads.
- `realize`: Standing a cooked value as a Generator's children: a geometry, grid, bundle, population or asset reference realized under the generator, an output split into the pieces it realizes as, and the folding of outputs into the one bundle `apply` writes.
- `run`: Running a Generator's bound graph: the bound graph and its signatures, its timeline and the clock each frame is cooked at, the cook that runs ahead through the timeline, presenting a cooked frame on the device, and standing a frames play of a held output.
- `diskcache`: A Generator's disk cache and baked snapshot: the outputs a graph declares `diskCache` on, loaded from the world's cache, the writes a commit makes for them, and the snapshot an earlier engine stored with the scene.
- `play`: A Generator's play of its graph (`call`): loading, clocking, presenting, standing and advancing it; binding a graph to the generator (`regenerate`); and standing a baked snapshot in place of cooking.
- `clock`: A Generator's clock, frame by frame: the live sources it polls, the material clocks and live material values it writes, the playhead it presents, the transport its peers share, advancing time, cooking again once the device returns, and the tick each frame runs.
# proc
Code-authored, graph-backed procedural generation for the Zero engine.
A graph is one function of `g`: `proc.define(function(g) ... end)`. Nodes are called by
family and name (`g.<family>.<name>({ ... })`), inputs are declared with `g:input(name, default, opts)`,
the returned table is the graph's outputs, and `io.output` is how the graph stands in the world.
`builder.module/README.md` holds every rule of that form.
This module owns the whole procedural model: the graph builder + data model,
the operation registry, the type system, the lazy cached evaluator, deterministic scoped hashing, and the node-family op
implementations. Authored `.procGraph` graphs are persisted via
`procGraph.assetType`; the `procgen.preview` / `procgen.spawn` operations live in
`procgen.toolbox` and are invoked as tools: `tools.use("procgen", "preview", args)`
from a script or an agent's `tool_exec` script, or `zero procgen preview` in the
shell. Generated
meshes/materials/textures/bundles are persisted through their own `.assetType`.
An op family can also come from outside this package: a `.procPack` asset
registers its ops in the same registry, called as `g.op.<id>(...)` exactly like the ones
shipped here (`proc.registerPack(name, ops)` is what it registers through, and
what a test or a tool calls to hold a family for the life of one VM).
`terrain.*` is one such pack, shipped in `terrainSystem.package/procPacks/`
and covering a whole landscape; `guides { path =
"systems/terrainSystem/documentation/terrain" }` is its guide.
To find out what the registry holds, use the `procgen` toolbox: `searchNodes`
searches it and `describeNode` describes one node or op. `proc.search_ops(query)` and
`proc.schema(id)` are the same answers in-process, for a graph builder looking
something up while it runs.
# Scatter
Strews copies of one shape over the surface of another, each with its own turn, lean and size.
Both the surface and the thing scattered are inputs, so this covers rocks on a hillside, crates on a deck, bushes
along a bank or rubble across a floor: wire it a different `source` and it is a different field.
It makes points on the surface (`points.on_surface`, area-weighted), gives every point its own random yaw, lean and
scale (`instances.randomize_transform`), and places the source on those points (`instances.on_points`). The transform
is read from the same point cloud the instances sit on, so each copy takes the pose of its own point.
## Inputs
| Input | Type | Default | What it does |
|-------|------|---------|--------------|
| `surface` | Geometry | none | What the copies land on. Points are area-weighted, so a bigger face gets proportionally more. |
| `source` | Geometry | none | The shape being copied. |
| `count` | Int | 200 | How many copies. |
| `seed` | Int | 1 | Changes the arrangement. The same seed always gives the same field. |
| `scaleMin` | Float | 0.8 | Smallest per-copy size multiplier. |
| `scaleMax` | Float | 1.4 | Largest per-copy size multiplier. Equal to `scaleMin` means uniform. |
| `tilt` | Float | 0.15 | Radians of random lean off vertical. `0` stands every copy upright. |
## Output
`instances`: a population, the points each carrying the source as its `Mesh`. A Generator draws it as one
hardware-instanced draw call per source; `instances.realize` merges it into a single Geometry.
## Calling it
Another graph calls a `.procGraph` as it calls a node, by its path or identity, naming the inputs in a table; the
call answers what the graph outputs (`instances`). Its declared inputs are the call's inputs.
# frame_budget
The share of a frame that cooperative engine work spends before it hands the
frame back.
Some engine work is one long sequence of small units run on a task: a scene
load applies one record after another, and the world-load `onRegister` sweep
fires one instance's hook after another. Run back to back in one frame, a long
sequence holds that frame for its whole length, and nothing else the engine
does (answering a call, drawing, input) happens until it is through. Asking
`due()` before each unit and yielding when it answers true runs the same work
across as many frames as it needs, a slice of each.
```luau
local FrameBudget = require("@builtin::modules.frame_budget")
for _, item in ipairs(items) do
FrameBudget.yield()
process(item)
end
```
- **One slice per frame, shared.** Each caller is charged the time it runs
between its readings of the slice in a frame (`task.runTime`), whoever runs
it, and the charges of every caller add up to the frame's slice. What the
rest of the frame runs (systems, components, other tasks) is not charged, so
a busy frame still gives the slice to the work. Two long pieces of work
running at once share a frame's slice rather than taking one each.
- **A unit is never split.** The first unit of a frame always runs, so a frame
holds at most the slice plus the one unit that crossed it. A unit that is
itself long stays one piece of work.
- **Code that cannot yield runs in its frame.** `due()` answers false outside a
coroutine that can yield, so a caller called from such code does all its
units in the frame it was called in, as it would without the budget.
A caller that does work of its own around the yield asks `due()` and calls
`wait()`, which yields to the next frame and opens that frame's slice as the
caller resumes; `yield()` is the two together.
Work whose unit is a native call that bounds itself by time is told how long
it may run: `remainingMs()` answers what is left of the current frame's slice,
or nil for code that cannot yield, which then runs the whole of its work in the
frame it was called in. The publish gate's script check runs this way:
```luau
local block, checking = __spacetime_vcs.scriptPublishBlock(FrameBudget.remainingMs())
while checking do
FrameBudget.wait()
block, checking = __spacetime_vcs.scriptPublishBlock(FrameBudget.remainingMs())
end
```
## The background lane
Some work is started early so it is ready when asked for, and no picture waits
on it, such as the search text an editor reads ahead of the first
`tools.search`. `background(fn)` runs `fn` on the background lane: every
`yield`, `due` and `wait` its work makes on that coroutine hands the frame back
for as long as a hold on the lane stands, and takes its slice as usual once
none does.
```luau
FrameBudget.background(function()
for _, path in ipairs(paths) do
FrameBudget.yield()
warm(path)
end
end)
```
Work the picture waits on holds the lane while it runs: `holdBackground(key)`
until `releaseBackground(key)`. A world's entry holds it under `"world entry"`
from the moment the world is ready (its `onRegister` sweep) until its
`onWorldLoad` has returned, so the frames of the entry carry the world's load
and the background work runs in the frames before and after it. A hold no one
releases lapses after `BACKGROUND_HOLD_SECONDS` (or the seconds it was taken
for), with a warning naming its key, so work on the lane always runs in the
end. `backgroundHolds()` lists the keys holding the lane now, and
`backgroundWaits()` answers whether the calling code's next unit waits for it
(a walk with a clock of its own asks it between its pieces).
`FrameBudget.DEFAULT_MS` is the slice a call that names none spends. `spent()`
answers how much of the current frame's slice is gone.
A caller with a budget of its own reads `mark()` where its work starts.
`ranMs(mark)` answers how long it has run since, none of the time it spent
suspended; `cpuMs(mark)` answers the CPU time of its work since: those
stretches and the stretches of every coroutine it resumes, and every one they
resume, while it waits on them, which a machine whose cores are taken by other
work does not stretch, so a bound that refuses work for running too long
refuses the same work on a loaded machine as on an idle one, and work handed to
a coroutine as work run in place. A task it starts and waits for runs while it
is suspended, which `cpuMs` does not count.
# 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.
# generator_inspector
The `Generator` component's card on an entity. It replaces the card's generic
`settings` section with one built from the bound graph: the graph it runs, as
an asset picker, and which of its outputs it realizes; then groups — Inputs,
one row per input the graph declares in the control its type takes, each able
to take an expression over the graph's own time; Timeline, the transport,
scrubber, range, frame rate, looping and wall time; Cook, what is cooking, what
cooking has cost and the frame budget — and the Flatten action. The
component's `inspector.luau` returns this module, so the editor's inspector
framework (`edui.inspector.componentSections`) shows it wherever the component
is on an entity. While the clock runs, or the range is still cooking, the card
asks the panel to follow it.
Editing an input row writes the value into the component's `params`, which
regenerates the live output in place. A write the input's type cannot hold is
refused, and the row says why.
`buildFieldSpecs(graph, params)` is the pure row mapping: one spec per declared
graph input, sorted by name, carrying its kind, its current value (the param
override when set, else the declared default), its declared range, the asset
kind a reference input picks from, and whether the value changes over time.
# 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).
# 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).
# 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.