# Chase Camera
A follow cam that trails behind the target's facing at a fixed `distance` and `height`. Designed for vehicles and fast platformers where `orbital_follow`'s orbit feels too floaty.
- **The distance holds at any speed.** The camera trails the target where it is drawn this frame, and what eases is its offset from the target, so a camera set 6 m behind a car stands 6 m behind it at 5 m/s and at 200 m/s. `positionSmoothing` softens a change of the framing (the target turning, a zoom, a stick's or a finger's look, the swing back behind the target); a mouse look turns the camera on the frame the mouse moves. `rotationSmoothing` how quickly the aim swings to a new heading.
- **Collision pull-in.** Each frame a sphere of `cameraRadius` is swept from `height * 0.5` over the target itself (wherever the framed point lags) out to the camera. Sweeps of that line ahead bring the camera in ahead of what is about to come between it and the target, at the speed that has it clear when the line gets there, and something no sweep could see coming brings it in on the frame it blocks the view, so no frame is drawn from inside a wall; once the way is clear it eases back out over `pullOutTime`. With less than 0.4 m of room on the line, the camera turns round the target to the nearest turn that has it. The aim comes down from above the target toward it as the camera comes in, so a camera pulled in close still holds the target in the picture. Every collider stops the sweep, invisible ones included; `cameraIgnore` lists the ones the camera sees through.
- **Fading what fills the view.** In play a thin occluder (a post, a lamp pole, a railing: a collider no wider than `occluderFadeWidth` across the line to the target at its narrowest, and no deeper along it) does not pull the camera in: while it stands between the camera and the target it fades to `occluderFade`, that share of its pixels left undrawn in a screen-space dither. The target fades as the camera comes within `bodyFadeDistance` of the point the sweep starts from, reaching `bodyFade` at the nearest the camera stands. Each fade eases over `fadeTime`; shadows stay whole and the fade is this engine's own. `fadeIgnore` lists entities never faded, `occluderFade = 0` pulls in for every collider, and `chase:fading()` reports what fades.
- **Free-look.** The `look` control orbits the camera around the target, up to `lookYawLimit` either side and between `lookPitchMin` and `lookPitchMax`, and the camera swings back behind the target `lookReturnDelay` seconds after the control is let go. `chase:recenter()` swings it back now, over `lookReturnTime`.
- **Bumps and landings are eased.** The camera frames a point that follows the target's motion with lag: `verticalLag` (default `0.15` s) eases a bump, a ramp's lip or a landing, held to `maxVerticalLag` (`0.5` m); `horizontalLag` (default `0`, so the distance holds at any speed) and `maxHorizontalLag` do the same across the ground. `leadTime` (default `0`), `maxLead` and `leadSmoothing` run the aim ahead along the target's motion, on top of `lookAhead`. `chase:tracking()` answers the lag, the lead and the target's velocity as the rig measures them.
## Vs. `orbital_follow`
| | `orbital_follow` | `chase` |
|---|---|---|
| Orbit | look control (yaw + pitch), stays where it was left | free-look that swings back behind the target |
| Heading | the rig's own | derived from the target's facing |
| Position ease | per-axis time constants | per-second blend of the framing |
| Rotation ease | n/a | separate per-second blend |
| Best for | character action, RPG | vehicles, platformers, ski/snowboard |
## Fields
| Field | Default | Notes |
|---|---|---|
| `target` | unset | The entity to chase: the entity, its id or its name. An entity reference, so a scene build that writes it names the entity the build placed. Falls back to `Camera.follow` when unset. |
| `distance` | `6.0` | Horizontal trail distance behind target, at any speed. |
| `height` | `2.5` | Vertical offset above target origin. |
| `minDistance`, `maxDistance` | `1.5`, `25.0` | Scroll-zoom bounds. |
| `zoomSpeed` | `0.12` | `exp(-scroll * zoomSpeed)` per tick. |
| `positionSmoothing` | `0.05` | Share of a framing change left after one second. 0 = locked, 1 = static. A mouse look lands on the frame it arrives. |
| `rotationSmoothing` | `0.15` | The same for the aim swinging to a new heading. |
| `lookAhead` | `0.6` | How far in front of target the camera aims. |
| `cameraRadius` | `0.3` | Radius of the pull-in sweep. 0 turns the pull-in off. |
| `cameraIgnore` | `{}` | Entities whose colliders the pull-in passes through. |
| `pullOutTime` | `0.4` | Seconds (time constant) of the ease back out once the way is clear. |
| `occluderFade` | `0.8` | Share of a thin occluder's pixels left undrawn while it stands in the way, in play. 0 pulls in for it as for a wall. |
| `occluderFadeWidth` | `1.5` | Metres an occluder stands across the line to the target at its narrowest, and along it, at most, to fade. |
| `bodyFade` | `0.9` | Share of the target's pixels left undrawn with the camera at its nearest, in play. 0 keeps it whole. |
| `bodyFadeDistance` | `1.0` | Metres from the sweep's start within which the target fades. |
| `fadeTime` | `0.15` | Seconds a fade takes from none to full, or back. |
| `fadeIgnore` | `{}` | Entities the camera never fades. |
| `lookSensitivity` | `0.3` | Degrees per unit of the `look` control. |
| `lookYawLimit` | `180` | Degrees free-look orbits either side of behind. |
| `lookPitchMin`, `lookPitchMax` | `-60`, `15` | Degrees free-look tilts down (raising the camera) and up (lowering it). |
| `lookReturnDelay` | `1.0` | Seconds after the look is let go before the camera swings back. Negative holds it. |
| `lookReturnTime` | `0.35` | Seconds (time constant) of the swing back. |
| `invertY` | `false` | Forward on the look control looks up unless this is on. |
| `inputMap` | `@builtin::inputMaps.cameraRig` | The map `look` and `zoom` are read from. A write on a live rig takes up the new map. |
## Use as a camera behavior
```lua
local camera = entity.find("cam").component.get("Camera")
camera.behavior = asset.ref("@builtin::controller.chase", "component")
camera.follow = car
```
The component carries the `cameraBehavior` tag in `.metadata`.
## Controls
The camera-rig map (`@builtin::inputMaps.cameraRig`), whose group stays live while a vehicle's map holds the player's controls:
- **Look**: right-button drag, the right stick, or a drag on the right of a touch screen. Orbits the camera; it swings back behind the target when let go.
- **Zoom**: scroll wheel, shoulder buttons, pinch. Changes `distance`.
For mouse look with no button held, point `inputMap` at a map of the world's own in the `camera` group that declares `look` and `zoom` with `pointerLock = true`: the camera group stays live while a vehicle holds the player's controls.
A vehicle that forwards its own zoom control to a chase camera (`VehicleController.camera`) leaves alone a camera that hears zoom from its own map, so one notch zooms once.
## Pair with
- `VehicleController`: the car turns, the chase camera trails its facing and holds its distance at any speed.
- `standard_controller`: the controller rotates the player to face the input direction; chase locks behind that facing.
- `controller.mount`: the same car seen from the driver's seat or the hood. Both read `Camera.follow`, so a key that switches views writes the Camera's `behavior`.
# controller.orbit
Orbit camera controller. Orbits around a target entity or position. Mouse drag to rotate, scroll to zoom, optional auto-rotate.
Public fields: `inputMap` (the camera-rig scheme, `@builtin::inputMaps.cameraRig`, by default; point it at a world's own map to rebind this camera), `target` (the entity to orbit: the entity, its id or its name, kept as an entity reference; unset orbits `Camera.follow`, else `targetX/Y/Z`), `targetX`, `targetY`, `targetZ`, `distance`, `minDistance`, `maxDistance`, `sensitivity`, `zoomSpeed`, `autoRotate`, `autoRotateSpeed`.
Controls: RMB drag to rotate, scroll to zoom.
```luau
entity(id).component.add("controller.orbit", { target = "player", distance = 10 })
```
# Module (asset type)
A module is a reusable, stateless (or globally-stateful) Luau library
that other code pulls in with `require()`. Modules are the unit of
factored-out logic in a world: helpers, math libraries, format
parsers, registries, shared algorithms.
## When to use one
- You have logic you want to share across multiple components,
services, scenes, or tools.
- You have a registry, lookup table, or shared cache that callers all
read from / write to.
- You want a stable API surface (`M.fn`) other code can depend on.
If the logic is bound to one entity, use a `.component`. If you want a
named UI of fields rather than functions, use a `.preset`.
## Where it lives
- Source: `/zero/source/.../<name>.module/`
- Identity: the source path with `/` written as `.` and each segment's
type suffix dropped — `/zero/source/demo/beats.module` is
`demo.beats`, and `/zero/source/kit.package/beats.module` is
`kit.beats`, the container's name kept and its `.package` suffix
gone. `asset.create` returns this string, `asset.resolve(...).identity`
reads it back, and the `require` forms below write it as
`<identity>`.
- Folder shape:
- `init.luau` (or `init.lua`) — module body. **Required.** Returns
a table (conventionally named `M`).
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
```luau
asset.create("module", "<name>")
-- Creates: /zero/source/<name>.module/
-- init.luau (canonical `local M = {} … return M`)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source, and that subfolder
-- leads the identity: `{ folder = "lib" }` produces `lib.<name>`.
-- `into` authors it inside a resolved container (a package, a toolbox),
-- whose own identity leads the same way:
asset.create("module", "<name>", { folder = "lib" })
asset.create("module", "<name>", { into = asset.resolve("myPkg.package") })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.module/` folder
indexes the asset and registers the module path with the resolver.
2. **Loading.** The first `require("<identity>")` runs
the file's body and caches the returned table. Subsequent requires
from anywhere return the **same table** — this is the
shared-state lever for "module-local" registries. The body runs in
an environment of the module's own: a name it declares without
`local` is readable by the module's own functions and by no other
script, so an export reaches its callers through the returned table
and nothing else. Requiring a component's folder runs its chunk the
same way, once, and its `update`, `start` and `public` stay in that
environment; a component runs on an entity through
`entity(id).component.add(name)`.
3. **Hot reload.** Editing the file re-runs the module body and folds
what it returns into the table already loaded, so that table keeps
its identity: a caller that captured it with `require` reads the new
source's functions and values through the reference it already
holds, and a later `require` returns that same table. A key the new
source drops goes away; a key something set at runtime stays. The
body's own `local`s start again from their initial values, so state
that must outlive an edit lives in `modules.state()`
(`guides { path: "core/scripting-and-tasks" }`).
4. **Identity resolution.** A module is reached by its `<identity>`,
and where the caller lives decides which spelling of it resolves.
For a module in a **world**, from a caller in that same world —
another module, a component, a scene entrypoint, or an `execute`
chunk:
- `require("<identity>")` — the identity on its own, resolved
against the caller's own root. It carries every folder segment,
so a module created with `{ folder = "demo" }` is
`require("demo.beats")`.
- `require("@root::<identity>")` — the same root-relative
resolution, written out.
- `require(".sibling")` — a module in the same folder, by its bare
name; `..name` steps up one folder, `...name` two.
Logs, stack traces and hot-reload notices name that same module
`@local.source.<identity>` — its key under the world source root.
The `<identity>` tail of that key is the form above, so a trace
reading `@local.source.demo.beats` is `require("demo.beats")`.
For a module in a **library** — content under
`/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's
root from anywhere: `require("@builtin::modules.transform")`.
Mounting a world as a library moves its files under such a root and
flips the caller root to `@<lib>::`, which is what keeps the
root-relative forms above resolving across the move.
## Discovery
- `asset.list("module")` — every registered module.
- `asset.inspect("<name>")` — public functions, source path, this
type README.
- `ls /zero/source/<name>.module` lists the files the folder holds.
## Authoring conventions
- Return a single `M` table from `init.luau`. Top-level statements
with side effects run on first require — useful for one-time
initialization, dangerous if they touch the engine before it's
ready.
- Write exported functions as `typed function`, not `function`: the
argument types are enforced at the call and the checker knows the
signature, so a caller's mistake is reported where they made it.
- Annotate exported functions with `--!desc` / `--!arg` / `--!return`
/ `--!example` so the LSP, `tools.list`, and `asset.inspect`
surface them. A function with no `--!desc` is reachable only by
someone already reading this file.
- Declare a VALUE with `Field.<kind>(default, mode, description)`, and
a table whose members are reached through a metatable with
`--!members <TypeName>` — the latter gives the surface its accepted
member set, its type, and its documentation from one table. See
`guides { path: "core/authoring" }` for all four rules and
`modules/api/engine/entity.module/members.module` for a worked
member table.
- Keep module state in module-local upvalues or in `modules.state()`.
A name the body declares without `local` lives in the module's
environment, which every run of the module shares: a function the
previous run left in place reads what the reload assigned. Module-locals start again from their
initial values with each hot reload; the table `modules.state()`
returns is the same table on both sides of every reload.
- Prefer focused modules over kitchen-sink modules. If two halves of a
module have no shared state, split them.
## Common pitfalls
- **Cyclic requires.** A `require` chain that loops will return the
partial table (the half built before the cycle was detected).
Design for one-way dependencies.
- **Engine-time side effects.** Don't `entity.spawn` at module
top-level — the engine may not be ready. Expose an `M.init` and
call it from a scene entrypoint.
- **Hot-reload + module-local cache.** A module that caches
expensive computation in upvalues loses that cache on reload —
fine for dev, but be aware in performance work.
- **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical.
- **Writing one while play runs.** A `/source` write made while play is
running lands on the play shadow, and a guarded play-exit discards it
unless it is kept. One `.module` write shadows `init.luau`, the
`README.md` and the `.metadata` together.
`vfs.write(path, bytes, { durable = true })` skips the shadow, and
`vfs.promotePlayShadow` keeps what is already on it — the `core/vfs`
guide has the model and what each route costs.
## Related types
- `.component` — for entity-bound state + lifecycle hooks.
- `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider.
- `.tool` — for a single agent-callable function with a YAML schema.
- `.package` — to group several modules + components + scenes into
one shippable folder.
## In the Inspector
Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
# Slot
A named place on an entity that another part fills: a wheel mount, an engine
bay, a seat, a weapon hardpoint, a socket in a modular wall, a mount on a ship.
The entity carrying `Slot` is where the part attaches: the part is built as a
child of that entity and stands at its transform. Put a `Slot` on an empty
child positioned where the part goes, one per slot.
What fills the slot is held by the `Assembly` on the slot's root (the nearest
`Assembly` on the entity or above it; one on a part built into a slot passes
the slot on to the `Assembly` holding that part), by the slot's path. A slot
under no `Assembly` holds its `default`.
## Fields
| Field | Type | Notes |
|---|---|---|
| `name` | string | The name the slot answers to in paths; empty takes the entity's name. |
| `kind` | string | The kind of part it takes (`wheel`, `engine`, `seat`). A part fits when its `Part.fits` names this kind. Empty takes any part. |
| `tags` | `{ string }` | Asset tags a part must carry, all of them, to fit. |
| `default` | instantiable asset | The part filling the slot when its Assembly names none. |
| `joint` | table | Joint fields binding the part's body to the body the slot stands on (`{ kind = "hinge", axis = { 1, 0, 0 } }`); the `Joint` component on the part's root is added with `connected` set to the slot. Empty seats the part as a child alone. |
## Paths
A slot's path is its name, under the path of the slot whose part it stands in:
an engine part carrying a `turbo` slot, filled into the `engine` slot, puts
that slot at `engine/turbo`. Paths are what `Assembly:fill`, `Assembly:resolve`
and the saved configuration use.
## Methods
| Method | Returns | Notes |
|---|---|---|
| `:path()` | string | This slot's path in its Assembly. |
| `:assembly()` | Assembly or nil | The Assembly that holds it. |
| `:fill(part)` | entity or nil | Fill through the Assembly (`Assembly:fill(self:path(), part)`); raises when the part does not fit, naming why. |
| `:empty()` | | Leave it empty, its default included. |
| `:fits(part)` | `(boolean, string)` | Whether a part fits, and why or why not. |
| `:filled()` | `{ part, entity, source }` or nil | The part filling it and the entity it was built on. |
| `:refresh()` | entity or nil | Rebuild the part when it differs from what the Assembly names. |
## Usage
```luau
-- A body with a wheel slot and an engine slot
local body = entity.spawn("buggy")
body.component.add("Assembly")
local fl = entity.spawn("wheel_fl", { parent = body.id, position = { x = -0.8, y = 0.3, z = 1.2 } })
fl.component.add("Slot", { kind = "wheel", default = "parts.StockWheel" })
local bay = entity.spawn("engine", { parent = body.id, position = { x = 0, y = 0.5, z = 1 } })
bay.component.add("Slot", { kind = "engine" })
bay.component.get("Slot"):fill("parts.V8")
print(fl.component.get("Slot"):fits("parts.V8")) -- false, "slot 'wheel_fl' takes parts of kind 'wheel'; 'parts.V8' fits { engine }"
```
Put the same children in a bundle (`asset.create("bundle", "Buggy", { entity = body })`)
and every instance of the bundle carries the slots. The `Assembly` README
covers configurations, the resolver, undo, multiplayer and saving.
# reflections system
Screen-space reflections — a polished floor reflects what stands on it, wet
ground reflects what is above it, and metal picks up its surroundings, all from
geometry the camera can already see.
Environment reflections describe a surface's surroundings in general. They
cannot show the character walking across the floor, because that character is
not in the environment — it arrived this frame. Screen-space reflections read
the frame the engine has just drawn, so anything visible can appear in anything
reflective, with nothing authored per surface.
What that buys and what it costs are the same thing: only what is **on screen**
can be reflected. A reflection of something behind the camera, or off the edge
of the frame, is not there to find. So reflections fade out toward the screen
edge rather than cutting off, and where a ray finds nothing the surface keeps
the shading it already had.
## Using it
Reflections are a render feature. List it on the scene's `RenderFeatures`
entity with the settings it should run under, and it persists with the scene:
```lua
local id = entity.spawn("render features").id
entity(id).component.add("RenderFeatures", {
features = {
{ feature = "@builtin::systems.reflections.ssr", settings = {
intensity = 1.0, -- how much of the reflection reaches the image
maxDistance = 40, -- how far a reflection ray travels, world units
quality = "auto", -- low | medium | high | ultra, or auto (the device's tier)
} },
},
})
```
Every setting is live: edit one in the inspector and the reflections follow.
`renderer.feature.schema("@builtin::systems.reflections.ssr")` lists every knob
with its default.
For code that adjusts reflections at runtime — a quality slider, a cutscene,
weather turning pavement wet — the module is the hand on the same knobs:
```lua
local ssr = require("@builtin::systems.reflections.ssr")
ssr.set({ intensity = 0.6, quality = "medium" }) -- any subset; the rest is kept
ssr.get() -- the settings in force
ssr.active() -- are the passes running
ssr.clear() -- the passes down
```
`set` brings the feature up when none is live, and an `intensity` of 0 takes
it down; the same feature is found rather than stacked when `RenderFeatures`
already runs it.
## What the knobs do
| field | effect |
|---|---|
| `intensity` | How much of the reflection reaches the image, in [0, 1]. 0 turns reflections off and releases the passes. |
| `maxDistance` | How far a reflection ray travels, in world units. |
| `thickness` | How thick a surface is assumed to be, in world units. A ray passing behind one by more than this went past it rather than onto it. |
| `roughnessCutoff` | Perceptual roughness up to which a surface takes the full screen-space reflection. Above it the reflection hands over to the probes and the sky, and is gone 0.1 higher. |
| `quality` | `low` / `medium` / `high` / `ultra` — how many steps the march spends and how many neighbouring rays a pixel gathers — or `auto` (the default), which follows the device's quality tier (`renderer.qualityTier()`): `high` on a desktop, `medium` on a handheld and at the medium tier, `low` at the low tier. `ssr.drawn()` reports the level in force and the sampling it spends. |
| `edgeFade` | How far from the edge of the screen reflections fade out, in UV. |
`roughnessCutoff` is the one to understand first. Every pixel traces one ray
drawn from the lobe its roughness describes, and gathers the rays of its
neighbours that stand on the same surface, so a rough floor shows a bright
sign as the soft, stretched streak its lobe spreads the sign into, and a
mirror shows it sharp. Up to the cutoff a surface takes the full screen-space
reflection. Above it the reflection hands over to the probes and the sky, and
it is gone 0.1 higher, so the hand-over has a soft edge in place of a line. The
default, 0.75, covers wet asphalt and polished stone. A scene that states a
lower cutoff (0.4 was the old default) leaves those surfaces to the probes.
Where the screen holds only part of a surface's lobe (the lobe reaches off the
edge of the frame, or behind the camera) the reflection covers the part it
found and the probe or sky fills the rest.
`maxDistance` and `quality` trade against each other: quality sets the step
count, so a long distance at a low quality samples coarsely and reflections
thin out at range. They thin rather than disappear because the hit refinement
adapts to the step size on its own.
How much of a reflection shows through is the surface's own Fresnel term, taken
from the G-buffer's metallic. Metal takes nearly all of it; a dielectric floor
takes a few percent head-on and much more at a grazing angle — which is why a
wet road reads dry underfoot and mirror-like down the street.
## How it renders
`ssr.renderFeature` runs two compute passes at the `afterDepthPrepass` seam,
before anything shades. `ssr_trace` draws one ray per pixel from the pixel's
GGX lobe (a visible-normal sample; a mirror, below roughness 0.1, keeps its
one reflection ray) and marches it against this frame's depth. The surface's
normal and roughness come from the G-buffer as the previous frame left them,
reprojected through the previous view-projection. The pass writes where each
ray hit and how confident the hit is, or the direction it travelled when it
found nothing. A rough pixel's ray marches fewer steps, because the next pass
blurs what the rays find.
`ssr_resolve` gathers each pixel's lobe over its own ray and the rays of up to
twelve neighbours (4 at `low` and `medium`, 8 at `high`, 12 at `ultra`),
weighing every ray against the pixel's own lobe and counting a neighbour only
where it shows the same surface. The light at a hit is read from the colour
the previous frame ended with, where the hit stood then. The resolve
accumulates the result over frames in a history target (one image pair per
view), holds that history to the spread of the rays it gathered, and writes the
scene's reflection channel, `@scene.reflection`: the light of the rays that
found something on screen, and the share of the lobe those rays cover.
A material reads that channel the same frame, at its own pixel, inside its
environment term: it mixes the traced light over the probe and the sky by the
share of the lobe the screen answered, so what the screen did not find comes
from the environment, and the material's Fresnel, roughness and tint weigh the
result into the pixel as they weigh any environment. The reflection stands
where the camera is now; only the light in it is a frame old. The `reflection`
capture pass shows it. Where the trace found nothing the channel holds zero and
the material reflects its environment alone.
A blended material (a `blend` other than `opaque` or `cutout`) reads none of
the channel. It draws over the depth the trace ran against, so the channel at
its pixel holds the reflection traced for the opaque surface behind it. A
blended pane of glass reflects its environment, or the reflection its shader
traces for itself through `@builtin::shaderModules.screenReflection`.
A camera drawing a diagnostic pass holds readings in its colour target rather
than light, so the passes have no light to read from that frame: such a frame
is drawn lit first, unpresented, the passes run for that, and the diagnostic
reads the channel gathered for where the camera stands now. A capture drawn
once, or a camera drawn again from a new station, is drawn lit first for the
same reason, so its first frame holds a reflection (without accumulated
history, so it shows more grain than a continuously drawn view). The march
steps uniformly in screen space and compares in world space; the full account,
including why thickness is tested after refinement rather than during the
march, is in the render feature's own readme.
Each view that draws the feature holds three screen-sized images of its own: the
rays and the history pair, about 50 MB at 1080p for the viewport.
The pass takes its camera from `@frame.camera`, so reflections are correct in
offscreen captures and render-to-texture cameras, not only the live viewport.
## The demo scene
The scene `@builtin::systems.reflections.demo.polished_floor`, loaded with the `scene.load` tool, is a polished
stone floor with three coloured pillars standing on it, under an afternoon
sky, with the feature listed on the scene's `render_features` entity. The
floor reflects the pillars and a player walking across it; delete the entity
and it mirrors the sky alone. `demo/polished_floor.scene/build.luau` is the
whole scene as code, materials included.
## Files
```
reflections.package/
ssr.renderFeature/ -- the trace and resolve passes, and the settings they take
ssr_trace.computeShader/ -- draws and marches one lobe-sampled ray per pixel
ssr_resolve.computeShader/ -- gathers each pixel's lobe, accumulates, writes the reflection channel
ssr.module/ -- ssr.set / .get / .clear / .active, the runtime hand on them
ScreenSpaceReflections.component/ -- the older one-feature component; RenderFeatures is the list
demo/polished_floor.scene/ -- the showcase: a polished floor, three pillars, the feature on one entity
```
# volumetrics
Volumetric (3D-texture) rendering, end to end, in one package. Built
entirely on the engine's generic `compute.*` GPU primitives — no
Rust changes are needed to author new volumetric content.
## Layout
| Asset | Identity | Role |
|---|---|---|
| `Volume.component` | `@builtin::systems.volumetrics.Volume` | Attach a 3D voxel texture to an entity; stands it in the scene through the entity's transform AABB, hidden by what stands in front of it. |
| `VolumetricSky.component` | `@builtin::systems.volumetrics.VolumetricSky` | Clouds in the sky: one per scene, the procedural cloud layer lit by the scene's sun (through the physical atmosphere's air and sky when a `PhysicalAtmosphere` stands in the scene), drawn by `volumetricSky.renderFeature` with no composite authored. |
| `VolumetricLighting.component` | `@builtin::systems.volumetrics.VolumetricLighting` | Light shafts, god rays and glowing air: light scattering between the camera and the scene, drawn by `lightScattering.renderFeature`. |
| `ParticipatingMedium.component` | `@builtin::systems.volumetrics.ParticipatingMedium` | Mark an entity as fog/smoke/dust the camera sees through and that shades the sun on what is under it. |
| `Smoke.component` | `@builtin::systems.volumetrics.Smoke` | Smoke rising from the entity's position: a chimney's column, steam, a smoulder, a black column over a big fire, smoke signals; lit by the scene with a shadow of its own. |
| `Fire.component` | `@builtin::systems.volumetrics.Fire` | Fire with its smoke at the entity's position: a campfire, a torch, a bonfire, a building on fire, an explosion's fireball; flames glow along a blackbody ramp and a flickering point light halfway up them lights the surroundings. |
| `plume.module` | `@builtin::systems.volumetrics.plume` | The smoke and fire plumes `Smoke` and `Fire` hold, from a script: styles, sizes, quality levels; fills a volume each drawn frame and stands it with `Volume:draw`. |
| `mediaTransmittance.module` | `@builtin::systems.volumetrics.mediaTransmittance` | The registry of media and the settings every media pass reads. |
| `mediaShadow.renderFeature` | `@builtin::systems.volumetrics.mediaShadow` | Writes the sun the media take to `@scene.sunOcclusion` and marches each view ray through the media. |
| `volume.module` | `@builtin::systems.volumetrics.volume` | Builders (`noise`/`sphere`/`box`/`wrap`) + the `.zvol` header reader + occupancy + brick paging + the per-entity raymarch dispatch + the draws standing in the scene (`Volume:draw`). |
| `volume.renderFeature` | `@builtin::systems.volumetrics.volume` | Runs every standing draw's march and composite for each view the frame draws, against its camera and depth. |
| `VolumeSequence.component` | `@builtin::systems.volumetrics.VolumeSequence` | Play an open volume sequence through an entity's transform AABB. |
| `volumeSequence.module` | `@builtin::systems.volumetrics.volumeSequence` | A run of `.zvol` frames streamed through a fixed ring of resident volumes. |
| `volumeDemos.module` | `@builtin::systems.volumetrics.volumeDemos` | Shared pipeline for the showcase scenes (fill + emissive raymarch + composite). |
| `volumetricSky.module` | `@builtin::systems.volumetrics.volumetricSky` | The cloud layer: tiling noise, weather map, raymarch, TAA and composite orchestration. |
| `volumetricSky.renderFeature` | `@builtin::systems.volumetrics.volumetricSky` | The cloud layer's passes for every view the frame draws, brought up by `VolumetricSky`. |
| `volumetricLighting.module` | `@builtin::systems.volumetrics.volumetricLighting` | The light-scattering settings, set from code. |
| `lightScattering.renderFeature` | `@builtin::systems.volumetrics.lightScattering` | The light-scattering passes, brought up by `VolumetricLighting`. |
| `shaders/*` | `@builtin::systems.volumetrics.shaders.*` | Compute shaders `volume_raymarch`, `volume_draw`, `plume_fill`, `volume_pages`, `volume_pack`, `cloud_noise`, `cloud_weather`, `cloud_raymarch`, `cloud_taa`, `cloud_layer_surfaces`; shaders `volume_draw_composite`, `cloud_layer_composite`, `cloud_layer_blit`, `cloud_sky_composite`; shader modules `volume_march`, `cloud_light`, `cloud_surface`, `cloud_shell`. |
| `importers/vdb_to_zvol.importer` | (auto-discovered) | `.vdb` → dense `.zvol` via the `openvdb` WASM plugin (procedural fallback when the plugin isn't loaded). |
| `presets/cumulus_default.preset` | `@builtin::systems.volumetrics.cumulus_default` | Canonical full `VolumetricSky` weather preset. |
| `demo/*.scene` | `@builtin::systems.volumetrics.demo.*` | `sdf_solids`, `smoke_plume`, `nebula`, `godrays`, `zvol_viewer`, `sky`, `showcase`, with their fill shaders. |
The guide `systems/volumetrics/documentation/README` (`guides { path = ... }`)
names the component for each effect, clouds, fog, light shafts, a fog or smoke
volume and the sky, with what each does and costs.
## Path convention — fully-qualified builtin identities
Every intra-package reference uses the asset's fully-qualified builtin
identity, the same convention every other builtin package follows:
```luau
local Volume = require("@builtin::systems.volumetrics.volume")
local Sky = require("@builtin::systems.volumetrics.volumetricSky")
local V = require("@builtin::systems.volumetrics.volumeDemos")
-- shader identities, e.g. asset.resolve("@builtin::systems.volumetrics.shaders.volume_raymarch")
```
Qualified identities are caller-independent: they resolve identically
from a module, a scene entrypoint, or a component. Caller-relative
(`.sibling`) requires are deliberately avoided here because the
component runtime caller identity is `@builtin::components.<Name>`, so a
`.sibling` require from a component resolves against the wrong root.
(An earlier revision of this package used a `~volumetrics` package-root
alias for relocatability; that alias is not resolvable on current main,
so the package uses qualified identities throughout.)
## Usage
```luau
-- Per-entity volume. The component resolves the name through `Volume.get`,
-- so a volume paged into a brick pool renders from the pool under the same
-- name:
local Volume = require("@builtin::systems.volumetrics.volume")
local cloud = Volume.noise({ name = "cloud", size = 64, scale = 4 })
cloud:buildSparse({ brickSize = 8 })
cloud:releaseDense()
entity(id).component.add("Volume", { volumeName = "cloud", density = 6.0 })
-- Procedural sky:
local sky = entity.spawn("sky")
sky.component.add("VolumetricSky", {})
preset.apply("cumulus_default", { entity = sky.id, component = "VolumetricSky" })
-- VDB import: drop a `.vdb` into the VFS; the importer writes a `.zvol`
-- alongside it. Load it with the zvol_viewer demo scene.
-- Animated run: one `.zvol` per frame, played through a bounded ring.
local Seq = require("@builtin::systems.volumetrics.volumeSequence")
Seq.open({ name = "plume", frames = framePaths, resident = 3, fps = 24 })
entity(id).component.add("VolumeSequence", { sequenceName = "plume", density = 6.0 })
```
## Plugin dependency
The VDB importer delegates real OpenVDB parsing to the `openvdb` plugin
in the builtin library, `@builtin::plugins.openvdb`. Without the plugin
the importer falls back to a deterministic procedural torus so the
pipeline stays functional.
# DecalProjector
Turns its entity into an oriented **box decal projector** — the deferred-decal
equivalent of Unreal's Decal Actor or Unity's Decal Projector. The entity's
Transform is the projection volume: position and rotation orient the box, scale
sizes it, and the projector stamps its `material` along the box's local −Z onto
every surface inside the box, reconstructing each covered pixel's world position
from scene depth and fading on faces turned away from the projection axis so the
decal wraps the surfaces facing it. The stamped colour becomes part of the
surface's base colour before it is lit, so the decal takes the light and shadow
of the surface it lies on; an emissive material's glow is added over it.
## Surface
| Field | Type | Meaning |
|-------|------|---------|
| `material` | `AssetRef<material>` | What the projector stamps. Its base-colour texture + tint drive the decal — a textured material projects its texture, a flat-colour material projects its colour. Defaults to `@builtin::materials.decal_default`. |
| `opacity` | `number` | Master fade, `0..1`. |
Registers into the `@builtin::modules.decals` registry on `awake`/`onEnable`
(and re-registers on property change / in edit mode), which the
`@builtin::renderFeatures.decals` render feature reads every frame.
## Example
```lua
-- A downward projector that stamps a texture onto whatever is under it.
local p = entity.spawn("floorDecal")
p.localPosition = { 0, 3, 0 }
p.localScale = { 6, 6, 4 }
p.localRotation = { 0.70710678, 0, 0, 0.70710678 } -- project down (-Y)
p.component.add("DecalProjector", {
material = "@builtin::materials.decal_default",
opacity = 1.0,
})
```
# SphereCollider (component)
A spherical collision shape. Works with or without a `Physics` component: on its
own it is static collision geometry, and alongside one it moves with the body.
## Sizing
`radius` is in the entity's local space, multiplied by the entity's world scale.
Leave it unset and the sphere derives from the entity's model bounds, and follows
the mesh when `renderer.mesh.setVertices` or `renderer.mesh.update` changes it:
by the next physics step the sphere takes the new geometry's size and centre.
```lua
entity.find("ball").component.add("SphereCollider", { radius = 0.5 })
entity.find("zone").component.add("SphereCollider", { radius = 5, isTrigger = true })
```
## Fields
| Field | Meaning |
|-------|---------|
| `radius` | Sphere radius. Unset derives from model bounds. |
| `isTrigger` | Report overlaps without blocking. |
| `friction` | Surface friction. |
| `restitution` | Bounciness. |
| `rollingResistance` | How strongly the surface resists a body rolling on it: a rolling body slows at this many times gravity on level ground, so a ball rolled at v stops after v^2 / (2 * rollingResistance * 9.81). 0 rolls on. |
| `spinningResistance` | The same for a body spinning on the surface about the contact normal. 0 spins on. |
| `surface` | The surface the collider is made of, by name: one `Physics.defineSurface` defined gives it its friction, restitution and resistances in place of the fields above, and contacts, contact events and ray and shape casts report the name either way. Empty names none. |
| `oneWay` | The direction, in the collider's own frame, bodies pass through it along: a body moving that way goes through, and a body meeting it from the side the direction points to stands on it (a jump-through platform is `{0, 1, 0}`). `Physics.passThrough(entity)` drops a standing body through. Unset blocks from every side. |
| `surfaceVelocity` | The velocity, m/s in the collider's own frame, its surface moves at along itself while the collider stays put: friction carries what rests on it (a conveyor belt, a treadmill, an escalator). Write it at runtime to change the speed or direction. Unset holds the surface still. |
| `contactTag` | The tag the world's contact filter reads this collider by: `Physics.setContactFilter(tagA, tagB, mode)` makes two tags pass through each other (`"ignore"`), report contacts and push nothing (`"sensor"`) or collide (`"solid"`). Empty names none. |
## Composing
A collider on a child entity attaches to the nearest ancestor carrying a
`Physics` component. A character is a `CapsuleCollider` for the body and a
`SphereCollider` trigger on a head entity; queries report whichever shape they
hit, so the head stays distinguishable from the torso.
# ShaftNetwork
A network of rotating parts and the links between them, solved inside the physics step: a drivetrain (engine, clutch, gearbox, differential, wheels), a tank's two tracks off one engine, a winch or a crane's slew on a geared motor, a windmill driving a pump, a conveyor, a propeller on a shaft, a clockwork gear train. Add it to any entity; a vehicle's chassis is the usual place.
Every part and link is solved together and implicitly at the physics tick, together with the tyres and the chassis when the network drives wheels: a locked clutch, a locked differential or a gear mesh holds without ringing at 30 Hz and 60 Hz, and a closed loop of gears creates no energy.
## Parts
`parts` is a list of parts, each with a `name` that links, `set` and the state read it by. A name is held once across the network's parts and links, since `set` reaches either by its name alone. A part turns about one axis with a moment of inertia, and is one of:
- a free part of its own: a crankshaft, a flywheel, a gearbox shaft, a motor's rotor;
- a wheel's spin: `wheel = wheelEntity` (a `WheelCollider`; an entity or its id, saved with the scene as an entity reference). The wheel spins on its own, with its own `inertia` or, when it states none, the part's; its `motorTorque` and `brakeTorque` still act on its axle. The wheels one network drives stand under one body.
- a hinge's turn: `joint = hingeEntity` (the entity carrying a hinge `Joint`): the joint's body against its connected body, about the joint's axis. The part's inertia is the two bodies' about the hinge (a body swung on a pin away from its centre turns with its own inertia plus its mass times the square of its arm), and the network's torque acts on the joint's body and, opposite, on the connected one. A hinge turns with one part: a second part naming it turns on its own and reads why. Give the hinge `stiffness = 0, damping = 0`: a hinge with a `stiffness` or `damping` and no motor carries a spring back to the angle it started at, which the network's torque then winds against. The step's own forces (the bodies' angular damping, their contacts, other joints) act on the bodies after the network, so a joint part reads its hinge's turn as the network leaves it and the body reads it as the step leaves it, apart by one tick of those forces.
| Field | Meaning |
|---|---|
| `inertia` | Moment of inertia about its axis (kg·m²). 0 or unset is a light shaft (0.001). A joint part takes its bodies'. |
| `wheel`, `joint` | What the part turns with (above); neither for a free part. |
| `torque` | A constant torque on the part (N·m): an electric motor, a load, a hand crank. |
| `curve` | A torque source's curve over the part's speed: `{ {rpm, N·m}, ... }` in rising rpm (or `{ rpm = .., torque = .. }` points), interpolated in straight lines and held at the end values past them. An engine's torque curve, a motor map. |
| `throttle` | The share of `curve` the source delivers (0 to 1, or any number: negative runs it backward). |
| `friction` | Friction torque holding the part to its frame, always on (N·m): an engine's internal friction, a bearing. |
| `brake` | Brake torque holding the part to its frame (N·m). |
| `damping` | Viscous drag (N·m per rad/s): a pump's or a propeller's load, an engine's pumping loss. |
A curve drives its part toward the speed where the curve falls to zero and no further, solved at the speed the part ends the tick with: a curve ending at 0 N·m is a rev limit however coarse the tick.
## Links
`links` is a list of links, each with a `name`, a `kind` and the parts it couples by name (`a`, `b`, and a differential's `input`):
| Kind | Fields | Meaning |
|---|---|---|
| `shaft` | `a`, `b` | They turn together, with any torque. |
| `gear` | `a`, `b`, `ratio` | `a` turns `ratio` times as fast as `b`, and `b` takes `ratio` times the torque: a gear pair, a gearbox's selected gear, a final drive, a belt or chain. `ratio = 0` is neutral (nothing coupled); a negative ratio turns `b` the other way (reverse). |
| `clutch` | `a`, `b`, `capacity`, `engage` | They turn together while the torque between them stays within `capacity` (N·m) times `engage` (0 to 1, default 1); past it they slip, passing that torque, and lock once their speeds meet. A slipping belt and a torque limiter are clutches too; a fluid coupling, whose torque grows with the difference of its sides' speeds, is a `spring` with `damping` alone. |
| `differential` | `input`, `a`, `b`, `ratio`, `locked`, `preload`, `bias`, `damping` | `input` turns `ratio` (default 1) times as fast as the mean of `a` and `b`, its torque split equally between them: open, the side with less grip spins and the other gets no more torque than it. `locked = true` holds `a` and `b` together. A limited-slip one: `preload` (N·m) passes that much torque from the faster side to the slower at any input, `bias` (a torque bias ratio, 1 open, 2 to 5 typical) lets one side take up to `bias` times the other's torque, and `damping` (N·m per rad/s) is a viscous coupling between them. |
| `spring` | `a`, `b`, `stiffness`, `damping` | A torsion spring between them: `stiffness` (N·m per radian) on the angle wound up between them, `damping` (N·m per rad/s) on their relative speed. A flexible shaft, a drive's compliance, a clock's mainspring. |
## Inputs at the tick rate
Every field above is an input. `net:set(name, values)` writes the fields of one part or link and leaves the rest. These writes are this engine's inputs, laid over the authored `parts` and `links`: they reach the next physics step, cost no scene save and no replication, and a driver writes them every frame. Writing `parts` or `links` changes the network itself, which is saved with the scene and reaches every session.
```luau
local net = car.component.get("ShaftNetwork")
net:set("engine", { throttle = 0.8 }) -- accelerator
net:set("clutch", { engage = 0.4 }) -- clutch pedal
net:set("gear", { ratio = 2.1 }) -- shift; 0 neutral, negative reverse
net:set("diff", { locked = true }) -- diff lock
net:set("rearLeft", { brake = 800 }) -- a steering brake on one track
```
## State
`net:state()` (or `Physics.shaftNetworkState(entityId)`) reads the network as of the last physics tick:
- `parts.<name>`: `speed` (rad/s; a wheel part's is its wheel's spin, a joint part's its hinge's turn), `rpm`, `torque` (what its `curve` and `torque` applied, N·m), `brakeTorque` (what its friction, brake and drag applied), `linkTorque` (what the links put on it), `throttle` and `brake` (the inputs in effect), and `problem`, present when the part names a wheel or a joint it cannot turn with (the entity is no `WheelCollider`, the joint is no hinge, the wheel already belongs to another network, one on an entity spawned before this one's, the hinge already turns with another part) and so turns on its own.
- `links.<name>`: `kind`, `ratio`, `engage`, `locked` (the inputs in effect: a gear indicator reads `ratio`), `torque` (N·m the link takes from `a`, or a differential's from `input`; positive as `a` drives the rest), `lockTorque` (what a differential's lock passes from `a` to `b`, or a spring pushes back with), `slip` (rad/s, `a` against `b`, against `ratio` times `b` for a gear), `slipping` (a clutch past its capacity, an open differential or one whose lock is past its capacity), `windup` (a spring's wound-up angle, radians).
- `settled`: whether the tick held every link, friction, brake and drive where its bounds allow: every shaft and gear at its ratio, every differential at the mean of its sides, every clutch and lock holding inside its capacity or slipping at it. It reads `false` when the links ask for speeds the parts cannot take together (a part shafted to two immovable parts turning at different speeds); the parts then turn as near to every link as they can come.
A tachometer, an engine sound's pitch, a clutch-slip squeal, a gear indicator and a shift logic read these.
## Cost
A car's network (an engine, a clutch, a gear and a differential driving two wheels) adds about 0.03 to 0.05 ms to a physics tick on a desktop, about 0.07 ms in a desktop browser and about 0.01 to 0.02 ms in Chrome on a Galaxy Tab S11, measured over eight such cars at 60 Hz and 30 Hz. The profiler reports it under `prepare_shaft_networks`, `update_wheel_colliders` and `finish_shaft_networks`, all three counted in its physics total.
A network costs a tick in proportion to its parts and links in the shapes machines take, a chain, a gear train, a tree of differentials and closed loops of a few gears among them: a part many links meet (a shaft geared to every wheel of a tank) and a chassis under many tyres cost no more than their links do, and cars each driving their own network cost in proportion to their number. A chain of geared parts its friction holds still costs about 2.5 µs a part on a desktop (0.22 ms a tick at 80 parts, in a development build) and about 4.5 µs a part in a desktop browser (0.38 ms at 80 parts). A network finds which of its friction, brakes, clutches and differential locks hold at their limit over its first tick and starts each later tick from where they stood, so its first tick, and a tick in which many of them let go or take hold at once, costs more than the ticks around it.
## Recipes
A rear-driven car (the wheels are `WheelCollider` entities under the chassis):
```luau
car.component.add("ShaftNetwork", {
parts = {
{ name = "engine", inertia = 0.2, friction = 15, damping = 0.02,
curve = { {1000, 180}, {4500, 260}, {6500, 210}, {7200, 0} } },
{ name = "gearbox", inertia = 0.02 },
{ name = "driveshaft", inertia = 0.05 },
{ name = "rearLeft", wheel = rl }, { name = "rearRight", wheel = rr },
},
links = {
{ name = "clutch", kind = "clutch", a = "engine", b = "gearbox", capacity = 450 },
{ name = "gear", kind = "gear", a = "gearbox", b = "driveshaft", ratio = 3.2 },
{ name = "diff", kind = "differential", input = "driveshaft", a = "rearLeft", b = "rearRight", ratio = 3.9 },
},
})
```
A four-wheel drive adds a centre differential (`input = "driveshaft"`, `a = "frontShaft"`, `b = "rearShaft"`) with a front and a rear differential below it. A tank drives each track's wheels from one side of a differential and steers with each side's `brake`.
A winch: a motor geared onto a drum on a hinge.
```luau
drum.component.add("Joint", { kind = "hinge", connected = crane.id, axisX = 1, axisY = 0, stiffness = 0, damping = 0 })
drum.component.add("ShaftNetwork", {
parts = { { name = "motor", inertia = 0.05, torque = 40 }, { name = "drum", joint = drum } },
links = { { name = "reduction", kind = "gear", a = "motor", b = "drum", ratio = 30 } },
})
```
A windmill driving a pump: the rotor's hinge part geared onto a pump part whose `damping` is the pump's load.
```luau
mill.component.add("ShaftNetwork", {
parts = { { name = "rotor", joint = rotor }, { name = "pump", inertia = 0.5, damping = 2 } },
links = { { name = "gearbox", kind = "gear", a = "pump", b = "rotor", ratio = 8 } },
})
```
`ecs.ShaftNetwork` is the native component underneath, with the parts and links as lists of records.
# DirectionalLight
A directional light in addition to the scene's sun: parallel light arriving from
one direction everywhere in the world, the way a body far enough away delivers
it. A second star over an alien planet, a moon hanging opposite the sun, a cold
fill from the far side of a set.
The sun is `Light { kind = "directional" }` — one direction, one colour and the
cascade set, held as a single field, so a second `Light` of that kind moves the
sun rather than joining it. This component adds a light instead. Several can
coexist; they share the scene's light buffer with point, spot and area lights,
so the cap is the combined count (64).
Public fields: `directionX/Y/Z` (the direction the light TRAVELS, normalised by
the engine), `colorR/G/B`, `intensity`, `mobility` (`auto` / `static` / `mixed`
/ `dynamic` — how a GI bake treats it).
Input aliases accepted by `component.add`: `direction`, `color`, `brightness`.
Methods: `:resolveMobility()`, `:lightMobility()`.
`lighting.lightRows()` reports one of these with `kind = "distant"`; the row's
`direction`, `color` and `intensity` are what the shading reads, and its
`position` follows the carrying entity. A GI bake gathers it the way it gathers
the sun, so a `mobility = "static"` light is baked whole and its live
contribution withheld.
```luau
entity(id).component.add("DirectionalLight", {
direction = { 0.3, -0.5, 0.4 },
color = { 0.7, 0.8, 1.0 },
intensity = 0.6,
})
```
# Model
Loads and displays a 3D mesh on an entity. Disabling the component hides the mesh. Supports procedural meshes (`cube`, `sphere`, ...), model files, and remote URLs. Tint and outline are shader effects applied to the mesh.
**Material lives on this component.** There is no standalone `Material` component — a material only renders where there is a mesh to render it on, so the `material` field is part of Model (and SkinnedModel). Set it at add time or assign the field later; properties are registry-wide.
Public fields: `model`, `material` (`AssetRef<material>`), `tintR/G/B`, `tintBlend`, `outlineR/G/B`, `outlineIntensity`, `outlineOccluded` (`"hide"`, the default, hides the rim where geometry stands in front of the mesh; `"dashed"` draws it there in dashes, the `occluded` choice of `@builtin::modules.outline`).
Methods: `:setTint(color, blend?)` (color: `{r, g, b}` array or `{r=, g=, b=}` map), `:clearTint()`, `:setOutline(color, intensity?)`, `:clearOutline()`, `:setMaterialProperty(prop, value)`, `:getMaterialProperty(prop)`, `:getMaterialPropertyNames()`.
```luau
entity(id).component.add("Model", { model = "cube", material = "gold" })
entity(id).component.get("Model").material = "checkerboard" -- swap material
entity(id).component.get("Model"):setTint({1, 0, 0}, 0.5)
entity(id).component.get("Model"):setMaterialProperty("roughness", 0.2)
```
**Tint is synced.** Every `tint*` field replicates, so `:setTint` is the colour every participant sees. A colour that changes every frame on many entities (a stress map, a heat map, a damage flash, per instance colour) belongs in an instance-data lane instead: wear `@builtin::materials.instance_color` (or `instance_color_unlit`) and write `renderer.instanceData.set(id, 2, r, g, b, coverage)`, which replicates nothing and costs about a twentieth of a tint write. `guides { path = "topics/rendering-instance-data" }` has the lane layout.
# lightCookies
Projects an authored image through a spot light's cone — a gobo, window blinds,
a headlight cutoff, a projector pattern.
## How it divides up
The renderer already projects a texture through a spot's frustum. At each shaded
point it reads `zero_feature_texture(uv, cookieLayer)`, with `uv` from that
point's position in the light's own clip space, and multiplies the cone by what
it finds. `SpotLight.cookieLayer = -1` means no cookie.
What the renderer does not decide is what goes in the layer. That is this
package: resample an authored image into one full layer of the shared
feature-texture array, and point a spot at that layer.
## Using it
```luau
local lightCookies = require("@builtin::systems/lightCookies.package/lightCookies")
-- Size the array once for every layer the scene will use.
lightCookies.configure({ resolution = 256, layers = 4 })
lightCookies.project(lampId, "/textures/cookies/window_blinds.png", { layer = 0 })
```
Or attach a `LightCookie` component next to the `SpotLight` and author
`texture` / `layer` / `gain` / `tint` on it.
`lightCookies.clear(lampId)` stops the projection; the layer keeps its contents.
## When a fill lands
`fill` and `project` queue the fill and return its layer at once. The module's
own loop writes it over the frames that follow: the rasterize is issued on the
next frame and the copy into the layer on the frame after, and the fill is
written once `renderer.featureTexture.state().fills` reports the copy landed in
its layer, one fill at a time in the order they were asked for. The loop belongs to the module, so a fill
lands even when the code that asked for it (a one-shot script, a task scope, a
component that is destroyed) has ended.
`lightCookies.status(layer)` reports where the last fill of a layer stands:
```luau
local s = lightCookies.status(0)
-- s.state: "queued" | "rasterizing" | "copying" | "written" | "refused"
-- s.reason: why a refused fill was refused, in the engine's words
-- s.filled: whether renderer.featureTexture.state().filled lists the layer
```
`status` reads a fill `"written"` from the first reading of the array that
reports its copy landed, so `s.state` and `s.filled` agree whichever of the
module's loop and the reader runs first in a frame.
A fill names a layer below the count `configure` sized the array to; one past
it is refused at the call, which returns nil and the reason. A fill that cannot
land once it is on its way (the GPU refuses its rasterize because its image was
given back first, a later `configure` left the array without its layer, or its
copy never reached the array) reads `"refused"` with the reason, and is also
logged as a warning.
A `LightCookie` component whose fill is refused at the call, such as one
authored before the scene's `configure` has sized the array, asks again each
time `configure` sizes it. `lightCookies.observe().configurations` counts
those calls for code of its own that does the same.
`lightCookies.observe()` reports how many fills are waiting, the one in
progress, and the loop's own counters.
## An empty layer puts the light out
The cone is multiplied by what it reads from its layer, so a spot pointed at a
layer nothing has filled renders black rather than plain. `project` fills before
it points the light, which is the order that keeps the cone lit; if you set
`SpotLight.cookieLayer` by hand, fill that layer first.
## The array is shared, and sizing it is explicit
The feature-texture array is one resource that every feature using
`zero_feature_texture` draws layers from, and it has no allocator: sizing it
zeroes every layer, including layers another feature owns. So this package never
sizes it as a side effect of setting a cookie, and `layer` is authored rather
than assigned. `lightCookies.configure` is the one call that resizes, made once
by whoever knows what else in the scene wants layers.
A scene that also bakes global illumination shares this array with the lightmap
atlas. Size it for both, and give cookies layers above the ones the bake fills.
## A cookie fills a whole layer
The cone's lookup runs over the layer's entire `uv` range, so an image is
resampled to the layer's extent rather than placed in a corner of it. One layer
carries one cookie.
## Alpha
The source's alpha is how much of the pattern applies. At alpha 0 the cone
passes through unmodulated, so a fully transparent image is a no-op rather than
a black cone.
# GravityField
Gravity fields: planet gravity, a pull toward a point, an axis or a surface, or a zone with its own direction. Every dynamic body a field reaches (rigid bodies, ragdoll bones, a vehicle's chassis, soft body particles) takes it as its gravity inside every physics substep, from where the body stands then, so a moon keeps its orbit, a slingshot past a planet bends the way it should, and a crate dropped anywhere around a small planet falls onto its surface. Where no field reaches, a body takes the world's gravity vector (`Physics.setGravity`). Fields are scene data, synced like any component, so every peer pulls the same way.
`Physics.gravityAt(point)` reads the gravity at any point (exactly what the step applies there), `Physics.upAt(point)` the unit up against it (the way a character stands on a planet and a camera keeps level), and `Physics.gravityFieldsAt(point)` which fields act there and what each gives. `Physics.bodyState(id).effectiveGravity` is the gravity a body takes, after its `gravityScale`. The built-in `CharacterController` stands and walks against `Physics.upAt`, so a player walks all the way around a small planet.
Public fields:
- `shape` (default `"point"`): what the field pulls toward, from where the entity stands and turned with it. `"point"`: the entity's position (a planet, a star, a black hole). `"axis"`: the entity's Y axis, or a segment of it `length` long (a cylinder, a capsule; with a negative strength, a rotating station's spin gravity). `"direction"`: along `direction` inside the box `halfExtents` (an anti-gravity zone, a wall to walk on, a current). `"surface"`: the nearest point of the entity's own colliders, whatever their shape (a box, a capsule, a convex hull, a mesh, a terrain). `"path"`: the nearest point of the line through `points` (a path, a spline sampled into points, a track a body rides along; repeat the first point at the end for a loop).
- `strength` (default `9.81`): the pull at `radius`, in m/s². Negative pushes away: a `"point"` field with a negative strength and `range` the shell's radius is an inverted sphere, dropping what is inside onto the shell.
- `falloff` (default `"constant"`): how the pull changes past `radius`. `"constant"`; `"linear"`, to nothing at `range`; `"inverseSquare"`, `strength * (radius / distance)^2`, a body of mass with `radius` its surface; `"curve"`, `strength` times the scale `curve` states at the distance.
- `radius` (default `1`) and `range` (default `0`: everywhere): where the falloff starts, and how far the field reaches, in world units from what it pulls toward (for a `"direction"` field: the height above the plane through the entity, against its pull).
- `halfExtents` (default zero: everywhere) and `direction` (default `{ 0, -1, 0 }`): a `"direction"` field's box and pull, in the entity's own frame.
- `length` (default `0`: the whole line): an `"axis"` field's segment length.
- `priority` (default `0`) and `combine` (default `"priority"`): where several fields reach a place, the `"priority"` fields of the highest priority are its gravity, summed when they share it, in place of the world's vector; `"add"` fields add on top of whatever acts there (a wind, a current, a tractor beam).
- `groups` (default `0xFFFFFFFF`): the collision groups the field acts on, against a body's `CollisionGroup` membership (a body with none belongs to every group).
- `curve` (default empty): a `"curve"` falloff's `{ distance, scale }` points, in order of distance.
- `points` (default empty): a `"path"` field's `{ x, y, z }` points, in the entity's own frame.
A body's `gravityScale` scales the gravity it takes, field or world. A field leaves its own entity's body alone, so a moving planet carries its gravity with it. Disabling the component (`.enabled = false`) switches the field off from the next step.
The step evaluates fields at every substep for every dynamic body while any field stands: about bodies times fields vector work each substep.
```luau
-- a small planet of radius 10 that walkers and crates fall onto, all the way round
local planet = entity.spawn("planet")
planet.component.add("SphereCollider", { radius = 10 })
planet.component.add("GravityField", { strength = 9.81, falloff = "inverseSquare", radius = 10, range = 80 })
-- a moon on a circular orbit 30 m out, set going on the first step: the field
-- and the moon's body stand in the physics world from the next step
local moon = entity.spawn("moon")
moon.localPosition = { 30, 0, 0 }
moon.component.add("Physics", { kind = "dynamic" })
moon.component.add("SphereCollider", { radius = 1 })
local off
off = Physics.onBeforeStep(function()
off()
Physics.setVelocity(moon.id, Physics.orbitVelocity(moon.position, planet.position))
end)
-- an anti-gravity zone that wins over the planet inside its box
zone.component.add("GravityField", { shape = "direction", direction = { 0, 1, 0 }, strength = 2, halfExtents = { 5, 5, 5 }, priority = 1 })
-- a ring station spinning gravity outward from its axis
station.component.add("GravityField", { shape = "axis", strength = -9.81, range = 50 })
-- which way is down here
local up = Physics.upAt(entity(player).position)
```
# restirLighting
Direct light from many small sources at a cost that does not grow with how many
there are.
A shading pass that loops every light pays for every light at every pixel, which
is why the number of lights has to be capped. Resampled importance sampling
breaks that link: each pixel draws a few candidates, keeps ONE of them with a
probability proportional to what it would contribute, and carries a weight that
makes the survivor stand for the whole set. What it keeps is then reused — by its
neighbours this frame, and by itself on the next one — so the set a pixel
effectively samples keeps growing while the number of candidates it draws stays
where you put it.
A cave of glowing crystals, a street of practicals, a control room of indicator
lamps: hundreds of sources, and each pixel looks at about a dozen.
## Using it
Put an `EmissiveSource` on the geometry that glows:
```lua
local id = entity.spawn("crystal", { position = { 2, 1, 0 } }).id
entity(id).component.add("EmissiveSource", {
color = { 0.3, 0.8, 1.0 },
intensity = 8.0,
radius = 6.0,
size = 0.4,
})
```
Or register sources from a script, which is how a generated scene does it:
```lua
local restir = require("@builtin::systems.restirLighting.restirLighting")
for i = 1, 400 do
restir.set(`lamp{i}`, {
position = { math.random() * 60 - 30, 1.5, math.random() * 60 - 30 },
color = { math.random(), math.random(), math.random() },
intensity = 4.0,
radius = 5.0,
})
end
```
The pass starts with the first source and stops with the last. Settings are on
`restir.configure`, or on a `ResampledLighting` component for a scene to author:
```lua
restir.configure({ candidates = 16, spatialSamples = 6 })
```
## What a pixel pays
`candidates + spatialSamples + 1` evaluations, reported by
`restir.perPixelCost()`. None of those terms is the source count.
The estimate is formed on a grid of one cell per 2x2 pixels (`resolution =
"full"` gives every pixel its own cell), across four passes:
| Pass | Runs over | Does |
|---|---|---|
| `restir_sample` | grid cells | draws `candidates` sources at random, resamples to one, merges the cell's own history |
| `restir_spatial` | grid cells | borrows from `spatialSamples` neighbours, each evaluated against this cell's surface |
| `restir_resolve` | pixels | shades the chosen source with the pixel's own normal, roughness and albedo |
| `restir_denoise` | pixels | averages that light over the cells around the pixel and composites it |
Which source to look at is a low-frequency decision a cell of pixels can share.
What the surface does with it is not, and is computed per pixel.
One source per cell is correct on average and different from its neighbour,
which is the grain a single sample carries. `restir_denoise` averages across the
cells around a pixel, weighing each by how nearly its surface is this one, so the
estimate keeps its value and loses its variance.
`mode = "reference"` replaces the reservoir lookup with a loop over every
registered source at every pixel. That is the picture the resampled mode is
estimating and the cost it is measured against — the same shading, the same
filter and the same composite, so the two are comparable directly.
## Temporal reuse
A cell keeps its reservoir across frames and merges it with the fresh
candidates, so a good find keeps paying after the frame that made it. The stored
world position is what says the cell is still looking at the same surface; a
camera move or an occluder passing in front fails that test and the history is
dropped rather than smeared.
`historyCap` bounds how many candidates the history is allowed to stand for.
Without it a converged cell would outvote every new candidate forever and a
lighting change would never work its way out. At the default of 20 a change is
absorbed over roughly twenty frames.
Removing a source, or turning its `intensity` down to 0, releases it; the pass
stops with the last one.
## Where it sits
Sources registered here are additional to the lights the engine holds rows for.
The passes run in `afterLighting` at orders 80-84 and add to the scene as it was
drawn, reading position, normal, albedo and metallic-roughness back out of the
G-buffer.
A source lights every surface within `radius` that faces it, along the straight
line between them.
## One frame, several targets
A render feature's `render` runs once a frame, and the passes it enqueues run
once per render target — the window, an offscreen capture, a camera rendering to
a texture. Each pass therefore reads the frame size out of the textures it is
handed and works out its own cell grid, so every target resamples at its own
resolution. A reservoir carries the grid width it was written under, which is
what stops one target's history being read as another's.
The reservoir buffers are sized to the widest grid any target has asked for. A
target wider than they have yet been sized for reports the grid it needed, and
the frame after that covers it.
## Reading what it did
`restir.stats()` returns the counters the passes keep on the GPU for the most
recent frame a read-back has landed for, carrying that frame's number so a
repeated read is distinguishable from a fresh one. `meanWeight` is counted in
sixteenths with each cell capped at 16 so the total fits a 32-bit counter;
`peakWeight` alongside it is exact to a thousandth, and is where an estimator
that has come loose shows first.
# PlayerPrototype
Marks the root of a player-setup subtree — the entity and children that define what a joining user becomes (avatar slot, spawn behaviour, controller). On awake it flips the entity to PrototypeOnly participation, so the prototype lives in the editor and drives spawning without being saved as a world entity itself; `kind` and `label` describe it for authoring surfaces. In edit mode it draws a cyan silhouette outline so the prototype root is easy to pick out, and surfaces its own setup-validation messages (missing camera, avatar slot, or wrong participation) on the component's error channel.
Location: `src/lua/lib/components/PlayerPrototype.component`
# Skybox
The scene's sky as a single **material**. Add it to an entity and the engine
renders that material across the sky behind everything else:
```lua
entity.spawn("sky").component.add("Skybox", { material = "sky_cubemap" })
entity.spawn("sky").component.add("Skybox", { material = "my_custom_sky" })
entity.spawn("sky").component.add("Skybox", { kind = "none" }) -- explicit no sky
```
`Skybox` is the generic, material-driven sky: it points at **any** sky material
— a builtin (`sky_procedural`, `sky_solid`, `sky_cubemap`, `sky_equirect`) or
your own authored sky-domain material — and makes it the active sky. For the
editable procedural atmosphere (day/night, sun, stars, moon), use the
[`ProceduralSky`](../ProceduralSky.component/README.md) component instead — it is
a `Skybox` over the `sky_procedural` material plus typed parameter controls.
A Skybox **materialises its material's GPU handle** when it binds it. The sky's
point-of-use is the sky pass, which never binds the material the way a `Model`
does, so the component performs the Disk→CPU→GPU upload (`:handle()`) itself. The
renderer binds the sky by the material's **identity** (the key it is resident
under once materialised), so a material-mode sky renders correctly after boot and
mode flips — no manual `:handle()` needed.
Like the directional light, the sky is conceptually **singular per scene**: the
engine copies the most recently authored sky into the scene-wide sky config the
renderer reads each frame. A sky belongs to the scene that spawned it; removing
the component reverts the scene to the engine fallback sky. State is bridged
through the native `Sky` ECS component (sky type `material` / `none`), so there
is no global sky singleton — two scenes can never clobber each other.
## Fields
| Field | Type | Default | Meaning |
|---|---|---|---|
| `material` | string | `sky_procedural` | The sky material to render. Any registered material whose shader is a sky-domain shader. Defaults to the procedural sky so an empty `Skybox{}` is never a black void. |
| `kind` | string | `material` | `"material"` renders `material`; `"none"` turns the sky pass off — the explicit authored form of "this scene has no sky". |
## Methods
| Method | Description |
|---|---|
| `skybox:setMaterial(name)` | Point the sky at a different material (materialises its handle). |
| `skybox:setNone()` | Turn the sky off explicitly. |
# AreaLight
A rectangular light source on an entity. The rect is centred on the entity's
world position, faces along the entity's world rotation applied to `face`
(default "Front", the entity-local -Z that `transform.forward` reports and that
`entity:lookAt` aims), and spans `width` by `height`. A rect under a carrier moves
and turns with it. Its light arrives from a surface rather than
a point, so shading falls off gradually across a wall, highlights stretch to the
shape of the source, and shadows carry a penumbra that widens with the rect's
size and the caster's distance.
# Text3D
Renders text in 3D world space. The quad auto-sizes to fit the text content and never clips. Positioning works like TextMeshPro: `offsetX/Y/Z` is a local offset from the entity, `pivotX/pivotY` is the anchor within the quad, and `billboard` makes it face the camera. With `billboard = false` the text reads from the entity's own forward, the local -Z that `transform.forward` reports and that `entity:lookAt` aims.
Sizing — three fields, two jobs:
- `worldHeight` — the quad's height in **world units** (default `1.0`). This is the one field that resizes a label, and it holds that height under every transform between the label and the world: a label hung off a shrunken detail box on a model comes out the size it asked for, and so does one whose own entity carries a `localScale`. Width follows the rasterised text's aspect. Measure the result with `getWorldSize()`, which reports the extent the quad is drawn at.
- `fontSize` — the **raster resolution** in texels (default `32`). Higher values sharpen the texture and change wrapping against `maxWidth`; the world-space size stays `worldHeight`.
- `scale` — rasterisation scale multiplier applied at raster time. Resolution only, like `fontSize`.
`maxWidth` is the width the text wraps at, in pixels of the raster `fontSize` states; `0` keeps it on one line. A label already drawn is laid out again when the field is written, so a caller re-wraps one label to line after line rather than making a label per line.
`alphaCutoff` decides whether the letters are a surface. At `0` (the default) the text is pure alpha blending: it draws over what is behind it and leaves the depth buffer alone, so a screen-space effect that reads scene depth — volumetric fog, screen-space shadows — integrates the whole distance behind the letters and the text sits inside it. Above `0`, coverage at or over the threshold is drawn opaque and written to depth, so those effects stop at the glyph shape instead. `0.5` reads well for most fonts; higher thins the letters, lower keeps more of the antialiased edge.
Public fields: `content`, `fontSize`, `color`, `alignment`, `richText`, `maxWidth`, `outline`, `outlineColor`, `background`, `scale`, `worldHeight`, `alphaCutoff`, `shadowX/Y`, `fontFamily`, `weight`, `slant`, `offsetX/Y/Z`, `pivotX/Y`, `billboard`. `weight` and `slant` are strings (`"regular"` / `"bold"`, `"normal"` / `"italic"`).
Methods: `setText(content)`, `setStyle(options)`, `getText()`, `getSize()`, `getWorldSize()`, `refresh()`.
```luau
entity(id).component.add("Text3D", { content = "Hello World" })
entity(id).component.add("Text3D", { content = "HP: 100", worldHeight = 0.5, fontSize = 96, color = "red", offsetY = 2.0, pivotY = 0 })
-- A title that keeps its letters crisp through volumetric fog.
entity(id).component.add("Text3D", { content = "RAISING", worldHeight = 3.0, alphaCutoff = 0.5 })
```
A label that is not showing, or came out in a face you did not ask for, reads
back out of the text system: `text.observe()` lists every live text object with
the entity that owns it and the texture its raster is in, and `text.face(h)`
names the font face the shaper actually used against the `fontFamily` that was
requested. `topics/text` walks both.
# Transform
Position, rotation, and scale for an entity, as the authoring face of the transform the
entity holds. Add it to an entity to reach these fields and methods.
Public fields: `positionX/Y/Z`, `rotationX/Y/Z/W` (quaternion), `scaleX/Y/Z`. They hold
the entity's LOCAL transform — where it stands relative to its parent — and an entity
with no parent stands at those coordinates in the world.
The entity's transform is what the component reports, and the fields mirror it. Adding
the component to an entity that already stands somewhere reads that placement into the
fields and leaves the entity where it is. A field the init table names is written onto the
entity instead, so `component.add("Transform", { positionX = 1, positionY = 2, positionZ =
3 })` moves the entity to `(1, 2, 3)`; every axis the table says nothing about keeps the
value the entity already holds, so adding it with `{ scaleY = 2 }` alone stretches the
entity on Y and leaves it standing where it stood.
Writing one field moves the entity on the axis that field names. The other axes of the
same vector are read off the entity first, so a position written after something else
moved the entity keeps the move on the axes it says nothing about.
Methods take one table each and are called with a colon:
| Method | Argument |
|---|---|
| `t:setPosition({x, y, z})` | position table, `{x, y, z}` or `{x =, y =, z =}` |
| `t:addPosition({dx, dy, dz})` | offset table, added to where the entity stands now |
| `t:setRotation({x, y, z, w})` | quaternion table, `{x, y, z, w}` or `{x =, y =, z =, w =}` |
| `t:rotateAxisAngle({ax, ay, az}, angle)` | axis table, and an angle in radians |
| `t:setScale(2)` or `t:setScale({x, y, z})` | one number for a uniform scale, or a table |
| `t:lookAt(target)` | a position table, or an entity id / name / proxy |
| `t:getPosition()` / `t:getRotation()` / `t:getScale()` | none |
`setPosition`, `addPosition`, `setRotation`, `rotateAxisAngle` and `setScale` write the
entity's local transform. `rotateAxisAngle` composes onto the rotation the entity
already holds, and reads its axis in the frame that rotation is relative to — the
parent's, and the world's for an entity with no parent.
The three getters report what the entity's transform holds at the moment they are
called, so a rotation written by `lookAt` — or a position written by another script —
reads back through them.
`lookAt` is the one method on a WORLD position. It takes one target: a position table
(`{x, y, z}` or `{x =, y =, z =}`), or an entity — an id string, an entity name, or an
entity proxy — whose world position is aimed at. It answers whether the rotation was
written, and the reason when it was not. The `Camera` component's `lookAt` reads the
same slot.
```luau
local t = entity(id).component.get("Transform")
t:setPosition({ 0, 5, 0 })
t:setScale({ 2, 2, 2 })
t:rotateAxisAngle({ 0, 1, 0 }, math.pi / 2)
local pos = t:getPosition()
```
# BoxCollider (component)
A box collision shape. Works with or without a `Physics` component: on its own
it is static collision geometry, and alongside one it moves with the body.
## Sizing
`half` is the box's half-extents in the entity's local space, multiplied by the
entity's world scale. Leave it unset and the box derives from the entity's model
bounds, so a bare `BoxCollider` matches what is rendered at any scale, and
follows the mesh when `renderer.mesh.setVertices` or `renderer.mesh.update`
changes it: by the next physics step the box takes the new geometry's size and
centre.
```lua
entity.find("crate").component.add("BoxCollider", {}) -- fits the mesh
entity.find("wall").component.add("BoxCollider", { half = { 2, 4, 0.2 } }) -- authored
```
## Fields
| Field | Meaning |
|-------|---------|
| `half` | Half-extents. Unset derives from model bounds. |
| `isTrigger` | Report overlaps without blocking. |
| `friction` | Surface friction. |
| `restitution` | Bounciness. |
| `rollingResistance` | How strongly the surface resists a body rolling on it: a rolling body slows at this many times gravity on level ground, so a ball rolled at v stops after v^2 / (2 * rollingResistance * 9.81). 0 rolls on. |
| `spinningResistance` | The same for a body spinning on the surface about the contact normal. 0 spins on. |
| `surface` | The surface the collider is made of, by name: one `Physics.defineSurface` defined gives it its friction, restitution and resistances in place of the fields above, and contacts, contact events and ray and shape casts report the name either way. Empty names none. |
| `oneWay` | The direction, in the collider's own frame, bodies pass through it along: a body moving that way goes through, and a body meeting it from the side the direction points to stands on it (a jump-through platform is `{0, 1, 0}`). `Physics.passThrough(entity)` drops a standing body through. Unset blocks from every side. |
| `surfaceVelocity` | The velocity, m/s in the collider's own frame, its surface moves at along itself while the collider stays put: friction carries what rests on it (a conveyor belt, a treadmill, an escalator). Write it at runtime to change the speed or direction. Unset holds the surface still. |
| `contactTag` | The tag the world's contact filter reads this collider by: `Physics.setContactFilter(tagA, tagB, mode)` makes two tags pass through each other (`"ignore"`), report contacts and push nothing (`"sensor"`) or collide (`"solid"`). Empty names none. |
## Composing
A collider on a child entity attaches to the nearest ancestor carrying a
`Physics` component, so a body made of several shapes puts each on its own
entity and each keeps its own material and trigger flag.
Past a few dozen boxes sharing one material, `CompoundCollider` is cheaper: it
is a single broadphase volume where separate components are one each.
# VehicleController
Drives a car, truck, kart or buggy built from `WheelCollider`s. Put it on the
chassis, the dynamic rigid body the wheels sit under, and a driving intent
(throttle, steer, brake, handbrake, boost) reaches the wheels. The intent comes
from the source `controlSource` names:
- `input` (the default): the player's controls, on keyboard, gamepad and touch
alike, from `@builtin::inputMaps.vehicle` through `Zin.controllers.vehicle`.
- `script`: the intent fields `throttle`, `steer`, `brake`, `handbrake` and
`boosting`, which code sets: an AI driver, a replay, an autopilot, a test.
`setIntent` sets them and switches the source (see "Driving it from code").
Its flight and its rollovers are physics alone: it flies ballistically off a
ramp and stays on its roof after a rollover until the recover control or
`recover()` rights it. Air control and self-righting are arcade assists a
field turns on (see "Arcade assists").
It drives the wheels from the physics step (its `fixedUpdate`): each step it
reads what the step left and writes the drive, the brakes and the steering for
the next one. So the car answers its intent at the step rate whatever the
frame rate, the same on every platform, and under `Physics.advance` from a
held clock as in real time: an acceleration run or a braking distance is
measured faster than real time with the intent set before the advance (or
changed from a step hook).
| Control | Keyboard | Gamepad | Touch |
|---|---|---|---|
| throttle | `W` / `S` | right / left trigger | stick, vertical |
| steer | `D` / `A` | left stick | stick, horizontal |
| brake | `Space` | south | button |
| handbrake | `Ctrl` | east | button |
| boost | `Shift` | north | button |
| recover | `R` | select | button |
| zoom | scroll | shoulders | pinch |
What each one does to the vehicle:
- **throttle** drives the driven wheels (`drive`: `all`, `front` or `rear`):
directly, the torque fading to nothing at `topSpeed`, or through an engine
and a gearbox when `engineCurve` is set (see "An engine and a gearbox").
Pulled back while the vehicle
rolls forward it brakes; at a stop it reverses, up to `reverseTopSpeed`.
Pushed forward while it rolls backward it brakes too. Under the direct
drive, a driven wheel that
spins on its own (`inertia` above 0) is spun no faster than `topSpeed` at
its tread (`reverseTopSpeed` in reverse, `topSpeed` times `boost` while
boosting): the drive's rev limit, written to the wheel's `maxDriveSpeed`.
So full throttle spins the wheels up on ice, in a burnout or in the air,
and they settle at that tread speed.
- **steer** turns the steered wheels, the pair nearest the chassis' forward
(its local -Z), at up to `maxSteerAngle` at rest, narrowing to
`steerAtTopSpeed` at `topSpeed`, turning at `steerRate`; with
`counterSteer` set, they turn toward the way the vehicle travels as it
slides (see "Holding a slide").
- **brake** brakes the wheels, `brakeBias` of it on the front and the rest on
the rear (see "Brakes"); **handbrake** holds the wheels `handbrakeWheels`
names (the rear pair by default) with `handbrakeTorque`.
- **boost** multiplies the drive torque, the top speed and the driven
wheels' spin limit by `boost`.
- **recover** (the control, or `recover()` from code) sets the chassis back on
its wheels where it lay, `recoverLift` above it, facing the way it faced.
- **zoom** changes how far the `camera`'s chase controller trails, when that camera hears no zoom control of its own (a chase camera on its default `@builtin::inputMaps.cameraRig` map zooms itself).
The component writes `motorTorque`, `maxDriveSpeed`, `brakeTorque` and
`steerAngle` on the wheels, each only when its value changes.
### Wheelspin
On wheels with an `inertia` (see the `WheelCollider` README, "Spin") the
drive spins a wheel faster than the road whenever it asks more than the tyre
puts down. The spin is bounded by the controller's top speeds: a 600 kg car on
wheels of `inertia = 1.2` and radius 0.35, its rear pair driven with the
default 1500 N·m from rest, spins its rear treads up to `topSpeed` (25 m/s)
on asphalt and in the air and holds them there, and on `forwardFriction = 0.15`
still spins them past twice the road speed as it pulls away. The limit holds
the drive: a gripping tyre turns its wheel at the speed the road passes under
it, so a car rolling faster than `topSpeed` (downhill, or its rear end lifting
over a crest) turns its wheels faster too. A lower `topSpeed` is a lower rev
limit, and while boosting the limit is `topSpeed` times `boost` (a `boost` of 1
keeps it at `topSpeed`). `tractionControl` holds the drive short of spinning
the wheels (see "Traction control"). Wheels with no `inertia` roll at the road
speed, and their drive is held by their grip.
## Brakes
`brakeTorque` is each wheel's brake at full brake with `brakeBias` at 0.5, its
default. `brakeBias` moves the brake between the axles: each front wheel brakes
with `brakeTorque` times 2 x `brakeBias`, and each rear wheel with `brakeTorque`
times 2 x (1 - `brakeBias`). So 0.5 brakes every wheel with `brakeTorque` on any
vehicle, a trike or a six-wheeler as well, and on a four-wheeled car (or any
with as many wheels at the front as at the rear) the front wheels take
`brakeBias` of the whole brake: a bias of 0.65 puts 1.3 times `brakeTorque` on
each front wheel and 0.7 times on each rear one. A road car's bias is 0.6 to
0.7: under a hard stop its weight moves onto the front tyres, and rear wheels
braked as hard as the front ones lock first, after which the rear of the car
lets go across the road and a brake into a corner spins it. A bias toward the
front keeps the rear wheels turning, so the car stops straight and turns while
it stops.
`antiLock = true` adds anti-lock brakes on wheels that spin on their own (an
`inertia` above 0; a wheel without one rolls at the road speed and never
locks). While braking above 1 m/s, each wheel is braked with the force its
tyre pushes back with at 0.95 of the slip its grip peaks at, read each step
from the grip curve its `WheelCollider` states (`Physics.tyreCurve`) at the
load it carries, on the surface it touches and at the slip angle it runs at,
so the wheel settles at that slip and turns as it brakes. A rear wheel takes
that share of its tyre's peak in its slip along the road and its slip angle
together, so the back of the car keeps the side grip its cornering needs; a
front wheel brakes along the road whatever it corners with. The load is the
one the tyre carries over the step to come: a falling load goes on falling by
the share it fell by over the last step, and a rising one counts at what it
was the step before, so the jolt of a bump or a landing does not brake the
wheel into a lock. A wheel that slips past twice its peak all the same (its
load fell away, it met a slippery patch) has its brake eased to half the
torque its tyre pushed back with, and let back on by 2 times itself each
second. A wheel off the ground, or touching it with no load on it, is left
unbraked. Under an engine drive the clutch is out while the anti-lock brakes,
so the engine neither brakes the driven wheels nor turns them. A tyre held
short of its peak grips harder than a sliding one (`slideGrip`, see the
`WheelCollider` README), so the car stops shorter and keeps steering: the
1420 kg rear-driven road car of the regression tests, on default tyres and
braked from 25 m/s through its engine and gearbox, stops in about 36 m with no
wheel locked above 2 m/s, and in about 40 m across three ridges 0.15 m high,
against 31.9 m at its tyres' full grip on a flat floor; the 1200 kg car
braked from 20 m/s stops with its wheels turning shorter
than on an even brake that locks all four, and braked into a gentle corner
with a bias of 0.65 it turns while it stops, where the locked car slides
straight on.
Set up a road car with both: a bias toward the front and anti-lock. The
anti-lock holds each rear wheel inside the grip its cornering leaves it, so a
car braked into a corner keeps its back in line on any split; the bias divides
the brake wherever the anti-lock leaves it as asked, on a wheel with no
`inertia` and under a brake lighter than the tyres' grip.
`handbrakeWheels` names the wheels the handbrake holds: `rear` (the default, a
road car's: locking the rear wheels steps the back end out into a slide),
`front` or `all`. While it is held under an engine drive the clutch is out, so
the locked wheels do not drag the engine down.
```luau
-- a road car that stops straight, and a drift car whose handbrake swings the back out
car.component.add("VehicleController", { brakeBias = 0.65, antiLock = true })
drifter.component.add("VehicleController", { drive = "rear", brakeBias = 0.6, handbrakeTorque = 4000 })
```
## Traction control
`tractionControl = true` holds each driven wheel near the slip its tyre grips
best at under the throttle, the way `antiLock` holds a braked one, on wheels
that spin on their own (an `inertia` above 0). Each step, each driven wheel on
the ground takes no more drive than its tyre pushes back with at 0.95 of the
slip its grip peaks at, read from the grip curve its `WheelCollider` states
(`Physics.tyreCurve`) at the load it carries, on the surface it touches and at
the slip angle it runs at, so it holds from a standstill up, on tarmac, dirt,
grass or ice, and on ground that changes under the wheel. A rear wheel takes
that share of its tyre's peak in its slip along the road and its slip angle
together, so a car driven out of a corner keeps the side grip its back needs.
A wheel that slips past twice its peak all the same (a bump unloads it, it
lands spinning) has its drive eased to half the torque its tyre pushed back
with, and let back on by 8 times itself each second. It reads the player's
controls (keyboard, gamepad and touch alike) and `setIntent`, and acts
whatever the throttle asks; a wheel in the air is left to the drive's rev
limit.
- **The direct drive**: each driven wheel's `motorTorque` is held to that
torque.
- **Through an engine** (`engineCurve`, or a `ShaftNetwork` of your own with a
part named `engine`): each driven wheel's share of the engine's torque is
measured from the network each step (the torque its links put on the wheel
over the torque the engine puts into the drivetrain), so it holds through
any gearing, clutch and differentials. The engine's throttle is eased to the
torque that drives the wheel with the least room with what its tyre holds,
plus the engine's own drag, trimmed toward the slip the wheels run at while
it is what holds the drive back (neither the throttle asked for nor the
clutch taking up the drive holds it to less). A wheel's share follows each
shift of the gearbox until it is measured in the new gear, and the trim
starts over off the throttle or on the brake, so every pull-away from a stop
holds the drive the way the first one did, whatever gear and speed the car
drove at before it. While it eases the throttle the link named `clutch` carries no more than
that torque, so neither the clutch taking up the drive from a standstill nor
the engine speed carried into a shift turns the wheels past their grip; a
clutch holding an engine that turns faster than the gear it is in after a
shift closes the throttle until the engine has come down to it.
`driveState().tractionLimited` reads whether it held the drive back this tick,
what a dashboard's traction light reads. The 1420 kg rear-driven road car of
the regression tests (an engine peaking at 452 N·m, six gears, a limited-slip
differential), launched at full throttle from rest, reaches 25 m/s on tarmac
(friction 1) in 4.7 s with no driven wheel past a slip ratio of 0.35 after its
first second, against 5.8 s with its rear wheels spinning to a slip ratio of 8
without it; on dirt (friction 0.65) in 8.2 s against 10.3 s, and on grass
(friction 0.45) in 13.5 s against 18.5 s; and it pulls away straight, where
without it the wheelspin turns it 19 degrees on dirt and spins it round 118
degrees on grass. The same car on the direct drive at 2500 N·m reaches 25 m/s
in 4.9 s against 5.8 s, and driven through an engine network of the author's,
in 4.7 s against 5.8 s.
It is off by default, so the throttle drives the wheels as asked: set it
`false` for a burnout, a power slide, a drift car steered on the throttle or a
monster truck's wheelspin.
```luau
-- a road car that pulls away and stops at the edge of its tyres' grip
car.component.add("VehicleController", {
drive = "rear", brakeBias = 0.65, antiLock = true, tractionControl = true,
engineCurve = { {1000, 180}, {4500, 260}, {6500, 220}, {7000, 0} },
})
```
## An engine and a gearbox
With `engineCurve` set, the throttle drives the wheels through an engine
rather than with `motorTorque`: the controller puts a `ShaftNetwork` on the
chassis (see its README) holding an engine with that torque curve, a clutch,
a gearbox and differentials down to the driven wheels, solved with the tyres
inside the physics step. The car accelerates with the torque the curve gives
at the engine's speed, multiplied by the gear and the final drive, and the
gearbox shifts by itself.
```luau
car.component.add("VehicleController", {
drive = "rear",
engineCurve = { {1000, 180}, {4500, 260}, {6500, 220}, {7000, 0} }, -- rpm, N·m
gears = { 3.6, 2.2, 1.5, 1.1, 0.9 }, reverseGear = 3.4, finalDrive = 3.9,
differential = "limited",
})
```
- **The engine** turns with `engineInertia` (kg·m²) and the torque of
`engineCurve` times the throttle (and `boost` while boosting). The curve's
last point is its rev limit: a curve whose last point still gives torque is
cut off 5% past it. `engineBraking` is the engine's own friction (N·m), always
on, so off the throttle in gear the car slows through its wheels.
- **The clutch** takes up the drive as the engine revs past the curve's first
point, and is in by the time the engine (or the gearbox side of it) turns 30%
of the way from there to the rev limit: the car pulls away from a stop with the
engine revving, and the engine idles down with the clutch out once the car
stops. It is out while the handbrake is held, and carries no more than
`tractionControl` asks the engine for while it eases the throttle.
- **The gearbox** starts in first and picks its gear by the road speed: it
shifts up once the engine speed the road speed calls for in the gear (the
driven wheels rolling at the road speed under them, through the gear and the
final drive) passes `shiftUpRpm` on the throttle, and down once it falls
below `shiftDownRpm` (0, their default, is 90% and 45% of the curve's last
rpm), holding each gear 0.4 s. So driven wheels spinning on a full-throttle
launch keep it in first, and wheels locked under the brake keep it in the
gear the car's speed calls for. It shifts only to a gear the engine would
turn in between the two. The throttle pulled back at a stop selects reverse
(`reverseGear`), and forward throttle at a stop first gear again.
- **The differentials** split the gearbox's output, through `finalDrive`,
equally between the driven wheels: the front and rear halves first, then
each axle's left and right. `differential` makes them `open` (the wheel with
less grip spins), `limited` (a torque bias ratio of 3) or `locked` (the wheels
turn together).
- A driven wheel that states no `inertia` spins under the engine as a 20 kg
wheel of its radius does (10 times its radius squared).
`topSpeed` still sets the speed the steering lock narrows to `steerAtTopSpeed`
at; `motorTorque`, `reverseTorque` and `reverseTopSpeed` are the direct drive's
alone. Changing an engine field, `drive` or `boost` builds the drivetrain
again; `gears`, `reverseGear` and the shift points apply from the next
physics step, in the gear the car is in.
`driveState()` reads `drivetrain` (`engine`), `gear` (1 for first, -1 for
reverse) and `rpm`, and the network itself reads through `Physics.shaftNetworkState(car.id)`:
the engine part is `engine`, the links `clutch` and `gearbox`.
A `ShaftNetwork` the author put on the chassis is driven in its place: a
network with a part named `engine` takes the throttle on that part, the gear on
its link named `gearbox` (shifting through `gears` and `reverseGear`, with the
rev limit and the clutch's take-up read from the engine part's `curve`) and the
clutch on its link named `clutch`, where it has them. So a drivetrain of your
own (a transfer case, a locked rear and an open front differential, a tank's
two tracks) keeps the controller's input, intent and shifting.
## Holding a slide
The A and D keys steer full lock or none, so a driver on a keyboard cannot
give a slide the small, changing opposite lock a stick gives it, and the
wheels spring back to straight the moment a key is let go. `counterSteer`
(0..1) turns the steered wheels toward the way the vehicle travels by that
share of its slide angle, the angle between its heading and its path over the
ground, and adds the driver's steer to it, within `maxSteerAngle` at any speed
(the driver's own lock narrows with speed). At 1, with the keys let go the
front wheels point along the path, as a car's front wheels trail it with the
wheel let go, and the driver holds the slide by working the keys against it as
it comes: W and D while it is narrower than wanted, A while it is wider. On
the ground the slide angle is `driveState().slideAngle` (degrees, positive
with the path to the right of the nose; 0 in the air, below 2 m/s and backing
up), what a drift score or a tyre sound reads.
```luau
-- a drift car driven from the keyboard
car.component.add("VehicleController", { drive = "rear", motorTorque = 2000, counterSteer = 1 })
```
The 1100 kg rear-driven car of the regression tests (wheels of radius 0.32,
`inertia` 1), with `stability` off, driven from the keys at 17 m/s into a
handbrake slide (D and Ctrl for 0.6 s) and then held with W, D and A decided
every 0.1 s from the slide a quarter of a second ahead (its angle plus a
quarter of a second of its rate), holds a slide of 14 to 38 degrees for 5 s,
gaining speed, its yaw rate within 40 degrees per second from half a second
after the handbrake is let go, with `counterSteer = 1`; with it at 0 the same
keys spin the car through 180 degrees at 100 degrees per second. With `counterSteer = 1` the same car still
spins when its driver decides from the slide as it stands, or a tenth of a
second ahead, and when W, or W and D, are held throughout; lifting W as the
slide grows, with no steering key, catches the slide at 46 degrees and the car
straightens. `counterSteer` applies to whatever the intent comes from: the
keys, a stick, or code. It is 0 by default, which steers only where the driver
steers.
An ordinary corner holds a few degrees between heading and path as well, and
`counterSteer` acts on those too. On the same car at 20 m/s a steer of 0.3
turns it at 11 degrees per second with `counterSteer = 1` and at 25 with it at
0 (its front wheels at 1.7 degrees against 3.8), while full lock turns it
about as fast either way; at 6 m/s the same steer turns it a little faster
with it (24 degrees per second against 20). A share below 1 catches a slide
less and leaves an ordinary corner's steering closer to the driver's.
## Stability
A car whose front and rear tyres grip alike, steered past what they grip with,
turns faster than its path can follow; the rear tyres slide past their peak
and lose grip while the front ones still push, and the car spins. `stability`
(on by default) watches for that: once the rear tyres' slip, along the road
and across it together, is past the slip they grip best at, and while the car
turns toward the side the rear slides from faster than its path does (the
slide grows), the steered wheels turn no further into that turn than lets the
front tyres push with the share of their grip the rear tyres still grip with,
times the share of the car's turning its path keeps up with, and never past
`maxSteerAngle`. Read from the grip curves the wheels' `WheelCollider`s state
(`Physics.tyreCurve`) at the slip each runs at, its brake and drive counted,
so it holds on any tyre and surface, braking, coasting or on the throttle.
Each tyre is read on the surface under it at the step the assist acts, so a
wheel crossing onto other ground (a painted terrain's layers included), a
surface redefined and a tyre retuned count from that step. The steering is
the driver's again once the slide holds steady or closes, so a slide the
driver makes with the throttle, or with a pull of the handbrake, and holds
with the steer stays theirs; what the assist takes away is the spin.
`driveState().stabilizing` reads whether it held the steering back this tick.
A rear wheel the handbrake holds grips with next to nothing across the road,
so while the handbrake is held at speed the assist lets the front turn the
car little further than its path: the road car below, held on the handbrake
from 25 m/s for 4 s with the wheel at full lock and `counterSteer` at 0,
turns 5 degrees, where with `stability` off it spins.
The 1420 kg rear-driven road car of the regression tests (an engine and six
gears, `brakeBias = 0.66`, `antiLock`, `counterSteer = 0.6`, its full lock 32
degrees at rest narrowing to 5 at 32 m/s) steered at 0.3 to 1 from 25 m/s
keeps its slide under 17 degrees at full brake and under 13 coasting (with
`counterSteer` at 0 or 1 as well) and keeps turning; with `stability` off the
same car slides to 93 degrees at full brake and steer 0.8, and to 68 coasting
at steer 0.6. The 1100 kg keyboard car of the regression tests, with every
default, still steps out into a handbrake slide and holds it at 15 to 19
degrees for 4.8 s on the keys, whether its driver decides from the slide a
quarter of a second ahead or from the slide as it stands; with
`counterSteer = 1` as well it holds it at 15 to 17 degrees for 4 s.
Set it `false` for a car whose spins or handbrake turns are the game, or to
leave the steering wholly to the driver.
## Arcade assists
Two assists turn on with a field, for a stunt game, a kart racer or a monster
truck show:
- **Air control** (`airControl` above 0): with no wheel on the ground the
chassis turns toward level, its nose raised to `airPitch` by throttle and
lowered by reverse or brake, spinning at `airSpin` where it is steered;
`airControl` is how fast it gets there. 4 is a stunt vehicle's.
- **Self-righting** (`recoverAfter` above 0): lying on its side or roof slower
than 1 m/s for `recoverAfter` seconds sets it back on its wheels, the way
`recover` does. 3 is a stunt vehicle's.
```luau
car.component.add("VehicleController", { airControl = 4, recoverAfter = 3 })
```
Both are 0 by default, so a vehicle added with no fields set is a simulation
vehicle. A scene that relied on a vehicle steering in the air or righting
itself states `airControl = 4` and `recoverAfter = 3`, the values these fields
held before they defaulted to 0.
## Driving it from code
`setIntent` drives the vehicle the way the player's controls do: the drive
split, the top speed, the steering lock that narrows with speed and the
assists all apply. It takes the keys `driveState` reports (`throttle` -1..1
positive forward, `steer` -1..1 positive right, `brake` 0..1, `handbrake` and
`boost` booleans) and switches `controlSource` to `script`. The table is the
whole intent: a key left out is neutral (0, or `false`), and the numbers are
clamped to their ranges. An unknown key, or a value of the wrong type
(`handbrake = 1`), is refused with an error naming it, and the intent stays as
it was. Writing the fields (`throttle`, `steer`, `brake`,
`handbrake`, `boosting`, `controlSource`) directly changes one at a time.
```luau
-- an AI car that steers toward a target each tick
local car = entity.find("aiCar")
local target = entity.find("waypoint")
local vc = car.component.get("VehicleController")
task.loop(function()
if not car:isLocal() then return end
local p, w = car.position, target.position
local dx, dz = w.x - p.x, w.z - p.z
local f, r = car.transform.forward, car.transform.right
local ahead = dx * f.x + dz * f.z -- metres ahead of the car
local side = dx * r.x + dz * r.z -- metres to its right
vc:setIntent({ throttle = 0.6, steer = math.clamp(2 * side / math.max(math.abs(ahead), 1), -1, 1) })
end)
```
Set `controlSource = "input"` to hand a vehicle that holds the controls back
to the player; a vehicle that never took them answers them once `takeControl()`
is called. A vehicle added with `controlSource = "script"` does not take the
controls as it wakes, so a player car and a code-driven car drive side by
side. A player car switched to `script` (an autopilot) keeps the controls it
holds, so the walking controls stay stood down until `releaseControl`.
Only the peer that owns the chassis drives it. The intent fields are synced:
code sets them on the owning peer (`car:isLocal()`), the way every synced field
is written, every peer reads the same intent, and a peer that takes the
vehicle over drives on with it.
## Fields
| Field | Default | Unit | Meaning |
|---|---|---|---|
| `inputMap` | `@builtin::inputMaps.vehicle` | | The controls it reads. |
| `takeControlOnAwake` | `true` | | Take the controls as it wakes; `false` waits for `takeControl()`. |
| `drive` | `all` | | Which wheels the throttle drives. |
| `motorTorque` | 1500 | N·m | Drive torque per driven wheel at full throttle. |
| `reverseTorque` | 800 | N·m | Drive torque per driven wheel at full reverse. |
| `brakeTorque` | 3000 | N·m | Brake torque per wheel at full brake, with `brakeBias` at 0.5. |
| `brakeBias` | 0.5 | 0..1 | Front against rear: each front wheel brakes with 2 x it, each rear one with 2 x (1 - it), times `brakeTorque`. |
| `antiLock` | `false` | | Anti-lock brakes on wheels with an `inertia`: each braked wheel held just short of its tyre's peak slip, a rear wheel within the grip its cornering leaves it, the clutch out. |
| `tractionControl` | `false` | | Traction control on wheels with an `inertia`: each driven wheel's drive held to what its tyre grips with just short of its peak slip, a rear wheel within the grip its cornering leaves it; an engine's throttle (and its clutch) eased to it. |
| `handbrakeTorque` | 6000 | N·m | Brake torque per wheel the handbrake holds. |
| `handbrakeWheels` | `rear` | | Which wheels the handbrake holds: `rear`, `front` or `all`. |
| `topSpeed` | 25 | m/s | Forward speed where the direct drive has faded to nothing, the fastest tread speed it spins a driven wheel with an `inertia` to, and the speed the steering lock narrows to `steerAtTopSpeed` at. |
| `reverseTopSpeed` | 8 | m/s | Reverse speed where the direct drive has faded to nothing, and the fastest tread speed the reverse drive spins a driven wheel with an `inertia` to. |
| `engineCurve` | `{}` | rpm, N·m | The engine's torque curve; set, the throttle drives through an engine and a gearbox. |
| `gears` | `{ 3.6, 2.2, 1.5, 1.1, 0.9 }` | × | Forward gear ratios, first gear first. |
| `reverseGear` | 3.4 | × | Reverse gear ratio. |
| `finalDrive` | 3.9 | × | Final drive ratio. |
| `shiftUpRpm` | 0 | rpm | Shift up once the engine speed the road speed calls for passes it; 0 is 90% of the curve's last rpm. |
| `shiftDownRpm` | 0 | rpm | Shift down once the engine speed the road speed calls for falls below it; 0 is 45% of the curve's last rpm. |
| `engineInertia` | 0.2 | kg·m² | The engine's moment of inertia. |
| `engineBraking` | 20 | N·m | The engine's friction, always on: its braking off the throttle. |
| `differential` | `open` | | `open`, `limited` or `locked`. |
| `boost` | 1.6 | × | Drive and top speed multiplier while boosting. |
| `maxSteerAngle` | 30 | degrees | Full lock at rest. |
| `steerAtTopSpeed` | 8 | degrees | Full lock at `topSpeed`. |
| `steerRate` | 150 | degrees/s | How fast the wheels turn toward the lock asked for. |
| `counterSteer` | 0 | 0..1 | Share of the slide angle the steered wheels turn toward the path by, added to the driver's steer within `maxSteerAngle`; 1 trails them along the path with the steer let go. |
| `stability` | `true` | | Stability assist: while the rear tyres slide past their grip and the slide grows, the steered wheels turn no further into it than the rear tyres' grip answers; `false` leaves the steering to the driver and `counterSteer`. |
| `airControl` | 0 | rad/s² | Air control assist: how fast the chassis turns in the air toward the attitude asked for; 0 leaves its flight to physics. |
| `airPitch` | 20 | degrees | Nose angle held in the air at full throttle or full reverse, under air control. |
| `airSpin` | 90 | degrees/s | Spin about the up axis at full steer in the air, under air control. |
| `recoverAfter` | 0 | s | Self-righting assist: time overturned before it rights itself; 0 waits for the recover control or `recover()`. |
| `recoverLift` | 1 | m | Height above where it lay that a righted vehicle is set down. |
| `camera` | | | A camera with `@builtin::controller.chase` that zoom moves, while that camera hears no zoom of its own. |
| `controlSource` | `input` | | Where the intent comes from: `input` (the player's controls) or `script` (the intent fields). |
| `throttle` | 0 | -1..1 | Intent under `script`: positive forward, negative reverse. |
| `steer` | 0 | -1..1 | Intent under `script`: positive right. |
| `brake` | 0 | 0..1 | Intent under `script`: share of `brakeTorque`. |
| `handbrake` | `false` | | Intent under `script`: the handbrake holds the wheels `handbrakeWheels` names. |
| `boosting` | `false` | | Intent under `script`: boost held. |
## Methods
- `takeControl()`: the controls go live; the walking controls stand down.
- `releaseControl()`: the controls go back; the wheels coast straight.
- `hasControl() -> boolean`
- `setIntent({ throttle?, steer?, brake?, handbrake?, boost? })`: drive it
from code; switches `controlSource` to `script`.
- `recover()`: set it back on its wheels now.
- `driveState()`: `{ source, throttle, steer, brake, handbrake, boost, speed,
groundedWheels, wheels, steerAngle, slideAngle, stabilizing,
tractionLimited, overturned, recoveries, lastRecover, drivetrain, gear, rpm }`:
the intent from the current source; `slideAngle` is the slide in degrees
(see "Holding a slide"); `stabilizing` and `tractionLimited` whether
`stability` held the steering back and `tractionControl` the drive this
tick; `lastRecover`
is `control`, `call` or `overturned`; `drivetrain` is `direct` or `engine`,
with the gear (1 first, -1 reverse) and the engine's rpm under an engine.
## Example
A monster truck: a heavy chassis on four big wheels with long travel, the
suspension force raised to carry the landings, with the arcade assists on.
```luau
local truck = entity.spawn("truck")
truck.position = { 0, 2.2, 0 }
truck.component.add("Physics", { kind = "dynamic", mass = 2000 })
truck.component.add("BoxCollider", { half = { 1.3, 0.4, 2.2 } })
for _, at in { { -1.5, -1.7 }, { 1.5, -1.7 }, { -1.5, 1.7 }, { 1.5, 1.7 } } do
local wheel = entity.spawn("wheel", { parent = truck.id })
wheel.localPosition = { at[1], -0.2, at[2] }
local tyre = entity.spawn("tyre", { parent = wheel.id })
tyre.component.add("Model", { model = "cylinder" })
tyre.localRotation = { 0, 0, 0.7071068, 0.7071068 }
tyre.localScale = { 1.6, 0.6, 1.6 }
wheel.component.add("WheelCollider", {
radius = 0.8, width = 0.6,
suspensionDistance = 0.8, springRate = 25000, damperRate = 5000,
maxSuspensionForce = 40000,
visual = tyre,
})
end
truck.component.add("VehicleController", {
motorTorque = 4000, brakeTorque = 8000, topSpeed = 25,
airControl = 4, recoverAfter = 3,
})
```
A car the player gets into takes the controls when the driver enters:
```luau
car.component.add("VehicleController", { takeControlOnAwake = false })
car.component.get("VehicleController"):takeControl() -- driver in
car.component.get("VehicleController"):releaseControl() -- driver out
```
# controller.character
Character-oriented controller component for builtin movement-driven actors.
# EditorPresence
Who a client of the world is and what it is doing, carried on the entity that
client occupies in edit mode. Every editor and every agent sub-client occupies
one such entity (`modules.api.editor.presence` makes and moves it): a temporary
`PlayerOwned` root, which the edit room relays the way a player's subtree is
relayed and the scene never records. It stands at the client's viewpoint.
The client that owns the entity writes the fields; every other client in the
same scene draws the participant from them:
- a view frustum and a camera icon in the participant's colour at its
viewpoint, with a name pill (and an agent's current tools) above it; a
participant outside the view has its pill held inside the edge of the view
that faces it, with an arrow pointing toward it;
- an outline in the same colour around every entity the participant has
selected or changed in the last moments, with a small pill naming the
participant above the first of them.
The pills are drawn on one overlay canvas that takes no pointer, so every
press reaches the editor beneath it. The `Participants` overlay of the
viewport's debug overlays turns the drawing on and off.
An agent has no viewport of its own, so its entity stands above the work it is
doing, and it is shown only while it is changing something. A participant in
another scene is not drawn.
## Fields
| Field | Synced | Meaning |
|---|---|---|
| `displayName` | yes | The person's display name, or the names of the agents working in the client. |
| `kind` | yes | `"person"` for an editor, `"agent"` for a sub-client. |
| `scene` | yes | The guid of the scene the participant has open. |
| `selection` | yes | The entities the participant has selected, comma-separated ids. |
| `editing` | yes | The entities the participant changed in the last two seconds, comma-separated ids. |
| `activity` | yes | The tools an agent's calls in flight are running. |
## Example
The participants this client draws, with what each is doing:
```lua
local Presence = require("@builtin::modules.api.editor.presence")
for _, p in ipairs(Presence.participants()) do
print(p.name, p.kind, p.activity, p.editing)
end
```
# Video
Plays an MP4 video onto a plane mesh attached to this entity. Creates a hidden child entity with a `Model` + `Material` that displays the video render target — same pattern as `UiPanel`'s 3D mode. The video renders to a standard render target (`rt:video_N`), so it can also be used in any material via `material.setTexture(...)`.
Public fields: `url`, `loop`, `autoplay`, `rate`, `width`, `height` (0 = auto aspect), `maxResolution`, `showOverlay`.
Methods: `play()`, `pause()`, `stop()`, `seek(time)`, `getInfo()`, `getHandle()`.
```luau
entity(id).component.add("Video", {
url = "@builtin/videos/test_bars.mp4",
loop = true,
autoplay = true,
})
```
# globalIllumination system
Production-grade baked global illumination for the Zero engine. Two
complementary techniques share one baking pipeline:
- **Lightmaps** — bake full irradiance (direct + multi-bounce indirect)
into a per-entity texture sampled in UV space. For static surfaces.
- **Volume probes** — path-trace incoming radiance at points in a 3D
grid, encode as spherical harmonics (SH L2), and publish the field
into the renderer's irradiance-volume set: every standard-PBR fragment
inside the volume samples the nearest probes by world-space position.
For moving entities and any static surface without lightmap UVs.
Both bake the same lighting model from the same scene: every sample is
path-traced through the scene BVH for up to `bounces` surface
interactions. Each path vertex contributes its emissive plus its albedo
times the shadowed direct light there, so the bake captures indirect
light, color bleed between surfaces, emissive surfaces acting as area
lights, and sky occlusion — the transport that is too expensive to
evaluate at runtime.
## Mobility decides who bakes
`Model.mobility` (`"auto"` | `"static"` | `"movable"`) is the single
selection axis for the whole system:
- **Static geometry** receives lightmaps and occludes / bounces baked
light. `Lightmap.bakeAll()` bakes every static receiver — no
per-entity setup.
- **Movable geometry** (and every player / skinned character) samples
the published probe fields — renderer-level, no per-entity setup. It
never bakes: a moving mesh baked as an occluder would freeze its
shadows into the world and walk away from them.
`"auto"` derives the answer per entity: a non-static `Physics` body, a
`SkinnedModel`, a `ClipPlayer`, a `Mover`/`FreeMover`, or a non-world
runtime participation (players, editor viz, prototypes) makes it
movable, and so does motion: geometry the running world places on more
than one frame (a script's update walking it in play, an engine system
posing it), or carries on an ancestor it places so, reads
`entity.inMotion` true and resolves movable. Everything else is static,
a prop a script places once included. An explicit `"static"`/`"movable"`
on the field overrides the derivation — that is the exclusion switch
when the derivation gets an entity wrong.
## Files
```
globalIllumination.package/
VolumeProbe.component/ -- define a probe volume (bounds + resolution)
BakedLighting.component/ -- keep the bake in step with the scene
lightmap.module/ -- Lightmap.bake / .bakeAll / .applyFromAsset / .clear
volumeProbe.module/ -- VolumeProbe.bake / .restore / .retire
scenarios.module/ -- Scenarios.capture / .blend / .mix
skyResponse.module/ -- SkyResponse.calibrate / .apply / .combine
bakeState.module/ -- BakeState.affects / .invalidate / .rebake
bakeViz.module/ -- the two debug overlays that make a bake visible
baking.module/ -- Shared utilities: light gather, surface
-- attributes, static mesh-instance gather
lightmap_bake.computeShader/ -- Compute shader: per-texel path-traced bake
probe_bake.computeShader/ -- Compute shader: per-probe path-traced bake
```
## A sky that moves without a re-bake
A probe bake follows each path until it escapes, and what escapes carries the
sky's colour — so an ordinary bake fixes the sky the moment it finishes.
The sky enters as `throughput * sky` where a ray escapes, and `throughput` does
not depend on the sky, so the field splits exactly, per channel:
```
field(sky) = lights + sky * aperture
```
```lua
local skyResponse = require("@builtin::systems.globalIllumination.skyResponse")
skyResponse.calibrate(volId) -- two bakes, once
skyResponse.apply(volId, { 0.3, 0.6, 0.9 }) -- no bake
```
`SkyResponse.component` is the authored form: calibrate once, then move
`skyR` / `skyG` / `skyB`.
Both terms come from bakes at the same settings, and the bake seeds each path
from the probe and sample index alone — so the two runs trace the same paths
and the subtraction that isolates the aperture carries no sampling residual.
## Lighting scenarios
A volume holds one bake, so a scene lit for noon cannot become a scene lit for
dusk without baking again — which takes far longer than a transition is allowed
to. Capture each bake under a name and blend the captures:
```lua
local scenarios = require("@builtin::systems.globalIllumination.scenarios")
-- light the scene for noon, bake, then:
scenarios.capture(volId, "noon")
-- light it for dusk, bake again, then:
scenarios.capture(volId, "dusk")
scenarios.blend(volId, { noon = 0.25, dusk = 0.75 })
```
`LightingScenario.component` is the authored form of the two-state case: name a
`from` and a `to` and drive `blend` from 0 to 1.
Irradiance adds, so blending the SH coefficients is the same as blending the
light that produced them. Each coefficient's fourth lane carries the probe's
per-axis visibility reach rather than light, and is taken whole from the
heaviest-weighted scenario — the mean of two distances describes no wall that
exists.
## A bake stays true to its scene
A bake is a photograph of a moment. Move a baked wall and its lightmap
goes on describing where the wall used to be — the shadow it cast stays
painted on the floor it no longer touches.
So a bake maintains itself. `BakedLighting` watches the engine's
authored-change feed (`layers.onEntityChanged`) and reacts the moment an
edit reaches the bake: the artifacts that described the old scene are
dropped, the withheld lights come back, and the scene re-bakes once the
edits settle. The bake attaches that component itself, so a scene that
has been baked is a scene that maintains its bake — there is nothing to
remember to run.
Dropping the artifacts (rather than flagging them) is what makes the
staleness visible: the viewport goes from baked to honest realtime light
the moment the edit lands.
Static geometry and every light the bake consumes reach it. Movable geometry
and dynamic lights never entered one, so editing them reaches nothing.
`BakeState.affects` is the answer, measured against a signature of what
the bake actually reads — which is also why the bake writing its own
bookkeeping back onto the entities it just baked cannot re-trigger it.
Turn off automatic re-baking (invalidation stays) with:
```luau
entity.find("scene").component.add("BakedLighting", { autoBake = false })
```
## Seeing the bake
Baked lighting is the one thing in a scene with no silhouette — texels on
surfaces and coefficients in a grid — so "did this actually capture the
room?" is otherwise a question you answer by reasoning rather than by
looking. Two overlays answer it directly, in the editor's Visualization
panel:
- **Baked Probes** — every baked probe drawn where it sits, tinted by the
light it captured, inside its volume's bounds. Light falling off through
the volume becomes visible and a dead probe reads as a black dot.
Displayed on a gamma curve: indirect light spans orders of magnitude, so
a linear scale against the brightest probe would draw most of a room as
black and claim a good bake captured nothing.
- **Lightmapped Surfaces** — a box around every surface currently drawing
baked texels, so lightmapped and probe-lit geometry are told apart at a
glance.
Both appear in the panel only while the scene holds what they draw. An
unbaked scene lists neither; baking makes them appear. That comes from
`debugViz.registerProvider(name, fn, { label, default, available })` — a
package contributes an overlay and declares when it has something to
show, without the debug driver needing to know it exists.
## How a bake works
1. `Baking.gatherMeshInstances` collects every static mesh-bearing
entity as `{ guid, transform, attributes }` — the attributes carry
the surface's linear albedo (base_color × average base-color texture
color) and emissive, read through the material's own asset behavior.
2. `compute.buildBvh` builds the scene BVH engine-side and uploads the
node + triangle buffers; each triangle carries its instance's
attributes, so the kernels know how every surface reflects and emits.
3. The bake kernel runs one thread per texel (lightmaps) or probe
(volumes). Each thread traces `samples` paths of up to `bounces`
surface interactions, with shadowed next-event estimation at every
vertex and sky on escape.
4. The work is planned, not dispatched whole. `Baking.planChunks` splits it
into dispatches that each stay inside a per-frame ray budget
(`Baking.RAY_BUDGET_PER_FRAME`, 2^20 estimated ray traversals), sized from
a cost model (`Baking.lightmapRays`, `Baking.probeRays`: a lightmap texel
spends `17 + 64 * direct + 64` rays on direct light and contact occlusion
and `bounces * (1 + lights)` per chain; a probe spends `bounces * (1 +
lights)` per sample). Each dispatch carries its stage and range in the
kernel's `params` uniform, and the running sums live in the bake buffer
between dispatches, so how the work was split does not change the result.
5. A `Baking.newGpuScheduler` issues the dispatches, one per pass, a frame's
worth at a time. It waits for the kernels to compile first, ends each frame
with a fence (a read of a one-vec4 buffer the batch records after the
frame's dispatches), keeps at most `Baking.MAX_FRAMES_IN_FLIGHT` fenced
frames queued, and checks the render device on every wait. A device that
was lost or replaced raises `[Bake] the render device was lost during the
bake` with what the device reported (`renderer.deviceErrors`), and
releases what the pass made. The budget bounds each frame, not the bake: a
bake of billions of rays is hundreds of frames of work, which is what keeps
the device alive on an integrated GPU and in a browser.
6. A receiver lights up when its texels are read back with the resolve's
completion flag set. Its bake buffers (144 bytes a texel) are freed once the
texels are persisted, and a `bakeAll` starts a receiver only when what it
holds fits half the device's memory budget (`Baking.bakeLimits`).
### What a device bakes
`renderer.deviceLimits()` states the largest buffer, the largest storage
binding, the workgroups per dispatch and the memory budget the device affords.
The largest lightmap a bake makes is the largest power of two within the atlas
page whose bake output (64 bytes a texel) fits one storage binding (a baseline
WebGPU device binds 128 MiB, which holds a 1024 lightmap and a 2048 one needs
more) and whose bake (144 bytes a texel) fits the bake memory budget. A derived
resolution is cut there with a warning naming the limit; a pinned `resolution`
past it raises.
### When a bake fails
A bake raises with its cause: the stage, a lost device, a dispatch the engine
refused (a buffer past the storage binding limit is refused by name before it
can invalidate the frame's command buffer), an error the device reported. It
leaves nothing applied. `BakeState.rebake` drops the artifacts its stages left
and posts `bake.rebake_failed` instead of "baked lighting is current again";
`baking.all` raises naming each stage that failed; `VolumeProbe.autoPlace` raises naming
the volumes that failed when any did, and marks no light baked. A failed automatic re-bake holds
automatic re-baking until an explicit bake succeeds.
## Quick start
### Lightmap
```luau
local Lightmap = require("@builtin::systems.globalIllumination.lightmap")
-- Bake every static receiver in the world. Without `resolution` each surface
-- derives its own from its area at 32 texels per metre, rounded up to a power
-- of two and capped by what the device can bake.
Lightmap.bakeAll({ samples = 32 })
-- Pin a resolution (a power of two from 32 up to what the device bakes) and, when
-- a scene wants a different pace, the per-frame ray budget: a larger budget
-- finishes in fewer frames, a smaller one leaves more of each frame to the
-- editor.
Lightmap.bakeAll({ resolution = 128, samples = 32, rayBudget = 2 ^ 21 })
-- Bake a single static entity
Lightmap.bake(floorId, { resolution = 256, samples = 64 })
-- Tear down (frees the bake resources + restores the original material)
Lightmap.clear(floorId)
```
### Volume probes
```luau
local VolumeProbe = require("@builtin::systems.globalIllumination.volumeProbe")
-- Author a probe volume that covers a room
local vol = entity.spawn("level_probes")
vol.localPosition = { 0, 0, 0 }
vol.component.add("VolumeProbe", {
sizeX = 20, sizeY = 6, sizeZ = 20,
resX = 8, resY = 4, resZ = 8,
})
-- Bake: publishes the field renderer-wide and persists it into the
-- scene's baked-lighting container. Every entity inside the bounds
-- receives it — no per-entity binding.
VolumeProbe.bake(vol.id, { samples = 256 })
```
## What's static vs dynamic
| Quantity | Static at bake time | Dynamic per frame |
|---|---|---|
| Geometry positions / rotations | yes | no |
| Lights (positions, colour, intensity) | yes | no |
| Sky / ambient values | yes | no |
| Material base colour | no | yes (modulated against lightmap) |
| Object position (inside a probe volume) | n/a | yes (samples nearest probes each frame) |
Re-bake when any of the "static" inputs change. Lighting changes that
are too dynamic to bake (e.g. flickering torch) should be added on top
of the baked term as additional realtime lights.
## Engine integration
This package is Luau / WGSL over generic engine capabilities: compute
shader dispatch, `compute.buildBvh` (scene BVH with per-instance
attributes), component lifecycle, the renderer's irradiance-volume set
(`lighting.setProbeVolume`), and the baked-lighting container asset
(`lightmapData`).
## See also
- `man shaders` — the WGSL bind-group layout these shaders extend
- `man compute` — compute dispatch + buffer management
- `man /Light` — the Light component baked into the result
- `man /Material` — material registry that lightmaps and receivers extend
# Birds Eye Camera
Strict overhead camera — looks straight down (-Y world) and follows the target's X/Z position. No yaw, no pitch, no orbit; only `height` (zoom).
## Vs. the other top-down behaviours
| Behavior | What it does | When to pick it |
|---|---|---|
| `birds_eye` | locked overhead, follows target XZ only | tactical / map views, navigation overlays |
| `rts` | overhead with yaw + WASD pan + RMB rotate | strategy games where the user drives the view |
| `isometric` | fixed angle (not straight down) + WASD pan | classic isometric game-feel |
## Fields
| Field | Default | Notes |
|---|---|---|
| `inputMap` | `@builtin::inputMaps.cameraRig` | The map whose `zoom` control adjusts the height. Point it at a world's own map to rebind this camera. |
| `target` | unset | The entity to look down on: the entity, its id or its name. An entity reference, so a scene build that writes it names the entity the build placed. Falls back to `Camera.follow` when unset. |
| `height` | `25.0` | World-Y distance above target. |
| `minHeight` | `5.0` | Scroll-zoom lower bound. |
| `maxHeight` | `120.0` | Scroll-zoom upper bound. |
| `zoomSpeed` | `0.15` | Multiplicative per scroll tick (`exp(-scroll * zoomSpeed)`). |
| `smoothing` | `0.18` | Share of an offset change left after one second. `0` snaps, `1` never moves. The target's own motion carries the camera at any speed. |
| `offsetX`, `offsetZ` | `0.0` | Constant XZ offset added to the target's position. |
## Use as a camera behavior
```lua
-- World-default
world.camera_default = asset.ref("@builtin::controller.birds_eye")
-- Per-scene swap
layers.active.camera.behavior = asset.ref("@builtin::controller.birds_eye")
layers.active.camera.follow = layers.active.players.localPlayer
```
The component carries the `cameraBehavior` tag in `.metadata`, so the slot validation in `Camera.behavior = ref` will accept it.
## Controls
- **Scroll** — adjust height (zoom in/out)
- No rotation, no panning — the target moves; the camera just follows.
# PlaneHold
Planar physics: holds bodies to a plane (a plane lock for every body it covers), the way a side-on 2D or 2.5D physics game (a bridge builder, a platformer, a pinball table, a side-scrolling vehicle game) keeps everything in one plane of a 3D world. Each dynamic rigid body it covers moves along the plane and turns only about its normal, under collisions, joints, impulses and velocities set from code; each soft body it covers keeps its particles on the plane. A body is put on the plane when the hold takes it, and a body spawned later into what the hold covers is held from its first step.
Public fields:
- `normal` (default `{ 0, 0, 1 }`, the XY plane of a side view) and `point` (default the origin): the plane, in world space.
- `covers`: `"subtree"` (default: this entity's body and every body under it; a piece torn off a soft body under it stays held), `"group"` (every body whose collision membership shares a bit with `groups`; a body with no `CollisionGroup` belongs to every group) or `"world"` (every body).
- `groups` (default `0xFFFFFFFF`): the collision groups a `"group"` hold covers.
- `free` (default `false`): the hold covers its bodies with no plane, so a body or a subtree leaves a hold further out.
Disabling the component (`.enabled = false`, the flag every component carries) switches the hold off: the bodies it held move freely from the next step, and enabling it again holds them again.
The nearest hold wins: a subtree hold on the body or its nearest ancestor, then a group hold, then a world hold. A plane a `SoftBody` states for itself (`plane`) stands over every hold. `Physics.planeHold(id)` reads which plane holds a body and where that hold stands.
```luau
-- a side-view level: every body under it stays in the XY plane
level.component.add("PlaneHold", { normal = { 0, 0, 1 } })
-- every body in the world held to the plane x = 2
holder.component.add("PlaneHold", { covers = "world", normal = { 1, 0, 0 }, point = { 2, 0, 0 } })
-- one crate leaves the plane
crate.component.add("PlaneHold", { free = true })
-- build phase free, simulate phase held
level.component.get("PlaneHold").enabled = false
```
# FirstPersonBody
Draws the body under this entity the way its avatar's `firstPerson` annotations say, for a
camera seated in the body (or a headset's eyes seated in it) and for every other view. An avatar whose `avatar.json` states
`firstPerson` (every avatar a VRM imports to) gets this component when it is instantiated or
worn, on every peer.
```luau
root.component.add("FirstPersonBody", { avatar = asset.resolve("my_vrm", "avatar") })
cam:seatIn(root) -- controller.first_person does this for the entity it rides
local s = root.component.get("FirstPersonBody"):stats()
print(s.seated, s.thirdPerson, s.firstPerson, s.hidden, s.split, #s.copies)
```
- `avatar` (synced): the avatar whose `firstPerson` annotations it applies.
- `firstPerson` (synced): the annotations applied when no avatar is set, in the same form.
## Where each mesh is drawn
| Annotation | A camera seated in the body | Every other view |
|---|---|---|
| `both` | drawn | drawn |
| `thirdPersonOnly` | left out | drawn |
| `firstPersonOnly` | drawn | left out, the cameras seated in other bodies included |
| `auto`, skinned | a copy with the first-person bone and every bone below it collapsed | drawn whole |
| `auto`, rigid, under the first-person bone | left out | drawn |
| `auto`, rigid, elsewhere | drawn | drawn |
A mesh no annotation names is `auto`. An annotation names a mesh by its name in the body; a
mesh with several primitives is an entity holding one child per primitive, and the
annotation reaches each of them. With no camera seated, nothing changes but that the
`firstPersonOnly` meshes are drawn by no view: they stay on `firstPersonHidden`, which every
camera leaves out until it names the layer.
The split rides three render layers, set in this engine only (`renderer.setLocalLayers`), so
the players who see the same body draw it whole and nothing is saved: `thirdPersonOnly`
holds what every view but the seated camera draws, `firstPersonOnly` what only the camera
seated in that body draws, and `firstPersonHidden` the `firstPersonOnly` meshes of a body no
camera of this engine is seated in. A camera whose `renderLayers` seeds `all` leaves out
`firstPersonOnly` and `firstPersonHidden` until it names them, and a camera seated with
`Camera:seatIn` also leaves out `thirdPersonOnly` and draws `firstPersonOnly`. A headset's
eyes seated in the body (`modules.firstPersonView.seatEyes`, which the XR presentation does
for the body it embodies) draw it the way a seated camera does.
`stats()` answers `{ applied, seated, bone, everywhere, thirdPerson, firstPerson, hidden,
split, copies, placements }`: the counts of the body's drawn parts by placement, the copies
the seated camera draws and each part's placement by its name.
# Latch
A latch point: a place on a body where it latches to a matching point on another body that comes within reach. A trailer hitch takes the coupler of a trailer backed onto it, two train cars couple on contact, a ship docks at a port lined up within an angle, a door catches as it swings shut, a magnet clicks onto a plate, a part snaps into a socket.
Public fields: `tag`, `accepts`, `offset`, `radius`, `maxAngle`, `maxSpeed`, `armed`, `lock`, `joint`, `partner` (written by the simulation).
Methods: `:release()`, `:onLatch(fn)`, `:onRelease(fn)`, `:latchJoint()`, `:state()`.
## When two points latch
The point is a frame: the entity's own frame, moved by `offset`. Put the Latch on the body itself, or on an entity under the body (a marker at the hitch ball, at a coupler, at a port), whose body the point rides on. After every physics step, two points latch when all of these hold:
- each `accepts` the other's `tag` (an empty `accepts` latches to points of its own tag, so two train couplers tagged `coupler` latch to each other);
- they ride on different bodies, both points are `armed`, and neither is latched;
- they stand within the larger of their two `radius` (metres);
- the turn that takes one frame onto the other is within the smaller of their two `maxAngle` (degrees; 180 latches turned any way);
- they close no faster than the smaller of their positive `maxSpeed` (m/s; 0 latches at any speed).
A point near several takes the nearest. The step that makes a latch joins the two with a Joint and the next step holds it.
## The joint a latch makes
The Joint is named `latch`, on the entity of the point that makes it, and holds the two frames together: point on point and turned alike. So lay out each point where, and turned as, its partner will stand once joined: a coupler marker on a trailer turned as the hitch marker on the truck is when the trailer stands straight behind it. Its fields come from `joint` (the making point's, else its partner's, else a fixed joint; the making point is the one `onLatch` names as `host`, so state `joint` on one point of a pair): any Joint kind and any Joint field but the anchors and ends the latch states, so a ball leaves the trailer free to swing, a hinge about `axis` leaves one turn free, a fixed joint docks, and `breakForce` / `breakTorque` make a catch that bursts open. It reads like any joint: `:latchJoint()` returns it, and `Physics.jointReaction`, `Physics.jointState` and `Physics.bodyState(id).joints` take it.
## Releasing, breaking, latching again
- `:release()` (or `Physics.releaseLatch(id)`) takes the joint off and frees both points. `lock = "permanent"` on either point refuses it: the latch holds until its joint breaks or a point is removed.
- Taking the latch's Joint off by hand (`Physics.removeJoint(latch:latchJoint())`) releases the latch too, with reason "release".
- A latch joint past its `breakForce` / `breakTorque` frees both points.
- Removing a Latch, or its entity, frees its partner on the next step.
A freed point latches again once it has stood clear of every point it latches to, so pulling a trailer away and backing it in again hitches it again. `:onLatch(fn)` and `:onRelease(fn)` hear each latch and each release (`reason` "release", "break", "removed" or "refused"); `Physics.onLatch` and `Physics.onUnlatch` hear every latch in the world.
## Refused
A Latch refuses, naming the field: an empty `tag`, an `accepts` entry that is not a tag, a negative `radius`, a `maxAngle` outside 0 to 180, a negative `maxSpeed`, a `joint.kind` that is not a name, a `joint` stating `connected`, `target`, `name`, `localAnchor` or `remoteAnchor`, and a second, named Latch on one entity. Added with one of these it does not start; written live, the field keeps the value it held and `:errors()` names why. `:state().problem` names a point with no body at or above it, or on a soft body. A latch whose `joint` the Joint refuses (a kind no Joint has, a rope with no `maxDistance`) is not made: both points are freed and `onRelease` hears reason "refused" with the Joint's `error`.
## Cost, determinism, multiplayer
Each step places every latch point on its body and sorts them into a grid of cells as wide as the widest reach, comparing each point with the points of the 27 cells around it: the cost per point per step is one placement, one grid insertion and a comparison with each point within three cells of it, the same however many points stand further away, and a world with no Latch does no work. The widest reach sets the cell for every point, so keep a point's `radius` to the reach it latches at. The pairs are taken nearest first, ties in the order the points' entities were made, so two engines running the same scene latch the same pairs on the same step. The latch is made on the peer that simulates both bodies; its Joint and `partner` reach every peer. A point on a body another peer simulates is that peer's to latch, so two points whose bodies two different peers simulate do not latch.
```luau
-- a truck's ball hitch and a trailer's coupler: back the trailer in and it hitches
local hitch = entity.spawn("hitch", { parent = truck.id, position = { 0, 0.5, -2.6 } })
hitch.component.add("Latch", { tag = "hitch", accepts = { "coupler" }, radius = 0.15, joint = { kind = "ball" } })
local coupler = entity.spawn("coupler", { parent = trailer.id, position = { 0, 0.5, 2.1 } })
coupler.component.add("Latch", { tag = "coupler", accepts = { "hitch" } })
coupler.component.get("Latch"):onLatch(function(e) print("hitched", e.distance) end)
-- release, drive away, back in again: it hitches again
coupler.component.get("Latch"):release()
-- a door catch that bursts open past 4000 N
catch.component.add("Latch", { tag = "catch", radius = 0.05, maxAngle = 5, joint = { kind = "fixed", breakForce = 4000 } })
```
# CompoundCollider (component)
One collision shape built from many box children, sharing a single broadphase
volume and a single material.
## When to reach for it
| Situation | Use |
|-----------|-----|
| A handful of shapes, each wanting its own material or trigger flag | Separate collider components on child entities |
| Many boxes sharing one material, such as a voxel chunk or a destructible wall | `CompoundCollider` |
The difference is cost. Separate collider components are one broadphase entry
each; a compound is one entry for the whole set, with contacts still resolved
per child. That crossover is what makes a compound the right answer for a voxel
chunk and the wrong one for a character's head.
## Children
Each child is `{ offset = vec3, half = vec3 }` in the entity's local space. The
whole set scales with the entity's transform.
```lua
entity.find("chunk").component.add("CompoundCollider", {
children = {
{ offset = { 0, 0, 0 }, half = { 0.5, 0.5, 0.5 } },
{ offset = { 1, 0, 0 }, half = { 0.5, 0.5, 0.5 } },
},
})
```
## Fields
| Field | Meaning |
|-------|---------|
| `children` | The box set. |
| `isTrigger` | Report overlaps without blocking, for every child. |
| `friction` | Surface friction, shared by every child. |
| `restitution` | Bounciness, shared by every child. |
| `rollingResistance` | How strongly the surface resists a body rolling on it: a rolling body slows at this many times gravity on level ground, so a ball rolled at v stops after v^2 / (2 * rollingResistance * 9.81). 0 rolls on. |
| `spinningResistance` | The same for a body spinning on the surface about the contact normal. 0 spins on. |
| `surface` | The surface the collider is made of, by name: one `Physics.defineSurface` defined gives it its friction, restitution and resistances in place of the fields above, and contacts, contact events and ray and shape casts report the name either way. Empty names none. |
| `oneWay` | The direction, in the collider's own frame, bodies pass through it along: a body moving that way goes through, and a body meeting it from the side the direction points to stands on it (a jump-through platform is `{0, 1, 0}`). `Physics.passThrough(entity)` drops a standing body through. Unset blocks from every side. |
| `surfaceVelocity` | The velocity, m/s in the collider's own frame, its surface moves at along itself while the collider stays put: friction carries what rests on it (a conveyor belt, a treadmill, an escalator). Write it at runtime to change the speed or direction. Unset holds the surface still. |
| `contactTag` | The tag the world's contact filter reads this collider by: `Physics.setContactFilter(tagA, tagB, mode)` makes two tags pass through each other (`"ignore"`), report contacts and push nothing (`"sensor"`) or collide (`"solid"`). Empty names none. |
# third_person
Third-person camera controller. Orbits behind/above a target entity. Right-click drag to rotate around the target, scroll to zoom. Falls back to a static center if no target.
Public fields: `target`, `centerX`, `centerY`, `centerZ`, `height` (vertical offset above target origin), `distance`, `minDistance`, `maxDistance`, `sensitivity`, `zoomSpeed`, `minPitch`, `maxPitch`, `yaw` (exposed for parent scripts).
Controls: RMB drag to orbit while nothing else in the world binds the right
button, scroll to zoom.
```luau
entity(id).component.add("third_person", { target = "player", distance = 5 })
```
# Physics
Adds rigid body dynamics to an entity. Body kind is `"dynamic"` (affected by forces), `"static"` (immovable), `"kinematic"` (placed by script at the pose its transform holds) or `"kinematicVelocity"` (carried by the solver at the velocity script gives it with `Physics.setVelocity`). Both kinematic kinds push dynamic bodies and are not pushed back.
Public fields: `kind`, `gravityScale`, `mass`, `linearDamping`, `angularDamping`, `ccd`, `interpolation`, `lockRotationX/Y/Z`, `lockTranslationX/Y/Z`, `dominance`, `canSleep`, `sleepLinearThreshold`, `sleepAngularThreshold`, `centerOfMass`, `inertia`, `softCcd`, `extraSolverIterations`, `extraPgsIterations`. Every field reaches the solver on the next step when written, and `Physics.bodyState(id)` reads each back as the solver holds it. A value outside what a field takes is refused with an error naming the field.
`dominance` (-127 to 127) decides who pushes whom between dynamic bodies: a body in a higher group pushes one in a lower group and is not pushed back, the way a player character shoves crates without slowing. Bodies in one group push each other as usual.
`canSleep = false` keeps the body simulated every step however slowly it moves (a probe coasting in zero gravity, a vehicle idling at rest); `sleepLinearThreshold` (m/s at the body's farthest point, default 0.05) and `sleepAngularThreshold` (rad/s, default 0.5, for a body with no colliders) set how still it must stay for half a second before it sleeps. `Physics.sleep(id)` puts a body to sleep at once.
`centerOfMass` (local, metres) and `inertia` (principal moments, kg·m²) replace the values the colliders give the body; leave them unset to derive them. A car body with `centerOfMass = { 0, -0.5, 0 }` resists the roll that tips it with the derived centre.
`softCcd` (metres) predicts contacts that far ahead of the body each step, which catches a fast body before it passes through a thin wall at a fraction of the cost of `ccd`. Set it to about the distance the body travels in one step (speed / tick rate).
`extraSolverIterations` and `extraPgsIterations` (0 to 16 each) stiffen one structure without raising the solver world-wide: the island the body is part of (everything jointed to it or touching it) runs the world's `solverIterations` plus the largest extra substeps any of its bodies asks for, and the world's `pgsIterations` plus the largest extra passes. A body held under a heavy load by impulse joints (a light link of a chain holding a heavy block) also asks its island for substeps short enough to hold it stable, which `Physics.bodyState(id).solvedSubsteps` reads. Put the same values on every member of a bridge, a chain or a ragdoll; the island's step costs about that many more substeps, and the rest of the world costs what it did.
`ccd` (continuous collision detection) sweeps the body along its motion so it cannot pass through thin geometry between two steps. It is off by default: the sweep runs on every body that travels further than its own thickness in one step — most of a collapsing structure or a debris burst — and it dominates the physics budget when a scene has many such bodies. Turn it on for the individual bodies that would visibly tunnel: bullets, thrown props, a wrecking ball.
```luau
entity(id).component.add("Physics", { kind = "dynamic", ccd = true })
```
A body on an entity under a parent lives in world space. It starts where its entity stands in the world, with the parent's position, rotation and scale applied, and a write to the entity's `position`, `localPosition`, `rotation` or `localRotation` places the body where that write puts the entity, in the same call: a ray cast right after the write meets it there. The one exception is a `kinematic` body while the clock runs: the write aims it, and the next step sweeps it there, carrying the dynamic bodies in its path. While the clock runs, the solver moves a `dynamic` or `kinematicVelocity` body and its parent does not carry it: moving or turning the parent leaves the body where the solver has it, and each step writes the entity's local transform from the body's pose, so the entity stays on the body. A `static` or `kinematic` body goes where its entity goes, its parent's moves included. With the clock held (edit mode, a paused session), every body goes where its entity goes. A change of parent that keeps the entity's local pose (`setParent` or `unparent` with `keepWorldTransform = false`) is a write of that kind: the entity's local pose read under its new parent (or as world, for `unparent`) places its body, every kind of body, whether the clock runs or is held, as a write to its `localPosition` does. The placement stops a `dynamic` body and leaves a `kinematicVelocity` body the velocity it was given; a `kinematic` body while the clock runs is aimed there, as for any write. `keepWorldTransform = true` leaves the entity where it stands in the world, and its body where it is, at the velocity it has. Colliders on the entity's children go with its body.
`mass` is the body's total mass in kilograms. At its default of 0 the mass comes from the space the body's solid colliders fill, at 1 kg per cubic metre, so a bigger collider makes a heavier body; a value greater than zero sets the total mass exactly. Either way the mass is spread evenly over that space: where two colliders overlap, the space they share is counted once, so a ball inside a box weighs what the box weighs, and a trigger (`isTrigger = true`) fills no space and adds no mass, inertia or shift of the centre of mass.
A body's colliders are the ones on its entity and on every entity beneath it that carries no `Physics` of its own, whatever order the components were added in: a collider added to a child before its parent got `Physics`, or a child moved under the body later, joins the body, and a child moved out from under it, or whose body's `Physics` is removed, stands alone as static geometry. The body's mass, centre of mass and inertia come from the shapes, poses and sizes of those colliders (a `mass` above zero is spread over them), so a car built from a chassis and child parts rolls and pitches the way its parts are laid out. `Physics.bodyState(id).colliders` lists them.
A body whose entity holds no collider is given a stand-in box: one fitted to the entity's model, or a 1 m box (half extents 0.5) when it renders none. It collides with everything and `Physics.bodyState(id).colliders` lists it. A collider component added to the entity replaces it, and the first solid collider (one that is no trigger) on an entity beneath the body takes its place as it joins the body, in the same frame when both are added together. A body whose colliders beneath it are still waiting for their mesh, or sit on an inactive entity, rests on the stand-in until one of them is built. The stand-in is given as the body is built: a built body whose last collider is removed or deactivated, or moves out from under it, holds no collider until another one joins it.
Methods: `:applyForce(x, y, z)`, `:applyImpulse(x, y, z)`, `:applyTorque(x, y, z)`, `:setVelocity(x, y, z)`, `:addVelocity(dx, dy, dz)`.
```luau
entity(id).component.add("Physics", { kind = "dynamic" })
entity(id).component.get("Physics"):applyImpulse(5, 0, 0)
```
# Light
Adds a light source to an entity. The entity's world transform determines the light's position, and a spot's aim: the cone axis is the entity's world rotation applied to `face`. A directional or distant light travels along `direction`. Point light positions are auto-synced from that world transform, so a light on a child entity burns where the entity stands — the position `entity.position` reports. A point light's `intensity` is on one scale with the `SpotLight` component's `intensity`/`brightness`: the same number at the same `radius`/`range` puts the same light on a surface either kind faces from the same place, and a spot spends it on the cone it opens on rather than all around itself. Distances are in metres and a point or spot light falls off by the inverse-square law: a surface facing the light 1 m away takes `intensity`, one at `d` metres takes `intensity / d^2`, so the same light gives 4 times as much at 0.5 m and a quarter as much at 2 m, and `radius` windows it smoothly to zero at the light's reach.
Kinds: `"point"`, `"spot"`, `"directional"` (the scene's sun), `"ambient"`, `"distant"` (a parallel light beside the sun).
Public fields: `kind`, `colorR/G/B`, `intensity`, `radius`, `directionX/Y/Z`, `face`, `angle`, `innerAngle`, `castsShadows`, `angularDiameter` (the disc size, in degrees, that sets how wide the sun's shadow penumbra grows with the distance from caster to receiver; 0.53 is the sun's and 0 draws a hard edge), `lightChannels`, `mobility`. `range`, `color` and `direction` are aliases accepting the composite/renamed forms.
Methods: `:setColor(color)` (color: `{r, g, b}` array or `{r=, g=, b=}` map), `:setIntensity(i)`, `:setRadius(r)`, `:setDirection(dir)`, `:setFace(face)`, `:setAngle(deg)`, `:setInnerAngle(deg)`, `:setKind(lightKind)`.
`kind = "spot"` opens a cone from the entity's position along its `face` (`"Front"` by default: the entity-local -Z that `transform.forward` reports and `entity:lookAt` aims; also `Back`, `Left`, `Right`, `Top`, `Bottom`), to the `angle` (outer, default 30) and `innerAngle` (inner, default 20) half-angles in degrees. These are the `SpotLight` component's fields, under the same names and with the same meanings. A spot aims by `face` and its entity's rotation, so a `direction` written to one is refused: `:setDirection` raises, an assigned `direction` keeps the value it held, and both name `face`. `"directional"` and `"distant"` are parallel lights: they arrive from the same direction at every point in the world and no distance attenuates them, so their `intensity` reads against the sun's rather than against a point light's. The `SpotLight` README carries the rest of how to balance a mixed point-and-spot rig.
```luau
entity(id).component.add("Light", { kind = "point", intensity = 2, radius = 10 })
entity(id).component.add("Light", { kind = "directional", direction = {-0.5, -1, -0.3} })
entity(id).component.add("Light", { kind = "spot", face = "Bottom", angle = 35, innerAngle = 25 })
```
# Part
Attach parts to the slots of another object: a wheel to a wheel mount, an
engine to an engine bay, a weapon to a hardpoint, a module to a socket.
`Part` declares the kinds of slot a part fits. Put it on the root of a bundle that
fills slots (a wheel, an engine, a seat, a turret, a wall module): the bundle
then fits every `Slot` whose `kind` its `fits` names. The declaration lives in
the bundle's template, so a part installed from another world's package fits
by kind the same way. Any other instantiable asset declares the kinds it fits
with a `fits` list in its `.metadata`.
## Fields
| Field | Type | Notes |
|---|---|---|
| `fits` | `{ string }` | The slot kinds this part fits. |
## Methods
| Method | Returns | Notes |
|---|---|---|
| `:fitsKind(kind)` | boolean | Whether `fits` names `kind`. |
## Usage
```luau
-- Author a wheel part and save it as a bundle
local wheel = entity.spawn("SportWheel")
wheel.component.add("Model", { model = "@builtin::meshes.cylinder" })
wheel.component.add("Part", { fits = { "wheel" } })
asset.create("bundle", "SportWheel", { entity = wheel })
```
`Assembly:candidates(path)` lists the bundles that fit a slot, and
`Assembly:fits(path, part)` says why one does not.
# 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.
# areaLights system
Lights that emit from a surface rather than from a point.
Every screen, neon sign, glowing window, ceiling panel and lantern face is an
area emitter. Standing a point light in the middle of one gets the brightness
roughly right and the character completely wrong: a point puts a pinpoint
reflection on the floor and a radial falloff on the wall, where the real thing
puts the shape of the emitter and a falloff that follows its extent.
## Using it
An emitter that should follow an entity's face is a component:
```lua
local id = entity.spawn("tv").id
entity(id).component.add("SurfaceLight", {
width = 2.0,
height = 1.2,
face = "front", -- front | back | up | down | left | right
intensity = 6.0,
range = 12,
})
```
The rectangle turns with the entity, so a tilted screen lights the direction it
actually points. Every field is live, and an `intensity` of 0 removes the light.
For code placing emitters directly:
```lua
local surfaceLight = require("@builtin::systems.areaLights.surfaceLight")
surfaceLight.set("strip", {
position = { 0, 5, -12 },
right = { 1, 0, 0 }, up = { 0, 1, 0 },
width = 0.6, height = 7,
color = { 1, 0.72, 0.35 }, intensity = 5,
})
surfaceLight.remove("strip")
surfaceLight.configure({ diffuse = 1, specular = 0.5 })
surfaceLight.clear()
```
## What the knobs do
| field | effect |
|---|---|
| `width` / `height` | Size of the emitting rectangle, world units. The shape of the light is the shape of this. |
| `face` | Which way the entity emits. |
| `range` | How far the light carries, with a smooth cutoff at the end. |
| `intensity` | Brightness. 0 removes the light. |
| `colorR` / `colorG` / `colorB` | Emitter colour. |
| `offset` | Distance the rectangle sits proud of the entity's origin, along the face's normal. |
| `diffuse` / `specular` | Scales on the two terms — the wash across a surface, and the reflected shape of the emitter. |
Shape is the point. A wide panel puts a broad pool on the floor; a narrow strip
puts a narrow elongated one. That difference is not reachable with a point
light at any brightness.
At most 32 emitters are held at once, because the shader loops every light for
every pixel.
## How it renders
`areaLighting.renderFeature` runs one compute pass after lighting. Diffuse is
the exact irradiance of the quad — Lambert's formula over its four edges — which
matters where a point approximation fails hardest: a wide emitter close to a
wall. Specular uses the representative point on the rectangle nearest the
reflection ray, with the lobe widened to cover the emitter's solid angle and its
peak scaled down to match, so a large emitter reads broader rather than
brighter.
## Files
```
areaLights.package/
SurfaceLight.component/ -- an emitter on an entity's face
surfaceLight.module/ -- the emitter registry and scales
areaLighting.renderFeature/ -- the compute pass
```
# controller.editor
The viewport camera you author from. It is the behavior on the editor scene's `EditorCamera` — a world's players never meet it, which is why it reads the editor's controls rather than a game's.
Rotates the pivot child exposed by a sibling `Player` component if present, otherwise rotates self.
Public fields: `moveSpeed`, `sensitivity`, `speedMin`, `speedMax`.
Controls come from the map on `inputMap`, `@builtin::inputMaps.editor` by default: `move` to fly, `flyVertical` to rise and drop, `look` to aim while flying, `zoom` (the wheel, turned over the Scene) to move the camera along the way it faces, or, while the right mouse button is held or the pointer locked, to set how fast it flies; `saveScene` (Ctrl+S) writes the scene being edited into its file. Rebind them by pointing `inputMap` at another map.
```luau
entity(id).component.add("controller.editor", { moveSpeed = 10 })
```
# WASDInput
Action-to-input-bus driver. Reads the `move` axis and `jump` action
each frame, remaps `move` to the active viewport camera's
forward/right basis (via `camera.main()` + `entity(camId).transform.forward`),
and writes the resulting world-space horizontal velocity to a target
component's input fields:
- `target.inputX`, `target.inputZ` — world-space velocity × speed
- `target.inputJump` — boolean, true while the jump action is held
Defaults to writing to `CharacterController` on the same entity, but
the field names are the contract — any component that exposes
`inputX/inputZ/inputJump` is a valid sink (vehicles, hovercraft,
custom CCs).
## Why generic
Independent of which camera is active and independent of the visual
layer:
- Works with any camera (third-person, top-down, FPS, fixed, vehicle).
- Works with no camera (falls back to world-axis WASD).
- Works without `Locomotion` or any animation system — CC moves,
visualization is opt-in.
- Works without a follow rig — `camera.main()` is the seam, not a
specific camera component.
## Public fields
| Field | Default | Purpose |
|---|---|---|
| `speed` | `5.0` | Multiplier on the unit-length input vector |
| `targetComponent` | `"CharacterController"` | Component to write `inputX/inputZ/inputJump` onto |
A custom control scheme is authored as an inputMap that rebinds the
`move` axis and `jump` action — not per-instance key fields on this
component.
## Example
```lua
-- Player with CC + WASDInput + any camera
entity(playerId).component.add("CharacterController")
entity(playerId).component.add("WASDInput")
-- Active viewport camera (any kind)
local cam = entity.spawn("cam", { parent = playerId })
cam.component.add("Camera", { fov = 60, priority = 0 })
cam.component.add("orbital_follow", { follow = playerId })
-- Press W → CC.inputX/inputZ are written camera-relative each frame
-- → CC translates the body → MovementState reports velocity →
-- (optional) Locomotion rotates the visible mesh + plays anims.
```
# Cinematic Camera
Wide-FOV, slow-easing follow with a configurable over-the-shoulder offset. Intended for cutscenes, dialogues, and walking moments where you want a more composed framing than `orbital_follow` and softer motion than `chase`.
The camera holds a right-shoulder offset relative to the target's facing and eases both position and look-at point as offsets from the target, so quick turns feel cinematic rather than jittery while the target stays framed at any speed: the smoothing softens a change of the framing, and the target's own motion carries the camera with it.
## Vs. the other follow cams
| | `orbital_follow` | `chase` | `cinematic` |
|---|---|---|---|
| Orbit (mouse) | yes | no | no |
| Framing ease | n/a | low (sticky) | high (cinematic) |
| Look-at ease | n/a | low | even higher than position |
| Composition | centered behind | locked behind | shoulder-framed |
| Best for | character action | vehicles, fast | cutscenes, walking, dialogue |
## Fields
| Field | Default | Notes |
|---|---|---|
| `target` | `""` | Entity ID. Falls back to `Camera.follow`. |
| `distance` | `4.5` | Trail distance behind target. |
| `height` | `1.8` | Vertical offset above target origin. |
| `shoulderX` | `0.6` | Right-shoulder offset (negative = left shoulder). |
| `fov` | `60.0` | Pushed once to the sibling `Camera` component on `awake`. |
| `positionSmoothing` | `0.35` | Share of a framing change left after one second. High = slow, cinematic. |
| `lookAtSmoothing` | `0.45` | Higher than position so framing reads as "anticipating". |
## Use as a camera behavior
```lua
world.camera_default = asset.ref("@builtin::controller.cinematic")
-- Or per-scene
layers.active.camera.behavior = asset.ref("@builtin::controller.cinematic")
layers.active.camera.follow = layers.active.players.localPlayer
```
The component carries the `cameraBehavior` tag in `.metadata`.
## Notes
- No user-driven rotation, no scroll-zoom — `cinematic` is set-it-and-let-it-frame.
- Swap `shoulderX` for a left-shoulder shot. Sign-flip in script for an interactive switch.
- Pairs especially well with `humanoid_visual` + `standard_controller` for narrative gameplay.
# controller.side_scroller
Side-scroller camera controller. Fixed-offset camera that follows a target from the side (classic 2.5D perspective). Maintains a constant position relative to the target and looks slightly ahead.
Public fields: `target`, `centerX`, `centerY`, `centerZ` (fallback), `offsetX`, `offsetY`, `offsetZ` (camera offset from target), `lookAheadX`, `lookAheadY`, `lookAheadZ` (look-at offset from target).
Controls: none — follows the target automatically.
```luau
entity(id).component.add("controller.side_scroller", { target = "player", offsetX = -8, offsetY = 3 })
```
# controller.first_person
First-person camera controller. Positions the camera at an entity's location (+ eye-height offset) and rotates with mouse look.
It resolves its follow target in this order: its own `target` field, then `Camera.follow` when `target` is unset, then the static `posX/posY/posZ` when neither is set. `Camera.follow` is the standard slot every behavior reads, so a first-person camera selected through `Camera.behavior` tracks whatever `Camera.follow` points at, the correct source for a player camera, whose body id is minted fresh per spawned clone and cannot be authored onto the behavior ahead of time.
Public fields: `target` (the entity to follow: the entity, its id or its name, kept as an entity reference; unset uses `Camera.follow`, then `posX/Y/Z`), `posX`, `posY`, `posZ`, `offsetX`, `offsetY` (eye height above target origin), `offsetZ`, `sensitivity`, `minPitch`, `maxPitch`.
Controls: pointer lock to rotate (yaw + pitch), which the standard scheme
takes while the world runs. With the cursor handed back, an RMB drag rotates
too — for as long as nothing else in the world binds the right button.
```luau
-- Track the Camera's follow target (set Camera.follow, no id authored here):
entity(id).component.add("controller.first_person", { offsetY = 1.6 })
-- Or a static camera at a fixed position:
entity(id).component.add("controller.first_person", { posX = 0, posY = 1.6, posZ = 3 })
```
# ParentConstraint
Copies the full transform (position + rotation + scale) from a target entity — like parenting but without hierarchy. The entity stays independent in the scene tree.
Public fields: `targetEntityId`, `axisX`, `axisY`, `axisZ`, `weight`.
Methods: `setTarget(entityId)`, `setWeight(w)`.
```luau
entity(id).component.add("ParentConstraint", {
targetEntityId = playerId,
weight = 1.0,
})
```
# PlayerNameLabel
Drives this entity's `Text3D` with the owning player's name, read from the nearest ancestor `PlayerAvatar`'s synced `displayName` so every peer renders the same name without a local registry lookup. The label re-rasterises when the display name changes, and in play it hides itself on the local player's own avatar, since name labels exist so other players are identifiable. A label shows a name or nothing: an avatar with no `PlayerAvatar` (a stock avatar placed as a non-player character) or one whose `displayName` is empty has its label's text emptied and the label hidden.
Location: `src/lua/lib/components/PlayerNameLabel.component`
# Joint
Connects two bodies with a joint constraint: the hinges, pins, ropes, springs and sliders that mechanisms and structures are made of, from a door, a chain or a ragdoll to a bridge, a truss or a tower that bends, shows its stress and breaks under load. Each end is a rigid body (an entity with `Physics`) or a soft body (an entity with `SoftBody`).
The engine solves joints inside its physics step, measures the load each one carries (tension or compression along a member, shear, bending; `Physics.jointReaction` / `Physics.jointReactions` read it) and breaks one when that load passes its `breakForce` / `breakTorque` (`Physics.onJointBreak` reports it), so a structure of members pinned at shared nodes bends, reports where it is overloaded and collapses inside the engine's own step.
Joint kinds: `"fixed"`, `"hinge"`, `"ball"`, `"prismatic"`, `"spring"`, `"rope"`, `"generic"`, `"rail"`.
Two bodies that join on their own when matching points come within reach (a trailer hitch, train couplers, a docking port, a door catch) take a `Latch` on each point: the step makes the Joint the Latch states and frees it on a release or a break.
Public fields: `kind`, `connected`, `localAnchorX/Y/Z`, `remoteAnchorX/Y/Z`, `axisX/Y/Z`, `remoteAxisX/Y/Z` (`remoteAxis`), `collideConnected`, `limited`, `limitMin`, `limitMax` (`minAngle`, `maxAngle`), `swingLimit`, `twistLimit`, `motorMode`, `motorTarget`, `motorVelocity`, `motorStiffness`, `motorDamping`, `motorMaxForce`, `motorModel`, `lockedAxes`, `axisLimits`, `axisMotors`, `stiffness`, `damping`, `restLength`, `maxDistance`, `yieldForce`, `yieldTorque`, `reelSpeed`, `breakForce`, `breakTorque`, `region`, `remoteRegion`, and a rail's `path`, `closed`, `ends`, `curve`, `tolerance`, `friction`.
`connected` is the other body: write the entity or its id, and it reads back as the entity; a name written into it is kept as written and found when the joint is built. It is an entity reference, so a Joint a scene's `build.luau` writes between two entities the build spawns (`connected = post` or `connected = post.id`) names the entity the build placed, through every rebuild, save, load and play.
```luau
-- scenes/main.scene/build.luau: a plank bridge, each plank hinged to the one before
function content()
local prev = entity.spawn("bank", { position = { 0, 2, 0 } })
prev.component.add("Physics", { kind = "static" })
prev.component.add("BoxCollider", { half = { 0.5, 0.25, 1 } })
for i = 1, 10 do
local plank = entity.spawn("plank" .. i, { position = { i, 2, 0 } })
plank.component.add("Physics", { mass = 2 })
plank.component.add("BoxCollider", { half = { 0.45, 0.05, 1 } })
plank.component.add("Joint", { connected = prev, kind = "hinge", axisZ = 1, axisY = 0, localAnchorX = -0.5, remoteAnchorX = 0.5 })
prev = plank
end
end
```
Methods: `:setMotor(targetVelocity, maxForce)`, `:onBreak(fn)`, `:isBroken()`, `:breakEvent()`, `:reattach()`, `:state()`, `:reaction()`, `:jointEntityId()`.
## Several joints on one body (trusses, hands, two-handed holds)
A body takes any number of joints. The first `Joint` on an entity has no name; add each further one under a `name` of its own, or with `Physics.addJoint`, which names it (`joint2`, `joint3`, ...) and returns it. Each is its own solver joint: its own kind, anchors, limits, motor, break thresholds, reaction, state, break record and removal.
A `Joint` on an entity that is no body itself (a marker parented under a beam's end, a hand under an arm) joins the nearest body above it, at that entity's position and orientation, with its anchor and axis measured in the entity's own frame. `connected` may name such an entity too, so two beams are pinned end to end through a marker on each. A joint that cannot be built says why in `:errors()`: an end with no body at or above it (a collider with no `Physics` is static geometry: give it `Physics { kind = "static" }` to join a joint to it), a `connected` id no entity carries, or both ends on one body.
```luau
-- a beam pinned at both ends
beam.component.add("Joint", { connected = leftPost.id, kind = "hinge", axisZ = 1, axisY = 0, localAnchorX = -2 })
beam.component.add("Joint", { name = "right", connected = rightPost.id, kind = "hinge", axisZ = 1, axisY = 0, localAnchorX = 2 })
-- a hand holding a crate on top of the arm joint the hand already carries
local grab = Physics.addJoint(hand, crate, { kind = "fixed", breakForce = 2000 })
Physics.jointReaction(grab) -- this joint's load alone
Physics.removeJoint(grab) -- let go; the arm joint stays
```
`Physics.jointState`, `Physics.jointReaction`, `Physics.setJointMotor` and `Physics.removeJoint` take the Joint itself, or an entity and the Joint's name. A break record's `entityId` and `joint` name the entity and the Joint that broke, and `Physics.bodyState(id).joints` lists each joint a body is in the same way.
`:reaction()` reads the joint's load (its stress) the way a structure is read: `axial` along the member at this body's end (tension positive, compression negative), `connectedAxial` at the other body's, `shear`, `bending`, `torsion`, a rope's or spring's `tension`, and `load`, the share of `breakForce` / `breakTorque` it stands at. `Physics.jointReactions(joints)` reads a whole structure's joints in one call, and `Physics.listenJointLoads(joints)` keeps each joint's peak between two reads; the physics guide's "Reading a joint's load" covers both, with a stress-colouring recipe.
## Joint frames, limits and motors (doors, ragdoll joints, sliders, 6DOF)
Each body carries a joint frame at its anchor, its X axis along `axis` (this body) or `remoteAxis` (the connected body; zero takes `axis`). `linX` / `linY` / `linZ` are travel along the frame's axes and `angX` / `angY` / `angZ` turns about them; zero is where the two frames coincide. The frame's Y and Z are the body's own carried by the shortest turn taking its X onto `axis` (`axis = {0, 1, 0}` puts the frame's Y along the body's -X). An axis reads positive as this body travels along it or turns right-handed about it, relative to the connected body.
- **Hinge range**: `limitMin` / `limitMax` in degrees (a prismatic's travel in metres). Writing either turns `limited` on.
- **Ball cone**: `swingLimit` is the half-angle in degrees the axis swings inside, `twistLimit` how far it twists either way; negative (the default) leaves each free.
- **Any axis**: `axisLimits = { angZ = {-30, 30}, linY = { min = 0, max = 0.5 } }`.
- **Motor**: `motorMode = "velocity"` holds `motorVelocity` (rad/s or m/s); `motorMode = "position"` pulls toward `motorTarget` (degrees or metres) with `motorStiffness` / `motorDamping`; neither applies more than `motorMaxForce` (0 uncapped). It drives a hinge's angle, a prismatic's travel, each angle of a ball joint and every free axis of a generic joint; `axisMotors = { angX = { mode = "velocity", velocity = 2, maxForce = 50 } }` drives single axes. `:setMotor(v, maxForce)` and `Physics.setJointMotor` set the same fields.
- **Contacts**: `collideConnected = false` stops the two bodies colliding with each other (limbs, links, parts overlapping at the joint).
- **Generic**: `kind = "generic"` holds the axes `lockedAxes` names (`{ "linX", "linZ", "angX", "angY", "angZ" }` leaves a slider along `linY`).
Every field is live: write it on the running joint and the next step uses it. `Physics.jointState(id)` reads the angle, travel, swing and twist, velocity, `atLimit`, and the force the limit and motor applied.
```luau
-- a door that opens 0 to 110 degrees, closed by a capped motor
door.component.add("Joint", { connected = frame.id, kind = "hinge", axis = {0, 1, 0}, limitMin = 0, limitMax = 110 })
local joint = door.component.get("Joint")
joint.motorMode = "position"; joint.motorTarget = 0; joint.motorMaxForce = 50
-- a shoulder on a cone that does not collide with the torso
arm.component.add("Joint", { connected = torso.id, kind = "ball", swingLimit = 70, twistLimit = 30, collideConnected = false })
```
```luau
entity(id).component.add("Joint", {
connected = frameEntityId,
kind = "hinge",
axis = {0, 1, 0},
})
```
## Springs: `stiffness`, `damping`, `restLength`
A `"spring"` joint pulls its two anchors toward `restLength` metres apart with `stiffness` (newtons per metre of stretch) and resists the speed its length changes at with `damping`. Left out (the fields read `-1`, the kind's own), `stiffness` is 100 and `damping` 10, and `restLength` is the distance the anchors stood at when the joint was built. Writing `restLength` on the live joint moves where it settles, and writing a negative one keeps the length it rests at.
A hinge, ball, prismatic or generic joint moves freely about its axes unless a limit or a motor holds it: its `stiffness` and `damping` default to none (the fields read `-1`, the kind's own). Set on one with no `motorMode`, they are a spring pulling each of its axes (a hinge's angle, a prismatic's travel, each angle of a ball joint, every free axis of a generic joint) back to where its frames align, read per unit of acceleration. A `motorMode = "position"` motor with `motorTarget` pulls toward any other position.
```luau
-- a bungee: two bodies held 5 m apart by a soft spring
a.component.add("Joint", { connected = b.id, kind = "spring", restLength = 5, stiffness = 200, damping = 20 })
-- a self-closing door: a hinge with a spring back to its closed angle
door.component.add("Joint", { connected = frame.id, kind = "hinge", axis = {0, 1, 0}, stiffness = 20, damping = 4 })
```
A `"rope"` joint is a maximum-distance limit solved inside the physics step: the bodies move freely while the anchors are closer than `maxDistance` (slack rope) and are held from separating beyond it (taut rope). It requires `maxDistance > 0`, and `maxDistance` is live: writing it on the running joint retunes the limit in place.
Without a `yieldForce` the rope holds at any force: lengthening it lets the load drop, and shortening it reels any load in at the solver's correction speed (3 m/s), however heavy. A rope given a `yieldForce` winds in at its `reelSpeed`, pulling with at most that force.
## Giving way and holding again: `yieldForce`, `yieldTorque`
`yieldForce` (newtons) is the most force a joint holds its travel with, and `yieldTorque` (newton-metres) its angles. While the load needs more, the joint gives way at exactly that force or torque; once the load falls below it, the joint holds again wherever it then stands. It keeps working throughout: only `breakForce` / `breakTorque` break a joint. 0 (the default) holds without bound.
- **Rope** (`yieldForce`): pays out. `maxDistance` grows to the length the rope gave way to and reads back as it stands, so the rope holds the load from there once it is light enough. Writing a shorter `maxDistance` winds the load in at `reelSpeed` (metres per second, 1 by default), slowing to arrive, pulling with at most `yieldForce` (a winch with a slip clutch, a tow rope taken up): it gains the full shortening when its load is below the yield, and pays out instead, holding from where it went, when the load is above it. A shock load (a body falling onto the rope) pays out as it brakes.
- **Prismatic** (`yieldForce`), **hinge** (`yieldTorque`), **ball** (`yieldTorque`), **generic** (`yieldForce` on its free travels, `yieldTorque` on its free angles): the axes hold still below the yield and slide or turn at it above (a friction slider, a breakaway barrier, a slip clutch on a drum, a stiff hinge). The axes take one of a yield, a motor or a `stiffness` spring; a motor capped by `motorMaxForce` is the yield that drives somewhere.
`:state()` (`Physics.jointState`) reads `slipping`, true while the joint gave way over the last step, and a rope's `length`; `:reaction()` reads the force it carries, which stands at the yield while it slips. A rope's payout is stated on its carrying entity as the `joint.length` named value too. A negative yield, or a `reelSpeed` of 0 or less, is refused naming the field: `Physics.addJoint` raises it, and a live write keeps the value the joint holds and reports it in `:errors()`.
```luau
-- a winch rope that holds 3000 N: a heavier load pays it out, a lighter one is reeled in
local rope = Physics.addJoint(hook, load, { kind = "rope", maxDistance = 4, yieldForce = 3000 })
rope.maxDistance = Physics.jointState(rope).length - 1 -- reel in a metre
print(Physics.jointState(rope).slipping, Physics.jointReaction(rope).tension)
-- a crash barrier that holds a 20 kN push and slides at it above
Physics.addJoint(barrier, post, { kind = "prismatic", axis = {1, 0, 0}, yieldForce = 20000 })
```
```luau
entity(ballId).component.add("Joint", {
connected = hookEntityId,
kind = "rope",
maxDistance = 8,
})
```
A soft body end is anchored on the body as a whole (its frame, the rigid motion that best fits its particles), or on a region of its particles: `region` for this entity, `remoteRegion` for the connected one, each `{ box = { min, max } }` (every particle between the corners) or `{ nearest = point }` (the one particle nearest the point), in the entity's unit box (-0.5 to 0.5 on each axis) unless `space = "world"`. A region end's anchor is measured from the centre of its particles. Motors, `breakForce` / `breakTorque` and `Physics.jointReaction` work the same at either kind of end, and the joint is removed with either body.
```luau
-- a soft punching bag hung by its top particle from a fixed hook
bag.component.add("Joint", { connected = hook.id, kind = "ball", region = { nearest = { 0, 0.5, 0 } } })
-- two jellies held face to face, breaking under 200 N
a.component.add("Joint", {
connected = b.id, kind = "fixed", breakForce = 200,
region = { box = { min = { 0.4, -0.5, -0.5 }, max = { 0.5, 0.5, 0.5 } } },
remoteRegion = { box = { min = { -0.5, -0.5, -0.5 }, max = { -0.4, 0.5, 0.5 } } },
})
```
A hinge's turn can be a part of a `ShaftNetwork`: `{ name = "drum", joint = drumEntity }` couples it to motors, gears, clutches, brakes and other hinges (a winch, a crane's slew, a geared contraption, a propeller on a shaft), the network's torque acting on the joint's body about its axis and, opposite, on the connected body. The `ShaftNetwork` component README has the fields.
## Rails: a point held to a path (tracks, coasters, zip lines, sliding doors)
`kind = "rail"` holds the point at this body's anchor (`localAnchor`) to `path` on the connected body: free to move along the path under gravity, contacts, forces and its motor, held across it. A rollercoaster car on its track, a train on its line, a trolley on a zip line, a door on a curved track, a bead on a wire, a camera dolly.
- **The path**: `path` is the points it runs through, `{ {x, y, z}, ... }` in the connected entity's local space, so a path on a moving body moves with it (at least 2 points; 3 for a loop). A spline from `modules.spline` is taken as it is, its `closed` with it. `curve = "smooth"` (the default) runs a smooth curve through the points; `"linear"` straight runs between them.
- **Ends**: `closed = true` makes the path a loop. An open path's ends are `ends = "capped"` (the default: the point stops at them) or `"open"` (the point runs off, the rail lets go of it, and `state().onPath` reads false with `left` naming the end). `:reattach()` takes a point that ran off back onto the path's nearest point: move the body back to the path first.
- **Held**: the point stands on the path to within the solver's precision, through bends and loops at speed; a point found more than `tolerance` metres (default 0.01) off it when a step begins is put back on it. A frictionless rail does no work: a cart keeps its energy round a loop. A soft body (`SoftBody`) is held by the particles `region` names (`{ nearest = point }` for one), through the body's own give: under load they stand off the path by as much as the body stretches there.
- **Driven**: `motorMode = "velocity"` holds `motorVelocity` m/s along the path (positive toward its end), `motorMode = "position"` brings the point to `motorTarget` metres along it with `motorStiffness` / `motorDamping`; neither pushes harder than `motorMaxForce` newtons (0 uncapped). `:setMotor(speed, maxForce)` sets a velocity motor. `friction` is a coefficient on the force holding the point to the path.
- **Refused**: a path that cannot be held (fewer points than the path needs, two consecutive points together, a point that is no position), a `tolerance` of 0 or less, a negative `friction`, or a field another kind takes (`stiffness`, `damping`, `restLength`, `maxDistance`, `limitMin` / `limitMax`, `swingLimit` / `twistLimit`, `lockedAxes`, `axisLimits`, `axisMotors`, `yieldForce`, `yieldTorque`) is refused by name, as for every joint kind: `Physics.addJoint` raises the reason and takes the Joint off the entity, and a Joint added as a component stands down with `lifecycle` "failed" and the reason as its `disabledReason`.
- **Read**: `:state()` (`Physics.jointState`) reads `progress` (metres from the path's start), `speed`, `length`, `closed`, `laps` (times round a loop), `onPath`, `left`, `atEnd` ("start" / "end" while a capped end holds the point), `offset` (metres off the path), `railMotorForce`, `frictionForce`, `tangent`, `normal` and `curvature`. `:reaction()` reads the force holding the point, with `localForce` along the path (x), toward the bend's centre (y) and across (z). `breakForce` releases the rail above that force, with the break event every joint sends.
```luau
-- a coaster car on a looping track
car.component.add("Joint", { connected = track.id, kind = "rail", path = trackPoints, closed = true, collideConnected = false })
local s = car.component.get("Joint"):state()
print(s.progress, s.speed, s.laps)
-- a zip line: the trolley's point 1 m above its centre, stopped at the far end
Physics.addJoint(trolley, cable, { kind = "rail", path = { {0, 12, 0}, {15, 6, 0}, {30, 3, 0} }, localAnchor = {0, 1, 0}, friction = 0.02 })
-- a sliding door on a curved track, driven open by a capped motor
Physics.addJoint(door, frame, { kind = "rail", path = arcPoints, motorMode = "position", motorTarget = 1.2, motorMaxForce = 300 })
```
# ProceduralSky
The editable atmospheric sky: a day/night gradient with a sun disc, glow, stars
and a moon, all derived procedurally from the directional light's elevation. Add
it to an entity like a light:
```lua
entity.spawn("sky").component.add("ProceduralSky", { timeOfDay = 18.5 })
entity.spawn("sky").component.add("ProceduralSky", { preset = "sunset" })
entity.spawn("sky").component.add("ProceduralSky", {
zenithColor = { r = 0.05, g = 0.1, b = 0.3 },
horizonColor = { r = 0.9, g = 0.4, b = 0.2 },
})
```
A `ProceduralSky` owns its material outright: it registers a **runtime GPU
material** of its own over the builtin procedural-sky shader and pushes every
visual parameter (colours, sun, stars, moon, turbidity, exposure) straight to
that record. The component's fields **are** the material definition — no
`.material` asset backs it, so retuning a scene's sky changes that scene's sky
and nothing else. The renderer reads the values from the material's group(1)
uniform like any other material — there is no sky-specific render path.
Those values also travel the native `Sky` bridge into the scene sky config,
alongside the time-of-day / auto-cycle / sun-sync controls. That config is what
`sky.get()` reports and what a saved scene records, so both name the sky being
drawn.
With `syncSunToLight` on (the default), the sky's `timeOfDay` is what the scene
is lit by: the scene's directional light takes its direction, colour and
intensity from the sun's position, so the sun in the sky and the sun the scene
is lit by are the same sun through a whole day/night cycle. Turn it off for a
light the sky leaves alone.
The intensity that arrives is the day/night curve between night and noon, and
`sunPeakIntensity` is the noon end of it — `1.0`, the sky's own daylight, unless
a scene asks for more. A harder sun on water or snow is stated here; setting the
light itself does not survive, because the sky writes over it every time the
hour moves.
Like the directional light, the sky is conceptually **singular per scene**. A
`ProceduralSky` fully defines its material on `awake` (every parameter from its
own fields), so switching scenes never inherits a previous scene's overrides.
Day/night comes from the sun's elevation, so evening presets render dark —
drive the look by `timeOfDay` (which orients the sun).
## Fields
| Field | Type | Default | Meaning |
|---|---|---|---|
| `preset` | string | `""` | Named look applied before explicit fields: `clear_day`, `sunset`, `sunrise`, `overcast`, `night`. |
| `timeOfDay` | number | `14.0` | 0..24 hours; orients the sun and the day/night gradient. |
| `autoCycle` | bool | `false` | Advance `timeOfDay` each frame. |
| `cycleSpeed` | number | `60.0` | Game-seconds per real-second for the auto cycle. |
| `syncSunToLight` | bool | `true` | Drive the directional light from the sun. |
| `sunPeakIntensity` | number | `1.0` | What the sun's light measures at noon; the day/night curve runs from night up to this. |
| `zenithColor` / `horizonColor` / `groundColor` | color | — | Sky gradient colours. |
| `sunSize` / `sunIntensity` | number | `0.02` / `20.0` | Sun disc size + brightness. |
| `starsIntensity` | number | `1.0` | Night star-field intensity. |
| `starsTwinkle` | number | `0.0` | How far each star's brightness swings over time; `0` holds the field still. The `night` preset twinkles at `0.3`. A twinkling sky changes the picture on every frame, so the renderer keeps drawing under it. |
| `moonSize` | number | `0.03` | Moon disc size. |
| `turbidity` | number | `4.0` | Atmospheric haziness. |
| `exposure` | number | `1.0` | Sky exposure multiplier. |
## Methods
| Method | Description |
|---|---|
| `sky:setTimeOfDay(hours)` | Set the time of day (0..24). |
| `sky:applyPreset(name)` | Apply a named look. |
| `sky:setZenithColor(c)` / `setHorizonColor(c)` / `setGroundColor(c)` | Set a gradient colour (`{r,g,b}` array or map; >1 auto-scales /255). |
# UiPanel
A UI panel component that renders a widget tree in one of three modes:
- `"2d"` — egui viewport overlay (HUDs, menus, debug panels).
- `"projected"` — screen-space UI at the entity's world position via `worldToScreen`. Always on top, no occlusion or lighting.
- `"3d"`: world-space billboard using egui render-to-texture. Respects depth/occlusion. The tree (inline, from `setTree`, or the screen a `source` library registers) is held on a hidden screen that is rasterized, styling and layout included, into a `rasterizeWidth` x `rasterizeHeight` texture every update; a quad in the child entity `<name>_ui3d` shows it, turned to face the active camera, and what the tree leaves transparent shows the world behind the quad. The quad is built in play.
Public fields: `mode`, `layer`, `visible`, `tree` (the widget tree, given inline), `source` (inline or `"lib::<path>"` / `"@..."` library module), `offsetX/Y/Z`, `maxDistance`, `fontSize`, `textColor`, `background`, `billboard3dScale`, `theme`, `rasterizeWidth`, `rasterizeHeight`.
Methods: `setTree(tree)`, `show()`, `hide()`, `toggle()`, `setMode(newMode)`, `getScreenName()`.
A library module named by `source` is mounted with `mount(ctx)`. When `mount` registers its own screen, the panel registers that screen again from its own code, so the screen is the panel's: its callbacks reach the panel's `onCallback`, which hands them to the `onCallback` the mount returned, and the screen is unregistered when the panel ends.
```luau
entity(id).component.add("UiPanel", {
mode = "2d",
layer = 10,
tree = { type = "label", props = { text = "HP: 100" } },
})
```
# SceneSetup
The per-instance state of a placed scene setup. A setup's `instantiate` adds it
to the placed root beside the `Asset` component whose `source` is the setup. It
holds this placement's `overrides`, by parameter path, and applies the setup with
them; the setup's members are applications of their assets, so the scene records
the root, its `Asset` and these overrides alone.
```luau
local setup = entity(root).component.get("SceneSetup")
setup:members() -- { [path]: { source, state } }, every depth
setup:get("fog/density") -- { value, origin, definedBy?, desc }
setup:set("fog/density", 0.05) -- this placement's override
setup:set("ao/@enabled", false) -- turns a member off here
setup:reset("fog/density") -- back to what the setup says
setup:orphans() -- overrides that address nothing
```
It applies the setup when it wakes and when it is enabled, applies a change of
`overrides`, turns the setup off when it is disabled and drops it when it is
removed; removing the `Asset` removes it. While it is disabled, a change of its
overrides applies the setup off. Across an edit/play flip the setup
stays applied: the instance that ends hands its application to the one that
wakes on the same root, so no frame is drawn without its sky, sun or fog. It
runs nothing per frame. A system
API's write of a parameter this placement states (`fog.set`) becomes this
placement's override.
Its application is one of the scene's applications: the effects that hold one
at a time (the sun, the ambient term, the sky, each render feature's settings)
go to the newest application standing. Another setup applied from code
(`setupRef:as("applicable"):apply(owner)`) holds them over this placement
until it is dropped, across flips, and its drop hands them back to this
placement. `audition(setup)` shows another setup in this placement's place as a
preview for the session; `endAudition()`, a flip or a reload ends it.
# Population
Draws a `.population` asset — one mesh at every transform the asset carries,
as ONE draw call per variant at any instance count.
```luau
entity.spawn("forest").component.add("Population", { source = "forest" })
```
The component owns what the draw costs: one GPU transform buffer and one
instanced-draw registration per variant. It builds them on awake, rebuilds
them when `source` changes or the asset's contents change on disk, and
releases them on destroy — so a scene reload replaces the draws instead of
stacking a second set, and despawning the entity takes them with it.
## Fields
| Field | Meaning |
|---|---|
| `source` | The `.population` asset to draw. |
| `castsShadows` | `false` renders the instances while blocking no light. |
## Reading what it draws
Both answers come back from the renderer, across every live registration:
```luau
local pop = entity.find("forest").component.get("Population")
pop:instanceCount() -- instances the engine reports drawing
pop:drawCalls() -- registrations — one per variant, at any instance count
```
## Where it comes from
`populationRef:instantiate(target?, opts?)` spawns exactly this: one entity
carrying this component. That is also what `Asset { source = <a population> }`
drives, which is how a baked procedural population reaches a scene — a root
record plus one child holding the reference, at any instance count.
The matrices a population carries are taken in this entity's space, so its
instances stand where the recipe placed them relative to the entity and move,
turn and scale with it.
# RenderFeatures
The scene's render features, on one entity: a list of `.renderFeature` assets,
each with the settings it runs under.
```lua
entity(id).component.add("RenderFeatures", {
features = {
{ feature = "@builtin::systems.reflections.ssr", settings = { intensity = 0.8, quality = "high" } },
{ feature = "@builtin::renderFeatures.outline" },
},
})
```
While the component is enabled every listed feature is live. A feature
something already runs — a script's `renderer.feature.create`, another entity's
list — is adopted and configured rather than stacked a second time. Each
feature runs its passes at the phase and order its own `render(ctx)` declares.
Disabling or destroying the component tears every one of them down.
Editing the list re-syncs it: an entry removed goes, one added comes up, and a
changed `settings` table reaches the live feature on its next frame.
`settings` are the knobs the feature's asset declares —
`renderer.feature.schema("@builtin::systems.reflections.ssr")` lists them with
their defaults. A knob the feature does not declare, or a value of the wrong
shape, is refused by name in the log.
Methods: `:getHandles()` — the live handles this component holds, keyed by the
feature asset's guid.
For code that tunes a feature at runtime — a quality slider, a cutscene —
`renderer.feature.find(ref)` and `renderer.feature.configure(handle, settings)`
reach the same knobs without an entity.
# MeshCollider (component)
Collision against mesh geometry. There are no size fields: the collider is the
mesh, scaled by the entity's transform.
## The two fits
| `fit` | Shape | Bodies | Concavity |
|-------|-------|--------|-----------|
| `"hull"` (default) | Convex hull of the mesh's points | Static and dynamic | Filled in, so a doorway becomes a slab |
| `"exact"` | The mesh's own triangles | Static | Followed exactly |
`"exact"` is for static bodies because a triangle mesh is a surface with no
interior: rapier cannot derive a mass tensor from one, and a dynamic body built
from it would fall through everything it touched. Setting `fit = "exact"` on a
dynamic body raises an error naming `"hull"` rather than quietly substituting it.
## Choosing the geometry
`mesh` names the asset to collide against. Left unset, the collider tracks
whatever mesh the entity renders, including a later swap. Set it to collide
against a cheaper proxy than the one on screen, which is the usual move for
detailed scenery where the visual mesh carries far more triangles than collision
needs.
```lua
entity.find("rock").component.add("MeshCollider", {}) -- what you see
entity.find("level").component.add("MeshCollider", { fit = "exact" }) -- concave, static
entity.find("rock").component.add("MeshCollider", { mesh = "rock_collision" }) -- cheap proxy
```
Because `mesh` is an asset reference, a collision proxy is visible to the asset
graph and survives a rename.
The collider follows the mesh's geometry. `renderer.mesh.setVertices` or
`renderer.mesh.update` on the mesh it is built from rebuilds it by the next
physics step, in edit mode and in play, once per changed mesh per frame however
many times the mesh was written, and bodies asleep on it or within its reach
wake. An edit is a new shape rather than a moving one, so it gives what touches
it no velocity; the physics guide states what a rebuild costs.
The collider loads the mesh it names itself, so an entity that draws nothing
collides all the same: an invisible wall, a trigger volume shaped like a mesh, a
level whose collision is a separate simplified mesh. The engine keeps that mesh
loaded for as long as a collider names it.
```lua
local wall = entity.spawn("invisibleWall")
wall.component.add("Physics", { kind = "static" })
wall.component.add("MeshCollider", { mesh = "@builtin::meshes.torus", fit = "exact" })
```
While a collider cannot be built, `Physics.bodyState(entity)` reads
`exists = false` with `waitingFor` naming what it is waiting for, and a wait
that lasts more than two seconds is logged as a warning naming the mesh.
## Cost
Built shapes are shared: every collider asking for the same mesh, fit and scale
gets the one built shape, so a field of a hundred identical rocks pays for one
hull rather than a hundred.
## Fields
| Field | Meaning |
|-------|---------|
| `mesh` | Mesh asset to collide against. Unset tracks the entity's renderable. |
| `fit` | `"hull"` or `"exact"`. |
| `isTrigger` | Report overlaps without blocking. |
| `friction` | Surface friction. |
| `restitution` | Bounciness. |
| `rollingResistance` | How strongly the surface resists a body rolling on it: a rolling body slows at this many times gravity on level ground, so a ball rolled at v stops after v^2 / (2 * rollingResistance * 9.81). 0 rolls on. |
| `spinningResistance` | The same for a body spinning on the surface about the contact normal. 0 spins on. |
| `surface` | The surface the collider is made of, by name: one `Physics.defineSurface` defined gives it its friction, restitution and resistances in place of the fields above, and contacts, contact events and ray and shape casts report the name either way. Empty names none. |
| `oneWay` | The direction, in the collider's own frame, bodies pass through it along: a body moving that way goes through, and a body meeting it from the side the direction points to stands on it (a jump-through platform is `{0, 1, 0}`). `Physics.passThrough(entity)` drops a standing body through. Unset blocks from every side. |
| `surfaceVelocity` | The velocity, m/s in the collider's own frame, its surface moves at along itself while the collider stays put: friction carries what rests on it (a conveyor belt, a treadmill, an escalator). Write it at runtime to change the speed or direction. Unset holds the surface still. |
| `contactTag` | The tag the world's contact filter reads this collider by: `Physics.setContactFilter(tagA, tagB, mode)` makes two tags pass through each other (`"ignore"`), report contacts and push nothing (`"sensor"`) or collide (`"solid"`). Empty names none. |
# Assembly
Holds what fills every slot at and under its entity: a vehicle whose wheel,
engine, seat and light slots parts fill, a mech with weapon hardpoints, a ship
or a modular building assembled from parts, a character with equipment points.
Put it on the root the slots belong to; the slots are the `Slot` components on
that entity and its descendants, and the role sockets of any `Humanoid` among
them (`righthand`, `head`, ...), which a part fills the way `Humanoid:attach`
seats an item.
## The configuration
`config` maps each slot's path to the guid of the part filling it, or to
`false` for a slot left empty. A slot it does not name holds the slot's
`default`. A part's own slots nest under the slot it fills (`engine/turbo`), so
one table describes the whole assembled object. A path naming a slot of a part
that is not built at the moment (the engine was swapped away) stays in the
table and applies when that part is back.
`config` is a synced, saved field, which gives the slot family its behaviour:
- **Undo.** Each `fill`, `empty` and `configure` is one undoable step; undo
puts the previous part back.
- **Multiplayer.** The entity's owner writes it and every peer builds the same
parts from it. A peer that does not own the entity is refused with the
owner's id.
- **Saving.** The configuration is saved with the scene, and the parts are
rebuilt from it when the scene loads. The parts themselves are runtime
children and are never written into the scene.
Changing what one slot holds rebuilds that slot's part (and the parts in its
slots) and nothing else: every other part, its entities and their state stay.
## Methods
| Method | Returns | Notes |
|---|---|---|
| `:fill(path, part)` | entity or nil | Fill a slot; `part` is an AssetRef, identity, guid or path, nil returns the slot to its default. Raises when the part does not fit, naming why, or when no slot answers to the path, listing the slots. |
| `:empty(path)` | | Leave a slot empty, its default included. |
| `:configure(config)` | | Replace the whole configuration. Keys are slot paths; a value is a part, `false`, or `{ part = ..., <slot> = ... }` for a part and its own slots. Nothing changes when any part does not fit; the refusal names each. |
| `:resolve()` | tree | Every slot: `{ path, name, kind, tags, from, part, guid, source, fill, slot, slots }`. `source` is `config`, `default`, `empty` or `none`; `fill` the entity the part was built on; `slots` the slots of that part. |
| `:slot(path)` | report or nil | One slot as `resolve` reports it. |
| `:fits(path, part)` | `(boolean, string)` | Whether a part fits a slot, and why or why not. |
| `:candidates(path)` | `{ { identity, guid, name } }` | The bundles this world holds that fit a slot. |
| `:refresh()` | | Rebuild every slot whose part differs from the configuration. |
An `Assembly` on a part's root (so the part can be assembled on its own too)
passes its calls, once the part is built into a slot, to the `Assembly` holding
that part, with its paths under the slot the part fills. Any other `Assembly`
below this one holds its own slots: an assembled car parented onto a truck, or
an assembled item a character holds through `Humanoid:attach`, keeps its own
configuration, and the `Assembly` above leaves its slots alone.
## Usage
```luau
local asm = car.component.get("Assembly")
-- One configuration for the whole car
asm:configure({
wheel_fl = "parts.SportWheel", wheel_fr = "parts.SportWheel",
wheel_rl = "parts.SportWheel", wheel_rr = "parts.SportWheel",
engine = { part = "parts.V8", turbo = "parts.Turbo" },
seat = "parts.BucketSeat",
})
-- Swap one part: only the front-left wheel is rebuilt
asm:fill("wheel_fl", "parts.OffroadWheel")
-- Why does a part not fit?
print(asm:fits("wheel_fl", "parts.V8")) -- false, "slot 'wheel_fl' takes parts of kind 'wheel'; 'parts.V8' fits { engine }"
-- What fills what
for _, s in ipairs(asm:resolve()) do
print(s.path, s.part, s.source)
for _, inner in ipairs(s.slots) do print(" ", inner.path, inner.part) end
end
-- What could go in the engine slot?
for _, p in ipairs(asm:candidates("engine")) do print(p.identity) end
```
The `Slot` README covers declaring slots and the `Part` README declaring what a
part fits.
# Force
A force and a torque a rigid body carries, applied by every physics step until the component changes or goes: a thruster, a rotor, a propeller, a fan, a hover pad, a jet pack, a constant wind on a sail, a magnet's pull, a conveyor that pushes. The step itself applies it: each step evaluates the force from the pose the body starts that step at, so it acts on the step it is meant for at any tick rate and any frame rate.
The force drives the body of its entity, or of the nearest ancestor holding one, so a body carries any number of forces through the entities under it: a rocket part with three thruster entities under it carries three, each acting where its entity stands on the part. One entity carries several `Force` components as well, each further one added under a `name` of its own (`craft.component.add("Force", { name = "padBack", ... })`, removed with `craft.component.remove("Force", "padBack")`); each acts from that entity's frame.
A force moves a dynamic body. A static or kinematic body carries its forces unmoved, and the log names each `Force` on one once; `Physics.forces(id).applied` reads whether this engine's step applies them.
Public fields:
- `force` (newtons) and `torque` (newton-metres), stated in `space`: `"local"` (default: this entity's own frame, so the direction turns with the body) or `"world"` (fixed however the body turns).
- `point` (default this entity's origin) in `pointSpace`: `"local"` (default: this entity's own space, scale included, moving with the body) or `"world"` (a point fixed in the world). A force acting off the centre of mass turns the body by the torque its offset makes.
- `throughCenterOfMass` (default `false`): the force pushes through the centre of mass and turns nothing, wherever `point` is.
- `scale` (default `1`): a factor on the force and the torque, saved with the scene (a trim, a fixed thrust).
- `scaleValue` (default `""`): a named value (`values.set`) on this entity or an ancestor whose number multiplies the force and the torque too; a name no entity on that chain holds scales them to 0. One throttle value on a vehicle drives every thruster under it, read by the step with no script copying it. A named value is live runtime state and is never saved with the scene, so a starting throttle is written when the game starts (a component's `awake`).
Disabling the component (`.enabled = false`) switches the force off from the next step. The fields sync like every component field, and the peer simulating the body applies the force, so every peer sees the same motion: another peer holds the body as a replica that moves as the simulating peer's step moves it. A named value the force follows is read on the simulating peer, so the body's owner writes the throttle, and a `replicate` rate on it (`values.declare`) lets the other peers read the same throttle. `Physics.forces(id)` reads which forces act on a body, each at its current world value with the entity and instance name it comes from, and their sum.
```luau
-- hold a 10 kg crate up against gravity
crate.component.add("Force", { force = { 0, 98.1, 0 }, space = "world" })
-- a rocket: two thruster entities under the hull, each pushing along its own +Y
for _, x in { -1, 1 } do
local t = entity.spawn("thruster", { parent = hull, position = { x, -2, 0 } })
t.component.add("Force", { force = { 0, 600, 0 }, scaleValue = "throttle" })
end
hull.values.set("throttle", 0.8)
-- a constant wind on a sail
sail.component.add("Force", { force = { 12, 0, 0 }, space = "world" })
-- a hovercraft: a pad pushing world-up at each of two corners, both on the craft entity
craft.component.add("Force", { force = { 0, 150, 0 }, space = "world", point = { 1, 0, 1 } })
craft.component.add("Force", { name = "padBack", force = { 0, 150, 0 }, space = "world", point = { -1, 0, -1 } })
```
# Camera
Manages viewport priority, render-to-texture, and capture. State is stored in the native `Camera` ECS component; the Rust camera system handles render scheduling and render targets.
Public fields: `fov`, `near`, `far`, `priority`, `textureHandle` (the guid of the texture the camera renders into; empty = main viewport), `renderLayers` (which render layers this camera draws — a space-separated spec of names, e.g. `"all"`, `"all !ui"`, or `"default sky"`; `ui`/`sky`/`debug`/`EditorUI` are built-in layers), `postProcessing` (whether this camera runs the post-process chain), `debugChannel`, plus the behavior slot below.
Methods: `:lookAt(target)` (entity id string OR `{x, y, z}` table), `:render()`, `:capture()`, `:setTargetTexture(tex?)` (a `renderer.texture.create` handle to render into, or nil for the viewport).
```luau
entity(id).component.add("Camera", { fov = 90, priority = 10 })
entity(id).component.get("Camera"):capture()
```
The scene's play-mode camera is reached as `layers.active.camera`, a handle that
reads and writes the fields above on whichever entity currently carries them.
`layers.active.camera.entity` is the entity ref for that camera and
`layers.active.camera.entityId` its id string, so a script that needs to attach
something to the camera — an `AudioListener`, a child entity — goes through the
ref:
```luau
local cam = layers.active.camera
cam.fov = 70 -- the camera's settings
cam.entity.component.add("AudioListener") -- the entity carrying them
```
## How the camera moves: `behavior` and `follow`
A `Camera` does not move itself. `behavior` names a component that does, and setting it attaches that component to this entity. Clearing it detaches whatever was attached.
```luau
local cam = entity(id).component.get("Camera")
cam.behavior = asset.ref("@builtin::controller.orbital_follow", "component")
cam.follow = playerBody
```
The attached behavior is an ordinary component on the camera's entity, so it is tuned the way any component is: read it with `component.get` and set its fields there. A `component.add` of the same type configures the instance the slot attached instead of adding a second one: the values it passes are written onto that instance and its proxy is returned. That add is the form a scene `build.luau` tunes the behavior with, because its values are saved with the scene and the loaded Camera's behavior takes them back. A key the component reads only as it is created (one of its `initKeys`, a private field) refuses the add and names the key.
```luau
cam.behavior = asset.ref("@builtin::controller.third_person_follow", "component")
local rig = entity(id).component.get("third_person_follow")
rig.cameraDistance = 6
-- the same, as an add of the type the slot attached
entity(id).component.add("third_person_follow", { cameraDistance = 6 })
```
`follow` is the standard slot every shipped behavior reads. Set the follow target on the **Camera**, not on the behavior, so swapping behaviors keeps it. A behavior that finds its own `follow` field empty falls back to this one, which is what lets a rig keep tracking the player across a behavior swap.
`followResolves` answers whether that slot names an entity that is live — `true` while it names a live one or names nothing at all, `false` once the target is despawned or the id names no entity. A rig whose target does not resolve holds its last pose, and this is the field that tells it from a rig posed correctly on a subject that has not moved. `camera.get` carries the same value beside `follow`, and a write naming an id with no entity behind it draws a warning where it lands.
```luau
cam.followResolves -- false once the followed entity is gone
tools.use("camera", "get", id).followResolves -- the same answer off the tool
```
The shipped behaviors live under `@builtin::controller.*`: `orbital_follow`, `third_person_follow`, `first_person`, `free`, `orbit`, `chase`, `isometric`, `rts`, `birds_eye`, `side_scroller`, `cinematic`, `menu`.
## Writing your own
Any component can be a camera behavior. Write one that moves its own entity and attach it the same way:
```luau
cam.behavior = asset.ref("MyChaseCam", "component")
```
`follow` lives on the Camera, so a behavior gets no property notification of its own when the target changes. Declare `onFollowChanged(newFollow, oldFollow)` to be told the moment it does — the Camera calls it on the component it attached, which is what lets a rig re-pose on the new subject at once. A behavior that reads `Camera.follow` on its own schedule declares nothing and is attached the same way.
```luau
typed function public:onFollowChanged(newFollow: any, oldFollow: any)
-- pose this entity against the new target
end
```
To make it appear in the discovery catalog alongside the shipped ones, declare the `cameraBehavior` tag in the component's `.metadata`:
```json
{ "tags": ["cameraBehavior"] }
```
The tag governs **discovery**, not attachment. A tagged component is listed by `layers.active.camera.behaviors` and is what tooling offers when something asks "which camera behaviors exist"; an untagged component attaches just as well and simply stays out of that list. Tag the ones you want other people (and agents) to find.
```luau
for name, ref in pairs(layers.active.camera.behaviors) do
print(name, ref.identity)
end
```
## Texture colour space
`textureColorSpace = "display"` applies the display transform when rendering into a texture. `"linear"` writes scene-linear values instead. `postProcessing` independently controls the effects chain in either mode. Floating-point targets retain values above one; normalized targets clamp to their representable range. The main viewport uses display encoding.
# ToonOutline
Draws the entity's mesh with an MToon-style outline: a shell of the mesh pushed out along its
normals and seen from inside, a line around the silhouette and its creases, drawn by the
`toonOutline` render feature (`modules.toonOutline`). A VRM avatar's body carries one on every
mesh entity whose MToon material states an outline, with the material's own outline colour,
width, width mode, lighting mix and width texture.
```luau
e.component.add("ToonOutline", { colorR = 0.1, colorG = 0.05, colorB = 0.05, width = 0.002, mode = "world" })
```
- `colorR`, `colorG`, `colorB`, `colorA`: the line's colour, linear.
- `width`: metres in `world` mode, a share of the screen's height in `screen` mode.
- `lightingMix`: how much the line takes the light falling on it, 0 none to 1 all.
- `widthTexture`, `uvScaleX`/`Y`, `uvOffsetX`/`Y`: a texture whose red channel scales the width
at each vertex's UV.
# scene.toolbox shared module
Cross-tool sharing for the `scene.*` toolbox: the hierarchy snapshot core
(`snapshot`, `findAll`, `leaf`) that backs tree / findAll /
findByComponent / summary, and the last-scene-name state that save / load
share. Tools call these functions; the functions call engine APIs.
# CapsuleCollider (component)
A capsule collision shape: a cylinder along the entity's local Y axis capped by
hemispheres. This is the shape characters use, because a rounded bottom slides
over small steps instead of catching on them.
## Sizing
`radius` and `height` are in the entity's local space, multiplied by the
entity's world scale. `height` is the full height of the cylindrical section,
excluding the caps. Leave both unset and the capsule derives from the entity's
model bounds, and follows the mesh when `renderer.mesh.setVertices` or
`renderer.mesh.update` changes it: by the next physics step the capsule takes
the new geometry's size and centre.
```lua
entity.find("player").component.add("CapsuleCollider", { radius = 0.3, height = 1.6 })
entity.find("pillar").component.add("CapsuleCollider", {})
```
## Fields
| Field | Meaning |
|-------|---------|
| `radius` | Capsule radius. Unset derives from model bounds. |
| `height` | Cylindrical section height. Unset derives from model bounds. |
| `isTrigger` | Report overlaps without blocking. |
| `friction` | Surface friction. |
| `restitution` | Bounciness. |
| `rollingResistance` | How strongly the surface resists a body rolling on it: a rolling body slows at this many times gravity on level ground, so a ball rolled at v stops after v^2 / (2 * rollingResistance * 9.81). 0 rolls on. |
| `spinningResistance` | The same for a body spinning on the surface about the contact normal. 0 spins on. |
| `surface` | The surface the collider is made of, by name: one `Physics.defineSurface` defined gives it its friction, restitution and resistances in place of the fields above, and contacts, contact events and ray and shape casts report the name either way. Empty names none. |
| `oneWay` | The direction, in the collider's own frame, bodies pass through it along: a body moving that way goes through, and a body meeting it from the side the direction points to stands on it (a jump-through platform is `{0, 1, 0}`). `Physics.passThrough(entity)` drops a standing body through. Unset blocks from every side. |
| `surfaceVelocity` | The velocity, m/s in the collider's own frame, its surface moves at along itself while the collider stays put: friction carries what rests on it (a conveyor belt, a treadmill, an escalator). Write it at runtime to change the speed or direction. Unset holds the surface still. |
| `contactTag` | The tag the world's contact filter reads this collider by: `Physics.setContactFilter(tagA, tagB, mode)` makes two tags pass through each other (`"ignore"`), report contacts and push nothing (`"sensor"`) or collide (`"solid"`). Empty names none. |
# Tessellation
Compute-shader mesh subdivision with material-driven displacement.
`Tessellation` sits next to `Model` on a renderable. The engine's
`tessellation` system reads the entity's current mesh geometry,
subdivides each triangle into `4^level` micro-triangles, displaces the
result along the interpolated normal from the entity material's
displacement map, and swaps the entity's `MeshInstance.mesh` for the
displaced derivative. The material is bound per-entity, so the
tessellated surface renders with the same PBR parameters and normal maps
as the source.
```luau
entity.find("floor").component.add("Tessellation", {
level = 4,
displacementScale = 0.05,
})
```
## Fields
| Field | Type | Purpose |
| --- | --- | --- |
| `level` | number | Subdivision level (0..=6). Clamped when out of range, and `getStatus()` answers `"clamped"`. `4^level` micro-tris per source tri. Under `mode = "adaptive"` this is the ceiling. |
| `displacementScale` | number | World-units of displacement per unit of sampled height. Sign matters — negative inverts inward. With no displacement map on the material, the surface is subdivided but left flat. |
| `mode` | string | `"static"` or `"adaptive"`; any other value makes `getStatus()` answer `"rejected_mode"` and leaves the entity rendering the mesh it already had. |
| `screenError` | number | Target micro-triangle edge in pixels, read under `mode = "adaptive"`. Smaller buys more subdivision at a given distance; zero or less asks for level 0. Default 8. |
| `stitch` | boolean | Place this surface's boundary on the coarsest lattice any patch sharing that boundary uses. Default `true`. |
## Methods
The `tessellation` system writes what each bake did onto the entity's
native `ecs.Tessellation` component, and these methods read it back.
`ecs.get(id, ecs.Tessellation)` reads the same values as its `status`,
`activeLevel`, `outputTriangles`, `outputVertices` and `stitchedEdges`
fields.
| Method | Purpose |
| --- | --- |
| `tess:getStatus()` | Read the latest status string: `""` before the first dispatch, then `"pending"`, `"ok"`, `"clamped"`, `"too_large"` or `"rejected_mode"`. |
| `tess:getActiveLevel()` | Read the level the installed mesh was baked at. |
| `tess:getTriangleCount()` | Read the installed mesh's triangle count: source triangles × `4^activeLevel`. |
| `tess:getVertexCount()` | Read the installed mesh's vertex count: source triangles × the lattice a patch carries at `activeLevel`. |
| `tess:getStitchedEdges()` | Read how many boundary edges the last bake placed on a coarser neighbour's lattice. |
## Adaptive level
```luau
entity.find("cliff").component.add("Tessellation", {
mode = "adaptive",
level = 5, -- ceiling, reached up close
screenError = 8, -- micro-triangles ~8 px on an edge
})
```
Under `mode = "adaptive"` the level is re-derived each frame from how
much screen the surface covers: the entity's bounding sphere is projected
under the viewport camera's own projection (perspective or orthographic),
and the level is the one whose `4^level` micro-triangles land near
`screenError` pixels on an edge — clamped to `level`. A surface therefore
gains detail as the camera approaches and sheds it on retreat. A sphere
the view frustum does not reach covers no pixels, so a surface behind or
outside the frame drops to level 0 until it comes back into view.
Sample `getTriangleCount()` across a dolly to watch it move. Two rules
bound the re-baking: a half-level dead band around the active level, so a
camera parked on a boundary holds one level, and a minimum spacing
between re-bakes, so a fast sweep through several levels re-bakes at a
bounded rate rather than every frame.
A whole entity holds one level, so the micro-triangles along every shared
edge inside it match by construction. Where two entities meet, see
*Shared boundaries* below.
## Shared boundaries
A surface's outline — the edges only one of its triangles uses — is the
only place another surface can meet it. Two surfaces whose outlines share
an edge and subdivide it to different levels place their points along it
on different curves: the finer one follows the displacement between the
coarser one's samples, and the space between the two curves is a crack
the background shows through.
Every frame, each tessellated surface's outline is placed in world space
and matched against the others'. Where a shared edge is found, the finer
surface bakes its points along that edge onto the coarser one's lattice,
so both trace one boundary. The rest of the finer surface keeps its own
level. `getStitchedEdges()` reports how many of its boundary edges were
placed this way, and a neighbour that changes level, moves away, or
appears re-bakes the surfaces that share an edge with it.
```luau
-- Two tiles meeting at x = 0, subdivided differently.
entity.find("tile_west").component.add("Tessellation", { level = 5, displacementScale = 1.5 })
entity.find("tile_east").component.add("Tessellation", { level = 2, displacementScale = 1.5 })
-- tile_west:getStitchedEdges() == 1 — its east edge is on tile_east's lattice.
```
Two outlines count as shared when both endpoints land on the same point
of a 0.1 mm world-space grid, which is what lets tiles authored to meet
match however each one is placed — the rounding each entity's own
transform leaves behind is orders of magnitude finer than one cell.
`stitch = false` leaves a surface subdivided uniformly to its own
level everywhere; its level is still what neighbours that do stitch clamp
themselves to.
## Output size
Each source triangle's micro-vertices are the grid points of one shared
barycentric lattice: `(n + 1)(n + 2) / 2` of them for `n = 2^activeLevel`,
carrying `n^2` micro-triangles. Micro-triangles meeting along an edge
inside a patch therefore name the same vertex, and the index buffer names
lattice addresses — three per micro-triangle. At level 6 a patch is 2145
vertices for 4096 triangles. Read the two counts with `getVertexCount()`
and `getTriangleCount()`.
## Displacement
Displacement height comes from the entity material's **displacement map**
(a grayscale height texture). A material without one still tessellates —
the geometry is subdivided for a smoother silhouette — but stays flat.
`displacementScale` scales the sampled height into world units along each
micro-vertex's interpolated normal.
## Limits
- Maximum subdivision level: 6 (= 4096 micro-triangles per source
triangle). Higher values are clamped, and `getStatus()` answers
`"clamped"`.
- Projected output cap: 64 MiB, counting the vertex buffer and the index
buffer together. A dispatch that exceeds this is skipped, and
`getStatus()` answers `"too_large"`: lower the level or use a
lower-poly source mesh.
# Appearance
Carries how the person behind an avatar wears it, as one appearance document
(`modules.avatarAppearance`), on the avatar root: the entity carrying
`Humanoid`, which is `player.avatar` for a player. The document and a game's
override rules are synced data of a few hundred bytes: every peer receives
them and composes the same character on its own engine, so no mesh, bone or
worn item is sent. Writing a new document recomposes only what differs from
the one before.
```luau
local avatarAppearance = require("@builtin::modules.avatarAppearance")
local doc = avatarAppearance.new("@builtin::avatars.humanoid")
doc.body_shape = { height = 1.9 }
doc.colours = { body = "#3366cc" }
doc.worn = { { slot = "hat", item = "@builtin::meshes.cone", adjust = { y = 0.05, scale = 0.2 } } }
local body = layers.active.players.localPlayer.avatar -- the avatar root (it carries Humanoid)
body.component.add("Appearance", {})
local look = body.component.get("Appearance")
look:wear(doc) -- the person's document
look:override({ worn = { hat = "my_helmet" } }) -- the game's view of it
print(look:size(), look:address(), look:get().worn[1].item)
```
- `document` (synced): the person's document as its canonical JSON. Emptied
(`:wear(nil)`), the avatar returns to how it stood before the first document.
- `rules` (synced): the game's override rules as JSON; the person's document stays as it is.
- `:wear(doc | nil)`, `:get()`, `:effective()`, `:override(rules | nil)`, `:address()`,
`:size()`, `:emotes()`, `:composed()`.
Location: `src/lua/lib/components/Appearance.component`
# contactShadows system
Short screen-space shadow traces that supply the small-scale contact a shadow
map cannot resolve.
A shadow map has a texel size. Contact finer than that texel — a chair leg on a
floor, a prop on a table, fingers on a desk — falls between texels and is simply
not there, which is why small objects read as hovering slightly above the
surface they are resting on. No amount of shadow resolution fixes it, because
the missing detail is below the sampling scale.
This traces a short ray through the depth buffer from each shaded pixel toward
the light and darkens the pixel when the ray passes behind visible geometry. It
adds the contact term; the shadow map keeps doing everything else.
## Using it
```lua
local id = entity.spawn("contact_shadows").id
entity(id).component.add("ContactShadows", {
strength = 0.9, -- how dark a fully occluded contact goes, 0..1
length = 0.35, -- trace length in WORLD units
steps = 16, -- samples along the trace
})
```
Every field is live. Setting `strength` to 0 turns it off without losing the
rest. For runtime control (a quality slider, a cutscene) drive the module:
```lua
local contactShadows = require("@builtin::systems.contactShadows.contactShadows")
contactShadows.set({ strength = 0.9, length = 0.35 })
contactShadows.get()
contactShadows.active()
contactShadows.lights() -- the lights this frame's traces aim at
contactShadows.drawn() -- the newest frame the passes drew, and the lights they traced
contactShadows.clear()
```
## What the knobs do
| field | effect |
|---|---|
| `strength` | How dark a fully occluded contact goes, in [0, 1]. 0 turns it off and releases the pass. |
| `length` | Trace length in **world** units. This is the scale of contact supplied, so it scales with the scene rather than the screen. |
| `steps` | Samples along the trace. More resolves finer occluders, at linear cost. |
| `bias` | Normal offset before the march starts, so a surface does not read as its own occluder. |
| `thickness` | World-space thickness assumed for an occluder. Past it the ray has emerged out the far side and stops counting. |
| `localLights` | Whether the scene's point, spot and distant lights supply contact of their own alongside the sun. |
| `maxTracedLights` | How many of them a single pixel may trace toward — the heaviest contributors at that pixel. Each one costs that pixel another march, so this is the per-pixel ceiling. |
`lightDirection` tracks the scene's sun on its own, re-read every frame. Pin it
through `contactShadows.set` when a scene wants the sun's trace aimed
elsewhere; a later `set` that names no direction goes back to tracking the sun.
## Lights
A lamp on a desk grounds the props under it the same way the sun does, and the
same shadow-map texel that loses the sun's contact loses its. So with
`localLights` the point, spot and distant lights supply contact too, each
traced toward and each weighted by the share of the pixel's light it put there
— its intensity and colour luminance against the same distance attenuation and
cone the renderer shades it with. A pixel darkens by the share of its light the
traces found blocked, which is what keeps a lamp's contact out of the regions
that lamp does not reach.
A local light's ray also stops at the light itself rather than running the full
`length`: geometry past a lamp stands between nothing.
The pool holds point, spot and distant lights. An area light shades from a
surface rather than a point, and the trace takes a single direction per light,
so contact under one comes from the sun and whatever punctual lights share the
scene with it.
The module selects the pool once a frame — every distant light, then the local
lights whose sphere of influence touches the view, ranked by what each is worth
at the camera — and that rank is what a scene holding more lights than the pool
has rows spends them on. `contactShadows.lights()` reads back exactly what it
selected. The view it selects against is the main camera's, so an offscreen
camera looking somewhere else traces toward the lights the main view holds.
At each pixel the pass then weighs the whole pool — intensity and colour
luminance against that pixel's own N·L, distance attenuation and cone — and
marches toward the `maxTracedLights` heaviest. So a lamp across the room that
ranked into the pool does not spend the budget of a pixel the lamp beside it is
lighting.
## How it renders
`contactShadows.renderFeature` runs the sun's trace at the depth seam, before
anything shades, and the local lights' traces after lighting.
The sun's march (`contact_shadows_sun`) starts at each surface, its normal read
off this frame's depth, and steps toward the sun. Each sample along the ray is
projected back to the screen and compared, in world space, against what the
depth buffer holds there: the ray is blocked while it is behind visible
geometry and still within `thickness` of it. The march is jittered per pixel
so the step pattern lands as noise rather than visible stair-stepping, and a
surface facing away from the sun takes nothing: it is already unlit by it. The
pass writes `strength` times how blocked the ray is, `contact_sun_blur` smooths
it along the depth, and a fragment pass composes it into the scene's sun
occlusion channel (`@scene.sunOcclusion`) with the `union` blend
(`src + dst - src * dst`). The sun's term is the only one that reads that
channel, so the sun's contact darkens the sun's light and nothing else: the
sky, the probes, an emissive surface and the other lights keep theirs, and a
participating medium's shadow written into the same channel composes with it.
With `localLights`, the local march (`contact_shadows`) reads the deferred
G-buffer's normal, so it needs the deferred path (the default). Its blur
composites the result over the shaded colour scaled by how lit the pixel
already is (`@scene.material` against the shaded colour), so a region the
shadow map has already darkened takes little further darkening and the two
shadow sources do not stack.
The forward view-projection needed to project a sample back to the screen is
the one the frame provides, rather than one passed in from script, so an
offscreen capture or an RTT camera projects through its own matrix.
## Files
```
contactShadows.package/
ContactShadows.component/ -- the scene's contact shadows, authored and persisted
contactShadows.module/ -- .set / .get / .clear / .active / .lights / .drawn / .refresh
contactShadows.renderFeature/ -- the passes, and the settings they read
contact_shadows_sun.computeShader/ -- the sun's trace, at the depth seam
contact_sun_blur.computeShader/ -- the sun's share, smoothed
contact_shadows.computeShader/ -- the local lights' trace
contact_shadows_blur.computeShader/ -- the local lights' composite
```
## At lower quality levels
The settings that carry its cost scale with the device's quality level (`Field.scaled`): the values a setup authors are the high look, and `renderer.feature.resolved(handle)` states what each level draws. The `graphics-quality` guide lists the rules.
# SpotLight
Adds a cone-shaped light source to an entity. Position comes from the entity's world transform; the cone axis is the entity's world rotation applied to the `face` direction, so a spot under a carrier turns with it. `face` defaults to `"Front"`, the entity-local -Z that `transform.forward` reports and that `entity:lookAt` aims, so aiming the carrier at something is what puts the cone on it. Shares the scene's light buffer with `Light` (point lights), and shares its intensity scale: the same `intensity` at the same range puts the same light on a surface either kind faces from the same place, and the cone decides how much of the room that light reaches rather than how bright it is where it lands. `angle` and `innerAngle` are half-angles from the cone axis, so `angle = 30` opens a 60-degree cone.
Public fields: `colorR/G/B`, `brightness` (→ intensity), `range` (→ radius), `angle` (outer half-angle, deg), `innerAngle` (inner half-angle, deg), `face` (`Front`/`Back`/`Left`/`Right`/`Top`/`Bottom`), `shadows`, `cookieLayer`, `mobility`. `intensity` and `radius` are aliases of `brightness` and `range`, spelled the way the `Light` component spells them.
Methods: `:setColor(color)`, `:setBrightness(b)`, `:setRange(r)`, `:setAngle(deg)`, `:setInnerAngle(deg)`, `:setFace(face)`.
Falloff: 0..innerAngle = full bright, innerAngle..angle = smoothstep to 0, > angle = 0. An `innerAngle` at or past `angle` gives a hard edge at `angle` (full bright out to it, nothing past it), so narrowing `angle` alone never lights anything outside the cone. Range falloff is the inverse-square law, distances in metres: a surface facing the light 1 m away takes `brightness`, one at `d` metres takes `brightness / d^2` (4 times as much at 0.5 m, a quarter at 2 m), and the curve is windowed smoothly to zero at `range`.
The cone is one further factor on that shared scale, and it is 1 inside `innerAngle`. So the reading that separates the two kinds is a room-wide or frame-wide average: a spot lifts it far less than a point light carrying the same number, because it reaches less of the room. Balance a mixed rig by the brightness of the surfaces each light is aimed at, not by how much of the frame each one lifts — and widen `angle` or `range` to cover more of the room where raising `brightness` would only deepen the spot's own pool.
A spot casts shadows by default; `shadows = false` keeps it purely additive. `cookieLayer` names a layer of the shared feature texture to project through the cone as a gobo, and `-1` (the default) leaves the cone uniform — fill the layer with `renderer.featureTexture.setLayer` before pointing a spot at it.
```luau
entity(id).component.add("SpotLight", {
color = {1, 0.95, 0.8},
brightness = 3.0,
range = 30,
angle = 30,
innerAngle = 20,
face = "Front",
shadows = true,
cookieLayer = 0,
})
```
# Player
Identity tag for a player entity. Attaches the Rust `PlayerOwned` marker via `__native` in `awake` and removes it in `onDestroy`. No public state, no update loop, no visuals.
```luau
entity(id).component.add("UserIdentity")
entity(id).component.has("UserIdentity") -- true
```
Future rules (not yet enforced):
- **Non-serialising.** Scene and world saves omit this component. Players are attached at runtime per peer, not inherited from the save file.
- **Non-removable.** Once an entity is a player, removing this component is a no-op. A player stays a player for its lifetime outside an explicit identity swap.
Visuals, cameras, input, and movement live in separate components (e.g. `PlayerController`, `PlayerTemplate` bundle content) so adding or removing them never affects identity.
# 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`
# AudioListener
The "ears" of the scene. Spatial audio is heard relative to the entity carrying this component — its transform sets the listener position and orientation. Attach it to whatever should hear: a camera, a character, a dedicated listener rig.
Public fields: `active` (`boolean`, default `true`).
Methods: `setActive(on)`.
```luau
entity.find("camera").component.add("AudioListener")
entity.find("player").component.add("AudioListener", { active = true })
```
A scene needs an active listener for its `Audio` sources to be heard positionally. Sources with no active listener are reported at load and play centered until a listener is added.
`active` is live: writing it takes effect on the next frame, so clearing it on the listener holding the ears hands them to another active listener, and clearing it everywhere leaves the scene with no ears. When several are active one of them drives the ears — the same one for as long as those entities live, whatever else changes about them — and the engine warns once, naming it. Recreating the entities, as a scene reload or entering play does, chooses again. `audio.observe().listener` reports the winner as `entity`, alongside `present`, `count` (how many are active) and the pose. Which one it picks is not something to author against: deactivate or remove the extras when it matters.
# AvatarAnimator
Runs an avatar's declared parameters, animator, expression menu and parts (the
`parameters`, `animator`, `menu` and `parts` of its `avatar.json`, see
`modules.avatarAnimator`) on the avatar root. An avatar that declares any of them gets this
component when it is instantiated, on every peer, and each peer seats its own copy of the
avatar's parts on the body.
The peer that owns the avatar holds its parameters: the Expressions tab of the app menu,
a game or the avatar's own components set them, and the synced ones reach every other
peer on the avatar channel within one parameter send interval (a tenth of a second); a
peer that joins later receives the current block at once. Every peer evaluates the same
animator from the same parameters and applies it to its own copy of the body: blend
shapes, the material values its expressions move, bone offsets added over the locomotion playing, the clips its states play (each
under its layer's mask and weight, over the locomotion), the parts it shows and hides and
the shader data lanes of its meshes. It evaluates on the session clock and dates each state
by the parameters the channel dates, so a remote peer plays a gesture clip at the point the
owner plays it. A body no other animator drives gets a graph of this component's own for
its clips.
```luau
local anim = layers.active.players.localPlayer.avatar.component.get("AvatarAnimator")
anim:set("Hat", false) -- every peer hides the hat
anim:set("EarAngle", 0.6)
print(anim:get("Speed"), anim:get("Voice"))
anim:emote(3) -- `Emote` reads 3 on every peer, `EmoteTime` how long since
print(anim:stats().cost.units, anim:stats().evaluationMs)
```
- `avatar` (synced): the avatar asset whose definition it runs.
- `:set(name, value)` on the owner; `:get(name)`, `:values()`, `:parameters()`, `:menu()`,
`:layers()` (each layer's `state`, `time`, `enteredAt` on the session clock, `blend`,
`weight` and the `clips` it plays with each one's `time`), `:emote(id)` (an emote
`multiplayer.avatarEmote` starts on the avatar's channel reads the same), `:stats()`
(`cost`, `evaluationMs`, `syncedBits`, `channel`, `owned`, `readsVoice`, `clips` with
whether each is bound and its `length` or `failure`, `materials`, `failure`).
## Material values
An expression of the avatar's map (`expressions` in `avatar.json`) can move material values
beside its blend shapes: `materials = { { material, property, value } }`, `material` the
material asset, `property` one its shader declares (`outline_color` for the colour of the
outline a `ToonOutline` draws) and `value` the target it reaches at weight 1. Playing the
expression moves each value from the material's own toward the target by the expression's
weight, the same weight its blend shapes take (held to 0 or 1 for an `isBinary` expression,
quieted by the overrides of the expressions over it), and the values of several expressions
on one property add up: `rest + sum(weight * (target - rest))`. Each entity of the body that
draws the material takes the values on a copy of its own, made the first time a value leaves
its rest, so two avatars wearing one material each show their own face. A VRM's material
colour and texture transform binds (`materialValues` in VRM 0.x) import as these.
`:stats().materials` lists each entity they reach.
A saved parameter is written into the avatar's appearance document, and one the person sets
themselves from the Expressions tab is also kept on their device for this avatar (a value a
script sets is never written to the person's device). The avatar starts with the document's
values and then the device's, and reads the document again whenever the avatar wears another.
Location: `src/lua/lib/components/AvatarAnimator.component`
# ambientOcclusion system
Ambient occlusion: the contact darkening of indirect light in corners, creases
and where objects meet.
Without it, every concave region takes as much ambient and environment light as
a flat one: a box resting on a floor has no seam, a corner is as bright as the
wall, and an untextured scene reads as plastic.
One effect answers one question: what fraction of the hemisphere above this
pixel is open. Its answer goes into the scene's occlusion channel before
anything shades, and PBR shading (`zero_pbr_shade`, which the `pbr` shader and
the materials built on it run) multiplies it into the indirect term alone
(ambient, irradiance, environment reflection). Direct light, emissive surfaces
and transparents keep the light they carry.
## Using it
The scene's occlusion is a component; author it once and it persists with the
scene:
```lua
local id = entity.spawn("ambient_occlusion").id
entity(id).component.add("AmbientOcclusion", {
intensity = 0.9, -- how far the darkening goes, 0..1
radius = 1.5, -- world-space reach
quality = "high", -- low | medium | high | ultra
})
```
Every field is live: edit one in the inspector and the shading follows. Setting
`intensity` to 0 turns it off without losing the rest.
For code that adjusts occlusion at runtime (a quality slider, a cutscene), reach
for the module directly, with the same options:
```lua
local ao = require("@builtin::systems.ambientOcclusion.ao")
ao.set({ intensity = 0.9 }) -- any subset; the rest is kept
ao.get() -- the settings in force
ao.qualityLevels() -- the cost each level pays
ao.active() -- is the pass running
ao.stats() -- what the pass built and ran this frame
ao.clear() -- off, settings kept
```
## What the knobs do
| field | effect |
|---|---|
| `intensity` | How far the darkening goes, in [0, 1]. 0 turns it off and releases the pass. |
| `radius` | World-space reach, roughly "how big is a crease worth darkening". Constant in world space, so it does not swell as the camera approaches. |
| `power` | Contrast curve on the visibility term. Above 1 deepens the dark end. |
| `thickness` | World-space thickness assumed for an occluder, so a thin foreground object stops occluding everything behind it out to the full radius. |
| `bias` | How far a neighbour must rise above the tangent plane before it raises a horizon, in [0, 1]. Raise it if a flat surface shades itself in patches; lower it if fine creases disappear. |
| `quality` | The cost of the estimate. See the table below. |
| `traced` | Trace the hemisphere against the scene acceleration structure while the scene's ray tracing is on (`renderer.setRaytrace(true)`). A frame drawn without ray tracing takes the screen-space estimate. |
| quality | screen-space slices x steps | depth taps per texel | traced rays per texel | resolution |
|---|---|---|---|---|
| `low` | 2 x 3 | 12 | 3 | half |
| `medium` | 3 x 4 | 24 | 6 | half |
| `high` | 4 x 6 | 48 | 6 | full |
| `ultra` | 6 x 8 | 96 | 12 | full |
The lower two levels compute occlusion on a half-resolution grid: a quarter of
the texels, each still costing its level's work. Occlusion is low-frequency
almost everywhere, and the filter that removes the sampling noise lifts the
coarse grid back to the frame in the same pass, weighting each texel by the
depth where it sits so silhouettes survive the upsample. What a half-resolution
grid loses is the innermost pixel of a sharp crease.
## How it renders
The pass runs at `afterDepthPrepass`, where this frame's opaque depth is
complete and nothing has shaded yet, in the `lighting` post stage:
1. The estimate. Screen-space, it is ground-truth ambient occlusion: a few
slices are walked through the texel, the steepest horizon is found in both
directions along each, and the visible arc between the two is integrated
against the cosine lobe around the normal in closed form. Traced, it is a
cosine-weighted hemisphere of short rays, and the fraction that reaches
nothing within `radius` is the visible fraction. Both reconstruct the
surface's normal from this frame's depth and store through one function.
2. The filter. Each tap is weighted by how close its depth is to the centre
pixel's, so the sampling noise goes without bleeding occlusion across a
silhouette. It writes the occlusion into the scene's occlusion channel
(`@scene.ao`).
PBR shading reads the channel at its own pixel the same frame, on the forward and
deferred paths alike. Depth and camera come from the render target
being drawn (`@scene.depth`, `@frame.camera`), so the result is correct in
offscreen captures and render-to-texture cameras at their own resolutions. Sky
pixels have no surface to occlude.
## Seeing the occlusion on its own
While occlusion is running, `ambientOcclusion` is a capture view: the filtered
visibility with no scene colour, white where the hemisphere is open and dark
where it is closed.
```
capture { pass = "ambientOcclusion" }
```
It is the fastest way to tell a shading problem from an occlusion one, and to
compare two `radius` values or quality levels without the lighting in the way.
## Files
```
ambientOcclusion.package/
AmbientOcclusion.component/ -- the scene's occlusion, authored and persisted
ao.module/ -- ao.set / .get / .qualityLevels / .active / .stats / .clear
ambientOcclusion.renderFeature/ -- the pass: estimate, filter, occlusion channel, capture view
ao_common.shaderModule/ -- the prelude both estimators are written against
ao_pass.computeShader/ -- the screen-space estimate
ao_trace.computeShader/ -- the traced estimate
ao_filter.computeShader/ -- the depth-aware filter that writes the channel
```
# antiAliasing system
Geometry is rasterised at one sample per pixel, so a silhouette crossing a pixel
either covers its sample or does not. A shallow-angle edge therefore comes out as
a staircase of hard steps rather than as a line, and that staircase is the most
recognisable artifact of an unfiltered render. In motion it gets worse: the step
pattern shifts as the edge moves, a specular highlight flashes on and off as it
crosses the sample point, and fine texture crawls.
Two corrections live here, and they work from different information.
**Edge antialiasing** (`EdgeAntiAliasing`, FXAA) works from the finished frame
alone. It finds each edge and shifts that pixel's sample across it. Fixed cost,
no dependencies, corrects the staircase in a still image — and knows nothing
about time, so what only appears in motion stays.
**Temporal antialiasing** (`TemporalAntiAliasing`) samples a different point
inside each pixel every frame and accumulates the frames, following the scene's
own motion to know where each pixel's surface was. That recovers detail no single
frame holds and settles exactly what edge antialiasing cannot see — the crawling
and flickering that exist only between frames. It needs the scene's velocity, and
costs a small amount of softening, which its `sharpness` puts back on the shown
picture.
A world created from the default template runs temporal antialiasing from its
first frame: the template's `.world_settings` names `antialiasing = "taa"` under
`[render]`, and the world entrypoint applies it as the world loads, tuned by
`[render.taa]`. A world whose settings name `"off"`, or name no mode, runs none.
They compose: edge antialiasing cleans up within a frame, the temporal pass
handles what happens between them.
## Using them
```lua
local id = entity.spawn("antialiasing").id
entity(id).component.add("TemporalAntiAliasing", { historyWeight = 0.9 })
entity(id).component.add("EdgeAntiAliasing", { edgeThreshold = 0.125 })
```
Every field is live. For runtime control (a quality slider, or turning one off)
drive the modules:
```lua
local antiAliasing = require("@builtin::systems.antiAliasing.antiAliasing")
local temporalAntiAliasing = require("@builtin::systems.antiAliasing.temporalAntiAliasing")
temporalAntiAliasing.enable({ historyWeight = 0.9, sharpness = 0.2 })
antiAliasing.enable({ edgeThreshold = 0.125 })
```
Each module has `.enable` / `.get` / `.active` / `.disable`, acting on its
render feature asset (`fxaa`, `taa`): `enable` lands each value where it takes
effect (a component's or a placed setup's own value when it states it, else the
asset's live value) and applies the pass when nothing else does, `disable` drops
the module's own application, and a component's stays. A component applies the
asset with its fields, owned by its entity; of two, the one edited last is in
force.
Temporal antialiasing draws at a quality level: its `quality` (on the
component and in `enable`) is `low`, `medium`, `high`, or `auto` (the
default), which follows the device's quality tier (`renderer.qualityTier()`).
`high` sharpens the shown picture by `sharpness`; `medium` and `low` show the
accumulation unsharpened, and the sharpening pass and the copy of its result
into the picture leave the frame. The accumulation is the same at every level.
`temporalAntiAliasing.drawn()` reports the level in force and the sharpening it
draws.
To see temporal antialiasing as a player sees it, read the frame the screen
showed: `capture { source = "presented" }` (`frames = n` for a run of
consecutive frames, which is how convergence and flicker read), or
`renderer.presentedFrames()` for the pixels with each frame's jitter and
history reset. Every view keeps its own accumulation: a render-to-texture
camera accumulates over its own renders, and an offscreen capture draws a fresh
view whose single render has no history behind it, so it shows none of the
accumulation and leaves the viewport's untouched.
## What the edge knobs do
| field | effect |
|---|---|
| `edgeThreshold` | How much a pixel's luminance must differ from its neighbours', as a fraction of the brightest of them, before it counts as an edge. Lower catches fainter edges and costs more. |
| `edgeThresholdMin` | The absolute floor under that test. It keeps the pass off dark areas, where a small relative step is still visually flat. |
| `subpixel` | How strongly features finer than one pixel are corrected. |
| `searchSteps` | How far the pass walks along an edge looking for its end. Longer reach resolves shallower edges, at linear cost. |
## What the temporal knobs do
| field | effect |
|---|---|
| `historyWeight` | How much of the accumulated result to keep each frame. Higher resolves more detail and settles smoother, at the cost of taking longer to let go of what a surface used to look like. |
| `neighbourhoodClamp` | How far outside the neighbourhood's own colour spread an accumulated sample may sit before it is pulled back in. Lower rejects more, trading some of the settling for a result that follows change faster. |
| `sharpness` | How strongly the shown picture is sharpened, in [0, 1]: a contrast-adaptive pass (`rcas`) after the display transform, which steepens edges without lifting either side past its plateau and is never written back into the accumulation. 0 shows the accumulation as it is. |
| `motionRejection` | How much fast motion shortens the memory, which is what stops a moving object trailing behind itself. |
| `stillSamples` | How many renders a pixel whose surface holds still accumulates, in [1, 256]. Each render samples a different point inside the pixel, so a still pixel holding several whole passes through the sample sequence settles on their average instead of rippling as the samples visit it; fewer let a still picture follow a slow change of its lighting sooner. |
## How they render
`fxaa.renderFeature` runs one compute pass in the `display` stage, on display
code values, so its edge thresholds read luma the way a viewer sees it. A
picture of the edge antialiasing is read from the presented frame
(`renderer.presentedFrames`, a `capture` with `source = "presented"`): the
`display` stage's render-feature passes draw there. The result is **not a
blur**. A blur softens everything; this moves each edge pixel's sample
perpendicular to the edge by a sub-pixel amount, so the step between two flat
regions becomes a gradient while both regions are left as they were. That is why
the pass has to find the edge's direction and extent rather than filtering a
neighbourhood — the offset depends on where along the edge the pixel falls, so a
pixel near the middle of a long edge barely moves and one near an end moves
nearly a full half-texel.
Luminance drives every decision there. The eye resolves luminance detail far more
finely than chroma, so a step that reads as a jagged edge is a step in luminance,
and an edge that is pure chroma needs no correction. A pixel whose neighbourhood
varies less than the threshold is passed through untouched, which is what keeps
flat regions and gentle gradients out of the filter entirely. Features finer than
a pixel produce no long edge to walk, so the 3x3 luminance average carries their
correction instead.
`taa.renderFeature` offsets where the projection samples each frame and
accumulates the frames that produces, reprojecting through `@scene.motion` and
bounding what it carries by the neighbourhood's own colour statistics. Its README
covers the sample sequence, the tests that decide whether an accumulated sample
is still about the same surface, and why the bound is computed in YCoCg. The
accumulation itself is `temporal_resolve`, the one resolve the temporal upscale
(`@builtin::systems.temporalUpscale`) folds its frames through as well. Both
then restate the frame's depth from `stable_depth`, the depth sample nearest
each pixel's centre while nothing there moves, so an effect after them draws
lines and patterns that hold still with the picture.
## Files
```
antiAliasing.package/
EdgeAntiAliasing.component/ -- the scene's edge antialiasing, authored and persisted
antiAliasing.module/ -- .enable / .get / .disable / .active
fxaa.renderFeature/ -- the edge pass
TemporalAntiAliasing.component/ -- the scene's temporal antialiasing, authored and persisted
temporalAntiAliasing.module/ -- .enable / .get / .disable / .active
taa.renderFeature/ -- the accumulation pass + the per-frame sample offset
taa_resolve.computeShader/ -- the accumulation at render scale 1
temporal_resolve.shaderModule/ -- the temporal resolve every reconstruction accumulates through
stable_depth.computeShader/ -- the depth a reconstruction restates for the passes after it
stable_surface.computeShader/ -- the G-buffer normal and material restated beside it
rcas.computeShader/ -- the sharpening of the shown picture after the temporal stage
```
# CollisionGroup
Sets collision group membership and filter masks on an entity's physics colliders using a bitmask. Two colliders collide only when `(a.membership & b.filter) ~= 0` AND `(b.membership & a.filter) ~= 0`.
Public fields: `membership` (default `0xFFFFFFFF`), `filter` (default `0xFFFFFFFF`).
Methods: `setGroups(membership, filter)`, `ignoreEntity(entityId, ignore?)`.
```luau
entity(id).component.add("CollisionGroup", { membership = 1, filter = 3 })
```
# third_person_follow
Over-the-shoulder camera. The rig hangs off a shoulder pivot beside the follow target and sits back along the heading it looks down, so framing is authored as offsets in space. The offset is measured in the camera's own frame, so the subject holds the same spot on screen whichever way it turns.
The rig owns that heading. Binding a follow target aims it along the subject's facing, and look input turns it from there and the recentre turns it back behind the subject once the player stops looking around (below). A facing that becomes known or is declared anew after the bind aims it behind the subject again, once for each change: a `Locomotion` or `LocomotionFull` arriving on the subject or leaving it, a body standing up under it, as an avatar that composes after the camera bound does, or the component's `forward` or `faceSign` changing (`CameraRig.facingSource` names what the facing is read from). The heading holds while the body turns. That is what makes the camera steerable for a character who turns to face where it is walking: hold "forward" and the character walks the line the camera looks down, instead of chasing a heading that moves as it turns.
The facing a bind reads is the way the body visibly faces (`CameraRig.visibleForward`): a composed avatar body faces its -Z, turned by `Locomotion` or `LocomotionFull` as it walks, read through the rotation anchor that component turns, so the rig lands behind every avatar whatever file its body came from and after `setCharacter` swaps its body. A target with neither component answers its transform forward.
Public fields: `follow`, `shoulderOffset` (x across the frame, y up it, z along the heading), `verticalArmLength`, `cameraSide` (0 = left shoulder, 1 = right), `cameraDistance`, `minDistance`, `maxDistance`, `aimYaw` (the world heading the camera looks along, in radians about +Y from world +Z) and `aimPitch` (how far it tilts off level), `damping` (per-axis time constants in seconds of the camera's offset from the point it frames: they soften a change of framing, a stick or touch look, a zoom or a recentre; a mouse look turns the camera on the frame the mouse moves), `horizontalLag`, `verticalLag`, `maxHorizontalLag`, `maxVerticalLag`, `jumpBand`, `leadTime`, `maxLead`, `leadSmoothing`, `recenterDelay`, `recenterTime`, `recenterTo`, `pullOutTime` (see below), `cameraRadius` (radius of the pull-in sweep; `0` turns the pull-in off), `cameraIgnore` (entities whose colliders the pull-in passes through), `occluderFade`, `occluderFadeWidth`, `bodyFade`, `bodyFadeDistance`, `fadeTime`, `fadeIgnore` (fading thin occluders and the subject's body, see below), `sensitivity`, `invertY` (off by default: pushing the mouse forward looks UP; on pitches the other way), `zoomSpeed`, `minPitch`, `maxPitch`.
In edit mode, or while play is paused, writing any framing field re-poses the rig immediately with damping bypassed, so edit mode shows the framing play mode will produce. While play runs, a write steers the rig: its next tick takes the new framing through the damping and the pull-in, the way it takes look input, so a script that turns the camera by writing `aimYaw` swings it round over frames, coming in ahead of a wall as a look does.
`follow` falls back to the `Camera.follow` slot when it is empty, so a rig selected through `Camera.behavior` tracks whatever that camera already follows.
Controls: mouse to look (play mode requests pointer lock, so no button is held), scroll to adjust `cameraDistance`.
## Following the subject: lag, lead and recentre
The camera frames a point that follows its subject's motion with lag, so a step, a stair, a landing, a start, a stop or a reversal is eased rather than copied:
- `horizontalLag` / `verticalLag` (defaults `0.2` / `0.25` s) are the time constants of that point closing on the subject across the ground and along up; `0` carries that motion on the frame it happens.
- `maxHorizontalLag` / `maxVerticalLag` (defaults `1.0` / `0.75` m) bound how far the subject gets from that point, however fast it goes, so the subject never leaves the middle of the frame by more.
- `jumpBand` (default `1.5` m) holds the camera's height through a jump: while the subject is off the ground (its `CharacterController`, or `MovementState`, reads it so) it rises up to this far above the framed height with the camera standing still, so a jump that lands where it took off moves the view along up not at all. Past the band the camera rises with the subject, which stands no farther above the framed height than the band, so a higher jump or a launch keeps it in the picture. A landing higher or lower is eased to over `verticalLag`, and a fall below the framed height is followed as on the ground. `0` follows every jump.
- `leadTime` (default `0.3` s), `maxLead` (`1.5` m) and `leadSmoothing` (`0.5` s): the aim runs ahead of the subject along its motion across the ground by its speed times `leadTime`, held to `maxLead` and eased as the subject starts, stops and turns, so the player sees where the subject is going. `0` aims at the subject.
- `recenterDelay` (default `2` s) and `recenterTime` (`1.25` s): in play, once look input has stopped for `recenterDelay` the heading turns back behind the subject over a time constant of `recenterTime`. `recenterTo` names what it turns behind: `facing` (the default), the way the subject visibly faces (its -Z, or the facing its `Locomotion` or `LocomotionFull` turns, `CameraRig.visibleForward`), or `motion`, the way it moves across the ground. While the subject moves the turn runs at the square of the share of its facing that points away from the camera (half the rate at 45 degrees off the view), so a subject running across the view or toward the camera keeps the heading where it is, rather than the camera and the subject turning each other round, and once it stops the turn waits `recenterDelay` again. A look the player makes while the subject stands holds the heading for as long as it stands: the wait starts once the subject moves off, and a subject that stops again with no look since turns behind after `recenterDelay`. A negative `recenterDelay` turns only on `rig:recenter()`, which turns the heading back now from any delay and ends a look's hold.
- `pullOutTime` (default `0.4` s): once the way is clear the camera eases back out over this time constant. The pull-in itself never cuts (below).
Setting the two lags and `leadTime` to `0` gives the camera that carries its subject's motion on the frame it happens. `rig:tracking()` answers how the camera follows right now: `lag` (how far the subject stands from the framed point), `lead`, `velocity` (the subject's, as the rig measures it), `recentering`, `idle` (seconds since look input) and `lookHeld` (a look the player made holds the heading while the subject stands).
```luau
local rig = entity(camId).component.get("controller.third_person_follow")
rig.verticalLag = 0.4 -- ease stairs and jumps more
rig.recenterDelay = -1 -- keep the heading the player leaves it at
rig:recenter() -- and turn it behind the subject on a button
```
## The control scheme
`inputMap` is the scheme the rig answers to. It reads two controls from it, each on its own:
- `look` — turns `aimYaw` and `aimPitch`.
- `zoom` — steps `cameraDistance`.
A map declaring only one of the two gives the rig that one and keeps the other where it is; the rig logs which control the map left out, and names the map. A field naming no map leaves the rig answering nothing, and logs that too. Point `inputMap` at a world's own map to rebind looking and zooming without touching this component.
**Repointing it on a live rig takes on the next frame.** The map the rig was holding is stood down — its controls leave the live set and its touch buttons leave the screen — and the map named here is taken up in its place:
```luau
entity(rigId).component.get("third_person_follow").inputMap = asset.resolve("mygame.input.cinema", "inputMap")
```
Assigning the map the rig already holds changes nothing, so re-stating the scheme leaves the live set where it is. While gameplay is paused the rig holds no map at all — the editor's camera has the controls — and it takes whatever `inputMap` names when play resumes.
```luau
local cam = entity(id).component.get("Camera")
cam.behavior = asset.ref("@builtin::controller.third_person_follow", "component")
entity(id).component.get("controller.third_person_follow").cameraDistance = 3
```
## The camera pulls in when a collider is in the way
Each frame the rig sweeps a sphere of `cameraRadius` from the shoulder point beside the subject itself (wherever the framed point lags) out to where its framing puts the camera, and stands the camera where the sphere first meets a collider. Every collider in the world stops that sweep, whether or not anything draws it: an invisible walk bound (a `BoxCollider` with no `Model`), a trigger volume and a solid wall all pull the camera in alike. The follow subject is the one entity the sweep passes by default.
The pull-in never cuts. Sweeps of that line ahead, from where the subject is moving to and along where the line is turning over the next 0.8 s, bring the camera in ahead of a wall end or a pillar about to come between it and the subject, at the speed that has it clear when the line gets there; only something no sweep could see coming (a wall that appears) brings it in on the frame it blocks the view, so no frame is drawn from behind geometry. The camera stands no nearer the sweep's start than 0.4 m while there is room round it: when the line has less room than that (the subject against a wall or a pillar the camera is behind), the camera turns round the subject about its up to the nearest turn that has the room, keeps looking the way its framing looks, and turns back onto the line once the line has the room again. A start touching a collider is swept with a thinner sphere, which slides along it, a start nearer it than the thinnest sphere has room for by a ray, and a start inside one holds the camera as far out as it stood.
So a camera that snaps in close to the player, or collapses onto it, while nothing visible stands behind the player is meeting a collider nobody can see. Two fields settle it:
- `cameraIgnore` lists the entities whose colliders the camera sees through. Name the walk bounds and gameplay volumes there and the sweep passes them as it passes the subject, while walls the player can see still pull the camera in. Each entry is an entity (or its id), and it is the collider's own entity that is listed.
- `cameraRadius = 0` turns the pull-in off: the camera stands where its framing puts it, through every collider.
```luau
local rig = entity(camId).component.get("controller.third_person_follow")
rig.cameraIgnore = { entity.find("NorthBound"), entity.find("SouthBound") }
-- or drop the pull-in entirely
rig.cameraRadius = 0
```
## Thin occluders and the subject's body fade instead of filling the view
In play the camera fades what would otherwise fill the view in place of the subject. A thin occluder (a pillar, a pole, a post, a railing, a doorframe's jamb, a tree trunk: a collider no wider than `occluderFadeWidth` across the line from the camera to the subject at its narrowest, and no deeper along it) does not pull the camera in: the sweeps pass it, and while it stands between the camera and the subject it fades to `occluderFade`, that share of its pixels left undrawn in a screen-space dither so the subject shows through. Walls, floors and every collider wider or deeper than that still pull the camera in, as above. The subject's own body fades as the camera comes within `bodyFadeDistance` of the aim point, reaching `bodyFade` at the nearest the camera stands (0.4 m), so a camera pulled in against a wall shows what lies past the subject rather than the back of its head. Each fade eases in and out over `fadeTime`, never in one frame.
A fade covers the entity and its descendants, in this engine's own views (each player's camera sets its own), and shadows stay whole. `fadeIgnore` lists entities the camera never fades: they pull it in whatever their size. `occluderFade = 0` brings back the pull-in for every collider, and `bodyFade = 0` keeps the body drawn whole. `rig:fading()` reports what the camera fades this frame, and `renderer.drawStats().cameraFaded` how many renderables carry a fade.
```luau
local rig = entity(camId).component.get("controller.third_person_follow")
rig.fadeIgnore = { entity.find("GateLever") } -- a lever the player must always see
rig.occluderFade = 0 -- or pull in for every collider
```
## Attach through `Camera.behavior`
The Camera owns the behavior slot, so assigning the rig there is what lets the Camera tell it when `follow` changes. A rig added straight onto the entity with `component.add` still poses, but the Camera does not know about it and a `follow` assigned afterwards will not reach it.
Assigning the slot attaches the rig to the camera's entity, so it is tuned on that instance: `component.get("third_person_follow")` and set its fields. A `component.add("third_person_follow", { ... })` after the assignment, in a scene `build.luau` or anywhere else, writes its values onto the instance the slot attached and returns it, so the Camera keeps the one rig it knows about. In a `build.luau` that add is the way to tune the rig: its values are saved with the scene and the loaded rig holds them.
## Player cameras: leave `follow` unset
Entering play drops and respawns `PlayerPrototype` subtrees, so the body is recreated with a NEW entity id. A `follow` authored on the rig keeps pointing at the original, which is no longer live, and the camera freezes at its last pose instead of tracking the player.
For a player camera, set the target on the **Camera** and leave the rig's own `follow` empty:
```luau
entity(rigId).component.get("Camera").follow = body -- PlayerPrototype rebinds this on every spawn
```
`PlayerPrototype` refreshes `Camera.follow` to the live body each time it clones, and the rig reads that slot whenever its own `follow` is empty. Set the rig's `follow` only for a camera that watches a fixed, non-respawning subject.
# ReflectionProbe
A reflection probe: bakes the scene into its own cube slot from its position, so reflective surfaces within its `radius` mirror the captured surroundings. Multiple probes in a scene are blended by proximity and rank (the renderer's per-fragment probe blend); a surface outside every probe's radius reflects the sky fallback, or the scene's ambient when no sky is captured. The probe renders a small editor-only gizmo marker (cyan octahedron) in edit mode and is invisible in play mode.
Every field is live: editing `radius`, `priority`, the proxy or `skyFallback` in the inspector re-pushes the probe, and `reflectionProbe.list()` reports what the component holds.
A probe is an **authoring-time** bake: it loads its persisted baked cube on awake (`reflectionProbe.loadBaked`) rather than re-baking on every load. A probe reflects once it holds a cube: until it is baked (or has a persisted bake to load) it adds nothing to the frame, arms no sky fallback, reads `baked = false` in `reflectionProbe.list()` and in `lighting.get`'s `environment.probes`, and the engine log names it with the call that bakes it. Set `probeId` on authored probes so the baked `probe_<probeId>.texture` asset keeps the same identity across reloads (the runtime entity id changes; the probeId does not).
Public fields:
- `radius` (number, default `12`) — influence radius in world units. A surface within it reflects this probe at a weight falling from full at the probe to zero at the radius.
- `bakeOnAwake` (bool, default `false`) — opt-in first-time bake on awake (deferred a few frames so geometry is GPU-resident; baking before the scene renders captures black). Only fires when no persisted baked cube exists yet.
- `probeId` (string, default `""`) — stable asset identity for the persisted baked cube. Empty → falls back to the entity id.
- `skyFallback` (bool, default `true`) - once the probe holds a cube, capture the scene's sky into the fallback slot so a surface outside every probe's radius reflects the sky.
Methods: `:bake()` — (re)bake this probe from its current position into its cube slot and persist it (runs off the calling frame).
```luau
-- One-liner (spawns an entity carrying this component):
reflectionProbe.add(0, 3, 0, { radius = 15, probeId = "lobby" })
-- Or attach directly + bake everything once the scene is built:
entity.find("zone").component.add("ReflectionProbe", { radius = 12 })
reflectionProbe.bakeAll()
```
Max 8 probes (cube slots). Registry policy lives in `@builtin::api.engine.reflectionProbe`; the generic per-slot capture primitive is the `environment` module.
# temporalUpscale system
Render fewer pixels than the display has, and get the display's pixels anyway.
Shading cost scales with pixel count, so rasterizing the scene smaller is the
one lever that buys frame time without taking anything out of the frame. What it
spends is sharpness: an upscale invents nothing, and one frame carries only as
many distinct samples as the scene had pixels.
This system spends the frames instead. The projection samples a different point
inside every pixel each frame, so consecutive frames are different estimates of
the same continuous image; the reconstruction carries them forward through the
scene's own motion vectors and mixes each new one in. After a handful of frames
the standing result holds samples from several different grids — detail no
single frame ever rasterized.
## Using it
Put `TemporalUpscale` on any entity in the scene:
```lua
entity(id).component.add("TemporalUpscale", { renderScale = 0.5 })
```
Half the scale is a quarter of the pixels. Every field is live: edit
`renderScale` in the inspector and the scene rasterizes at the new size from the
next frame. Removing the component puts the render scale back where it was
before the component moved it, so the frame returns to the resolution it had.
### The visibility raster
The visibility raster rasterizes through the same sub-pixel offset this pass
moves the projection by, so the depth and motion it lays describe the image the
resolve shades.
For code that wants it without a component — a settings screen, a benchmark —
reach for the module:
```lua
local Upscale = require("@builtin::systems.temporalUpscale.temporalUpscale")
Upscale.enable({ renderScale = 0.5, sharpness = 0.35 })
Upscale.get()
Upscale.disable()
```
Leaving `renderScale` out of `enable` leaves the scale where it is, which is what
lets `@builtin::systems.renderScale.renderScale` keep steering it against a frame
budget while the reconstruction runs.
## Where it runs
The reconstruction is a compute pass at the head of the `display` stage
(`afterScenePost`), ahead of the debanding, edge antialiasing and sharpening
the stage then lays on it: the seam where the
frame has already reached the display's resolution and the UI has not been
composited onto it yet. So the scene is reconstructed and the text over it stays
untouched, drawn once at the display's own size.
Its accumulation is a history target created with `screenSpace = "composite"`,
which is what keeps it the size of that composited image while the scene renders
smaller. Every view accumulates in images of its own: an offscreen render (an RT
camera, a `capture`) runs the reconstruction on its own picture and leaves the
viewport's accumulation as the viewport left it. The scene's depth and velocity
stay at the scene's resolution; the pass maps each composite pixel back into
that grid to read them.
Where the composite lands depends on who presents the viewport. In a runtime
session the renderer presents it, and the upscale to the display's resolution
happens before `afterScenePost` — so the composite is the display's own size and
the reconstruction resolves onto the display's grid. Under a UI viewport panel
the panel draws the scene target at its own rect, nothing upscales before the
composite, and the two spaces carry the same size: the pass then accumulates at
the render resolution and the panel scales the result. It says so in the log on
the second frame when that is what it finds.
## The resolve, and the sample sequence
The reconstruction folds each frame in through the temporal resolve
(`@builtin::systems.antiAliasing.temporal_resolve`), the one temporal
antialiasing runs at scale 1: the history is read through a Catmull-Rom spline,
which keeps the contrast of thin lines through a slow pan; samples
are weighed in a reversible tonemapped space; the history is variance-clipped
in YCoCg against the scene samples within a texel and a half of the pixel; and
the frame's share is halved wherever the history passes the clip untouched.
Every frame takes the same share: a frame trusted more when one of its samples
landed nearest a pixel weighs each pixel by where the jitter fell in its row as
well as its column, which settled the rows of one scene texel on alternating
values along every thin edge. The clip pulls the history fully into the
current frame's neighbourhood wherever it falls outside it, so a surface that
moves across a still background, a change of light and the first frames after
the reconstruction starts reach the picture at once.
The sequence of points inside the pixel the projection samples is eight per
display pixel, scaled by how many display pixels a scene pixel covers: 32 at
half scale. A run too short for that visits some display pixels more often than
others, and the converged picture kept that unevenness as a fixed pattern along
every thin edge.
`sharpness` sharpens the shown picture with `@builtin::systems.antiAliasing.rcas`
after the reconstruction, outside its history, so it never compounds.
## Its relationship to the other temporal pass
`@builtin::systems.antiAliasing.temporalAntiAliasing` is the same resolve at the
scene's own resolution, and a world created from the default template runs it.
The frame has one temporal reconstruction, so enabling this module with a
reconstructing backend (`"taau"`, `"dlss"`, or `"auto"`) has temporal
antialiasing stand aside (`temporalAntiAliasing.yieldedTo()` names this module);
`disable` hands the frame back, and temporal antialiasing runs again if it is
still enabled. Backend `"none"` reconstructs nothing and leaves it running.
## Files
```
temporalUpscale.package/
TemporalUpscale.component/ -- the settings, authored and persisted
temporalUpscale.module/ -- enable / get / active / disable
taau.renderFeature/ -- the jitter, the two targets, the pass
taau_resolve.computeShader/ -- the reconstruction itself
```
# controller.rts
RTS camera controller. Top-down strategy camera. WASD to pan (aligned to camera yaw), scroll to zoom, right-click drag to rotate. Optionally lock to a target entity.
Public fields: `inputMap` (the camera-rig scheme, `@builtin::inputMaps.cameraRig`, by default; point it at a world's own map to rebind this camera), `target` (the entity to follow: the entity, its id or its name, kept as an entity reference; unset follows `Camera.follow`, else pans free with WASD), `centerX`, `centerY`, `centerZ`, `distance`, `minDistance`, `maxDistance`, `moveSpeed`, `sensitivity`, `zoomSpeed`, `minPitch`, `maxPitch`.
Controls: WASD to pan, scroll to zoom, RMB drag to rotate.
```luau
entity(id).component.add("controller.rts", { distance = 15, moveSpeed = 12 })
```
# controller.mount
A camera that rides a body: it stands at a point of the body's own frame,
faces an orientation in that frame, and moves with the body where it is drawn
each frame, so it stays on its seat as the body drives, turns, pitches and
rolls, smooth whatever the physics tick rate and the frame rate. A driver's
seat, a hood or bumper view, a helmet, a turret sight, a boat's bridge, a
coaster car, a mech's cockpit.
```luau
local cam = entity.spawn("cockpit")
local camera = cam.component.add("Camera", { fov = 70 })
camera.behavior = asset.ref("@builtin::controller.mount", "component")
camera.follow = car
local mount = cam.component.get("@builtin::controller.mount")
mount.offset = { x = -0.35, y = 0.9, z = 0.2 } -- the driver's eye, in the car's frame
mount.headMotion = 0.04 -- the head moves with braking and cornering
```
A key that switches between this view and a chase view behind the car writes
the Camera's `behavior` (`@builtin::controller.chase` reads the same
`Camera.follow`):
```luau
camera.behavior = asset.ref("@builtin::controller.chase", "component") -- behind the car
camera.behavior = asset.ref("@builtin::controller.mount", "component") -- back in the seat
```
A hood view is the same rig with `offset` on the bonnet; a rear view turns it
round with `mountYaw = 180`; a turret sight puts `follow` on the turret's own
entity, which the rig reads the drawn pose of like any body.
## Fields
| Field | Default | Notes |
|---|---|---|
| `follow` | empty | The body to ride. Empty takes the Camera's `follow` slot. Any entity: a body, or an entity parented under one (a seat, a turret), read where it is drawn. |
| `offset` | `{0, 1.2, 0}` | Where the camera stands: metres along the body's own axes, x right, y up, z back (a car's forward is its local -Z). |
| `mountYaw` | `0` | Degrees the view is turned right of the body's forward. |
| `mountPitch` | `0` | Degrees the view is tilted up from the body's forward. |
| `lookSensitivity` | `0.3` | Degrees per unit of the `look` control. |
| `lookYawLimit` | `120` | Degrees the look turns either side of the mount's direction. |
| `lookPitchMin`, `lookPitchMax` | `-45`, `45` | Degrees the look tilts down and up. |
| `lookReturnDelay` | `0.6` | Seconds after the look is let go before the view comes back. Negative holds the look. |
| `lookReturnTime` | `0.25` | Seconds (time constant) of the view coming back. |
| `invertY` | `false` | Forward on the look control looks up unless this is on. |
| `headMotion` | `0` | Metres the eye moves against each g of acceleration along the body's forward and side axes; the view leans with it, dipping under braking and swaying out of a turn. 0.04 is a belted driver. |
| `headLag` | `0.12` | Seconds (time constant) the head takes to follow a change of acceleration. |
| `inputMap` | `@builtin::inputMaps.cameraRig` | The map `look` is read from. The camera-rig map stays live while a vehicle holds the player's controls. A write on a live rig takes up the new map. |
## How it moves
The rig reads `Physics.drawnPose` of its body every frame: the pose the frame
draws the body at, blended between physics ticks. A camera placed from the
body's transform (`entity.position`) would move in whole ticks while the body
is drawn between them, and the cabin would shake on screen.
Head motion reads a motion probe the rig places at the mount point
(`Physics.probeMotion`) on the rigid body that carries `follow`: the followed
entity's own body, or for a seat or a turret entity the body it is parented
under. The probe reads the acceleration a rider there feels, which the rig
turns into the followed entity's own axes. A body this peer does not simulate
gives the probe nothing to read, and the head holds still on it.
The camera entity stands unparented: the rig writes its world pose every
frame.
## Controls
- **Look**: right-button drag, the right stick, or a drag on the right of a
touch screen (the camera-rig map). The view returns to the mount's
direction once the control is let go.
For mouse look with no button held, point `inputMap` at a map of the world's
own in the `camera` group that declares `look` with `pointerLock = true`: the
camera group stays live while a vehicle holds the player's controls.
# SceneModule
A placement of a `.sceneModule`: the module this entity is built from, and the
params this placement sets. In edit mode it runs the module's builder and
reconciles the result under this entity; what lands is permanent scene content —
saved in `scene.json`, replicated, selectable and inspectable like anything
placed by hand.
Public fields:
- `source` — the module to build. Gated by capability, so it accepts any asset
whose type defines `instantiate`. `module` is an input alias for
it.
- `params` — this placement's input overrides, keyed by the names the module
declares in its `inputs`. A name the module declares overrides that input's
default; a name it does not declare is left alone.
Those two are the whole record. A placement in `scene.json` reads:
```json
{
"id": "ent_ee2d09b7c4ee5a28",
"name": "orchard_0",
"components": [
{
"type": "@builtin::components.SceneModule",
"data": {
"enabled": true,
"params": { "rows": 2 },
"source": { "name": "Orchard", "type": "sceneModule", "guid": "49ba97ac-…" }
}
}
]
}
```
The entities the build placed sit beside it as records of their own, each
naming this entity as the build that placed it and its own chain of names from
the build root down to it:
```
buildOwner=ent_ee2d09b7c4ee5a28 buildKey=orchard
buildOwner=ent_ee2d09b7c4ee5a28 buildKey=orchard/tree_r1
buildOwner=ent_ee2d09b7c4ee5a28 buildKey=orchard/tree_r1/canopy
```
```luau
local pusher = entity.spawn("pusher_0")
pusher.component.add("SceneModule", {
source = asset.resolve("CoinPusher", "sceneModule"),
params = { seed = 0, coinCount = 40 },
})
pusher.localPosition = { 0, 0, 0 }
```
Placing the same module twice with different params yields two different
results from one asset:
```luau
for i = 0, 2 do
local p = entity.spawn("pusher_" .. i)
p.component.add("SceneModule", { source = coinPusher, params = { seed = i } })
p.localPosition = { i * 4, 0, 0 }
end
```
## Rebuilds
A write to the module's `init.luau`, or a change to `params`, re-runs the
builder and **reconciles** the result: an entity the previous build placed is
updated in place, one the build no longer emits is removed, and a new one is
spawned. Ids hold, so a reference to a built entity survives the rebuild.
A rebuild recognises its own entities by computing those ids again: the same
placement and the same place in the hierarchy give the same string. The scene
save writes them and the load brings them back, so a rebuild in a later session
lands on exactly the entities the first build placed with nothing carried
between the two.
A CHANGE is what rebuilds, and the changes are `source`, `params`, and the
module's code on disk. Loading and mode flips are not changes: the entities are
in the scene as authored content, the last bake is what they hold, and the
placement runs nothing. A rebuild whose module, params and module source are
all unchanged is skipped too. `:rebuild()` forces one anyway — for a change
nothing else reports, such as an asset the builder resolves changing underneath
it, or a module edited while the world was closed.
A build that raises leaves the previous one in the scene and says so, rather
than emptying the placement over a typo. A build that runs as its scene loads
and states no records, over a placement that built entities before, is held to
the same rule: the previous build stays and a warning names it. A rebuild after
the load (`:rebuild()`, a write to the module) applies an empty statement.
A build that runs as its scene loads reruns on every load, so what it adds,
changes and stops placing is not recorded in the scene's unsaved edits: the
load shows it live, and a save writes it into `scene.json`.
## Who states the params
A placement an author made — dragged in, spawned by a tool, written by a script
— holds its own params. Nothing else sets them.
A placement a **build** made is stated by that build. A scene's `build.luau`
that places one names its `source` and its `params`, and every run of that build
states them again — on load, on a write to the file, on `:build()`. So a param
set on such a placement is a preview: it rebuilds at once and holds until the
next run of the build, which states the params its own source gives.
Both moments say so. Setting a param on a build-placed placement names the file
that states it:
```
[warn] [client user] a build placed this entity and states its SceneModule params — a param
set on the placement holds until that build runs again and states them from its
own source { placement="tent_ring_placement", set="count = 9",
statedIn="/zero/source/scenes/main.scene/build.luau (content)" }
```
and the run that states them again names what it replaced:
```
[warn] [client user] a build ran and stated this placement's SceneModule params over the ones
set on the placement — the file the build is written in is where they are stated
{ placement="tent_ring_placement", replaced="count: 9 → 7",
statedIn="/zero/source/scenes/main.scene/build.luau (content)" }
```
A run that states what the placement already holds says nothing. To change the
value for good, change it where the build states it.
A build that stops stating a placement takes what the placement built with it.
When a run no longer adds the `SceneModule` to an entity it places, because it
dropped the module or now places it there through `instantiate`, the entities
the placement built under that entity go with the component, so the entity
holds only what the build states now. A placement an author
added to an entity a build places is the author's: a run of that build leaves
it and what it built in place.
## Play
In play of an editor session the placement builds from its module the way it
does in edit mode, and what the build lands exists in the play scene alone: it
records nothing in the scene's unsaved edits, so a module edited while the scene
was closed shows its current output in play before any save. A runtime-profile
boot has no edit session: the entities load as authored content from
`scene.json`, nothing builds, and the component is inert there.
## Methods
- `:rebuild()` — re-run the builder and reconcile, ignoring the signature.
Returns false on a runtime-profile boot, where nothing builds.
- `:declaredInputs()` — the bound module's declared inputs, sorted:
`{ name, kind, default, values? }`. The set `params` can address.
# PositionConstraint
Constrains an entity's transform (position, optionally rotation and scale) to follow a target entity, with optional offset. Use `weight` to control smoothing.
Public fields: `targetEntityId`, `targetPositionX/Y/Z`, `offsetX/Y/Z`, `axisX`, `axisY`, `axisZ`, `weight`, `constrainRotation`, `constrainScale`.
Methods: `setTarget(entityId)`, `setOffset(x, y, z)`, `setWeight(w)`.
```luau
entity(id).component.add("PositionConstraint", {
targetEntityId = carId,
offset = {0, 5, 10},
weight = 0.15,
})
```
# PlayerSpawn
A world entity that spawns players from a prototype. It carries the fields describing how spawning happens: which `prototype` to instantiate, the `team` and `role` assigned to spawned players, a `maxPlayers` cap (0 = unbounded), the `spawnPolicy` (how many players spawn from this point), and the `placement` (where a spawned player is positioned). The entity's own transform is the spawn point when `placement` is `at_spawn_transform`. In edit mode it draws an orange silhouette outline at the spawn point and surfaces its own setup-validation messages (missing or mis-targeted prototype) on the component's error channel.
Location: `src/lua/lib/components/PlayerSpawn.component`
# weather system
Weather that the world acknowledges.
Rain and snow as particles fall through a scene that never changes, and the eye
reads that immediately: particles in front of a dry world. What sells weather is
the ground going dark and reflective, snow lying on what faces up, and the patch
under a roof staying clear of both.
## Using it
Weather is a component — author it once and it persists:
```lua
local id = entity.spawn("weather").id
entity(id).component.add("Weather", {
wetness = 0.8,
snow = 0.0,
shelter = 1.0,
})
```
Every field is live. Both `wetness` and `snow` at 0 releases the pass entirely.
For code driving weather over time — a storm cycle, a scripted downpour:
```lua
local weather = require("@builtin::systems.weather.weather")
weather.set({ wetness = 0.4 }) -- any subset; the rest is kept
weather.get()
weather.active()
weather.bakeShelter() -- re-read the cover after moving a roof
weather.shelterField() -- where the cover field stands
weather.clear()
```
## What the knobs do
| field | effect |
|---|---|
| `wetness` | How wet surfaces are. Darkens them and adds a sheen that rises toward grazing angles. |
| `snow` | How much snow has settled on upward-facing surfaces. |
| `shelter` | How strictly cover is respected. 1 leaves anything under a roof dry; 0 wets the world evenly. |
| `shelterDistance` | How far up the shelter test looks, world units. |
| `shelterResolution` | Cells across the cover field that test reads, 8-64. More resolves a roof's edge and a narrow overhang. |
| `shelterRegion` | The square of world the cover field covers, `{ x, z, size }`. Omitted, the square already in force is kept; a `size` of 0 hands the extent back to the scene's own geometry, which is where it starts. |
| `gloss` | How strong the wet sheen is. |
| `snowBias` | How steeply a surface must face up before snow settles. |
| `wetTint` / `snowColor` / `skyColor` | What a wet surface darkens toward, the colour of settled snow, and the tint the sky puts on the radiance the surroundings hand a wet surface. |
Rain and snow treat orientation differently on purpose. Rain wets a wall
somewhat; snow either lies on a surface or it does not, so `snowBias` is a
threshold and wetness is a ramp.
## How it renders
`surfaceWeather.renderFeature` runs one compute pass after lighting. It
reconstructs each pixel's world position and normal, reads how much sky that
point can see out of the cover field, and applies wetness and snow weighted by
that and by orientation.
## What the cover field is
Shelter is a fact about the world, so it is answered from the world. The weather
module bakes a cover field over the scene: an XZ grid whose every column holds
the heights of the undersides standing over that place, found by casting a ray
up through the geometry the renderer draws. A point is sheltered when a column
records a surface between just above the point and `shelterDistance` above it.
A surface therefore reads the same cover from every camera, at every lens, and
whether or not the roof over it is in frame.
The four cells around a point are blended, so cover fades across one cell at a
roof's edge instead of switching on a cell boundary. `shelterResolution` is what
one cell is worth: the grid spans the scene's geometry, so at 64 cells over a
100 m scene a cell is 1.6 m.
A column was read along a ray cast at its cell's own centre, up to a cell away
from the point reading it, and the surface that point stands on has climbed by
then if it runs at a slope. The point's normal says how much, so the height its
own surface reaches at the cell is what cover has to clear there: a hillside, a
ramp and a pitched roof stand open to the sky rather than sheltering themselves.
A face steep enough to stand as a wall carries nothing, because its own column
records its base below it.
A column holds the eight lowest surfaces standing over its cell, so cover under
a ninth is read as open sky.
The field is baked when weather starts, and re-derived whenever the count of
renderables the frame drew moves — which is how geometry that loads after the
weather was set gets its cover. The interval between those checks grows with
what a bake costs, so keeping the field current stays inside a small share of
wall clock however large the scene is. Cover that moves or reshapes without
changing that count is re-read by calling `weather.bakeShelter()`.
Wetness darkens and adds a sheen against water's reflectance — a water film
refracts more light into the surface where it is absorbed, and reflects what
remains in a tighter lobe. What the sheen reflects is the light the surface
stands in, taken the way the surface itself takes it: the radiance the
surroundings hand the whole hemisphere under `skyColor`'s tint, through a
Schlick term that rises toward grazing; plus the sun and every lamp the scene
holds, each through the Cook-Torrance lobe the lit passes shade it with and on
the terms of its own kind — a cone where it points, a rect from the face it
emits along, a distant light along its one direction. So a wet floor in a warm
room reflects that room, a wet floor under a bright sun carries the sun, and a
wet floor with the lights out reflects nothing.
Snow takes over a surface's colour rather than tinting it, modulated by how lit
the surface already was so it does not glow in a dim scene.
## Files
```
weather.package/
Weather.component/ -- the scene's weather, authored and persisted
weather.module/ -- weather.set / .get / .clear / .active
surfaceWeather.renderFeature/ -- the compute pass
```
# components.FreeMover
WASD + mouse free-fly mover. Attach to an entity to make it move under
WASD input with mouse look, independent of any character controller or
physics rig. Used by the editor's free camera and any debug "fly-around"
viewpoint.
Public fields: `speed`, `sensitivity`, `sprintMultiplier`.
# Mover
`Mover.component` — see `init.luau` for the component surface.
Location: `src/lua/lib/components/Mover.component`
# HeightfieldCollider (component)
A regular grid of heights, which is the shape terrain collides with. Testing
against it costs a cell lookup rather than a walk down a triangle tree, so a
large landscape collides at a cost that stays flat as it grows.
## The grid
`rows` and `cols` are the grid's dimensions, `extent` its world span as
`{ x = width, y = heightScale, z = depth }`, and `heights` the row-major grid
itself, indexed `heights[r * cols + c + 1]`. The grid is centred on the entity.
`rows` maps to the entity's local Z and `cols` to its local X.
```lua
entity.find("terrain").component.add("HeightfieldCollider", {
rows = 64, cols = 64,
extent = { x = 300, y = 1, z = 300 },
heights = grid,
})
```
Use `setGrid(rows, cols, heights)` to replace the grid and the dimensions
describing it together, so the two are never out of step.
## Replication
`heights` is `NoSync`. It is large, and every peer can rebuild it from its own
copy of the terrain, so replicating it would send a whole landscape over the
wire to reproduce something each peer already has.
## Fields
| Field | Meaning |
|-------|---------|
| `rows` / `cols` | Grid dimensions. |
| `extent` | World span, with `y` scaling the heights. |
| `heights` | Row-major height grid. Not replicated. |
| `isTrigger` | Report overlaps without blocking. |
| `friction` | Surface friction. |
| `restitution` | Bounciness. |
| `rollingResistance` | How strongly the surface resists a body rolling on it: a rolling body slows at this many times gravity on level ground, so a ball rolled at v stops after v^2 / (2 * rollingResistance * 9.81). 0 rolls on. |
| `spinningResistance` | The same for a body spinning on the surface about the contact normal. 0 spins on. |
| `surface` | The surface the collider is made of, by name: one `Physics.defineSurface` defined gives it its friction, restitution and resistances in place of the fields above, and contacts, contact events and ray and shape casts report the name either way. Empty names none. |
| `surfaceLayers` | The surfaces the height samples name, by name: each painted layer of a terrain collides as its own surface. |
| `surfaceMap` | Per height sample, row-major as `heights`, the one-based index into `surfaceLayers` of the surface it names (0 for `surface`). A contact or cast on the field names the layer of the sample nearest the point and collides with that surface's coefficients. |
| `oneWay` | The direction, in the collider's own frame, bodies pass through it along: a body moving that way goes through, and a body meeting it from the side the direction points to stands on it (a jump-through platform is `{0, 1, 0}`). `Physics.passThrough(entity)` drops a standing body through. Unset blocks from every side. |
| `surfaceVelocity` | The velocity, m/s in the collider's own frame, its surface moves at along itself while the collider stays put: friction carries what rests on it (a conveyor belt, a treadmill, an escalator). Write it at runtime to change the speed or direction. Unset holds the surface still. |
| `contactTag` | The tag the world's contact filter reads this collider by: `Physics.setContactFilter(tagA, tagB, mode)` makes two tags pass through each other (`"ignore"`), report contacts and push nothing (`"sensor"`) or collide (`"solid"`). Empty names none. |
# PathFollower
Moves its entity along a path at a constant speed in metres per second, and
turns it to face the way it moves: a train or tram on its track, a patrol on
its route, a boat down a river, a camera dolly, a ghost car on a racing line,
a creep walking a tower-defence lane.
The path is any of:
- a list of points (`points`): straight lines between them, or a smooth
Catmull-Rom curve through them with `smooth = true`;
- a spline from `@builtin::modules.spline` (`follow(spline.new(...))` takes
its points, its mode and whether it is closed);
- a route or a lane loop from `@builtin::modules.pathNetwork`
(`follow(net:route(a, b))`, `follow(net:lanePath(ids, { closed = true }), { mode = "loop" })`).
Speed is constant along the curve whatever the spacing of the points, because
the path is measured by arc length (`spline.measure` / `spline.atDistance`).
## Fields
| Field | Default | Meaning |
|---|---|---|
| `points` | `{}` | The points the path runs through, in order. |
| `smooth` | `false` | A smooth curve through the points rather than straight lines. |
| `closed` | `false` | The path joins its last point back to its first. |
| `speed` | `5` | Metres per second along the path; negative runs it backward. |
| `distance` | `0` | How far along the path the entity is, in metres. Set it to place the entity. |
| `mode` | `"loop"` | At the end: `"loop"` starts again, `"pingPong"` turns back, `"once"` stops (and sets `playing` false). |
| `orient` | `true` | Turn the entity to face its direction of travel (its -Z forward), pitching with the slope. |
| `height` | `0` | Metres above the path the entity rides. |
| `playing` | `true` | Whether it moves. |
The follower sets the entity's transform each frame, so it drives an entity
with no dynamic body: a kinematic train, a prop, a camera rig. A car driven by
physics follows a path by steering toward `net:lookAhead(...)` instead (see the
`pathNetwork` module).
## Methods
| Method | |
|---|---|
| `:follow(path, opts?)` | Follow a path from its start; `opts` sets `speed`, `mode`, `smooth`, `closed`, `distance`, `height`, `orient` with it. Answers the path's length. |
| `:length()` | The length of the path being followed, in metres. |
```luau
local spline = require("@builtin::modules.spline")
local tram = entity.spawn("tram")
tram.component.add("Model", { model = "@builtin::meshes.cube" })
tram.component.add("PathFollower", { speed = 8 })
tram.component.get("PathFollower"):follow(spline.new({
{ 0, 0, 0 }, { 60, 0, 20 }, { 120, 0, 0 }, { 60, 0, -40 },
}, { mode = "catmullRom", closed = true }))
```
# Humanoid
Marker component for entities carrying a skeleton conforming to the
standard humanoid bone layout (Synty / Unreal-Mannequin convention).
Content reads a humanoid body's bones and attachment sockets through this
component instead of re-walking the descendant tree, and seats items on
those sockets with `:attach`.
## Bone naming convention
```
Hips
Spine_01 → Spine_02 → Spine_03 → Neck → Head
└ Eyes, Eyebrows, Jaw
UpperLeg_R / UpperLeg_L
LowerLeg_R / LowerLeg_L
Ankle_R / Ankle_L
Ball_R / Ball_L → Toes_R / Toes_L
Clavicle_R / Clavicle_L
Shoulder_R / Shoulder_L
Elbow_R / Elbow_L
Hand_R / Hand_L
IndexFinger_01..04 / Thumb_01..04 / Finger_01..04
```
Mixamo / Unity-Humanoid imports go through a bone-rename pass at import
time (tracked separately).
## Fields
| Field | Type | Notes |
|---|---|---|
| `height` | number | Foot-to-head height in T-pose, metres. Default 1.8. |
| `eye_height` | number | Foot-to-eyes height, metres. Default 1.65. |
| `bones` | `{ [string]: entity }` | Computed; bone-name → entity-proxy map. Re-walks on read. |
| `sockets` | `{ [string]: entity }` | Computed; role (`righthand`, `head`, …) → the bone filling it on this body, through the body's RetargetProfile. |
## Methods
| Method | Returns | Notes |
|---|---|---|
| `:bone(name)` | `entity \| nil` | Nil-safe single-bone lookup; same as `self.bones[name]`. |
| `:socket(point)` | `entity \| nil` | The bone at a role, or at an exact bone name. |
| `:attach(point, childId, opts?)` | `entity \| nil` | Seats `childId` on the socket bone at the socket's frame, moved by `opts.position` / `opts.rotation` / `opts.scale`. Position and scale are metres in the humanoid's own space, whatever bone units the rig was authored in; rotation is relative to the bone, as a quaternion `{ x, y, z, w }` or Euler degrees `{ pitch, yaw, roll }`. An option outside those three, or a value in none of those forms, raises with the item left as it was. Returns the socket bone. |
| `:attachments()` | `{ { id, point, position, rotation, scale } }` | Every item seated with `attach`, with the point and transform it was seated with. An avatar body swap re-seats each on the new body. |
## Usage
```luau
-- Read a specific bone
local h = entity(playerId).component.get("Humanoid")
local head = h.bones.Head -- entity proxy
local handR = h:bone("Hand_R") -- nil-safe lookup
-- Seat a hat 12 cm above the head, on any humanoid body
local hat = entity.spawn("hat")
h:attach("head", hat.id, { position = { 0, 0.12, 0 } })
-- Read height for camera mounting
local cam = entity.spawn("eye_cam", { parent = playerId })
cam.localPosition = { 0, h.eye_height, 0 }
```
## Tag convention
Bundles carrying a humanoid skeleton tag themselves with both
`playerVisual` AND `humanoid` in their `.metadata`. Tooling can filter
to humanoid-conforming visuals via
`asset.list("bundle", nil, { fields = { tags = { "playerVisual", "humanoid" } } })`.
# controller.isometric
Isometric camera controller. Fixed-angle overhead camera (classic isometric view). WASD to pan on the XZ plane, scroll to zoom. The viewing angle is fixed (no rotation).
Public fields: `inputMap` (the camera-rig scheme, `@builtin::inputMaps.cameraRig`, by default; point it at a world's own map to rebind this camera), `target` (the entity to follow: the entity, its id or its name, kept as an entity reference; unset follows `Camera.follow`, else pans free), `centerX`, `centerY`, `centerZ`, `distance`, `minDistance`, `maxDistance`, `moveSpeed`, `zoomSpeed`, `yaw` (default pi/4), `pitch` (default ~35.26 degrees).
Controls: WASD to pan (world-axis-aligned), scroll to zoom.
```luau
entity(id).component.add("controller.isometric", { distance = 12, moveSpeed = 8 })
```
# LookAtConstraint
Rotates an entity to face a target entity or a fixed world position. Use `weight` for partial/smoothed orientation.
Public fields: `targetEntityId`, `targetPositionX/Y/Z`, `axisX`, `axisY`, `axisZ`, `weight`.
Methods: `setTarget(entityId)`, `setWeight(w)`.
```luau
entity(id).component.add("LookAtConstraint", {
targetEntityId = playerId,
weight = 0.5,
})
```
# Audio
Adds audio playback to an entity, driven by a `.soundClip` asset. Supports sound effects, music, and spatial/3D audio tied to entity position.
Public fields: `clip` (`AssetRef<soundClip>`), `sourceType` (`"SoundEffect"` / `"Music"` / `"Ambient"`), `volume`, `pitch`, `looping`, `spatial`, `maxDistance`, `rolloff`, `autoplay`, `channel`, `pitchValue`, `volumeValue`.
`pitchValue` and `volumeValue` name named values (`values.set`, the `topics/values` guide) the voice follows: it plays at `pitch` times the value and `volume` times the value the entity, or its nearest ancestor holding one, carries under that name, read every frame with no script writing the source. An engine note on a car follows `car.values.set("rpmRatio", rpm / 1000)`; a tyre squeal on a wheel takes `volumeValue = "wheel.skid"`.
A spatial source plays at full volume within one unit of the listener and reaches silence at `maxDistance` (default 50). Across that window its amplitude is `(1 - t)^rolloff` for a source `t` of the way through, so the default `rolloff` of `1` is a linear fade — half the distance, half the amplitude — a larger exponent drops away sooner, and `0` holds full volume to the edge.
Methods: `play()`, `pause()`, `stop()`, `setVolume(v)`, `setPitch(p)`.
```luau
entity(id).component.add("Audio", { clip = explosionClip })
entity(id).component.add("Audio", { clip = fireClip, spatial = true, looping = true })
```
A loose audio file (ogg/mp3/wav/flac) needs to be imported into a `.soundClip` asset before it can be referenced here — the importer creates the container and encodes its playable payload.
Whether the clip streams its compressed payload or decodes fully on load follows the clip's own `loadType` setting: `"decompressOnLoad"` and `"streaming"` apply directly, and `"auto"` (the clip's default) picks by the clip's duration — short one-shots decode up front, longer tracks stream. The clip decides: each source this component builds asks `clipRef:streams(bytes)`.
# CutsceneTrigger
Plays a cutscene when something happens, without writing the wiring: the scene
entering play, the player reaching this entity, or a call from your own code.
```luau
-- the game opens on a cutscene
entity.spawn("Intro").component.add("CutsceneTrigger", {
cutscene = "mygame.scenes.intro",
trigger = "onPlay",
})
-- a cutscene when the player reaches the gate
entity.find("GateArea").component.add("CutsceneTrigger", {
cutscene = "mygame.scenes.gate_opens",
trigger = "onEnter",
radius = 4,
})
```
The cutscene itself is a module returning a definition — see the `cutscene`
module for its shape, and the `topics/cutscenes` guide for the whole picture.
## Fields
| Field | Default | Notes |
|---|---|---|
| `cutscene` | `""` | The module path a cutscene definition is returned from. |
| `trigger` | `"onPlay"` | `onPlay` as the scene enters play · `onEnter` when the local player comes within `radius` · `manual` only on a `play()` call. |
| `radius` | `3` | How close the local player has to get, for `onEnter`. |
| `delay` | `0` | Seconds to wait after the trigger before it starts. |
| `once` | `true` | Whether it plays only the first time it is triggered. |
| `skippable` | `true` | Whether the player can skip it, overriding the definition. |
| `played` | `false` | Whether it has already played. Local to this peer. |
## Methods
- `play()` — start the cutscene now, whatever `trigger` says. This is what
`trigger = "manual"` is for.
- `isPlaying()` — whether the cutscene this trigger started is still running.
## Notes
- `played` is `NoSync` on purpose: a cutscene is something each player watches for
themselves, so one player having seen it is not a reason another player does
not.
- Playing goes through `cutscene.play`, so only one cutscene is ever on screen —
a trigger that fires while another cutscene runs ends that one first. The
`onEnter` trigger holds off while any cutscene is playing rather than cutting
across it.
- A trigger destroyed while its own cutscene is on screen ends the cutscene, so
the player is never left looking through a camera nothing moves.
# SoftBody
Makes an entity a deformable body: a jelly, a cushion, a balloon, a cloth, a soft version of the entity's own model, or a shell that crumples and keeps the dent, like a car body after a crash. The body is a set of particles held together by elastic elements, simulated in the same step as rigid bodies, so it rests on and pushes rigid bodies, rigid bodies rest on, bounce off and dent it, and soft bodies collide with each other.
A soft body is its own body and its own collision surface: it goes on an entity with no `Physics` and no collider component, and whichever is added second is refused with an error naming the conflict (logged, and readable as the refused component's `disabledReason`). The body fills the entity's unit box (-0.5 to 0.5 on each axis) times its world scale, so it sits where a default cube or sphere primitive of that scale would. `shape = "mesh"` instead fills every closed part of the entity's model with tetrahedra of `cellSize`, and the model is drawn carried by them; a model with no closed part, or a cell size past the 60000-cell cap, is refused with the reason and the fields that change it. While the simulation runs, the entity's position and rotation follow the body as a whole, and a `Model` on the entity moves with it; the deformed surface is drawn by the physics view (`capture` with `pass = "physics"`) with the body's elements over it coloured by load and its pinned and attached particles marked, the same lines `Physics.debugLines` returns and the edit-mode collider overlay draws, and read by `Physics.softBodyState` (its `diagnostics` count inverted cells, self-crossings, loaded elements, pinned and attached particles).
Public fields: `shape` (`"box"`, `"sphere"`, `"balloon"`, `"cloth"`, `"mesh"`, `"custom"`, `"rope"`), `cellSize` (for `mesh`: the cells' edge in metres, 0 takes the model's longest extent divided by `resolution`), `collideWith` (for `mesh`: `"cage"`, the cells' boundary, or `"surface"`, the model's own surface), `resolution` (particles along the longest edge, 2 to 24), `mass` (kg; the default 0 weighs it at 1 kg per cubic metre of its shape, like a rigid body), `stiffness` (Young's modulus in pascals for a box or sphere, default 300; spring stiffness for a balloon or cloth), `damping` (0 rings on, 1 settles without overshoot), `model` (a solid's cells: `"corotational"`, the default, `"neoHookean"` or the cheap `"volume"`), `solver` (`"constraints"`, the default, or `"fem"` for stiff materials, below), `poisson` (Poisson's ratio, 0 up to 0.5), `plasticYield` (the strain past which a dent stays; 0, the default, is fully elastic), `plasticCreep` (how fast per second the strain past the yield sets, default 10), `plasticMax` (the most permanent strain a part takes, default 0.5), `inflation` (the share of its built volume a closed shape is held at), `shapeMatching` (hertz of the pull back toward the body's rest shape as a whole, 0 for none), `selfContact` (whether the surface collides with itself), `repairs`, `preserveVolume`, `friction`, `restitution`, `collisionMemberships`, `collisionFilter`, `canSleep`, `attachments`, `pins`, the tear fields `tearStrain`, `tearForce`, `tearSmoothing`, `interiorToughness`, `maxTearsPerStep`, `minPiece` and `piece`, for a `custom` body `particles`, `elements`, `cells`, `triangles` and `particleRadius` (below), for a `rope` `from`, `to`, `length`, `segments`, `thickness`, `stretchStiffness`, `bendStiffness` and `breakForce` (below), and for any body `regions` and `plane` (below). The material (`stiffness`, `damping`, `poisson`, the plastic fields, `inflation`, `shapeMatching`, `preserveVolume`, `friction`, `restitution`, the collision groups), the `solver` and `repairs` take effect on the running body, waking it. Writing `shape`, `resolution`, `cellSize`, `collideWith`, `mass`, `model`, `selfContact` or `canSleep` rebuilds the body; in play mode a rebuild of the same particles (a new `model`, `mass` or `selfContact`, or the entity moved while the clock is paused) keeps the deformation that stayed, and one while the simulation runs keeps every particle where it is and how it moves. A reload of this component's code keeps the body as it stands: the reloaded component takes it over, dents, motion and pins included.
**Permanent deformation.** With `plasticYield` above 0, a part of the body strained further than the yield flows toward the shape it is held in, so a dent, a crumple or a crease stays once the load is gone: a car shell that keeps its crash, clay that keeps a print, a sheet that keeps a fold. `Physics.softBodyState(id).plastic` reads how deep it is, in metres; `:repair()` (or `Physics.repairSoftBody(id)`) restores the shape the body was built in, the body put back in it where it stands and moving on as it moved. Leaving play for edit mode puts the body back in that shape too.
**Writing particles.** `Physics.softParticles(id, region?)` reads a body's particles (`indices` from 0, world `positions`, `velocities` and `restPositions`, where each stands in the rest shape) and `Physics.setSoftParticles(id, particles)` writes them, the read taken back as it is: a rewind, a replay, a saved damaged object, a level that starts with something bent, a network correction, one dent pushed out. `positions` and `velocities` move the particles and the body springs back toward its rest shape from there; `restPositions` changes the rest shape, the permanent part of it (a read's `restPositions` are where each particle rests, which a crumple's elements pull away from, so to keep the shape a body stands in after a crash write its `positions` as `restPositions`), which stays once the body settles the way a dent past `plasticYield` stays (`plastic` reads it, `:repair()` undoes it). `indices` names the particles written, every particle in order without it. The write applies at once: a read straight after sees it, the next step simulates from it, and from `Physics.onBeforeStep` it is the state that step starts from. Positions are written before the rest places, which are measured through the frame the written positions give; each element takes the rest shape its particles' places give it, which can differ from the one a crumple's elements flowed to, so a deep crumple written back keeps its dent and settles a little way from the written shape, into it or out of it. Rest places that state the shape the body was built in (a read taken before its first dent) put that shape back exactly, the way `:repair()` does, so a rewind to before a crash replays it the same way every time. A write that places every particle (a whole read written back) is the whole state the body steps on from, so two rewinds to one read fall the same way, and the frame after any write draws the body where it was written, paused or not. A pinned particle stands where it is written, held there by its pin whatever velocity is written to it. A rewind starts from the read alone, while the run the read was taken from carried on with what the solver had built up, so the two can part by rounding where a hit amplifies it (a box balancing on an edge); writing the read back the moment it is taken (from `Physics.onBeforeStep`) makes that run a replay of it too. Each element of a crumple keeps a flow of its own that a read's rest places do not carry: written back over the body while it still holds the read's dent, a read leaves those elements as they are, and over any other state it gives each element the rest its particles' places give, so a body read with a deep crumple steps on from the two a little apart.
**Stiff materials.** The default solver (`solver = "constraints"`) sweeps the body's elements with its contacts a few times a substep, which leaves a stiff body (`stiffness` 1e6 and up: a beam, a chassis rail, a stiff panel) with more give than its material has, and past a point flying apart. `solver = "fem"` solves the whole body's elasticity at once each substep, so a 2 m beam of `stiffness` 1e8 held by one end stands out within 3 cm of straight on it where it swings from its pin on the default solver. Contacts, `attachments`, `pins`, plasticity, tearing and cutting all work on it, a `Joint` on one of its regions is answered through the whole body, and `Physics.softBodyState(id).solver` reads which solver the body runs on. It costs more per step, most for a body resting on many contacts (a resolution-6 box on the ground about 5 to 6 ms on native against 1 to 1.5 ms), so keep it for the parts that need it. The physics guide's "Stiff materials: the FEM solver" has the measured costs and the world settings that tune it (`Physics.softBodySettings`: `femMaxDenseDofs`, `femMaxIterations`, `femTolerance`).
**Tearing and cutting.** With `tearStrain` (a stretch, as a share of an element's rest length) or `tearForce` (a pull in newtons) above 0, the body tears where it is loaded past it: a cloth rips, a net gives under a heavy ball, a panel comes off a car that hits a wall. `Physics.cutSoftBody(id, { point = p, normal = n })` cuts it along a plane (or `{ a, b, c }`, a world-space blade triangle), and `Physics.tearSoftBody(id, region)` tears it at a region, both in play mode. The torn entity keeps the largest piece, and every piece split off becomes an entity of its own, a copy of the torn one without its children, standing at the root of the scene so it flies free of whatever the torn one hangs from, carrying this component with the same fields, its share of the model, the material, and the velocity, dents and pins that fell on its side; its `piece` field names the piece its body is. `Physics.onSoftBodyTear(fn)` hears each tear with the torn entity, the pieces' entities, where and why. A piece is play state: left out of every save, and leaving play takes it away and gives the torn entity back its whole body. `tearSmoothing` averages the load over time before the test, `interiorToughness` makes the inside of the body harder to tear than its surface, `maxTearsPerStep` bounds how many edges tear in one step, and `minPiece` is the smallest piece a tear splits off. The tear fields take effect on the running body.
**A body authored particle by particle (`shape = "custom"`).** A truss, a bridge deck, a crane, a cable net, a soft robot, a car frame of nodes and beams: list the particles and link them with elements of their own. `particles` is a list of `{ position = { x, y, z }, mass = kg }` (or just positions) in the entity's local space, metres before its scale; `elements` a list of `{ a, b, kind = ..., ... }` linking particles `a` and `b` by their number in that list (from 1). An element's `kind` is `"rod"` (the default: it holds its length against a pull and a push), `"cable"` (a pull only: it goes slack when its ends close in), `"strut"` (a push only), `"spring"` or `"actuator"` (a rod whose length is driven). Each takes its own law in SI units, 0 meaning none: `stiffness` (newtons per metre; 0 holds the element as stiff as the solver holds anything), `damping` (newton-seconds per metre, damping its own spring, so it needs a `stiffness`), `maxForce` (it gives way at this force and springs back once the load drops), `yieldForce` (past this force it stays bent: it carries the yield force while its length flows to where the load puts it, up to `plasticMax` of its length squeezed and `plasticMaxStretch` stretched, then holds again where it stands (a hit fast enough to carry it past that bound within one physics substep can leave it set a little past it); it gives way as fast as the load moves its ends, and `plasticCreep` does not pace it; a load it cannot carry takes its ends to that bound, where it stops with a jolt its `breakForce` has to carry as well as the standing load: a member held rigid stops within one substep, at several times that load), `breakForce` (it breaks under this pull or push), `breakStrain` (it breaks stretched past this share of its length), `group` (a name `regions` select it by and its breaks report), `breakGroup` (when one element of the group breaks, every element of it breaks in the same step), `collide` (rigid and soft bodies hit it as a segment of `particleRadius` and push its two particles; true by default) and, for an actuator, `targetLength` and `speed` (metres, metres per second). `cells` (tetrahedra, `{ a, b, c, d }`) give it solid material of the body's `stiffness` and `poisson`, and `triangles` (`{ a, b, c }`) a surface other bodies collide with: a deck a wheel drives on. Pins and attachments hold its particles as they hold any body's, `{ nearest = point }` naming one particle; `plane = { normal, point }` puts the whole body on a plane and keeps it there, the way a side-on bridge stays flat (a body built flat in the plane: a solid held to one is pressed flat into it). A structure carrying a load heavy against its particles (a vehicle on a bridge) holds its shape on `solver = "fem"`; the default solver carries such a load along a chain of members only slowly, and the structure sags (the physics guide's "Structures from particles and elements" has the numbers). `Physics.softElements(id)` (or `:elementStates()`) reads every element's force (newtons, positive pulling and negative pushing), strain, length, rest length, permanent set, load against its break limit, whether it broke and where its two ends stand (`endA`, `endB`, world space), all in one call; `Physics.driveSoftElements(id, { [n] = length }, { speed })` (or `:drive`) drives element lengths, a ram or a muscle. A break removes the element whole, its particles staying; a part it disconnects becomes a piece of its own, and `Physics.onSoftBodyTear` hears each break with the broken elements in `elements` (`index`, `group`, `breakGroup`, `force`, `load`; the element whose own load broke it first) and the physics `step` it broke in. The element laws apply to the running body; the particles and the list of links rebuild it. A model on the entity is carried by the cells or the surface triangles; a body of links alone has neither, and is drawn as its elements: each element a round tube of its `thickness` (0 takes twice `particleRadius`) with the entity's material, a ball where three or more meet, carried by the particles every frame. An element listed `hidden = true` is left out of the drawing (a brace or a bending spring that is not seen), and an element that breaks stops being drawn. `Physics.softBodyState(id).render` reads `drawnAs = "elements"` and how many `elements` it draws. After a break, the read of the body's entity and the read of each piece's are the same, every element wherever the break left it, so one read covers the whole structure. A piece a break splits off is a copy of the entity, its other components included, so a component that drives the structure runs once by checking that the `SoftBody`'s `piece` is empty.
**A rope or a cable (`shape = "rope"`).** A tow line, a climbing rope, a power line, a grapple rope, a bridge's cable stays: `from` and `to` are its ends in the entity's local space, `length` its length (0 takes the distance between them, a rope built taut; a longer one is built hanging between them in a catenary), `segments` the elements along it (it has one particle more), `thickness` its diameter (what it collides through and the tube it is drawn as) and `mass` its weight (1 kg a metre when 0). It is built from those as a chain of particles and elements and stepped on the FEM solver: it hangs, drapes and wraps over what it touches, its segments colliding with rigid bodies, terrain and soft bodies. Its segments hold their length both ways, like a chain's links, and bend freely at the particles; `stretchStiffness` is its axial stiffness E A in newtons (default 1e6, a centimetre-thick polyester rope; 0 as stiff as the solver holds anything), `bendStiffness` its flexural rigidity E I (0 hangs limp), `damping` damps its stretch and `breakForce` snaps a segment past that pull. `pins` hold its particles in the world and `attachments` tie them to rigid bodies, `{ nearest = from }` and `{ nearest = to }` naming its ends. `Physics.softElements(id).force[k]` is the pull in segment k counted from `from`. It is drawn as a round tube of its thickness with the entity's material. The physics guide's "Ropes and cables" has the measured loads, sags, swings and costs.
**Regions with a material of their own.** `regions` gives parts of any soft body their own material: a crumple zone that gives way while the cabin holds, a soft tip on a stiff tool, a padded skin over a hard frame, the weak members of a structure. Each entry is `{ name, region = { box = { min, max } } | { nearest = point }, stiffness, damping, poisson, plasticYield, plasticCreep, plasticMax, tearStrain, tearForce, tearSmoothing, density }`: `region` selects particles the way `attachments` and `pins` do (in the shape the body was built in, in the entity's unit box, for a `mesh` body the model's own local coordinates and for a `custom` body those of its `particles`; a `space = "world"` region where the body stood in the world when it was built), and an element (a cell, an edge) takes the material when all its particles are inside; on a `custom` body `group = "name"` selects the elements of that group instead. On a `custom` body `stiffness` and `poisson` are those of its `cells`, so a region of links (a `group`, or a body with no cells) states neither, and is refused naming the field when it does: its links take the `stiffness` of their own elements. A value an entry leaves out is the body's own, and later entries win over earlier ones. `density` (kilograms per cubic metre of the region's cells) weighs its particles when the body is built; everything else applies to the running body in place. `Physics.softBodyState(id).regions` reads each back: its values, the `elements` and `cells` that took them, the `particles` it covers, and `plastic`, the largest permanent strain of its elements (0 where it stayed elastic). `:setRegion(name, values)` changes one on the running body.
`attachments` holds regions of the body to rigid bodies, two-way: a list of `{ target, region }`, `target` the entity id of a body with `Physics`, `region` `{ box = { min, max } }` (every particle between the corners) or `{ nearest = point }` (the one particle nearest the point) in the entity's unit box, `space = "world"` for world coordinates, empty for the whole body. Each region follows its rigid body and the rigid body carries its weight and pull. Changing the list re-ties only the entries that changed; a rebuilt body is tied again, and removing either side releases the hold. `Physics.softBodyState(id).attachments` reads each entry back with the force it pulls with, or why it holds nothing. To join soft bodies to each other, or to anchor a joint on a soft body, use a `Joint`, whose ends each take a region.
Methods: `:state(opts?)` returns the same report as `Physics.softBodyState(entityId, opts)`. `:elementStates()` reads every element at once (`Physics.softElements`), `:drive(targets, opts?)` drives element lengths (`Physics.driveSoftElements`), and `:setRegion(name, values)` changes a region on the running body and returns its entry. `:repair()` restores the shape the body was built in and returns the new `repairs` count. `:attach(target, region?)` adds an attachment and returns its index (the same as `Physics.attachSoftRegion`); `:detach(target?)` releases the regions held to `target`, or all of them, and returns how many it removed.
The body is built at the start of the frame after the component is added. Until then `Physics.softBodyState(id).status` is `"pending"` (with `exists = false`, and `waitingFor` naming what the build waits on); once built it is `"built"`, and a component that was not built reads `"refused"` with the reason in `refusal`.
`Physics.softBodyState(id).cage` reports a `mesh` body's fill: `cellSize`, `cached` (taken from the cage cache, as a second instance of a model is), `buildMs`, `generateMs`, `filledParts`, `strayParts`, `openParts`, `seams` (springs sewing touching parts together), `pieces`, `enclosedVolume` and `digest`.
```luau
local jelly = entity.spawn("jelly")
jelly.position = { 0, 2, 0 }
jelly.component.add("SoftBody", { shape = "box", resolution = 6 })
print(Physics.softBodyState(jelly).status) -- "pending" in the call that added it
-- on a later frame:
local s = Physics.softBodyState(jelly)
print(s.status, s.particleCount, s.volumeRatio, s.sleeping) -- "built", 216, ...
```
```luau
-- a cloth whose left edge hangs from a pole
flag.component.add("SoftBody", { shape = "cloth" })
flag.component.get("SoftBody"):attach(pole, { box = { min = { -0.5, -1, -0.5 }, max = { -0.45, 1, 0.5 } } })
print(Physics.softBodyState(flag).attachments[1].forceMagnitude) -- on a later frame
```
```luau
-- a cloth that rips when pulled past 1.4 times its length
sheet.component.add("SoftBody", { shape = "cloth", resolution = 12, tearStrain = 0.4 })
Physics.onSoftBodyTear(function(e)
print(e.entity, "tore", e.kind, "at", e.position, "into", #e.pieces + 1, "pieces")
end)
-- a jelly cut in two along the plane x = 0
Physics.cutSoftBody(jelly, { point = vector.create(0, 0, 0), normal = vector.create(1, 0, 0) })
```
```luau
-- a stiff beam held by one end, on the FEM solver
beam.localScale = { 2, 0.2, 0.2 }
beam.component.add("SoftBody", { shape = "box", resolution = 16, stiffness = 1e8, mass = 8, solver = "fem",
pins = { { name = "root", region = { box = { min = { -0.5, -1, -1 }, max = { -0.45, 1, 1 } } } } } })
print(Physics.softBodyState(beam).solver) -- "fem"
```
```luau
-- a slab of clay that keeps the print of whatever lands on it
clay.component.add("SoftBody", { shape = "box", stiffness = 3000, plasticYield = 0.02 })
-- on a later frame, after something landed on it and left:
print(Physics.softBodyState(clay).plastic) -- metres of dent that stayed
clay.component.get("SoftBody"):repair() -- and gone again
```
```luau
-- a side-on bridge of eight one-metre panels: a top chord that yields past
-- 4 kN, breaks past 9 kN and drops as one, over a stronger deck and web
local particles, elements = {}, {}
for i = 0, 8 do table.insert(particles, { position = { i, 0, 0 }, mass = 20 }) end
for i = 0, 7 do table.insert(particles, { position = { i + 0.5, 1, 0 }, mass = 20 }) end
for i = 1, 8 do table.insert(elements, { i, i + 1, group = "deck" }) end
for i = 1, 7 do
table.insert(elements, { 9 + i, 10 + i, yieldForce = 4000, plasticMax = 0.03, breakForce = 9000, group = "chord", breakGroup = "chord" })
end
for i = 1, 8 do
table.insert(elements, { i, 9 + i, group = "web" })
table.insert(elements, { 9 + i, i + 1, group = "web" })
end
bridge.component.add("SoftBody", {
shape = "custom", particles = particles, elements = elements, solver = "fem",
pins = { { name = "left", region = { nearest = { 0, 0, 0 } } }, { name = "right", region = { nearest = { 8, 0, 0 } } } },
plane = { normal = { 0, 0, 1 }, point = bridge.position },
})
-- each frame: colour the members by load
local e = Physics.softElements(bridge)
for i = 1, e.count do print(i, e.force[i], e.load[i]) end -- newtons (+ pull, - push), share of break force
Physics.onSoftBodyTear(function(t)
for _, b in t.elements do print("member", b.index, b.group, "broke at", b.force, "N, step", t.step) end
end)
```
```luau
-- a car shell whose front crumples while the cabin holds
shell.component.add("SoftBody", { shape = "box", resolution = 10, stiffness = 2e5, solver = "fem",
regions = {
{ name = "crumple", region = { box = { min = { -0.5, -0.5, 0.3 }, max = { 0.5, 0.5, 0.5 } } },
stiffness = 1e4, plasticYield = 0.01 },
} })
print(Physics.softBodyState(shell).regions[1].plastic) -- the crumple zone's permanent strain
shell.component.get("SoftBody"):setRegion("crumple", { stiffness = 2e4 })
```
# ClipPlayer
Plays one `.animation` clip on the skinned body it is attached to, through the
canonical AnimGraph. The graph retargets the clip from its source rig onto the
body's rig and drives the body's bone entities each frame, so any humanoid clip
plays on any humanoid body. It is the single-clip case of the animation
contract: build a one-clip graph on start, then advance and apply it each frame.
Attach it to the same entity as the skinned mesh. The body's rig comes from its
`Skeleton`; the clip's source rig from the clip itself (or `sourceRig`). All the
retarget and pose machinery lives in the graph — this component only configures
the clip and ticks it.
```luau
entity.find("hero").component.add("ClipPlayer", { clip = "A_Walk_F_Masc" })
```
Public fields: `clip` (the `.animation` to play), `sourceRig` (the clip's source
rig; empty resolves from the clip), `looping`, `speed`, `playing` and
`startedAt`.
## Playing in phase on every peer
`startedAt` is a session time (`multiplayer.sessionTime()`, seconds on the
timeline every participant of a session reads alike). Set, the playhead sits at
`(sessionTime - startedAt) * speed` on every frame: wrapped by a looping clip,
held at the end by one that plays once, and held at the start before
`startedAt` arrives. The playhead follows the session clock on every frame the
component updates, whatever the engine's time scale. While the engine is
paused the component does not update and the playhead holds; on resume it is
placed in phase again. The field replicates like the others, so every peer that
holds the component plays the clip at the same clip time, within the session
clock's accuracy (`multiplayer.sessionClock().accuracyMs`). Choose a start a
little in the future so the value reaches every peer before the clip begins:
```luau
local player = entity.find("dancer").component.get("ClipPlayer")
player.startedAt = multiplayer.sessionTime() + 0.5
```
Unset, the clip advances from wherever its playhead is, by each frame's time.
## Faces: blend-shape tracks
A clip can carry blend-shape (morph target) weight tracks beside its bones, one
per shape, addressed by the shape's name: an imported glTF keeps its `weights`
animations and an imported FBX its blend-shape curves. ClipPlayer plays those
tracks on the meshes of the body that carry shapes of those names, so a smile,
a blink or a set of visemes plays like any other clip. Attached to a mesh with
blend shapes and no skin (a face mesh), it plays the clip's weight tracks alone:
```luau
entity.find("face").component.add("ClipPlayer", {
clip = asset.resolve("Smile", "animation"),
looping = true,
})
```
`skeleton.clipShapes(bytes)` names the shapes a clip drives. To play a face
clip over a body clip, layer it on the body's graph with a shape mask
(`AnimGraph.Layer` with `AnimGraph.shapeMask(layout, "face")`) or use
`AnimOverlay` with `region = "face"`; the animation guide's "Faces" section
covers both.
# PostProcess Component
Applies a **stack of post-process effects** to the scene, declaratively, from a
single entity. Each effect references a `.shader` asset (`@domain: post-process`)
and carries its own **configurable property values** — tuned like material
properties, with no shader edit required.
This is the load-time **reproducer** for post-processing: where an agent's live
`postprocess.add(...)` + `postprocess.setProperty(...)` calls produce effects
that vanish on reload, a `PostProcess` component re-registers the exact same
stack — with the exact same tuning — every time the scene loads. The persist
freeze converts live execute-origin effects into `.shader` assets + one entity
carrying this component, so **what you see is what you get** across save/reload.
## Properties
| Field | Type | Description |
|---|---|---|
| `effects` | array | The effect stack. Each entry: `{ shader, priority?, enabled?, layer?, values?, textures? }`. |
| `shape` | `"global"` \| `"box"` \| `"sphere"` | Where the stack applies. Default `"global"` (unbounded). |
| `extents` | vec3 | Box region half-extents, world units. Default `{5, 5, 5}`. |
| `radius` | number | Sphere region radius, world units. Default `5`. |
| `falloff` | number | Soft-edge distance outside the volume the stack fades over. Default `0`. |
| `priority` | number | Order of this region against other `PostProcess` regions, added to each effect's own priority. Default `0`. |
| `display` | struct `{ curve, exposure }` | The display transform this region sets while it is live — `curve` (0 linear, 1 Reinhard, 2 ACES, 3 Khronos PBR Neutral, default `3`) and `exposure` (multiplier on the scene's light before the curve, default `1`). Takes effect only when `setsDisplay` is `true` and `shape` is `"global"`. |
| `setsDisplay` | boolean | Whether this region writes `display` to the chain's `__display__` transform while it is live. Default `false`. |
Each effect entry:
| Key | Type | Description |
|---|---|---|
| `shader` | asset reference | The `.shader` asset (a `@domain: post-process` shader) this effect runs. Builtin shaders (`@builtin::shaders.post.vignette`, …) or scene-authored custom shaders both work. |
| `priority` | number | Chain order within this region — lower runs earlier. Default `100`. |
| `enabled` | boolean | Per-effect toggle. Default `true`. |
| `layer` | `"all"` \| `"scene"` | Which composited image this effect grades: `"scene"` is the rendered picture before the UI reaches it, in the scene's own light; `"all"` is the picture fitted to the screen with every widget on it. Left empty, the entry follows its shader's `space` — a `light` shader grades `"scene"`, a `display` shader grades `"all"`. |
| `values` | table | Named property overrides `{ [prop] = value }`, applied via `postprocess.setProperty` after the effect is added — the configurable tuning. |
| `textures` | table | Texture bindings `{ [prop] = path }`, applied via `postprocess.setTexture` after the effect is added. |
The component-level `enabled` flag (engine-managed, not declared here) toggles the
**whole stack**: disabling the component removes every effect (and restores the
chain's own display transform if this region set one); enabling it re-registers
them (`onEnable` / `onDisable`).
## Usage
```lua
entity.find("fx").component.add("PostProcess", {
effects = {
{ shader = "@builtin::shaders.post.vignette", priority = 0,
values = { intensity = 0.6 } },
{ shader = "@builtin::shaders.post.grayscale", priority = 10,
values = { intensity = 1.0 } },
},
})
```
Setting the display transform from a `global` region:
```lua
entity.find("look").component.add("PostProcess", {
setsDisplay = true,
display = { curve = 2, exposure = 1.5 }, -- ACES
})
```
Two `global` regions with `setsDisplay = true` both write `__display__` — whichever
registers last wins the frame. The regions setting it share one ordered record of
who is live, so they come off in any order: removing the newer of two leaves the
older one's display standing, removing the older leaves the newer one's, and
removing the last leaves whatever stood before any of them wrote.
The exposure package drives `__display__.exposure` on its own, from a GPU readback
each tick it meters. A region arriving or leaving sets the exposure and the
package's next readback sets it again, so with auto-exposure running the exposure
a region asks for holds for a frame while its curve holds for as long as the region
does.
## Methods
- `pp:getEffectNames()` — the live effect names currently registered, in stack order.
- `pp:setProperty(index, prop, value)` — tune a property of one effect at runtime
(forwards to `postprocess.setProperty`), like editing a material property.
# orbital_follow
Three-ring orbit camera. Framing is authored as three rings around the follow target: a bottom, a centre and a top, each with a `height` above the target's origin and a `radius` out from its axis. Vertical look slides the camera along a smooth path through those rings, as far as it takes to turn the view by the look's angle; horizontal look orbits around them. The shape of the orbit is geometry you can see and edit rather than a pair of pitch limits you cannot.
Public fields: `follow`, `ringBottom` / `ringCenter` / `ringTop` (each `{ height, radius }`), `verticalAxis` (0 at the bottom ring, 1 at the top), `horizontalAxis` (the world heading the camera looks along, in radians about +Y from world +Z), `radiusScale`, `aimHeight` (the aim point above the target's origin), `damping` (per-axis time constants in seconds of the camera's offset from the point it frames: they soften a change of framing, a stick or touch look, a zoom or a recentre; a mouse look turns the camera on the frame the mouse moves), `horizontalLag`, `verticalLag`, `maxHorizontalLag`, `maxVerticalLag`, `jumpBand`, `leadTime`, `maxLead`, `leadSmoothing`, `recenterDelay`, `recenterTime`, `recenterTo`, `pullOutTime` (see below), `cameraRadius` (radius of the pull-in sweep; `0` turns the pull-in off), `cameraIgnore` (entities whose colliders the pull-in passes through), `occluderFade`, `occluderFadeWidth`, `bodyFade`, `bodyFadeDistance`, `fadeTime`, `fadeIgnore` (fading thin occluders and the subject's body, see below), `sensitivity` (radians the view turns per unit of look, the same in heading and in pitch wherever the rings run within about 78 degrees of round the aim point, as the default rings do at every `radiusScale` from 0.2 to 3; where they head more steeply toward or away from it, a vertical look moves the camera along them by five times that angle times its distance from the aim point), `invertY` (off by default: pushing the mouse forward looks UP, drawing the camera toward the bottom ring; on pitches the other way), `zoomSpeed`, `minRadiusScale`, `maxRadiusScale`.
The rig owns that heading. Binding a follow target aims it along the subject's facing, so the shot opens from behind whoever the camera is told to follow, and look input turns it from there and the recentre turns it back behind the subject once the player stops looking around (below). A facing that becomes known or is declared anew after the bind aims it behind the subject again, once for each change: a `Locomotion` or `LocomotionFull` arriving on the subject or leaving it, a body standing up under it, as an avatar that composes after the camera bound does, or the component's `forward` or `faceSign` changing (`CameraRig.facingSource` names what the facing is read from). The heading holds while the body turns. That is what makes the camera steerable for a character who turns to face where it is walking: hold "forward" and the character walks the line the camera looks down, instead of chasing a heading that moves as it turns.
The default rings frame a roughly 1.8 m humanoid standing at its origin: the centre ring sits above head height at the widest radius for a resting shot from behind and slightly above, the bottom ring drops to knee height and pulls in to look up, and the top ring climbs and tightens for a near-overhead look down.
In edit mode, or while play is paused, writing any framing field re-poses the rig immediately with damping bypassed, so editing a ring moves the camera to the shot that ring describes. While play runs, a write steers the rig: its next tick takes the new framing through the damping and the pull-in, the way it takes look input, so a script that turns the camera by writing `horizontalAxis` swings it round over frames, coming in ahead of a wall as a look does.
`follow` falls back to the `Camera.follow` slot when it is empty, so a rig selected through `Camera.behavior` tracks whatever that camera already follows.
Controls: mouse to orbit and to slide along the rings (play mode requests pointer lock, so no button is held), scroll to scale the ring radii.
```luau
local cam = entity(id).component.get("Camera")
cam.behavior = asset.ref("@builtin::controller.orbital_follow", "component")
entity(id).component.get("controller.orbital_follow").ringCenter = { height = 2.6, radius = 6 }
```
## Following the subject: lag, lead and recentre
The camera frames a point that follows its subject's motion with lag, so a step, a stair, a landing, a start, a stop or a reversal is eased rather than copied:
- `horizontalLag` / `verticalLag` (defaults `0.2` / `0.25` s) are the time constants of that point closing on the subject across the ground and along up; `0` carries that motion on the frame it happens.
- `maxHorizontalLag` / `maxVerticalLag` (defaults `1.0` / `0.75` m) bound how far the subject gets from that point, however fast it goes, so the subject never leaves the middle of the frame by more.
- `jumpBand` (default `1.5` m) holds the camera's height through a jump: while the subject is off the ground (its `CharacterController`, or `MovementState`, reads it so) it rises up to this far above the framed height with the camera standing still, so a jump that lands where it took off moves the view along up not at all. Past the band the camera rises with the subject, which stands no farther above the framed height than the band, so a higher jump or a launch keeps it in the picture. A landing higher or lower is eased to over `verticalLag`, and a fall below the framed height is followed as on the ground. `0` follows every jump.
- `leadTime` (default `0.3` s), `maxLead` (`1.5` m) and `leadSmoothing` (`0.5` s): the aim runs ahead of the subject along its motion across the ground by its speed times `leadTime`, held to `maxLead` and eased as the subject starts, stops and turns, so the player sees where the subject is going. `0` aims at the subject.
- `recenterDelay` (default `2` s) and `recenterTime` (`1.25` s): in play, once look input has stopped for `recenterDelay` the heading turns back behind the subject over a time constant of `recenterTime`. `recenterTo` names what it turns behind: `facing` (the default), the way the subject visibly faces (its -Z, or the facing its `Locomotion` or `LocomotionFull` turns, `CameraRig.visibleForward`), or `motion`, the way it moves across the ground. While the subject moves the turn runs at the square of the share of its facing that points away from the camera (half the rate at 45 degrees off the view), so a subject running across the view or toward the camera keeps the heading where it is, rather than the camera and the subject turning each other round, and once it stops the turn waits `recenterDelay` again. A look the player makes while the subject stands holds the heading for as long as it stands: the wait starts once the subject moves off, and a subject that stops again with no look since turns behind after `recenterDelay`. A negative `recenterDelay` turns only on `rig:recenter()`, which turns the heading back now from any delay and ends a look's hold.
- `pullOutTime` (default `0.4` s): once the way is clear the camera eases back out over this time constant. The pull-in itself never cuts (below).
Setting the two lags and `leadTime` to `0` gives the camera that carries its subject's motion on the frame it happens. `rig:tracking()` answers how the camera follows right now: `lag` (how far the subject stands from the framed point), `lead`, `velocity` (the subject's, as the rig measures it), `recentering`, `idle` (seconds since look input) and `lookHeld` (a look the player made holds the heading while the subject stands).
```luau
local rig = entity(camId).component.get("controller.orbital_follow")
rig.verticalLag = 0.4 -- ease stairs and jumps more
rig.recenterDelay = -1 -- keep the heading the player leaves it at
rig:recenter() -- and turn it behind the subject on a button
```
## The camera pulls in when a collider is in the way
Each frame the rig sweeps a sphere of `cameraRadius` from the aim point over the subject itself (`aimHeight` above it, wherever the framed point lags) out to where its framing puts the camera, and stands the camera where the sphere first meets a collider. Every collider in the world stops that sweep, whether or not anything draws it: an invisible walk bound (a `BoxCollider` with no `Model`), a trigger volume and a solid wall all pull the camera in alike. The follow subject is the one entity the sweep passes by default.
The pull-in never cuts. Sweeps of that line ahead, from where the subject is moving to and along where the line is turning over the next 0.8 s, bring the camera in ahead of a wall end or a pillar about to come between it and the subject, at the speed that has it clear when the line gets there; only something no sweep could see coming (a wall that appears) brings it in on the frame it blocks the view, so no frame is drawn from behind geometry. The camera stands no nearer the sweep's start than 0.4 m while there is room round it: when the line has less room than that (the subject against a wall or a pillar the camera is behind), the camera turns round the subject about its up to the nearest turn that has the room, keeps looking the way its framing looks, and turns back onto the line once the line has the room again. A start touching a collider is swept with a thinner sphere, which slides along it, a start nearer it than the thinnest sphere has room for by a ray, and a start inside one holds the camera as far out as it stood.
So a camera that snaps in close to the player, or collapses onto it, while nothing visible stands behind the player is meeting a collider nobody can see. Two fields settle it:
- `cameraIgnore` lists the entities whose colliders the camera sees through. Name the walk bounds and gameplay volumes there and the sweep passes them as it passes the subject, while walls the player can see still pull the camera in. Each entry is an entity (or its id), and it is the collider's own entity that is listed.
- `cameraRadius = 0` turns the pull-in off: the camera stands where its framing puts it, through every collider.
```luau
local rig = entity(camId).component.get("controller.orbital_follow")
rig.cameraIgnore = { entity.find("NorthBound"), entity.find("SouthBound") }
-- or drop the pull-in entirely
rig.cameraRadius = 0
```
## Thin occluders and the subject's body fade instead of filling the view
In play the camera fades what would otherwise fill the view in place of the subject. A thin occluder (a pillar, a pole, a post, a railing, a doorframe's jamb, a tree trunk: a collider no wider than `occluderFadeWidth` across the line from the camera to the subject at its narrowest, and no deeper along it) does not pull the camera in: the sweeps pass it, and while it stands between the camera and the subject it fades to `occluderFade`, that share of its pixels left undrawn in a screen-space dither so the subject shows through. Walls, floors and every collider wider or deeper than that still pull the camera in, as above. The subject's own body fades as the camera comes within `bodyFadeDistance` of the aim point, reaching `bodyFade` at the nearest the camera stands (0.4 m), so a camera pulled in against a wall shows what lies past the subject rather than the back of its head. Each fade eases in and out over `fadeTime`, never in one frame.
A fade covers the entity and its descendants, in this engine's own views (each player's camera sets its own), and shadows stay whole. `fadeIgnore` lists entities the camera never fades: they pull it in whatever their size. `occluderFade = 0` brings back the pull-in for every collider, and `bodyFade = 0` keeps the body drawn whole. `rig:fading()` reports what the camera fades this frame, and `renderer.drawStats().cameraFaded` how many renderables carry a fade.
```luau
local rig = entity(camId).component.get("controller.orbital_follow")
rig.fadeIgnore = { entity.find("GateLever") } -- a lever the player must always see
rig.occluderFade = 0 -- or pull in for every collider
```
## Attach through `Camera.behavior`
The Camera owns the behavior slot, so assigning the rig there is what lets the Camera tell it when `follow` changes. A rig added straight onto the entity with `component.add` still poses, but the Camera does not know about it and a `follow` assigned afterwards will not reach it.
## Player cameras: leave `follow` unset
Entering play drops and respawns `PlayerPrototype` subtrees, so the body is recreated with a NEW entity id. A `follow` authored on the rig keeps pointing at the original, which is no longer live, and the camera freezes at its last pose instead of tracking the player.
For a player camera, set the target on the **Camera** and leave the rig's own `follow` empty:
```luau
entity(rigId).component.get("Camera").follow = body -- PlayerPrototype rebinds this on every spawn
```
`PlayerPrototype` refreshes `Camera.follow` to the live body each time it clones, and the rig reads that slot whenever its own `follow` is empty. Set the rig's `follow` only for a camera that watches a fixed, non-respawning subject.
# SkinnedModel
Component that drives skinned model playback and animation graph integration.
Like `Model`, it carries the `material` field (`AssetRef<material>`) — material lives on the model that renders it, not as a standalone component. Set it at add time or assign `entity(id).component.get("SkinnedModel").material = "..."` later; `:setMaterialProperty` / `:getMaterialProperty` / `:getMaterialPropertyNames` operate on the assigned material (registry-wide).
**Tint is synced.** Every `tint*` field replicates, so `:setTint` is the colour every participant sees. A colour that changes every frame on many characters (a damage flash, a team colour, a heat map) belongs in an instance-data lane instead: wear `@builtin::materials.instance_color` (or `instance_color_unlit`) and write `renderer.instanceData.set(id, 2, r, g, b, coverage)`, which replicates nothing. `guides { path = "topics/rendering-instance-data" }` has the lane layout.
## Blend model
`skinning` chooses how the pass combines a vertex's joint influences.
- `"linear"` (default) averages the joint matrices themselves. The average of
two rotations is not a rotation, so a strongly twisted joint loses volume
toward its axis — at a 180° twist a limb collapses onto the axis entirely.
- `"dualQuaternion"` averages the joints' rigid motions as unit dual
quaternions and renormalises, so the blend is a rotation at every weight and
the cross-section is carried through the twist. Non-uniform joint scale rides
along as a separately blended stretch. It costs a quaternion extraction per
influence, so it is worth setting on characters whose wrists, shoulders or
spine twist far, and leaving off elsewhere.
```lua
entity.find("hero").component.get("SkinnedModel").skinning = "dualQuaternion"
```
A rig at rest renders identically under either model.
## Collapsing bones
`collapsedBones` lists bones, comma-separated, that this mesh draws collapsed.
Every vertex weighted to a listed bone, or to a bone below one, is drawn at the
listed bone's origin, so that part of the mesh is out of the picture. The bones
keep animating and every other mesh on the same armature draws them as they are:
a second `SkinnedModel` on the same `skeletonRoot` and `model` with
`collapsedBones = "Head"` is the same body without its head.
```lua
local copy = entity.spawn("body_without_head")
copy.component.add("SkinnedModel", {
model = original.model, material = original.material,
skeletonRoot = original.skeletonRoot, collapsedBones = "Head",
})
```
A collapsed joint is a zero scale, which the `"linear"` skinning model blends with
the vertex's other joints.
## Render self-check
A few frames after its mesh attaches, a SkinnedModel checks that the mesh
names something the engine can draw (on the GPU, or held off the device until
this display puts it back) and that the pose it is drawn in has not collapsed it: the
posed vertices the skinning pass wrote are measured against the mesh's own
bind-pose extent, so a 1 cm part of a prop is judged by its own size. A mesh
that fails is swapped for the builtin ERROR marker, drawn un-skinned with the
error material, and the reason is logged. Setting `model` again takes the
marker down and checks the new mesh.
`renderCheck()` answers the verdict: `{ state = "pending" | "passed" |
"failed" | "skipped", reason }`.
```lua
local v = entity.find("prop_part").component.get("SkinnedModel"):renderCheck()
if v.state == "failed" then print(v.reason) end
```
# SpringBones
Swings the hair, cloth, tails and accessories of the body under this entity behind the
body's own motion, stops them at the body's colliders, and turns the bones its constraints
name from their sources. An avatar whose `avatar.json` states a `secondaryMotion` (every
avatar a VRM imports to) gets this component when it is instantiated, on every peer, and each
peer simulates its own copy of the body.
```luau
root.component.add("SpringBones", { avatar = asset.resolve("my_vrm", "avatar") })
local s = root.component.get("SpringBones"):stats()
print(s.applied, s.springs, s.joints, s.colliders, s.constraints, #s.unresolved)
```
- `avatar` (synced): the avatar whose `secondaryMotion` it applies.
- `motion` (synced): the motion applied when no avatar is set, in the same form.
- `paused` (synced): holds every bone where the body's pose puts it.
## The data
Every bone is named by its name in the body. Positions are in the bone's own space, lengths
in metres at the body's scale.
```json
{
"springs": [
{ "name": "hair_front", "center": "J_Bip_C_Head", "colliders": [0, 1],
"joints": [
{ "bone": "hair_1", "tail": "hair_2", "stiffness": 1.0, "drag": 0.4,
"gravityPower": 0.2, "gravityDir": [0, -1, 0], "hitRadius": 0.02 },
{ "bone": "hair_2", "tail": "", "stiffness": 1.0, "drag": 0.4,
"gravityPower": 0.2, "gravityDir": [0, -1, 0], "hitRadius": 0.02 }
] }
],
"colliders": [
{ "bone": "J_Bip_C_Head", "shape": "sphere", "offset": [0, 0.08, 0], "radius": 0.1 },
{ "bone": "J_Bip_C_UpperChest", "shape": "capsule", "offset": [-0.05, 0, 0], "tail": [0.05, 0, 0], "radius": 0.09 }
],
"constraints": [
{ "kind": "roll", "bone": "LowerArm_twist_L", "source": "J_Bip_L_LowerArm", "axis": "X", "weight": 0.5 }
]
}
```
- A joint's `tail` is the next bone of its chain; a chain's last bone leaves it empty and its
tail continues 7 cm past it. A spring's `colliders` index `colliders` from 0, and `center`
names the bone whose space the chain moves in (empty for the world).
- The solver is the VRM 1.0 spring bone's: each tail carries its inertia less `drag`,
returns toward its rest direction by `stiffness`, falls along `gravityDir` by
`gravityPower`, keeps the bone's length and is pushed out of every collider its spring
names by its `hitRadius`.
- A constraint is `rotation` (the bone takes the source's rotation away from its rest),
`roll` (the part of it about `axis`, `X`, `Y` or `Z`) or `aim` (the bone's `axis`,
`PositiveX` through `NegativeZ`, points at the source), each by `weight`. Constraints apply
before the springs.
`stats()` answers how much of the data the body carries (`unresolved` names the bones it
does not); `reset()` starts every chain again from the body's rest.
# WheelCollider
A wheel of a ray-cast vehicle (Unity-style). Add it to a child entity of a rigid body: every wheel under one body is one wheel of that body's vehicle, simulated by rapier's ray-cast vehicle controller (`DynamicRayCastVehicleController`). The system finds the nearest ancestor with a `Physics` component and drives it.
Each physics tick a wheel casts its suspension ray straight down the chassis' local **-Y** from its own position, which is the suspension **mount**. The ray passes through triggers and through the chassis' own colliders, so a chassis `BoxCollider` around the mounts is fine. The wheel stands on the nearest surface along the ray whose normal faces back along it within `groundAngle` (45 degrees by default); the ray reads past a steeper face, such as the side of a crate, a kerb's face or a wall, to the ground beyond it, so a wheel meets a box on the road on its top. The controller then applies the suspension, drive, brake and tyre grip to the chassis as impulses, and the opposite of each, at the tyre's contact, to the dynamic body the wheel stands on: a car parked on a deck, a seesaw, a soft body or another car weighs on it as the same chassis resting on it directly does, and a car that drives or brakes on a floating deck pushes the deck the other way, the two sharing one momentum. The push into that body reaches it whole where its contacts hold it up, as a deck or a crate lying on the floor is held, and where it would throw a light body out from under the tyre, or tip it about the edge it stands on, it reaches the body only as far as the tyre can follow it, the spring's compression over a tick, and the body pushes the chassis back no harder than that. Along the ground, the drive, brake and grip push the body as far as its own movement was counted when they were sized: a car on its own wheels or a deck on ice takes the whole push and moves under it, while a crate the floor's friction holds passes it on to the floor. The fixed world carries whatever the body does not take.
Drive conventions: positive `motorTorque` drives toward the parent body's local **-Z** (the engine's forward); positive `steerAngle` steers right.
## Fields
| Field | Meaning |
|---|---|
| `suspensionDistance` | Suspension travel (m): the wheel hangs at most this far below the mount, and the spring compresses by at most this much from its rest, where the bump stop holds the wheel. |
| `targetPosition` | Where the spring rests, as a share of `suspensionDistance` below the mount. The spring's rest length is `suspensionDistance * targetPosition`, and the wheel reaches the ground within that length plus its radius. 1 rests at full extension. The spring compresses from its rest by up to `suspensionDistance`, where the bump stop is. |
| `springRate`, `damperRate` | Spring stiffness (N/m) and damping (N·s/m) per wheel. |
| `maxSuspensionForce` | The most force (N) one wheel's suspension pushes with (default 6000). Raise it for a vehicle heavier than about 2 t on four wheels. |
| `bumpStopRecovery`, `bumpStopSpeed` | How the bump stop pushes a chassis standing past it back out: by `bumpStopRecovery` of the depth each physics tick (default 0.2), and no faster than `bumpStopSpeed` (m/s, default 1). |
| `groundAngle` | The steepest surface the wheel stands on (degrees, default 45): the widest angle between a surface's normal and the suspension, pointing back up it. The ray reads past a steeper face to the ground beyond it. A wheel at 60 climbs a 50 degree face that a default wheel reads past (a rock crawler, a kart riding kerbs, a bogie on a ramp); one at 30 stands only on gentle ground. |
| `radius`, `width` | Wheel size (m). An unset radius comes from the wheel entity's model bounds, or else from its visual's. The ray is cast from the centre of the tread, so a chassis leaning over flat ground meets it at the same points at any lean. It is cast from a shoulder instead when the ground under that shoulder stands more than 1 mm above the ground under the centre, so a kerb or a plank under one shoulder holds the wheel up, or when the centre finds no ground. |
| `motorTorque` | Drive torque (N·m). A wheel with no `inertia` drives with `motorTorque / radius` newtons, up to `forwardFriction` times the load it carries; a wheel that spins on its own takes it on its axle (see Spin below). |
| `maxDriveSpeed` | The tread speed (m/s, default 0) up to which `motorTorque` drives a wheel that spins on its own: below it the wheel takes the whole torque, and from it on only what holds its tread there, on the ground and in the air, the way a rev limit holds an engine. A reverse drive is held to it backward. 0 drives the wheel at any speed. It bounds what the drive does: a gripping tyre turns its wheel at the speed the road passes under it, so a car rolling faster than the top (down a hill, or its rear end lifting over a crest) turns its wheels faster than it while its drive puts nothing on them. A wheel with no `inertia` rolls at the road speed and its drive is held by its grip alone. |
| `brakeTorque` | Brake torque (N·m). A wheel with no `inertia` brakes with up to `forwardFriction` times the load, while `motorTorque` is 0, and so does `rollingResistance`; a wheel that spins on its own takes it on its axle, beside the drive. A braked car stands still on any slope its brakes' grip holds, gravity included. |
| `steerAngle` | Steering angle (degrees), positive steers right. At light throttle the car turns on the radius its geometry gives, the wheelbase over `tan(steerAngle)`, as long as the turn asks less of its tyres than their sideways grip (`sidewaysFriction`); driving the steered wheels hard tightens the turn and driving only the others widens it. |
| `frictionSlip` | The tyre's combined grip limit (default 10.5): the drive, brake and side grip together reach at most the suspension load times this before the tyre slides sideways. Lower it (1 or less) for ice, a drift car or skids. |
| `sideFrictionStiffness` | The tyre's cornering stiffness (default 1): how hard it pushes back across its contact for each radian its contact slips off the line it rolls along, as a share of `corneringStiffness` times the load it carries. A standing tyre holds its contact still across the ground, so a chassis leaning on its springs or tipping over turns about its tyres' contacts; a rolling one answers a steady push across it with a steady slip angle, about 6 degrees at its sideways grip at the defaults. |
| `corneringStiffness` | The base cornering stiffness (default 10): the sideways force, per newton of load, per radian of slip angle, that `sideFrictionStiffness` scales. At 10 and a `sidewaysFriction` of 1 the tyre's grip across the road peaks at about 6 degrees of slip angle; at 25 at about 2.3 degrees (a stiff race tyre), at 5 at about 11 (a soft, balloon or off-road tyre). |
| `forwardFriction` | Longitudinal grip coefficient (default 1): drive and brake force are held to this times the load the wheel carries. |
| `inertia` | The wheel's moment of inertia about its axle (kg·m², default 0). Above 0 the wheel spins on its own (see Spin below); about half the wheel's mass times its radius squared, 1 to 2 for a car wheel. 0 rolls it at the road speed. |
| `forwardFrictionStiffness` | Slip-ratio stiffness of a wheel that spins on its own (default 1): how hard its tyre pushes along the road per unit of slip ratio, as a share of 10 times the load it carries. At the defaults its force reaches its load at a slip ratio of 0.1. |
| `slideGrip` | The share of its grip a tyre of a wheel that spins on its own keeps once it slides (default 0.75): up to its peak slip it grips with all of `forwardFriction` and `sidewaysFriction`, and from `slideSlip` times that slip on with this share of them. |
| `slideSlip` | Where a tyre's grip curve has fallen off, for a wheel that spins on its own (default 2): the slip, as a multiple of its peak slip, at which its grip has fallen in a straight line from its peak to `slideGrip` of it. 1 lets go at once past the peak (a peaky tyre); 3 to 5 falls off gently and holds a slide. See Grip curve below. |
| `loadSensitivity`, `referenceLoad` | Tyre load sensitivity (default 0): every grip coefficient and stiffness of the tyre is scaled by `(load / referenceLoad) ^ -loadSensitivity`, so its grip per newton falls as its load rises, and at `referenceLoad` (N, default 4000) it grips with its coefficients as stated. 0 grips in proportion to load; 0.1 to 0.3 is a road tyre. Held to 0..0.9. See Grip curve below. |
| `sidewaysFriction` | Sideways grip coefficient (default 1): the force the tyre pushes back with as the chassis moves across its contact, in a turn or under a push from the side, reaches at most this times the load it carries, less what its drive or brake spends of it. A car turning harder than that slides wide: steered 10 degrees, a 2 t truck turns on the 19 m its steering gives at 5 m/s and slides wide on its wheels at 20 m/s. Gravity's pull across a slope is held by the tyre's combined grip, `frictionSlip`, so a truck standing across a slope stays where it stands until it tips. |
| `rollingResistance` | Drag on a freely rolling wheel, times the load it carries. The ground under the tyre adds its own `rollingResistance` (see Ground below). |
| `surfaceGrip` | How this tyre grips particular ground: `{ { surface = "ice", grip = 0.35 }, { surface = "loose", grip = 0.8 } }`. On a surface an entry names, by its name or one of its tags, the tyre grips with `grip` of its stated grip in place of the surface's `friction`: a studded tyre on ice, an off-road tread on gravel. The surface's own name is matched first, then its tags in their order. Empty by default. |
| `is2D` | The wheel applies no sideways grip. |
| `visual` | The wheel's visual: an entity, or its id (see below). |
| `solid` | The wheel is a volume other bodies strike (default false): see Solid wheels below. |
| `mass` | The wheel's mass (kg, default 20) as a body of its own once it comes off. |
| `breakLoad` | The force (N) above which the wheel comes off its vehicle (default 0, never): see Wheels that come off below. |
| `attached` | Whether the wheel is on its vehicle (default true). Set false to take it off, true to put it back on its mount. |
| `detachReason` | Why the wheel came off: `"load"` or `"command"`; empty while it is on. |
The suspension ends at a **bump stop**: once the spring has compressed by `suspensionDistance` from its rest, the wheel holds the chassis off the ground there like a solid contact. It stops the chassis closing on the ground within the tick, so a landing faster than the springs can take, or a chassis heavier than its springs carry, ends on the stops with the tyre on the ground rather than in it, and the chassis is not thrown back up. A chassis that stands past its stops (put there by a script, say) is eased back out by `bumpStopRecovery` of the depth each tick, at no more than `bumpStopSpeed` (1 m/s by default).
The spring is applied as an impulse worked out from the state at the start of each tick. So that it cannot feed on itself, its rate is held, per tick, to what the chassis' mass **and its rotational inertia** integrate stably: a light chassis, or one whose pitch or roll inertia is small next to its wheelbase, gets less of a very stiff spring than authored. The damper is applied to the velocity the chassis ends the tick with, which is stable at any rate, so the authored `damperRate` always acts whole. A damper pulls a wheel down no harder than its spring pushes it.
## Ground
A tyre's grip coefficients (`forwardFriction`, `sidewaysFriction`, `frictionSlip`) are stated for ground of friction 1. On a surface content defined (`Physics.defineSurface`), named by the collider under the tyre or painted on a `Terrain` under it, every one of them is scaled by the surface's `friction`, or by the tyre's own `surfaceGrip` entry for that surface; its stiffnesses are not, so on slippery ground the tyre reaches its lower peak at a smaller slip. The ground's `rollingResistance` adds to the tyre's own: the surface's, or the collider's own on a collider naming none. So one car on tarmac, gravel, grass and ice brakes, accelerates and corners differently with no script, wheel by wheel: a car with its left wheels on ice and its right on tarmac pulls right under the brake. Ground naming no defined surface leaves the tyre's grip coefficients as stated, whatever the collider's own `friction`. A surface defined without a `friction` takes 0.5, so a tyre grips it with half its stated grip: state `friction = 1` for ground a tyre grips as stated (dry tarmac), and lower for looser ground, for example `Physics.defineSurface("tarmac", { friction = 1.0, rollingResistance = 0.01 })`, `"gravel"` 0.6, `"grass"` 0.45, `"ice"` 0.1. `surface` and `ground` in the runtime state name what each tyre stands on, and `Physics.tyreCurve(wheelId, { surface = "gravel" })` measures the curve on a given surface.
## Runtime state
Read-only, updated every physics tick, and readable through `Physics.getWheelState(wheelId)`:
- `isGrounded`: the tyre touches the ground anywhere within the suspension's full travel, `suspensionDistance` below the mount. Past the spring's rest it carries no load.
- `compression` (0 with the spring at or past its rest length, up to `suspensionDistance`, where the bump stop is).
- `angularVelocity` (rad/s) and `rotation` (rad): the wheel's spin and its angle about the axle, both growing as it rolls forward. A wheel with no `inertia` turns by the distance rolled over the radius; one that spins on its own turns at its own spin.
- `skid` (m/s): how fast the tyre slides while its grip is used up; 0 while the tyre holds. Sideways for a wheel with no `inertia`; along the road too for one that spins on its own, so a locked or spinning tyre reads its slide.
- `slipRatio`: the tread's speed less the road's under it, both positive rolling forward, as a share of the road speed (taken as at least 0.5 m/s), so its sign is the way the tyre pushes the car along the road. Rolling forward it reads 0 rolling, above 0 in wheelspin (1 at twice the road speed) and -1 locked; rolling backward the signs turn over, a wheel spinning backward past the road reading below 0 and a locked one 1. 0 for a wheel with no `inertia`.
- `slipAngle` (degrees): the angle between the line the tyre rolls along and the way its contact moves over the ground, positive as the contact moves toward the wheel's right: how far into a drift the tyre is.
- `roadSpeed` (m/s): how fast the ground passes under the tyre along the line it rolls along, positive rolling forward. `load` (N): the force the tyre presses the ground with, which its grip is sized by.
- `sideImpulse`, `forwardImpulse` (N·s): what the tyre applied to the chassis this tick, and `sideForce`, `forwardForce` (N) the same over the tick. `suspensionForce` (N). `stopImpulse` (N·s): what the bump stop applied this tick, the part of a landing or a load the suspension could not take.
- `center`, `hitPoint`, `hitNormal`: the wheel centre and the ground contact, in world space. A wheel with no ground within its travel hangs at full travel.
- `surface`: the surface the tyre touches (`Physics.defineSurface`), the one the collider under it names there or, on a painted `Terrain`, the layer under the contact; absent on ground naming none. `ground`: the entity id of what it touches. Both are also on the component (`wheel.component.get("WheelCollider").surface`).
- `reaction` (N): the force the ground and whatever struck the wheel's volume put on the wheel in the last tick: the suspension's push, the bump stop's, the tyre's along and across the road, and the contacts on its volume, their push and their friction, added as vectors. What `breakLoad` is measured against. `detachLoad` (N): the `reaction` the wheel came off at, 0 for one taken off by command.
- `vehicleOrder`: the wheel's place among the wheels of its vehicle, from 1: the order the vehicle steps them in, which is the order they arrived in the world, and the order `Physics.vehicleState` lists them in. A wheel that came off keeps the place it last held; one that has not stepped on a vehicle reads 0.
**Drivetrains.** An engine, a clutch, a gearbox and a differential driving the wheels are a `ShaftNetwork` (on the chassis, say) whose parts name the wheels: `{ name = "rearLeft", wheel = rl }`. A wheel a network drives spins on its own (with its own `inertia`, or the part's when it states none), its `motorTorque` (up to `maxDriveSpeed`) and `brakeTorque` still acting on its axle, and the network's links (a shaft, a gear ratio, a clutch, an open, locked or limited-slip differential) are solved with the tyres and the chassis in one step: one wheel on ice spins behind an open differential while the other stands, and a locked one drives both. The `ShaftNetwork` component README has the fields, and the physics guide (`topics/physics`) a car recipe.
A driver for the wheels is built in: `VehicleController` on the chassis reads the vehicle input map, or the intent code gives it through `setIntent` (an AI driver, a replay, a test), and writes `motorTorque`, `brakeTorque` and `steerAngle`.
`Physics.vehicleState(chassisId)` reads the whole vehicle as `{ speed, groundedWheels, wheels, detachedWheels }`: `speed` the chassis' forward speed (m/s, negative in reverse), `groundedWheels` how many wheels are grounded, `wheels` each wheel's state (the `Physics.getWheelState` record, with its `entityId`), in the order the vehicle steps its wheels, and `detachedWheels` the wheels that came off it. That order is the order the wheels arrived in the world (the first spawned first), and each wheel's place in it is its `vehicleOrder` (from 1). The vehicle steps its wheels in that order on every run and every engine, whatever entity slots the wheels were given, so a car stepped the same steps from the same state reads the same `Physics.stateDigest`.
## Spin: wheelspin, lock-up and drifts
A wheel with an `inertia` above 0 spins on its own. Its spin is integrated each tick from the torques on its axle: `motorTorque` drives it, `brakeTorque` (with `rollingResistance` times its load) holds it toward still, and its tyre pushes back. The tyre pushes the chassis along the road in proportion to the slip between its tread and the road (the slip ratio, `forwardFrictionStiffness`), up to `forwardFriction` times its load; the wheel and the chassis are solved together, so it is stable at the engine's 30 Hz and 60 Hz ticks with a wheel however light. So:
- **Wheelspin.** A drive torque past what the tyre puts down spins the wheel up faster than the road (`slipRatio` above 0), and the car gains speed only as fast as its grip pushes it: 250 N·m on each wheel of a 600 kg car (`inertia = 1.2`, radius 0.35) spins its wheels to more than twice the road speed on ice (`forwardFriction = 0.15`) and the car gains 2.2 m/s in 2 s, while on asphalt it pulls away with a slip ratio under 0.09 and reaches 8.6 m/s. The drive spins the wheel up to `maxDriveSpeed` at its tread and holds it there, the way a rev limit holds an engine: the same car with `maxDriveSpeed = 25` and 1500 N·m on each rear wheel spins its rear treads to 25 m/s from rest on asphalt and in the air and no faster, and still spins them past twice the road speed pulling away on `forwardFriction = 0.15`. `VehicleController` sets it from its `topSpeed`. With `maxDriveSpeed` 0 `motorTorque` acts whatever the wheel's spin, so a wheel driven past its grip keeps spinning up until the drive eases. `VehicleController`'s `tractionControl` eases it: it holds each driven wheel's drive to what its tyre pushes back with just short of the slip its grip peaks at, read from `Physics.tyreCurve`; a driver of your own does the same by cutting `motorTorque` while `slipRatio` stands past a target (0.1 to 0.5) the way the drive turns the wheel.
- **Lock-up.** A brake torque past what the tyre holds stops the wheel (`angularVelocity` 0, `slipRatio` -1) while the chassis slides on, and a sliding tyre grips with `slideGrip` of its grip. The same car braked from 20 m/s stops in 26.9 m with every wheel locked (20000 N·m), and in 22.5 m with each brake held at 0.95 of what its tyre holds at the `load` it reads. A locked tyre holds only `slideGrip` of its grip, so a brake held at the peak keeps it locked: anti-lock braking is a driver that eases `brakeTorque` off while `slipRatio` stands past about 0.15 against the way the car rolls (below -0.15 rolling forward), letting the wheel roll again.
- **Drift.** A tyre's grip along the road and across it is one grip: a tyre slid past its peak, spinning or locked, pushes against its slip in both directions with `slideGrip` of it, so the rear wheels of a car locked on the handbrake, or spun up under power, let go across the road and the car rotates into a drift (`slipAngle` on the rear tyres). Throttle and counter-steer hold it: from 15 m/s, the rear pair locked on 6000 N·m with the front steered 20 degrees for 0.7 s turns the car 32 degrees across its path, and 450 N·m on the rear with the front steered along the way the car moves holds it past 10 degrees for 1.6 s; a rear-driven car kicked into a slide at 10 m/s holds it past 10 degrees for 2.6 s with its throttle cut while the rear slip ratio stands above 0.5. Holding the throttle with the rear wheels spinning far past that leaves them next to no grip across the road, and the car spins. `VehicleController`'s `counterSteer` gives a car that counter-steer from the controller: it steers the front wheels along the way the car moves as it slides, so a car driven from keys that steer full lock or none holds a drift on the throttle and the steering keys (the `VehicleController` README, "Holding a slide").
A wheel in the air keeps its spin, turned by its drive up to `maxDriveSpeed` and slowed by its brake. A chassis lying still with its wheels spinning in the air (on its roof, say) falls asleep like any other body, and its wheels spin on from where they were when it wakes. A wheel with no `inertia` (the default) rolls at the road speed.
## Grip curve: peak, fall-off and load sensitivity
A tyre's grip is a curve over its slip (a tyre or tire curve, or grip curve). Along the road its force rises with the slip ratio at `forwardFrictionStiffness` times 10 per newton of load, and across it with the slip angle (its tangent) at `sideFrictionStiffness` times `corneringStiffness` per newton, each up to its peak: `forwardFriction` and `sidewaysFriction` times the load. The two directions share one grip, an ellipse their two peaks span, so a tyre braking or driving hard has less left for cornering. On a wheel that spins on its own, past the peak the grip falls in a straight line to `slideGrip` of it at `slideSlip` times the peak slip and stays there, the tyre pushing against its slip; a wheel with no `inertia` grips up to its peak across the road and holds it there. A `loadSensitivity` above 0 makes the tyre grip with less per newton the more it carries, every grip and stiffness scaled by `(load / referenceLoad) ^ -loadSensitivity`: a heavy vehicle grips with less per kilogram than a light one on the same tyres, and a wheel loaded by weight transfer (the outside wheels in a corner, the front ones under braking) gains less grip than the load it takes, so a car's balance moves with its load. The whole force is held to `frictionSlip` times the load as well.
So a tyre is stated by its peak (`forwardFriction`, `sidewaysFriction`), where it peaks (the stiffnesses), how it falls off (`slideGrip`, `slideSlip`) and how it takes load (`loadSensitivity`, `referenceLoad`): a peaky sim tyre, a forgiving drift tyre, a kart's, a truck's, a tyre on ice or on gravel. `@builtin::modules.tyres` holds presets of these fields (`road`, `grippy`, `peaky`, `drift`, `loose`, `ice`, `heavy`), as content, and any curve the fields state is one the engine takes:
```luau
local Tyres = require("@builtin::modules.tyres")
wheel.component.add("WheelCollider", Tyres.with("drift", { radius = 0.35, inertia = 1.2 }))
```
`Physics.tyreCurve(wheelId, opts?)` (the `phys.tyreCurve` tool) measures the curve a wheel states: its force against slip angle and, for a wheel that spins on its own, against slip ratio, at each load asked for, with each sweep's `peak` and `slide` and `gripScale`, the share of its stated grip it has per newton at that load. It is the force the wheel's solve settles on at that slip, so a tune can be checked by numbers before it is driven.
Measured on a 600 kg car on four wheels that spin on their own (`inertia = 1.2`, radius 0.35), at the engine's 30 Hz and 60 Hz ticks. A grippy curve (peak 1.2, falling to 0.9 of it by 3 peaks) corners at 11.0 to 11.1 m/s² on a skidpad, reaches 17.5 m/s after 2 s of 600 N·m on each wheel and stops from 20 m/s in 18 to 18.5 m with every wheel locked; the default curve (1, falling to 0.75 by 2) corners at 8.2 to 8.6 m/s², reaches 14.7 m/s and stops in 26.2 to 26.7 m; a peaky curve (1.2, falling to 0.5 by 1.2) corners at 7.5 to 8.5 m/s², reaches 12.0 m/s and stops in 32.5 to 33.3 m, and a handbrake turn from 15 m/s swings it 32 degrees across its path before counter-steer straightens it out; a slidey curve (0.8, falling to 0.4 by 1.5) corners at 5.1 to 5.6 m/s², reaches 6.4 m/s, is still sliding 6 s into the stop, and ends the same handbrake turn still 12 degrees across its path. With a `loadSensitivity` of 0.3 the car at 1200 kg (springs, dampers and `maxSuspensionForce` doubled) corners at 0.82 of the 600 kg car's peak, against the stated `2 ^ -0.3` = 0.81, and at 0 at the same one; with 0.5 and `referenceLoad` at its wheels' static load, weight transfer onto the outside wheels lowers its skidpad peak by 2.3 to 2.6%.
## Solid wheels
A wheel's suspension is a ray, so on its own a wheel has no volume: a post, a wall or another car meets the chassis' collider and passes through the tyre. A `solid` wheel carries a volume as well, riding with the wheel centre as the suspension travels and steering with it: the wheel entity's own collider when it has one that is not a trigger (a `SphereCollider`, or a `MeshCollider` hull of a tyre model on the wheel entity), else a cylinder of the wheel's `radius` and `width` about its axle. Walls, posts and other bodies strike it on its tread and on its faces, the contact holds the chassis back as a contact on the chassis' own collider does, and contact events name the wheel entity (`otherCollider`). Its contacts low on its tread, in the cap under the wheel centre that `groundAngle` spans (below the centre by the radius times the cosine of the angle), are the suspension's: the ground, a ramp, a kerb or a plank met there is mounted by the suspension as a ray-only wheel mounts it, and a car on solid wheels settles and drives as the same car on ray-only wheels does. With the default 45 degrees a wheel of radius 0.35 m mounts a kerb up to 10 cm high and strikes anything taller. The cylinder adds no mass to the chassis and takes the collision groups of the chassis' colliders; a collider of the wheel's own keeps its own. A trigger on the wheel entity stays a trigger beside the volume, standing where the wheel entity stands on the chassis.
## Wheels that come off
A wheel comes off its vehicle when its `reaction` passes its `breakLoad`, or when `attached` is set false (`Physics.detachWheel(wheel)`). It leaves as a dynamic body of its own, on the wheel entity, with its `mass` and with the wheel entity's own collider as its collider, whenever it is taken off and whether or not it is `solid`: that collider leaves the chassis with it, and the chassis' mass, centre of mass and inertia are worked out again over the colliders it keeps. A wheel with no collider of its own, or whose own collider is a trigger, leaves on a cylinder of its `radius` and `width`, and a trigger of its own leaves the chassis with it on its body and goes back to its mount with it. It rolls, bounces and lies down like any body, and `Physics.getVelocity`, `Physics.applyImpulse` and the contact listeners reach it. The wheel entity stays under the chassis in the hierarchy, standing where its own body is, and its visual follows that body. The vehicle drives on the wheels it has left, the others keeping their suspension, spin and tyre state, and a `ShaftNetwork` part naming the wheel turns on its own (its `problem` says the wheel came off) until it goes back on.
The mount is a fuse: a wheel torn off by its `breakLoad` passes its chassis no more than that over the tick it breaks in, of the blow's push and of the turn it gives the car alike. The wheel leaves moving as the blow left it, and the chassis keeps the rest of its momentum, so a car whose front wheel strikes a post carries on past it on its other wheels while the wheel stays at the post. Carrying on along its line, the car brings the wheel behind the torn one to the same post: a `breakLoad` that wheel's glancing blow stays under keeps it on, and a lower one sheds it too. A wheel taken off by command leaves moving as its chassis moved where it stood, spinning as it spun.
`reaction` is a force over one physics tick. A 600 kg car on four wheels reads about 1.5 to 2 kN per wheel at rest and about 1.9 kN rolling over an 8 cm kerb at 15 m/s; striking a post at 15 m/s with one solid wheel reads about 285 kN at a 30 Hz tick and 570 kN at 60 Hz (the same blow over half the time). A `breakLoad` of a few tens of kN keeps wheels on through kerbs, jumps and landings and loses them to a crash.
Set `attached` true again (`Physics.attachWheel(wheel)`) and the wheel goes back on its mount: its own body goes, and the vehicle drives on it from the next physics tick. `Physics.vehicleState(chassis)` lists the wheels on the vehicle under `wheels` and those that came off under `detachedWheels`, each with its `detachReason` and `detachLoad`. `attached` and `detachReason` are synced fields: on a shared world the peer simulating the vehicle breaks its wheels, every peer takes the wheel off, and the wheel's body moves on every other peer as the simulating peer moves it.
## Seeing the suspension
`capture { pass = "physics" }` and the edit-mode collider overlay draw every wheel over the colliders: its suspension ray over its whole reach, `suspensionDistance` and the radius below the mount (green on ground, red in the air, as `isGrounded` reads), the travel from the mount to the tyre's centre coloured by how much of it is taken up (blue extended, yellow half way, red bottomed out), the tyre's radius as a white circle across its steered axle, and where the tyre meets the ground (yellow) with the ground's normal (cyan). `Physics.debugLines({ layers = { "wheels" }, entities = { chassis } })` returns those lines with each wheel's `grounded` and `compression` (the same values as `isGrounded` and `compression` here), `travel`, `suspensionLength`, `restLength`, `radius`, `mount` and `contactPoint` / `contactNormal`. In edit mode the vehicle stands at rest, so its wheels draw where they are mounted and follow their authored fields as they change.
## Visuals
The wheel entity's transform is the suspension mount, so it stays where it is authored. Put the tyre mesh on another entity under the chassis (a child of the wheel is the usual place) and name it in `visual`, as the entity or its id (a prefab or player clone of the car points it at its own copy of the tyre): every tick the wheel places that entity at the wheel centre, turns it by the steering angle and spins it about the axle, starting from the rotation it had when the wheel first posed it.
Methods: `setMotor(torque)`, `setBrake(torque)`, `setSteer(angle)`.
```luau
local car = entity.spawn("car")
car.position = { 0, 1, 0 }
car.component.add("Physics", { kind = "dynamic", mass = 600 })
car.component.add("BoxCollider", { half = { 0.9, 0.3, 2.0 } })
for _, at in { { -0.85, -1.3 }, { 0.85, -1.3 }, { -0.85, 1.3 }, { 0.85, 1.3 } } do
local wheel = entity.spawn("wheel", { parent = car.id })
wheel.localPosition = { at[1], -0.3, at[2] }
local tyre = entity.spawn("tyre", { parent = wheel.id })
tyre.component.add("Model", { model = "cylinder" })
tyre.localRotation = { 0, 0, 0.7071068, 0.7071068 } -- the cylinder's axis along X
tyre.localScale = { 0.7, 0.25, 0.7 }
wheel.component.add("WheelCollider", {
suspensionDistance = 0.3,
springRate = 20000,
damperRate = 2000,
visual = tyre,
})
end
```
# RenderFeature
Runs a `.renderFeature` render pass for the lifetime of the entity carrying it.
A scene's features are listed together, each with its settings, on
`RenderFeatures`; this is the one-feature form. A feature already live on the
same asset is adopted rather than stacked a second time.
A render feature is authored content — a `.renderFeature` asset whose `init.luau`
returns `{ setup?, render, teardown? }` and enqueues GPU passes every frame. This
component is the declarative way to keep one running: on awake / enable it calls
`renderer.feature.create(feature)`, and on disable / destroy it tears the feature
down. A render feature is a **global** pass, so a single component on a single
entity drives it for the whole scene.
## Fields
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `feature` | `assetRef("renderFeature")` | none | The render feature asset to run. |
## Methods
- `:getHandle()` — the live `RenderFeatureHandle` this component created (its
`guid` is the feature's stable id), or `nil` when disabled / before awake.
## Persist
This component is the persist-side mirror of a live `renderer.feature.create(…)`
call. When you enable a render feature ad-hoc during play, the scene-authoring
freeze (`tools.sceneAuthoring.acceptChanges`) promotes the feature's source into a
`.renderFeature` asset and records it on one entity carrying this component — so
loading the scene re-runs the exact same render pass.
## Example
```lua
local e = entity.spawn("acrylic_pass", {})
e.component.add("@builtin::components.RenderFeature", {
feature = asset.resolve("acrylic", "renderFeature"),
})
```
# 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.
# CachedIndirect
The scene's cached indirect light, as a component. The fields are the effect —
editing one re-pushes it, and the values persist with the scene.
# cachedIndirect
The settings for the scene's cached indirect light, and the lifetime of the
passes that draw it. Owns the cache the render feature drives.
`set` / `get` / `clear` / `active` / `invalidate` / `cache`.
·renderfeature · born here
❒asset # cachedIndirect
The scene-wide user of the world-space radiance cache. Runs the cache's
allocate, gather and resolve passes and composites the result against the
scene's albedo, so indirect diffuse light is gathered once per patch of world
and reused by every later frame and every pixel standing on that patch.
Driven through `@builtin::systems.radianceCache.cachedIndirect`.
# radianceCache
A world-space store of lighting results that survives the frame that produced
it. `create(name, opts)` hands back a cache that owns its own fixed table of
slots, addressed by hashing a world-space cell, so it covers an unbounded world
in bounded memory.
A technique either drives the built-in screen-space producer with `run`, or
enqueues its own producing pass over `bindings()` and lets the cache own the
table, the addressing and the eviction.
# radiance_cache
The addressing of the world-space radiance cache, shared by every pass that
touches it: which cell a point belongs to, how coarse that cell is at its
distance from the camera, which of the six facings it is subdivided by, and the
hash that turns all of that into a slot in a fixed table.
Also the lookup — the interpolation over the eight cells surrounding a point,
rejecting the ones on another surface — and the reconstruction of a pixel's
world position from the depth target.
A shader that includes it binds `rc_params` and `rc_cells`. The passes that
insert also bind `rc_keys` as `atomic<u32>`, which this does not touch.
·computeshader · born here
❒asset # rc_alloc
Claims a cache slot for every patch of world the frame is looking at, walking
the frame at a coarse stride. A patch already in the table is stamped with this
frame and with the pixel that can see it; one that is not takes the first slot
that is empty or whose occupant has aged out, through an atomic exchange so two
pixels racing for the same slot produce one winner.
Stamping is half the eviction policy: what no pixel asks for stops being
stamped, and `rc_gather` releases it.
·computeshader · born here
❒asset # rc_apply
Composites the cached bounce into the image: the light arriving at each surface
times the surface's own albedo, added to the drawn colour.
·computeshader · born here
❒asset # rc_gather
Fills the cache, one slot per thread and a fraction of the table per frame.
Runs over cache slots rather than pixels, which is what the cache buys: a
thousand pixels looking at one wall share one gather, and that gather is not
repeated next frame. Each frame visits the slots whose index falls on this
frame's residue, so the table turns over every `stride` frames.
What a slot gathers is a form-factor sum over the surrounding pixels, averaged
into what the slot already holds. Also releases slots nothing has asked for in
`maxAge` frames.
·computeshader · born here
❒asset # rc_resolve
Reads the cache back out per pixel: works out which patch the pixel stands on
and interpolates over the eight cells surrounding it.
The only per-pixel cost the cache carries, and it gathers nothing. Alpha carries
how much of the lookup the cache could cover, so a pixel over a patch the cache
has not filled yet is left alone rather than darkened.
# Package (asset type)
A package is an asset — a `<Name>.package/` folder that bundles
components, modules, scenes, presets, tools, and any other typed
sub-assets under one identity, installed into a world as one unit.
Packages are how authoring sets get distributed across worlds.
A **library** is the addressable root scope content resolves under
(`@builtin`, `@<name>`) — a whole world mounted into this one under a
namespace, via `zeromind.installLib` / `world.installLibrary`. A package is
an asset that lives inside such a root, and one library holds as many
packages as its author put there. A package is installed by guid the
way every asset is (`zeromind.installAsset`).
## When to use one
- You're authoring a coherent feature suite (character controller
stack, voxel engine, UI kit, animation library) and want to ship
it as one install target.
- You want a stable identity worlds can install and resolve sub-assets
against (`@<lib>::pkg.sub_module`).
- You want versioning + a per-package metadata layer that travels with
the contents.
If you're authoring inside a single world and don't need a separate
install lifecycle, you don't need a package — drop your `.component`
/ `.module` / etc. directly in `/zero/source/`. Packages are for
cross-world distribution.
## Where it lives
- Source: `/zero/source/.../<Name>.package/` (or, for legacy
packages, a folder containing `package.yaml` at its root).
- Identity: `<Name>` (the `.package` suffix collapses in identity —
mirrors `.module`). A file at `<Name>.package/<sub>/init.luau`
resolves under the same identity it would at `<Name>/<sub>/init.luau`.
- Folder shape (container-style — open child set):
- `package.yaml`: metadata (name, version, description) and the
packages it depends on (`dependencies`). **Required.**
- `README.md` — instance documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
- Sub-asset folders: any combination of `.component/`,
`.module/`, `.scene/`, `.preset/`, `.tool/`, `.toolbox/`,
`.material/`, `.shader/`, etc.
The validator permits unlisted children (`allow_unlisted: true`) by
design — packages are open containers.
## How to create one
```luau
asset.create("package", "<Name>")
-- Creates: /zero/source/<Name>.package/
-- package.yaml (metadata scaffold)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source instead of the root:
asset.create("package", "<Name>", { folder = "systems" })
```
Then scaffold sub-assets inside it:
```luau
local pkg = asset.resolve("<Name>.package")
asset.create("component", "Spinner", { into = pkg })
asset.create("module", "util", { into = pkg })
```
## `package.yaml`
```yaml
name: inkBlocks # optional; the folder stem when absent
version: "1.0.3"
description: "Ink and paper style blocks"
dependencies:
- { name: starterBlocks, version: "1.0.8" }
- styleKit # a bare name states no version
```
`dependencies` lists the packages this package needs. Each entry's `name` is
a reference the package records, the same kind of reference a `require` or an
asset name in a data file makes:
- **It resolves in the author's world.** Install the dependency here first
(`zeromind.installAsset`); the entry then names the copy this world holds.
A push refuses a package whose dependency resolves to nothing, naming it.
- **An install brings it along.** Installing the package installs every
dependency it lists, at the version this world holds when the package is
pushed, under `/source/deps/<owner world>/`, deduplicated against what the
installing world already holds. `zeromind.preview` lists each one before
anything is written, and the install's `deps` lists what it brought.
Uninstalling the package leaves a dependency that another installed
package still uses.
- **`version` is checked, not chosen.** A stated `version` has to equal the
`version` the dependency's own `package.yaml` states in this world;
`asset.validate` (and so the push) refuses the package naming both when
they differ. To depend on another version, install that version here. An
install lands one release of each dependency its closure names, so in a
world the package is installed into, itself or as a dependency of the
package installed, it runs the release the install placed, and
`asset.validate` names a stated `version` that release does not state as
a warning.
## How it operates
1. **Registration.** Writing `package.yaml` indexes the package with
the package registry.
2. **Install.** A package is read before it is installed: `zm ls-tree
@<guid>` in the shell lists what it contains, and `zm show
@<guid>:<path>` and `zm grep <pattern> @<guid>` read it, so candidates
are compared by what they do. The one that fits is installed by guid,
the way every asset is: `zeromind_install` over the engine's MCP, or
`tools.use("zeromind", "installAsset", <guid>)` inside the engine. The
install writes the package's files (and the deps its `.refs`
record, the packages its `package.yaml` lists under `dependencies`
included) into this world's source, so its sub-assets resolve here.
`tools.use("zeromind", "preview", <guid>)` reports what an install would
write before it writes anything.
3. **Sub-asset resolution.** Because `.package` collapses in
identity, sub-asset paths work whether the package folder is
suffixed (`<Name>.package/<sub>`) or not (`<Name>/<sub>`).
4. **Updates.** `tools.use("zeromind", "updates")` lists installed content
with upstream changes available; re-running the install pulls them.
5. **Metadata.** `package.yaml::name` overrides the folder stem if
present (rare); `version` + `description` are surfaced in the
package index.
6. **Hot reload.** Edits to sub-assets hot-reload as normal; edits to
`package.yaml` reload package metadata.
## Discovery
- `asset.list("package")` — every registered package.
- `asset.inspect("<name>")` — sub-asset catalog, source, this type
README.
- `ls /zero/source/<Name>.package` lists the files the folder holds.
- `library.list()` — the library assets registered in this world,
including the ones packages under an installed library contribute.
## Authoring conventions
- Name packages by their feature (`voxels`, `cameraRigs`,
`dialogSystem`), not by their owner — the host library is the
`@<lib>::` scope prefix.
- Cluster cohesive sub-assets together. A "character controller"
package should ship the controller component, its preset configs,
its supporting modules, and a demo scene — not just the component.
- Document the package's surface in `README.md` — what install
installs, what each sub-asset does, how they relate. Agents reading
`cat /zero/source/<Name>.package/README.md` get the full picture in one shot.
- Version conservatively — breaking a package means breaking every
world that installed it. Use semantic version bumps.
## Common pitfalls
- **Missing `package.yaml`.** Without it the folder isn't recognized
as a package even if it has a `.package/` suffix.
- **A dependency named only by a string the code builds.** A package
whose files reach another package only through a name assembled at
runtime records no reference to it, so an install arrives without it.
List that package under `dependencies` in `package.yaml`.
- **Identity collapse.** Sub-asset paths skip the `.package` suffix.
Don't include `.package` in `require` strings.
## Referencing inside a package: the `~` rule
`~` means **this package**, resolved structurally from the referring file's own
location. It is the only package-specific syntax. It is rename-safe (no package
name is ever written) and library-agnostic (it never names the host library, so
it survives `@builtin` being renamed or the package being mounted elsewhere).
`~.tail` maps to `<pkg>.package/tail` from anywhere inside the package.
| Referencing from | Use | Example |
|---|---|---|
| An asset/module **inside this package** | `~.tail` | `require("~.modules.myThing")`, `shader: "~.shaders.myThingBlend"` |
| A **different package** under the same root | root-relative identity | `require("@root::systems.otherPkg.modules.x")` |
| A **different library's** public API (a deliberate external dependency) | `@otherlib::…` | `require("@physics::modules.rigidbody")` |
**Never write `@builtin::` (or any host-library name) to reference your own
package** — that couples the package to the library it currently lives in and
breaks if the library is renamed or the files move. Use `~.`. It works from
Luau `require()` and from asset-reference strings in data files (a material's
`mat.yaml` `shader:` field, a component's default asset ref); the engine
resolves it against the referring file's own package. `asset.resolve` takes a
`~.` name the same way, against the package of the file that calls it:
`asset.resolve("~.materials.myThingStandard", "material")`.
`~.` is the package-relative self-reference; `@root::` is the root-relative one
(the library root, or the world source tree for non-library content). The
`core/requiring-modules` guide covers the root model in full.
A package that ships substantial functionality should include a `.guide` asset
(a `<name>.guide/guide.md` folder anywhere under the package); the `guides` tool
discovers it live, so collaborators find the system the way they find built-in
guides. A package's test suite reaches the shared `Test` framework through its
enclosing asset: `local Test = asset.containing(__FILE__).modules.shared`
(`asset.containing` returns the deepest enclosing typed asset, the `.testSuite`,
not the outer `.package`).
## Related types
- Any of `.component`, `.module`, `.scene`, `.preset`, `.tool`,
`.toolbox`, `.material`, `.shader`, `.style`, `.service`,
`.importer` — packages bundle these.
## In the Inspector
Package: the name, version and description package.yaml declares, how many things the package holds and what they are, and **Open** for package.yaml. A package.yaml that does not decode is listed under Problems with the decoder's error.
# 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`.
# SubsurfaceScattering
Marks an entity's meshes as carrying light beneath the surface. The terminator
softens and warms instead of ending on a line, and light spreads through a thin
edge instead of stopping at it.
```lua
entity(headId).component.add("SubsurfaceScattering", {
color = { 1.0, 0.3, 0.16 },
radius = 0.02,
})
```
Every field is live — editing one in the inspector moves the shading on the next
frame, and the values persist with the scene. Removing the component stops the
entity scattering, and the pass is released with the last marked entity.
| field | effect |
|---|---|
| `color` | What light becomes beneath the surface. Its channels also set how far each one travels, so a tint weighted to red spreads red furthest. |
| `radius` | How far light travels beneath the surface before leaving, in world units over [0, 1]. Skin at human scale sits near 0.02. |
| `strength` | How much of the spread is mixed back into the frame, in [0, 1]. 0 leaves the shading exactly as it was lit. |
A radius below zero is reported as a warning and the last good setting stays
live, so a typo in the inspector does not stop the component.
Code that marks meshes at runtime can drive the same settings through
`@builtin::systems.subsurfaceScattering.subsurface`.
·renderfeature · born here
❒asset # sssDiffusion
The render pass behind the `SubsurfaceScattering` component and the `subsurface`
module.
The transport it draws is a spread of exitant light across a surface, so it runs
on the frame that was just drawn. Each marked mesh is drawn into a mask carrying
its tint and radius — one draw per group of meshes sharing both. Two passes then
spread the lit colour along that mask, once across and once down; two lines
rather than a disc is what makes the reach cost twice the taps instead of their
square. A final pass mixes the result back by `strength`.
Weights are a Gaussian in units of each channel's own reach, and the reach is
the tint: a channel the surface passes freely is the one that travels furthest,
which is what carries red past the terminator while green and blue stop at it.
Taps are confined to the mask and to a depth tolerance, so light spreads across
one surface and stops at its silhouette rather than dragging the background into
it. The radius is world-space, converted to a pixel span from each pixel's own
depth, so a surface keeps the same softness as the camera moves toward it.
Depth and camera come from the render target being drawn, so the pass is correct
in offscreen captures and RTT cameras at their own resolutions.
# sssMask
Fills a marked mesh's silhouette with the scattering it was authored with: the
tint in RGB, and in alpha the world-space distance light travels beneath the
surface before it leaves, over [0, 1]. Alpha above zero is what marks a pixel as
scattering at all, so a target cleared to zero reads as "no subsurface here".
A geometry pass draws through a material pipeline built for the frame's own
colour format, which is why the mask is 8-bit rather than float. One group holds
one radius, so that quantisation lands on the authored value rather than varying
across a surface.
One material carries one group's values and `sssDiffusion.renderFeature` issues
one draw per group, so meshes scattering differently keep their own numbers.
| property | meaning |
|---|---|
| `scatter_color` | The tint, and per channel how far that channel travels. |
| `scatter_radius` | The distance light travels beneath the surface, in world units. |
·computeshader · born here
❒asset # sss_across
Blurs subsurface diffusion across the image — one half of the separable pair.
The body is `sss_diffuse`; this shader supplies the axis.
## Includes
- `sss_diffuse`
## Bindings
| name | kind |
|------|------|
| `sss_src` | `texture2d` |
| `sss_mask` | `texture2d` |
| `scene_depth` | `texture_depth` |
| `frame_cam` | `buffer` |
| `sss_params` | `buffer` |
| `sss_out` | `storage2d (rgba16f)` |
·computeshader · born here
❒asset # sss_composite
Composites the diffused subsurface term back over the lit scene.
## Bindings
| name | kind |
|------|------|
| `scene_color` | `texture2d` |
| `sss_diffused` | `texture2d` |
| `sss_mask` | `texture2d` |
| `sss_params` | `buffer` |
| `composite_out` | `storage2d (rgba16f)` |
# sss_diffuse
One separable subsurface-diffusion blur. The including shader defines `AXIS` —
the direction this pass blurs along — so the same body serves the horizontal and
the vertical halves of the separable pair.
```wgsl
const AXIS: vec2<f32> = vec2<f32>(1.0, 0.0);
#include "@builtin::systems.subsurfaceScattering.sss_diffuse"
```
·computeshader · born here
❒asset # sss_down
Blurs subsurface diffusion down the image — one half of the separable pair.
The body is `sss_diffuse`; this shader supplies the axis.
## Includes
- `sss_diffuse`
## Bindings
| name | kind |
|------|------|
| `sss_src` | `texture2d` |
| `sss_mask` | `texture2d` |
| `scene_depth` | `texture_depth` |
| `frame_cam` | `buffer` |
| `sss_params` | `buffer` |
| `sss_out` | `storage2d (rgba16f)` |
# subsurface
Light that enters a surface at one point and leaves at another — the transport
that softens and warms the terminator on skin.
```lua
local subsurface = require("@builtin::systems.subsurfaceScattering.subsurface")
subsurface.mark(headId, { color = { 1, 0.3, 0.16 }, radius = 0.02 })
subsurface.unmark(headId) --> true when it had been marked
subsurface.marked(headId) --> { color, radius }, or nil
subsurface.list() --> every entity scattering, sorted
subsurface.groups() --> the marked set gathered by what it scatters
subsurface.setStrength(0.7) --> how much of the spread reaches the frame
subsurface.active() --> is the pass running
subsurface.clear() --> unmark everything, release the pass
```
`mark` on an entity that is already marked replaces what it scatters. A radius
below zero is an error rather than a silent clamp, and an entity that does not
exist is an error rather than a mark that never draws. The pass is created with
the first mark and released with the last.
`groups` is what the render feature draws from: meshes sharing a tint and a
radius are one draw, so per-entity scattering costs one pass per distinct
setting rather than one per mesh. It also drops entities that have since been
despawned, so a removed character does not keep its group alive.
For scattering a scene should simply have, author the `SubsurfaceScattering`
component instead — same settings, persists with the scene, edits live in the
inspector.
The full description of the knobs and how the passes work is in the package
readme: `guides { path = "systems/subsurfaceScattering" }`.
# ScreenSpaceReflections
Reflections off the scene's own drawn frame, as a one-feature component. A
scene lists its features together, each with its settings, on `RenderFeatures`
(`{ feature = "@builtin::systems.reflections.ssr", settings = { ... } }`); this
component carries the same knobs as fields for one feature.
```lua
local id = entity.spawn("reflections").id
entity(id).component.add("ScreenSpaceReflections", {
intensity = 1.0,
maxDistance = 40,
quality = "high",
})
```
Polished floors start reflecting what stands on them, wet ground reflects what
is above it, and metal picks up its surroundings — all from geometry the camera
can already see, with nothing authored per surface.
Roughness decides who gets them. A screen-space ray traces one direction, which
is a mirror; `roughnessCutoff` is where that stops being a fair stand-in for a
surface's real lobe, and past it the pass leaves the surface alone.
Every field is live: edit one in the inspector and the reflections follow.
Setting `intensity` to 0 turns them off without losing the rest of the settings.
Several of these in one scene share one set of reflections: the one edited last
is in force, removing it hands the reflections to the newest of the others, and
only removing the last one takes them down. While one stands in the scene, the
reflections come back if something else takes them down.
How much a reflection shows through is the surface's own Fresnel term, so metal
takes almost all of it and a dielectric floor takes a few percent head-on and
more at a grazing angle — the same way a wet road reads dry underfoot and
mirror-like down the street.
For code that adjusts reflections at runtime, reach for
`@builtin::systems.reflections.ssr` — same options, no component.
The full description of what each knob does and how the passes work is in the
package readme: `guides { path = "systems/reflections" }`.
# Polished floor
A polished stone floor with three coloured pillars standing on it, under an
afternoon sky, with screen-space reflections listed on the scene's
`RenderFeatures` entity — so the floor reflects the pillars, and a player
walking across it, rather than the sky alone.
Load `@builtin::systems.reflections.demo.polished_floor` with the `scene.load` tool.
Players arrive facing the pillars from floor height, which is the grazing
angle a polished dielectric reflects at most strongly.
## What it shows
- **The feature on one entity.** `render_features` carries a `RenderFeatures`
list with `@builtin::systems.reflections.ssr` at `intensity = 1`,
`maxDistance = 60`, `quality = "high"`. Delete the entity and the floor
mirrors the sky alone; put it back and the pillars stand in the floor.
- **Only what the camera sees.** A pillar's reflection comes from the frame
the camera drew, so turning away from a pillar takes its reflection with it,
and the reflection fades toward the screen edge rather than cutting off.
- **The environment underneath.** Where a ray finds nothing the floor keeps
the sky reflection the environment gives it, at the same mip and Fresnel
weight, so the seam between the two is a change of content and not of
brightness.
- **Roughness decides how they look.** The floor sits at roughness 0.06 and
reflects as a mirror. The pillars sit at 0.55, under the feature's
`roughnessCutoff`, and reflect glossily: soft and stretched along the lobe
their roughness describes.
## Contents
- `floor` — a 60 m slab of `PolishedStone`, a near-black dielectric at
roughness 0.06, with a collider.
- `pillar_1..3` — 1.6 × 5 × 1.6 m boxes in `PillarRed`, `PillarGreen`,
`PillarBlue`, sunk into the slab.
- `sun`, `ambient`, `sky` — a side-lit afternoon under a `ProceduralSky`.
- `render_features` — the `RenderFeatures` entity this scene exists for.
- `PlayerSetups` / `Spawns` — the humanoid player on an orbital-follow
camera, spawning in front of the pillars. The scene's player intent is
`"spawns"`.
## Entry point
- `entrypoint.luau` — nothing to set up: the reflections run from the
`RenderFeatures` entity the moment the scene loads.
# ssr
Screen-space reflections — polished floors reflect what stands on them, from
the frame the engine has already drawn.
```lua
local ssr = require("@builtin::systems.reflections.ssr")
ssr.set({ intensity = 1, maxDistance = 40, quality = "high" })
ssr.get() --> the settings in force
ssr.active() --> are the reflection passes running
ssr.clear() --> off, settings kept for the next set()
```
`set` takes any subset — omitted fields keep their current value, so adjusting
one knob does not mean restating the rest. An `intensity` of 0 turns
reflections off and releases the passes rather than running them at zero
strength.
`roughnessCutoff` is the field that decides who gets reflections at all. A
screen-space ray traces one direction, which describes a mirror; past the
cutoff a real surface scatters over a lobe too wide for one ray to stand in
for, and the pass leaves those surfaces alone.
`maxDistance` and `quality` trade against each other. Quality sets how many
steps the march spends, so a long distance at a low quality samples coarsely —
reflections thin out at range rather than disappearing, because refinement
adapts to the step size on its own.
For reflections a scene should simply have, author the
`ScreenSpaceReflections` component instead — it carries the same settings,
persists with the scene, and edits live in the inspector. This module is for
code that changes reflections at runtime: a quality slider, a cutscene, weather
turning pavement wet.
The full description of what each knob does and how the passes work is in the
package readme: `guides { path = "systems/reflections" }`.
·renderfeature · born here
❒asset # ssr
The render feature behind `ScreenSpaceReflections` and
`@builtin::systems.reflections.ssr`. Two compute passes run at the
`afterDepthPrepass` seam, once the visibility raster has laid the frame's depth
and before anything shades:
| order | pass | output |
|---|---|---|
| 60 | `ssr_trace` | one ray per pixel, drawn from the pixel's GGX lobe: where it hit and how confident the hit is, or the direction it travelled when it found nothing, into the feature's `ssr_rays` target |
| 61 | `ssr_resolve` | each pixel's lobe gathered over its own ray and its neighbours' rays, accumulated over frames in the feature's history target, into `@scene.reflection` |
That channel is what a material's environment term reads the same frame, at
its own pixel: the traced light, mixed over the probes and the sky by the share
of the surface's lobe the screen answered, with the material's own Fresnel,
roughness and tint weighing it into the pixel the way they weigh any
environment. Nothing here touches the lit picture.
The trace marches against this frame's depth, which the visibility raster
has just written, so the reflection stands where the camera is now. What it reads
about the surfaces (the reflecting surface's normal and roughness, the hit's
normal) comes from the previous frame: the G-buffer as that frame left it
(`readsPrevious`), reprojected through the previous view-projection
`@frame.camera` carries in its rows `[5..9)`. The resolve reads the light at each
hit from `@scene.colorHistory`, the light the previous frame ended with, at
the pixel the hit stood at then. A point the previous frame did not show
reflects its environment alone.
## The rays
Every pixel draws one ray from the lobe its roughness describes. A mirror (below
perceptual roughness 0.1) takes the reflection vector. A rougher pixel samples a
half vector from the distribution of normals visible from the camera (Heitz
2018) at `alpha = roughness²`, and reflects the view ray about it, from noise
that depends on the pixel and the frame. Each ray carries the density it was
drawn with, as `log2(pdf)`, so the resolve can weigh it against another pixel's
lobe.
The ray texel is `rgba16f`: for a hit, `xy` is the hit pixel minus this pixel (in
whole pixels), `z` is `log2(pdf)` and `w` the confidence in (0, 1]; for a ray
that found nothing, `xy` is the octahedral encoding of the direction, `z` the
same `log2(pdf)` and `w` is -1; a pixel that traced no ray holds zero. A
mirror ray carries 15 in `z` in place of a density.
## The march
`ssr_trace` walks the ray through the depth buffer.
Steps are uniform in **screen** space, not world space. A ray heading toward
the horizon covers enormous world distance across a few pixels, so stepping in
world units there means either missing every thin occluder near the camera or
spending the whole budget on distance nothing can be seen at. The world
parameter is recovered from the screen parameter through `1/w`, which is what
interpolates linearly under perspective.
At each step the ray's world position is compared against the world position
reconstructed from the depth sample under it. Comparing in world space is what
lets `thickness` mean a distance in world units rather than a depth-buffer
epsilon whose meaning changes with range.
The march looks only for the **crossing**, where the ray first passes behind
the depth buffer. Thickness is tested after bisecting that crossing, not
during the march: one march step covers roughly as much depth as a surface is
thick, so a ray tested during the march can jump from in front of a surface to
well behind it without ever landing inside it.
Bisection runs for whichever is larger, the quality tier's budget or however
many halvings bring one march step under `thickness`. A coarse march that
stopped bisecting early would leave the crossing bracketed more loosely than a
surface is thick, and every hit would then fail the thickness test, so
long-range reflections would vanish outright instead of thinning.
A rough pixel's ray marches fewer steps and refinements (down to 0.35 of the
tier's, reached 0.65 of roughness above a mirror), because the resolve blurs
what the rays find.
A hit on a surface that faces along the ray (what is on screen there is that
surface's far side) is trusted at half the confidence.
## The resolve
For each pixel the resolve gathers its own ray and up to `taps` neighbours (4 at
`low` and `medium`, 8 at `high`, 12 at `ultra`) on a disk of up to 6 px that
turns with the pixel and the frame and grows with roughness. A neighbour counts
only where its normal is within 0.9 of the pixel's and its depth within 5
percent. Each ray is weighed by the pixel's own lobe: `D · Vis · cos / pdf`.
A pixel's result is the light of the rays that hit and the share of the lobe
they cover. A ray that found nothing counts toward the lobe and carries no
light. The history accumulates that result, premultiplied, at up to 0.9 of the
previous frame for a rough surface and none for a mirror, with the history's
light and coverage both held to the mean plus or minus 1.25 standard deviations
of the rays gathered: a reflection whose rays now find nothing keeps nothing.
## What the channel holds
`@scene.reflection` holds linear radiance in `.rgb` and in `.a` the share of
the lobe the screen answered, multiplied by `intensity` and by the hand-over
above `roughnessCutoff`. A surface at or below the cutoff keeps the full share,
one 0.1 above it holds zero, and between the two the share fades. A miss is a
zero the material reads as "the environment alone". The channel is cleared at
the top of every scene render this feature does not run for, so such a frame
reflects the environment alone too. The passes read the light the previous
frame ended with, so they run on the lit channel alone (`debugChannel = 0`); a
camera drawing a diagnostic pass is drawn lit first, unpresented, so the passes
run for where that camera stands, and the diagnostic reads the channel gathered
for it.
## Memory
Each view that draws the feature holds three screen-sized `rgba16f` images: the
rays and the history pair. At 1080p that is about 16.6 MB each, about 50 MB for
the viewport.
# ssr_common
The screen-space reflection passes' shared ground: the view-space reconstruction from depth, the ray-to-screen projection the march steps along, the GGX lobe helpers (distribution, masking, visible-normal sampling and its density), the octahedral direction coding, the per-pixel noise and the frame it is turned to, the camera and surface reconstruction both passes read, and the constants that fix the lobe sampling (the mirror roughness, the hand-over width, the neighbourhood radius, the history weight).
Included with `#include "@builtin::systems.reflections.ssr_common"` by a shader that declares the bindings `frame_cam`, `scene_depth`, `scene_normal`, `scene_material`, `ssr_params` and `history_state` (the feature's history target's state buffer) and includes `shaderModules.gbuffer_material`.
·computeshader · born here
❒asset # ssr_resolve
Gathers each pixel's reflection lobe from the rays the trace drew, accumulates
it over frames, and writes the result into `@scene.reflection`.
A pixel's lobe is the GGX distribution its roughness describes. The pixel's own
ray and the rays of up to `taps` neighbours on a disk (turned by pixel and
frame, radius up to 6 px, growing with roughness) are weighed against that lobe:
`D · Vis · cos / pdf`, where `pdf` is the density the neighbour's ray was drawn
with. A neighbour counts only where it shows the same surface: its normal within
0.9 (cosine) of the pixel's and its depth within 5 percent of the pixel's.
Each ray carries the place it hit, not the light. The resolve reads the light
from `@scene.colorHistory` where the hit stood in the previous frame, and takes
a sky hit's direction from the camera ray through the sky pixel.
The output states two things per pixel: `.rgb`, the light of the rays that found
something on screen, and `.a`, the share of the lobe those rays cover. A ray that
found nothing counts toward the lobe and carries no light, so a lobe the screen
answers half of is `a = 0.5`, and the material fills the other half from the
probes and the sky. `.a` also carries `intensity` and the hand-over above
`roughnessCutoff`.
The accumulated value is stored premultiplied in the feature's history target,
and every frame the history is held to what this frame's rays found, within
1.25 standard deviations of their mean:
- its coverage, to the coverage of every ray that reached an answer: a hit
covers by its confidence, and a ray that left the screen through open space
covers nothing, so a reflection whose rays now find nothing keeps nothing;
- its light, to the light of the hits, in a space where bright values do not
own the average. A pixel whose rays found no light keeps no history.
A surface above roughness 0.25 keeps up to 0.9 of the previous frame; a surface
below 0.1 keeps nothing, takes no neighbours and reads its one ray. A surface in
between whose lobe is narrower than a pixel lends no neighbour's light to its
own, and reads its 4 nearest rays (within 1.5 px) for the spread its history is
held to.
## Includes
- `ssr_common`
- `gbuffer_material`
- `display`
## Bindings
| name | kind |
|------|------|
| `ssr_rays` | `texture2d` |
| `scene_color` | `texture2d` |
| `scene_depth` | `texture_depth` |
| `scene_normal` | `texture2d` |
| `scene_material` | `texture2d` (`sample: uint`) |
| `history_prev` | `texture2d` |
| `frame_cam` | `buffer` |
| `ssr_params` | `buffer` |
| `history_state` | `buffer` |
| `history_out` | `storage2d (rgba16f)` |
| `ssr_out` | `storage2d (rgba16f)` |
·computeshader · born here
❒asset # ssr_trace
Draws one ray per pixel from the pixel's GGX lobe, marches it through the depth
buffer and reports where it hit.
## Includes
- `ssr_common`
- `gbuffer_material`
- `display`
## Bindings
| name | kind |
|------|------|
| `scene_depth` | `texture_depth` |
| `scene_normal` | `texture2d` |
| `scene_material` | `texture2d` (`sample: uint`) |
| `frame_cam` | `buffer` |
| `ssr_params` | `buffer` |
| `ssr_rays` | `storage2d (rgba16f)` |
# Fire
Fire with its smoke, as a component: a campfire or a hearth, a torch, a brazier
or a candle-sized flame, a bonfire or a pyre, a building, a vehicle or a forest
on fire, or an explosion's fireball. Put it on an entity where the fire burns
and it burns there: flames that glow white-hot at the core through yellow and
orange to dull red at the tips, grey or black smoke rising over them lit by the
scene with a shadow of its own, and a point light that lights the ground, the
walls and the people around it and the smoke from within.
```luau
local e = entity.spawn("campfire")
e.localPosition = { 0, 0, 0 }
e.component.add("Fire", { style = "campfire" })
```
An explosion is a burst: the `explosion` style ignites when the component
starts, and gameplay sets it off again by changing `ignite`:
```luau
local boom = entity.spawn("barrel_explosion")
boom.localPosition = { 6, 0, 3 }
boom.component.add("Fire", { style = "explosion" })
-- later, to set it off again:
local fire = boom.component.get("Fire")
fire.ignite = fire.ignite + 1
```
For smoke alone use the `Smoke` component.
Fires and smoke whose boxes overlap draw as one group, the widest first and the
ones it holds over it: small fires breaking out along a burning barn show in
front of the barn's big smoke plume.
## Styles
| `style` | What it is | Height | Flames | Light |
|---|---|---|---|---|
| `campfire` | Flames a metre high under a thin grey smoke | 5 m | 1.2 m | 6, radius 9 m |
| `torch` | A small flame with a thin wisp of smoke | 1.6 m | 0.6 m | 3, radius 6 m |
| `bonfire` | Roaring flames a few metres high under heavy smoke | 12 m | 3.6 m | 14, radius 20 m |
| `burning` | Wide flames under thick black smoke: a building or vehicle on fire | 22 m | 6.6 m | 24, radius 30 m |
| `explosion` | A fireball that swells, rises and cools into dark smoke over 2.6 s | 9 m | the ball | 40 while it burns |
## Public fields
| Field | Type | Sync | Default | Meaning |
|---|---|---|---|---|
| `style` | enum | Sync | `"campfire"` | The kind of fire (above). |
| `height` | number | Sync | `0` | Metres the fire and its smoke rise; 0 takes the style's. Its width scales with it. |
| `radius` | number | Sync | `0` | Metres from the centre to the edge of the flames at their base; the smoke widens from it as it climbs, by the style's spread. 0 takes the style's at this height. |
| `flame` | number | Sync | `1` | How bright the flames burn, as a multiple of the style's. |
| `flameHeight` | number | Sync | `0` | Metres the flames reach above the base; 0 takes the style's (the Flames column, scaled with `height`). Tall flames for a house fire: `flameHeight = 10`. |
| `smoke` | number | Sync | `1` | How thick the smoke is; 0 burns clean. |
| `color` | color | Sync | white | Tints the style's smoke colour. |
| `light` | number | Sync | `-1` | The intensity of the point light it casts; -1 takes the style's, 0 casts none. |
| `flicker` | number | Sync | `1` | How far the light rises and falls with the flames (0 to 1); 0 holds it steady. |
| `speed` | number | Sync | `1` | How fast the flames lick and the smoke climbs. |
| `windX`, `windZ` | number | Sync | `0` | Metres the top of the smoke drifts along world x and z, on top of what the scene's wind carries it. |
| `sceneWind` | number | Sync | `1` | How far the scene's wind carries the smoke: 1 drifts with every `Wind` blowing at the source (`Physics.wind`), the top carried by the wind for as long as the smoke takes to climb there (up to half the plume's height; a thin wisp drifts far, a big fire's column stands up to the wind); 0 leans it by `windX` / `windZ` alone. |
| `seed` | number | Sync | `0` | Which turbulence it takes. |
| `loop` | boolean | Sync | `false` | For `explosion`: start over once its smoke has cleared. |
| `ignite` | number | Sync | `0` | For `explosion`: each change sets it off again. |
| `quality` | enum | NoSync | `"auto"` | `auto` follows the device's quality tier; `high`, `medium`, `low`. |
The light is a point light halfway up the flames, where it lights the ground,
the logs and the walls around the fire and the smoke from within. It stands on
a child entity the fire puts up for the session and keeps out of every save
(`fire:lightEntity()` answers it), and flickers with the flames (`flicker`),
each peer drawing its own.
A fire is seen the way anything is: a wall, a roof or any opaque surface in
front of it hides it. A building on fire shows its flames where it is open, so
stand the fire where the roof has burnt through, in a doorway or at a broken
wall, or above the roofline.
## Cost
The same as the `Smoke` component's: a 3D texture written every frame the scene
draws and marched over the pixels its box covers, at 48, 40 or 32 voxels across
with 96, 64 or 48 march steps for `high`, `medium` and `low`, over the whole
view at `high` and half its width and height at `medium` and `low`. A campfire
filling a 1920 x 1080 view costs 7 to 14 ms at `high` and 0.38 ms at `medium` on
a desktop GPU; from 9 m away 0.69 and 0.13 ms.
## Related
- `Smoke`: smoke without flames.
- `plume` module: the same fire from a script (`plume.create`).
# ParticipatingMedium
Marks its entity as a volume of fog, smoke, dust or steam — something light has
to travel through. What is behind the volume comes out dimmer than what is
beside it, and overlapping volumes stack.
```luau
local id = entity.spawn("fog_bank").id
entity(id).component.add("ParticipatingMedium", {
sizeX = 30, sizeY = 8, sizeZ = 30,
density = 0.15,
})
```
## Fields
| Field | Meaning |
|---|---|
| `shape` | `"box"` (default) or `"sphere"` |
| `density` | Extinction per world unit. `0` releases the medium. |
| `sizeX` / `sizeY` / `sizeZ` | Half-extents, for a box |
| `radius` | Radius, for a sphere |
`density` is the physical knob: a ray crossing `d` world units of a medium of
density `k` leaves with `exp(-k * d)` of the light it entered with. A 20-unit
bank at `0.15` therefore passes about 5% of the light straight through it.
The entity's position places the volume; move the entity and the shadow moves
with it.
## Notes
- The light-space map is sized to the bounding sphere of everything registered.
A small bank sharing a scene with a very large one lands on few texels — set
`extent` and `centre` through `mediaTransmittance.set` to bias the map toward
the region you care about.
- Attenuation applies to surfaces. The sky keeps its own colour.
- The attenuated light is the sun's: `sunDirection` sets which way the map's
rays travel.
See `mediaTransmittance` for the scene-wide settings and the direct API.
# Smoke
Smoke rising from a chimney, a stove pipe, a vent, a kettle or a cooling tower,
the wisps over embers or ruins, the thick black column over a city block, an
oil well or a wreck seen from far away, or the puffs of a smoke signal: a smoke
volume lit by the scene, as a component.
Put it on an entity where the smoke leaves (the top of the chimney) and the
smoke rises from there, with the sun on one
side and the smoke's own shadow on the other, greyed by the ambient light and
lit by the lamps near it, a lamp inside it from within. It
churns as it climbs, widens, thins toward the top and drifts with the wind.
```luau
local e = entity.spawn("chimney_smoke")
e.localPosition = { 4, 9, -2 } -- the chimney's top
e.component.add("Smoke", { style = "chimney", windX = 2 })
```
Smoke with a blaze under it is the `Fire` component. Plumes whose boxes overlap
draw as one group, the widest first and the ones it holds over it.
## Styles
| `style` | What it is | Height |
|---|---|---|
| `chimney` | A thin grey column from a chimney or a stove pipe | 7 m |
| `steam` | White steam from a vent, a kettle or a hot spring, thinning out fast | 3.5 m |
| `smoulder` | Low, wide grey wisps over embers or ruins | 2.5 m |
| `column` | A tall, thick black column over a city block, an oil well or a wreck | 30 m |
| `signal` | Separate puffs rising one after another | 9 m |
## Public fields
| Field | Type | Sync | Default | Meaning |
|---|---|---|---|---|
| `style` | enum | Sync | `"chimney"` | The kind of smoke (above). |
| `height` | number | Sync | `0` | Metres it rises; 0 takes the style's. Its width scales with it. |
| `radius` | number | Sync | `0` | Metres from the centre to the edge of the opening the smoke leaves (a chimney's flue, a vent, the fire under a column); the smoke widens from it as it climbs, by the style's spread (a `column` from 2.5 m to 9 m over its 30 m). 0 takes the style's at this height. |
| `density` | number | Sync | `1` | How thick the smoke is, as a multiple of the style's. |
| `color` | color | Sync | white | Tints the style's smoke colour. |
| `speed` | number | Sync | `1` | How fast it climbs and churns. |
| `windX`, `windZ` | number | Sync | `0` | Metres the top drifts along world x and z, on top of what the scene's wind carries it. |
| `sceneWind` | number | Sync | `1` | How far the scene's wind carries the smoke: 1 drifts with every `Wind` blowing at the source (`Physics.wind`), the top carried by the wind for as long as the smoke takes to climb there (up to half the plume's height; a thin wisp drifts far, a big fire's column stands up to the wind); 0 leans it by `windX` / `windZ` alone. |
| `seed` | number | Sync | `0` | Which turbulence it takes, so two plumes side by side differ. |
| `quality` | enum | NoSync | `"auto"` | `auto` follows the device's quality tier; `high`, `medium`, `low`. |
## Cost
The smoke is a 3D texture written every frame the scene draws and marched like
any `Volume`, only over the pixels its box covers. What each level holds:
| Level | Voxels across | March steps | Shadow samples | Local lights | March resolution |
|---|---|---|---|---|---|
| `high` | 48 | 96 | 6 | 4 | the view's |
| `medium` | 40 | 64 | 4 | 2 | half the view's width and height |
| `low` | 32 | 48 | 3 | 1 | half the view's width and height |
`auto` draws `high` on a desktop's or browser's high tier, `medium` on a
handheld's high tier and every medium tier, and `low` on the low tier.
Measured on a desktop discrete GPU with the view at 1920 x 1080, the march of a
campfire's plume filling the whole view costs 7 to 14 ms at `high`, 0.38 ms at
`medium` and 0.35 ms at `low`; seen from 9 m away, 0.69, 0.13 and 0.08 ms. The
fill costs 0.01 to 0.02 ms. A scene holding several plumes close to the camera
draws them at `medium` to keep the frame. The march skips the parts of the box the column cannot
reach.
## Related
- `Fire`: a blaze with its smoke, and the light it casts.
- `plume` module: the same smoke from a script (`plume.create`), every style in
`plume.STYLES`.
- `Volume`: any 3D texture as a volume; `scattering` lights it by the scene.
- `ParticipatingMedium`: a bank of fog, haze or mist filling a box.
# Volume
Per-entity attachment that renders a 3D voxel texture (cloud, smoke,
nebula, imported VDB grid) into the scene as a volumetric body. The
component does NOT own the volume's lifetime — producers (the
`volume` module, a custom compute fill, or `compute.writeTexture3D`)
build the texture and pass its name in `volumeName`. The entity's
world transform defines the AABB the raymarcher samples.
`volumeName` is resolved through `Volume.get`, so a volume the `volume`
module built is rendered as it stands — at its own dimensions, from its own
density channel, through its occupancy grid, and out of its brick pool if it
is paged. A name no volume answers to is taken as a bare 3D texture some
other system owns, and `occupancyName` / `isRgba` describe it.
## Usage
```luau
local Volume = require("@builtin::systems.volumetrics.volume")
local cloud = Volume.noise({ name = "cloud", size = 64, scale = 4 })
cloud:buildOccupancy({ brickSize = 8 })
local e = entity.spawn("cloud_entity")
e.localScale.set(8, 4, 8)
e.component.add("Volume", {
volumeName = "cloud",
occupancyName = cloud.occupancyName,
density = 6.0,
})
```
A paged volume costs what it holds and is named the same way:
```luau
local cloud = Volume.noise({ name = "cloud", size = 128, threshold = 0.6 })
cloud:buildSparse({ brickSize = 8, threshold = 0.01 })
cloud:releaseDense() -- the brick pool is now the only copy
local e = entity.spawn("cloud_entity")
entity(e.id).localScale = { 8, 4, 8 }
e.component.add("Volume", { volumeName = "cloud", density = 6.0 })
```
## Public fields
| Field | Type | Sync | Default | Meaning |
|---|---|---|---|---|
| `volumeName` | string | Sync | `""` | Required. Name of the volume, or of a bare 3D texture, to render. |
| `occupancyName` | string | Sync | `""` | R8 occupancy texture for a bare texture's empty-space skipping. Empty = no occupancy. A volume the module built carries its own, and a name set against one is reported as left aside. |
| `density` | number | Sync | `1.0` | Density gain multiplier. |
| `absorption` | number | Sync | `1.0` | Beer-Lambert absorption coefficient. |
| `emission` | number | Sync | `1.0` | Emission gain. |
| `color` | color | Sync | `{1,1,1,0}` | RGB tint + density floor in alpha. |
| `stepSize` | number | NoSync | `0` | World units per ray step. `0` = auto-derive from volume extent. |
| `maxSteps` | number | NoSync | `256` | Ray-march step cap. |
| `target` | string | Sync | `"scene_volume_rt"` | Output render target name (composite key). |
| `targetWidth` | number | NoSync | `1280` | Output width (px). |
| `targetHeight` | number | NoSync | `720` | Output height (px). |
| `useOccupancy` | boolean | NoSync | `true` | Toggle empty-space skipping. |
| `isRgba` | boolean | Sync | `true` | `false` reads density from the red channel. Left `true`, a volume the module built is read from the channel it was built with, and a bare texture as RGBA. |
All public fields use the `Field.<kind>(default, Sync|NoSync)` schema
(PR #3019). Visual params (look, tint, density) propagate Sync;
quality knobs (stepSize, maxSteps, target resolution, useOccupancy)
are NoSync — each client picks its own perf/quality point.
## Lifecycle
- **`awake`** — no-op. The volume texture is owned by the producer
and looked up lazily on the first `update`.
- **`update(dt)`** — resolves `volumeName` through `Volume.get`, falling
back to a wrapper over a bare texture of that name, and dispatches the
compute raymarcher into `target`. The resolution runs every frame, so a
volume built, paged or destroyed after this component attached is picked
up on the next one.
- **`onPropertyChanged(key, value, old)`** — drops the resolved volume
when `volumeName`, `occupancyName`, or `isRgba` changes, forcing a
re-resolve on the next frame.
## Related
- `volume` module — texture builders and name lookup (`Volume.noise`,
`Volume.get`, `Volume.wrap`, `:buildSparse`, `:render`).
- `vdb_to_zvol.importer` — VDB → dense voxel pipeline that produces
textures consumable by this component.
- `volumeDemos` / `volumetricSky` packages — worked examples.
# VolumeSequence
Plays an open volume sequence through an entity's transform AABB.
The sequence is opened by a producer and named here — the same split the
`Volume` component makes between "what data to render" and "where it appears
in the world". Each tick the component advances the playhead and raymarches
the frame that is resident into the shared `scene_volume_rt` target, in both
play and edit mode, so the run animates while it is being authored.
```luau
local Seq = require("@builtin::systems.volumetrics.volumeSequence")
Seq.open({ name = "plume", frames = paths, resident = 3, fps = 24 })
local id = entity.spawn("plume_entity").id
entity(id).localScale = { 8, 8, 8 }
entity(id).component.add("VolumeSequence", { sequenceName = "plume", density = 6.0 })
```
`fps` and `playing` are pushed into the sequence when they change, so a
script calling `seq:setFps()` / `seq:pause()` between two ticks is left
standing until the authored value itself moves.
The component does not own the sequence: despawning the entity leaves the
ring allocated, and `volumeSequence.close(name)` is what frees it.
## Sharing
The playhead, the rate and the ring belong to the sequence, so several
entities naming one run play the same frame from the same three textures:
the playhead advances once per engine frame however many components tick it,
and the rate is whichever component's `fps` moved last. Give each entity its
own run when they should play independently.
`target` is a render target, and a raymarch writes the whole of it — two
volumes visible at once (a sequence beside a `Volume`, or two sequences) need
a `target` name each, or the later write replaces the earlier one and only
one of them appears. Composite each target the way any volume render is
composited — see `volume.compositeShaderSource()`.
# VolumetricLighting
The air between the camera and the scene, as a component. Add it to an entity
and light travelling through that air scatters toward the viewer, so a lamp
becomes a glow rather than an invisible point and the sun cuts shafts where
something crosses it.
```lua
local id = entity.spawn("air").id
entity(id).component.add("VolumetricLighting", {
density = 0.06,
anisotropy = 0.7,
})
```
Every field is live — editing one in the inspector changes the air on the next
frame, and the values persist with the scene. Setting `density` to 0 empties the
air and releases the passes while keeping the rest authored; removing the
last one in the scene clears it.
| field | effect |
|---|---|
| `density` | How much medium there is per world unit at the reference altitude. 0 is off. |
| `heightFalloff` / `heightRef` | How fast density thins with altitude, and the altitude `density` is quoted at. 0 falloff fills the scene evenly. |
| `steps` | Samples along each view ray. More resolves a beam's edge more cleanly. |
| `colorR/G/B` | What the medium scatters. Warm dust and cold mist differ here. |
| `anisotropy` | How forward-biased the scattering is, in (-1, 1). Positive values throw light onward, so haze blooms around a source you look toward. |
| `sunIntensity` / `sunColorR/G/B` | The sun's contribution to the medium. |
| `lightScale` | The scene lights' contribution to the medium. |
| `shadowSteps` / `shadowDistance` | Samples taken back toward the sun to decide whether a point in the air is lit, and how far they reach. **0 leaves the sun's contribution unshadowed**, so the haze glows evenly and no shafts form. |
| `maxDistance` | How far along the view ray the march runs. A ray that escapes to sky stops here. |
The lights are the scene's own, each scattering on the terms its kind emits on:
a point fills the air around it, a spot fills its cone, a rect reaches the air on
the side its face emits along, and a parallel light lays an even glow across the
whole medium. One added, moved, re-aimed or recoloured at runtime changes the
glow it throws with nothing to keep in step here.
One body of air fills the scene, so one of these per scene is enough — the last
one to push wins.
The work runs in `lightScattering.renderFeature`; the settings live in
`@builtin::systems.volumetrics.volumetricLighting`, which is also how to drive
them from a script.
# VolumetricSky
Clouds in the sky, as a component. Add it to one entity and the sky gets a
volumetric cloud layer lit by the scene's own sun: cumulus by default, its
coverage, altitude, wind and look set by a preset. The component owns the
cloud volume, bakes its noise field when what it is baked from changes, and
the `volumetricSky` render feature it brings up draws the layer into every
view the frame draws, over the sky and over the surfaces under it. Adding
the component is the whole set-up: no composite is authored. The layer draws
in edit mode as well as in play, and drifts with the wind once play runs.
## Usage
```luau
-- Defaults (the v4-tuned cumulus look — `Sky.defaultPreset()` hands out a
-- copy of the same table this field defaults to)
local sky = entity.spawn("sky")
sky.component.add("VolumetricSky", {})
-- Or apply a captured preset:
preset.apply("cumulus_default", { entity = sky.id, component = "VolumetricSky" })
-- Inline tweak. `component.add` writes the `preset` field as it is given,
-- so a table handed here carries the whole configuration:
local p = require("@builtin::systems.volumetrics.volumetricSky").defaultPreset()
p.noiseScale, p.octaves, p.coverage = 9.0, 5, 0.20
p.densityGain = 0.04 -- v5 σ_t
sky.component.add("VolumetricSky", { shaderVariant = "v5", preset = p })
```
`volumetricSky.module`'s `M.spawn` / `M.configure` take the same parameters
by name, folding each into the current configuration and leaving the rest
where they stand:
```luau
local Sky = require("@builtin::systems.volumetrics.volumetricSky")
Sky.spawn({ shaderVariant = "v5", noiseScale = 9.0, coverage = 0.20 })
```
## Schema (Field<T> / Sync / NoSync)
The 28 shaping / weather / lighting params travel as ONE Sync field
— `preset = Field.table(DEFAULT_PRESET, Sync)` — so replicating a
sky change is **one mutation, not 28**, and copying a sky between
scenes is **copying one field, not 28**. Per-client quality knobs
sit outside the preset as NoSync fields so each client picks its
own tier without disturbing peers.
`SkyPreset` and `DEFAULT_PRESET` are declared by `volumetricSky.module`,
which this component reads its default from and which routes an option by
that same key set — so the shape below and the module's `M.spawn` options
are one declaration.
| Field | Type | Sync | Default | Meaning |
|---|---|---|---|---|
| `preset` | `SkyPreset` table | Sync | `DEFAULT_PRESET` (v4 cumulus) | All shaping / weather / lighting (see below). |
| `shaderVariant` | string | Sync | `"v4"` | `"v3" \| "v4" (default) \| "v5"`. |
| `wind` | vec3 | Sync | `{0,0,0}` | Animated drift offset (advanced per frame from `preset.windSpeed`). |
| `cloudSize` | number | NoSync | `256` | Volume W,D resolution. |
| `cloudHeight` | number | NoSync | `128` | Volume H resolution. |
| `stepSize` | number | NoSync | `4.0` | World units per ray step. |
| `maxSteps` | number | NoSync | `224` | Ray-march step cap. |
| `shadowSteps` | number | NoSync | `8` | Shadow ray step count. |
| `alphaCutoff` | number | NoSync | `0.99` | Early-exit α threshold. |
| `jitter` | number | NoSync | `1.0` | Ray-origin jitter strength. |
| `taaBlendAlpha` | number | NoSync | `0.1` | TAA current-sample weight. |
| `targetWidth` | number | NoSync | `0` | Render target width (`0` = the width of the view the scene is drawn into, `getViewportSize()`). |
| `targetHeight` | number | NoSync | `0` | Render target height (`0` = the view's height). |
| `noiseRegenRate` | number | NoSync | `10` | Times per second wind drift re-bakes the cloud volume (`0` = every frame the wind moved). |
### Preset (`SkyPreset`) shape
Noise / shaping: `noiseScale, octaves, coverage, densityGain,
altitudeLow, altitudeHigh, anvilBias, detailScale, detailOctaves,
detailStrength, detailThreshold, baseLowRemap, baseHighRemap, color,
windSpeed, seed`.
Volume placement: `horizExtent, cloudBaseAltitude, cloudTopAltitude`.
Look (visual, not perf): `phaseG`.
Sun / sky: `sunColor, sunIntensity, sunDiscSize, horizonColor, zenithColor,
groundColor, ambient`. The clouds are lit by the scene's own sun every frame: the sun's direction, its colour, and its intensity up to a
unit sun, which scales these too, so a night leaves the clouds dark and a sun at
zero leaves them black. `sunDir` is deprecated and kept so a stored preset
still loads.
v5-only: `cloudType, worleyBlend`.
See `presets/cumulus_default.preset/preset.yaml` for the canonical
full preset shape, and the `init.luau` `DEFAULT_PRESET` table for
the runtime defaults.
## Where the frame time goes
Two passes carry the cost, and different fields reach each:
- **The bake** (`cloud_noise_*`) fills every voxel of the
`cloudSize × cloudHeight × cloudSize` volume with layered noise. It is
the most expensive pass the layer has (around 10 ms at 256×128×256 on a
desktop GPU), and it runs only when the volume's inputs move: at once
for a change to `preset`, `cloudSize`, `cloudHeight`, `shaderVariant`
or the render device, once the program it compiles is resident for an
edit to the noise shader's own source, and at most `noiseRegenRate`
times per second for wind drift. A sky whose `preset.windSpeed` is zero
bakes once. `cloudSize` / `cloudHeight` set what one bake costs;
`noiseRegenRate` and `windSpeed` set how often it is paid.
- **The raymarch** (`cloud_raymarch_*`) runs for every view of every
frame. `stepSize`, `maxSteps`, `shadowSteps`, `alphaCutoff` and
`targetWidth` / `targetHeight` set its cost.
`profiler.gpuFrame()` reports both as `compute.<shader>` spans; a span's
`frames` count is how many frames of its window the pass ran in, and
`volumetricSky.volumeBakes()` counts the bakes themselves.
## Field-mutation gotcha (and why `update()` reassigns the whole vec3)
Under the new Field<T> / Sync / NoSync schema, `public` is not a
plain Lua table — it's wrapped in a proxy whose `__newindex`
metamethod performs type-checks, marks the field dirty, and queues
Sync replication. Writing `public.wind = {x,y,z}` triggers all four
steps. Writing `public.wind[1] = x` reads `public.wind` (getter),
mutates the returned table directly, and **bypasses the setter** —
no Sync replication, no dirty flag, no `onPropertyChanged`. Always
assign the whole vec3 / preset / color table; never index-mutate.
The same caveat applies to `public.preset`: `public.preset.coverage = 0.2`
won't replicate. To change one preset field, copy the table, mutate,
reassign:
```luau
local p = public.preset
local next = {}
for k, v in pairs(p) do next[k] = v end
next.coverage = 0.2
public.preset = next
```
## Lifecycle
- **`awake`** / **`onEnable`**: start the sky's clock and hold the cloud
layer up (`volumetricSky.holdLayer`), which brings up the render feature
that runs the layer's passes.
- **`update(dt)`**: advances `wind` (reading `preset.windSpeed`),
hands the noise inputs to `volumetricSky.fillClouds`, which bakes the
volume when they moved (see "Where the frame time goes"), then queues
the raymarch dispatch for the frame's deferred phase.
- **`editorUpdate(dt)`**: the same bake and dispatch in edit mode, so the
editor viewport, an edit-mode capture and a probe baked in edit mode show
the clouds. The wind stands where the scene holds it; drift runs in play.
- **`onDisable`** / **`onDestroy`**: let go of the layer
(`volumetricSky.releaseLayer`). When the last sky lets go, the render
feature comes down and `M.destroy` releases the volume, the render targets
and the programs, so the next frame is drawn with no cloud layer and no
cloud pass runs.
- **`onModuleReload(path)`**: a reload of `volumetricSky.module` starts it
with no holders, so a sky holding the layer holds it again on the reloaded
module.
The layer is one per engine: every sky standing holds it, and it comes down
with the last one.
### Why the raymarch is dispatched from `task.defer`
The raymarch produces ONE full-screen layer for ONE view, and the frame
composites it over everything that frame drew — so it has to be rendered
from the view the frame ends up drawn with. Which view that is settles
only once the frame's script work is finished: a cutscene walking the
camera from a task loop, a camera controller, a component ordered after
this one, an editor tool — each writes the camera after `update` has
run, while the renderer reads the camera once all of them are done.
Taking the camera snapshot in the deferred phase reads what every one of
them has already written, and still queues the dispatch ahead of the
frame's render. Snapshotting in `update` instead renders the layer for
whatever the camera was midway through the frame; on a hard cut that is
a different place entirely, and the frame the cut lands on composites a
cloud layer belonging to the shot it just left.
A caller driving `volumetricSky.dispatchRaymarch` directly owes the same
discipline.
## Related
- `volumetricSky.module` — orchestration backend.
- `presets/cumulus_default.preset` — canonical full preset; copy
to author named weather (storm, overcast, dawn, …).
- `Volume.component` — per-entity flow for non-cloud volumetric content.
- `demo/sky.scene` — worked example.
# cloudShadow
The shadow the cloud layer (`VolumetricSky`) casts on everything the sun
lights under it. A cloud is density rather than a surface, so the shadow is
the optical depth of cloud between each point and the sun, and the sun keeps
`exp(-tau)` of its light there (scaled by the sky's `shadowStrength`).
Each frame the cloud layer draws, `enqueue` runs three passes for every view,
at the `afterDepthPrepass` seam:
1. `cloud_shadow_map`: a map of lines toward the sun, one per texel, each
marched across the layer through the same clouds the raymarcher draws
(`cloud_density`), recording the optical depth above the layer's base and
above a quarter, a half and three quarters of the way up. The texels are
packed most closely around the camera and still reach as far as the layer
is drawn (`cloud_shadow_space`).
2. `cloud_shadow_apply`: the share of the sun the clouds take from each
surface in view.
3. A composite laying that share into the scene's sun occlusion channel
(`@scene.sunOcclusion`) with the `union` blend, so it stands with a
participating medium's and a contact shadow's share as `a + b - ab`: the
two transmittances multiply, and neither is taken twice. The sun's term
reads the channel, so the clouds dim the sun's diffuse and specular light
alone and the sky, the ambient term and the other lights still reach the
surface.
The air reads the same map. A pass marching it merges what `bindings()` names
into its own `inputs` and `buffers`, includes
`@builtin::systems.volumetrics.shaders.cloud_shadow` and multiplies the sun's
light at each of its samples by `cloud_shadow_transmittance(p, cam, to_sun)`.
The height fog, the volumetric light (`lightScattering`), the participating
media's view march (`mediaShadow`) and the march of every standing volume
(`volume_draw`: `Volume`, `Smoke`, `Fire`) do, so the air and the smoke in a
cloud's shadow are dark and the sun falls through the gaps.
With no cloud layer drawing, nothing is enqueued, the map's parameters say no
shadow is cast, and `cloud_shadow_transmittance` answers 1 without reading the
map.
## Quality levels
| level | map texels | samples per line |
|-------|------------|------------------|
| high | 384 x 384 | 16 |
| medium | 256 x 256 | 12 |
| low | 192 x 192 | 8 |
The level is the cloud layer's own (`VolumetricSky`'s `quality`).
## Direct use
```luau
local CloudShadow = require("@builtin::systems.volumetrics.cloudShadow")
local shadow = CloudShadow.bindings()
ctx.enqueue {
kind = "compute", program = myAirMarch,
inputs = { frame_cam = "@frame.camera", cloud_shadow_map = shadow.inputs.cloud_shadow_map },
buffers = { cloud_shadow = shadow.buffers.cloud_shadow },
}
print(CloudShadow.state().casting)
```
·computeshader · born here
❒asset # godrays_fill
Fills a volume with shafted light. One invocation per voxel.
## Bindings
| name | kind | what it is |
|------|------|------------|
| `vol` | `storage3d` (rgba16f) | the volume written — RGB emission, A density |
| `U` | `buffer` (read, f32) | the demo's fill parameters |
·computeshader · born here
❒asset # nebula_fill
Fills a volume with a spiral nebula: RGB carries emission, A carries density.
One invocation per voxel at workgroup size 4x4x4.
## Bindings
| name | kind | what it is |
|------|------|------------|
| `vol` | `storage3d` (rgba16f) | the volume written, read-write so a pass can accumulate |
| `U` | `buffer` (read, f32) | the demo's fill parameters, in the order the shader reads them |
`U` holds: elapsed time, spiral frequency, arm thickness, core brightness, edge
brightness, dust density, noise strength.
·computeshader · born here
❒asset # sdf_solids_fill
Fills a volume with signed-distance solids. One invocation per voxel.
## Bindings
| name | kind | what it is |
|------|------|------------|
| `vol` | `storage3d` (rgba16f) | the volume written — RGB emission, A density |
| `U` | `buffer` (read, f32) | the demo's fill parameters |
·computeshader · born here
❒asset # smoke_plume_fill
Fills a volume with a rising smoke plume. One invocation per voxel.
## Bindings
| name | kind | what it is |
|------|------|------------|
| `vol` | `storage3d` (rgba16f) | the volume written — RGB emission, A density |
| `U` | `buffer` (read, f32) | the demo's fill parameters |
·computeshader · born here
❒asset # zvol_viewer_fill
Leaves the volume as it is. The ZVOL viewer uploads voxels straight into the
volume's 3D texture from the CPU, so the fill stage this shader occupies has
nothing to compute — it reads one value from each binding so both stay live.
## Bindings
| name | kind | what it is |
|------|------|------------|
| `vol` | `storage3d` (rgba16f) | the volume the viewer writes into from the CPU |
| `U` | `buffer` (read, f32) | the fill parameters the spawn API supplies |
·computeshader · born here
❒asset # emission_raymarch
Marches a camera ray through an emissive volume and writes the result to a 2D
target. Emission accumulates along the ray and density attenuates what is behind
it, so a volume reads as light rather than as a surface.
## Bindings
| name | kind | what it is |
|------|------|------------|
| `vol` | `texture3d` | the volume marched — RGB emission, A density |
| `smp` | `sampler` | how `vol` is filtered along the ray |
| `out_tex` | `storage2d` (rgba16f) | the image the march writes |
| `U` | `buffer` (read, f32) | camera, volume placement and march settings |
`U` carries the inverse view-projection, the volume's world transform, the step
count, density and emission gains, and the target's inverse size.
# VDB → ZVOL importer
Claims `.vdb` (OpenVDB) writes and produces a sibling `.zvol` — the
engine-native dense RGBA8 volumetric format consumed by the volumetrics
system.
This is a standard `importer` asset: `init.luau` returns a
`{ canImport, import }` module that the importer dispatcher
(`@builtin::assetTypes.importer`) loads lazily and runs only when a matching
file is written. It does **not** execute anything at load time.
## Pipeline
1. **Real parse** — if the `openvdb` plugin in the builtin library
(`@builtin::plugins.openvdb`) is loaded, the VDB B-tree is parsed into a
dense RGBA8 voxel buffer and wrapped in a 64-byte ZVOL header.
2. **Procedural fallback** — without the plugin, a deterministic
noise-modulated torus is synthesised (FNV-1a hash of the first 256 source
bytes seeds it) so the importer + demo wiring stays functional. The
`produced_by` field in the result distinguishes the two paths.
## ZVOL header (64 bytes)
| offset | size | field |
|--------|------|-------|
| 0 | 4 | magic `ZVOL` |
| 4 | 4 | u32 version (1) |
| 8 | 4 | u32 width |
| 12 | 4 | u32 height |
| 16 | 4 | u32 depth |
| 20 | 4 | u32 format (1 = rgba8) |
| 24 | 12 | f32[3] aabb_min |
| 36 | 12 | f32[3] aabb_max |
| 48 | 16 | reserved |
| 64 | … | voxel data, `w*h*d*4` bytes, XY-major Z-slowest |
·renderfeature · born here
❒asset # lightScattering
The render passes behind the `VolumetricLighting` component and the
`volumetricLighting` module. Light shafts and glowing air in a scene come from
adding that component to an entity; this feature runs while one stands.
Three compute passes in the `medium` stage, after the fog.
**`vol_scatter`** marches each view ray at half resolution, from the camera to
the surface the ray hits, or to the medium's reach when it escapes to sky, since
an unbounded march would integrate the whole horizon into every sky pixel. At
each step it evaluates the medium's density and accumulates the fraction of the
sun's light sent toward the camera, attenuating by everything already crossed.
The medium's surroundings light it too, as they light a surface standing in it:
the scene's ambient term, the sky and reflection probes the environment captured
and the baked light-probe volumes (`@scene.environment`,
`@scene.environmentSampler`, `@scene.reflectionProbes`), averaged over every
direction through `@builtin::shaderModules.ambient_light`. They change over the
room, the canopy or the sky rather than over a step, so each ray reads them once
per stretch of four, where the medium that stretch holds stands. The sky reaches
that point as far as the point sees it, past the static geometry (the
sky-visibility field) and past every surface standing over it, movable and
instanced ones included: the feature draws the overhead cover map
(`@builtin::systems.skyVisibility.overheadCover`) at `afterLighting`, ahead of
the march, and the march reads it as `overhead_map`. The air under a canopy or a
roof so takes the share of the sky it sees, and the medium's `skyLight` scales
what it takes. Haze in front of the sky stands in for the sky it hides, by day
and by night, and with the sun, every light and the surroundings dark the
medium scatters nothing.
A surface-only renderer draws the pool of light a lamp throws on the floor but
not the beam that carried it there, because nothing between the lamp and the
floor is ever shaded. Marching the ray shades that space.
The sun's contribution is gated by a short march back toward it, tested against
the depth buffer. That is what turns uniform haze into shafts: the medium is lit
only where the path back to the sun is clear, so an occluder carves a dark volume
out of the beam rather than only shading the surface behind it. Because the test
reads the depth buffer, an occluder outside the view frustum does not cast into
the medium.
**`vol_lights`** marches the same rays for the scene's lights that stand
somewhere. The lights are the scene's own. `@scene.lights` is the same buffer
the lit passes read, so a light added, moved or recoloured at runtime changes the
beam it throws with no bookkeeping here. A spot's cone gate is evaluated at the
sample itself rather than at a surface, which is what makes the cone visible as a
volume instead of only where it lands, and a rect lights the sample from the part
of its face nearest to it. Attenuation matches the lit passes' windowed falloff,
so a beam and the pool of light it lands in agree about how far the source
reaches, and the pass spends its work only where that is: a tile of rays marches
with the lights whose reach meets it, a ray with the ones whose reach it crosses,
over the stretch of the ray they reach. A light whose radius reaches no ray costs
the march nothing.
Scattering follows Henyey-Greenstein, so the medium brightens toward a source you
are looking at and stays dim when it is behind you: the difference between haze
that reads as air and haze that reads as a grey wash.
Each ray's first sample is offset by a per-pixel fraction of a step, trading the
banding a fixed step pattern produces for noise.
Consecutive renders of a view share each ray's samples. Each render marches every
other sample of a ray, and lays its half beside the half the view's previous
render marched, taken from where the end of the ray stood in that render, so a
camera holding still sees every sample of the ray for the price of half. The
halves are held in history targets, one pair of images per view, beside the
length of each ray: a ray whose previous render ended at another distance (an
object moved across it), one that falls off the previous picture, and every ray
of a view with no previous render (its first, its first after a cut, a one-shot
capture) march all of their samples.
**`vol_composite`** upsamples both and composites them. The taps are weighted by
how closely their depth matches the full-resolution pixel's, which keeps a beam
from bleeding across a silhouette: the halo a plain bilinear upsample leaves
behind.
The camera comes from `@frame.camera`, the camera of the render target being
drawn, its inverse view-projection to unproject a pixel and its view-projection to
project a point back, so an offscreen capture or an RTT camera marches through
its own matrices at its own resolution.
Parameters arrive through the `vol_params` buffer, packed by the
`volumetricLighting` module.
·renderfeature · born here
❒asset # mediaShadow
Participating media in the frame, for every view it draws. Brought up by
`mediaTransmittance` while a medium is registered and released with the last.
A fog bank or a smoke cloud in one place is the `ParticipatingMedium`
component; adding one to an entity registers it.
| Where | Pass | Work |
|---|---|---|
| `afterDepthPrepass`, order 45 | `media_shadow_apply` | For every surface, the share of the scene's sun the media take on the way to it, written to `@scene.sunOcclusion` |
| `afterLighting` | overhead cover | What stands over each point around the camera (`@builtin::systems.skyVisibility.overheadCover`) |
| `medium` stage, order 29 | `vol_surroundings` | The light the surroundings hand the air at each node of the surroundings grid around the camera, once per render |
| `medium` stage, order 30 | `media_view` | March each view ray across the media in front of the surface: dim what is behind, add the light scattered toward the camera, the surroundings' light read from the grid |
| `medium` stage, order 30 | composite | Lay the result over the frame |
The surroundings grid, the view march and the composite declare
`environmentCapture = false`: the sky fallback and the reflection probes the
media are lit by are captured without them, so each capture holds the light of
the scene as it stands, a recapture leaves the media as they were, and a
reflecting surface is seen through the media in front of it. The sun occlusion
stays in the captures, so the ground a capture sees under a medium is dimmed
as the camera sees it.
## Why the sun occlusion channel
A medium in front of the sun takes the sun's light from the surfaces under it
and leaves the light arriving from every other direction. The sun occlusion
channel is the scene's per-pixel answer to how much of the sun is taken; the
sun's term reads it at the fragment's own pixel, the way it reads the
translucent casters' colour, so the ground under a thick medium is lit by the
sky and the ambient like the ground in an opaque blocker's shadow. It is
written at the depth seam, against this frame's depth and for the camera being
drawn, before anything shades.
What the channel holds is optical depth, not a depth to compare against:
- **Overlapping media stack.** Optical depth is additive, so two volumes that
intersect contribute to the same total with nothing to resolve.
- **Geometry inside a volume is lit by the part it has reached.** The ray toward
the sun starts at the surface, so a post standing in the middle of a fog bank
is dimmed by the half between it and the sun rather than by the whole column.
## Inputs
`@scene.color`, `@scene.depth`, `@frame.camera`, `@frame.light`,
`@scene.environment`, `@scene.reflectionProbes`, and the
`media_params` / `media_volumes` buffers packed by
`@builtin::systems.volumetrics.mediaTransmittance`. Writes
`@scene.sunOcclusion`.