# Module (asset type)
A module is Luau code that runs when other code calls it: other code
pulls it in with `require()` and calls its functions. It has no
lifecycle hooks or callbacks; nothing attaches it to an entity or runs
it every frame. Anything that is code can be a module: a whole game
system (rules, an inventory, a level generator, a match flow), a
helper, a format parser, a registry, a shared algorithm. The engine's
own APIs (`physics`, `input`, `audio`, `camera`, `entity`, `asset`,
`http` and the rest) are modules.
## 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 code runs on an entity, driven by hooks and callbacks, 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**.
# entity
The `entity` global: spawning, despawning, finding, and the reference you get
back when you call it.
`entity` is a table you can also call. `entity.spawn(...)` and its siblings act
on the scene; `entity(id)` hands back an **entityRef** — the per-entity surface
carrying `.position`, `.component`, `:despawn()` and the rest.
```luau
local id = entity.spawn("Crate")
local e = entity(id)
e.position = { 0, 1, 0 }
e.component.add("Model", { mesh = "@builtin::meshes.cube" })
```
## What lives here
| File | What it is |
|------|-----------|
| `init.luau` | The `entity` global — typed wrappers over the Internal `__entity` namespace, plus the coercions and `entity.hierarchy`. |
| `members.module/` | The entityRef's member set: every member's kind, type and description, in one table. |
| `ref.module/` | The entityRef metatable — what `entity(id)` returns and how a member access dispatches. |
## Where the entityRef's surface is defined
`members.module` is the single description of it. The runtime's accepted-member
set derives from that table, the LSP's `entityRef` type is generated from it,
and each member's documentation is published from it. Nothing describes the
entityRef anywhere else — a second description could only drift from this one.
To add a member: declare it in `members.module` with its `kind`, `type` and
`doc`, and implement it in `ref.module`. A member missing from the table is
refused by the runtime; a member in the table with no implementation answers
nil.
## Related
- `entity.hierarchy` — swap a blockout entity for a generated asset.
- `ecs.*` — the ECS storage surface. **ECS components are not script
components**; `entity(id).component` is the script-component surface and the
two are separate systems.
·renderfeature · born here
❒asset # surfaceWeather
The render feature behind `Weather` and `@builtin::systems.weather.weather`. One
compute pass runs once the opaque scene is lit, at `afterOpaqueLit` order 57,
ahead of the air that hazes the opaque scene and of the transparent phase.
## What decides the response
**Orientation.** Rain and snow arrive from above, so an upward face collects
both and a wall collects far less. Snow is the stricter of the two — it settles
or it does not, so its orientation term is a threshold rather than a ramp.
**Shelter.** `@builtin::systems.weather.weather` bakes a cover field over the
scene — an XZ grid whose columns hold the heights of the undersides standing
over that place — and the pass reads the point's own column, blended across the
four cells around it. Cover is a fact about the world, so a surface reads the
same answer from every camera and every lens. Without this an overhang gets the
same rain as open ground, which is the detail that gives away painted-on
weather.
A point outside the grid is outside the geometry the field was baked over, so
nothing stands above it.
## Wetness
A water film has a higher index of refraction than air, so more light refracts
into the surface and is absorbed, and what does reflect leaves in a tighter
lobe. Both fall out of the same fact, so wetness darkens the surface and adds a
sheen against water's 0.02 reflectance at normal incidence.
The sheen is a reflection, so it carries the light the surface stands in — taken
the way the surface itself takes that light:
* **The surroundings**, as one radiance over the whole hemisphere: the scene's
ambient term, the quantity `zpbr_environment_radiance` hands every PBR
surface, under `skyColor`'s tint. It enters through the Schlick term at the
viewing angle, which is what makes a wet floor brighten toward grazing.
* **The sun**, from the scene's directional light, and **every lamp the scene
holds**, out of `@scene.lights` — the same buffer the lit passes read. Each
goes through the GGX/Smith/Schlick lobe those passes shade it with, at the
film's own roughness, and on the terms its own kind is lit by: a point light
through the windowed falloff that ends its reach, a spot through that and its
cone, a rect from the face it emits along and against the part of it the film
looks at, a distant light along its one direction everywhere. So a lamp's
reflection in the water and the pool of light it lays on the floor agree
about where that lamp is and how far it reaches.
A surface therefore answers the light in the room it stands in: warm under
lamps, dark once the lights are out, and carrying the sun where the film happens
to face it.
## Snow
Settled snow takes over a surface's colour rather than tinting it. Its
brightness is modulated by how lit the surface already was, so snow in a dim
scene stays dim rather than glowing.
## Camera
`@frame.camera` supplies the inverse view-projection; the forward matrix is
inverted from it in the shader, which keeps offscreen captures and
render-to-texture cameras correct.
Parameters arrive through the `weather_params` buffer, packed by
`@builtin::systems.weather.weather`.
# lighting
Scene-lighting base capability: ambient + directional ("sun") light and procedural-sky setup with modify-or-spawn, read-merge-write semantics, plus clear color, and the per-frame reads of the resolved lights. Identity is the component, never the entity name: the sun is the `Light` the renderer's snapshot names as the directional holder, the ambient is the light-role component of kind "ambient", and the sky is the entity carrying a sky-role component. Name-based lookup, word resolution, and sky-material orchestration (presets, material swap) live in the `lighting` toolbox.
`sun` and `ambient` configuration patch the scene's resolved sun / ambient light components, spawning a carrying entity when the scene has none. A partial update (e.g. only `intensity`) reads the component's current fields first and merges the given fields on top, so unspecified fields keep their authored values instead of resetting to a default. `sky` writes the sky entity's ProceduralSky component the same way — any of its fields, plus `enabled = false` to remove the sky component.
## Types
- `SunOpts` — `{ direction?, color?, intensity?, castsShadows? }`.
- `AmbientOpts` — `{ color?, intensity? }`.
- `ProceduralSkyOpts` — ProceduralSky component fields, plus `enabled = false` to remove the sky.
- `SetupOpts` — `{ sun?, ambient?, sky?, clearColor? }`.
- `SetupResult` — `{ sun?, ambient?, sky? }`, the entity ids each provided section resolved to.
- `Sun` — `{ direction, color, intensity, castsShadows, entityId? }`.
- `Ambient` — `{ color, intensity, entityId? }`.
- `LightRow` — one punctual light as the renderer resolved it.
## Exports
Writes — each takes the opts above and answers with the entity the light resolved to:
- `M.setSun(opts: SunOpts) -> string` — set the scene's sun, returning its entity id.
- `M.setAmbient(opts: AmbientOpts) -> string` — set the scene's ambient term, returning its entity id.
- `M.applySetup(opts: SetupOpts) -> SetupResult` — apply a lighting setup in one call. All fields optional — only provided fields change. `clearColor` is `{r, g, b}`.
- `M.setProbeVolume(key: string, volume)` / `M.removeProbeVolume(key: string)` — publish or retract a baked irradiance probe volume.
Reads — each takes no arguments, and answers from the resolved lighting state at a cost independent of scene size:
- `M.sun() -> Sun` — the sun the frame is shaded by.
- `M.ambient() -> Ambient` — the ambient term the frame is shaded by.
- `M.lightRows() -> { LightRow }` — every punctual light the renderer resolved this frame.
- `M.revision() -> number` — a counter that moves on each frame the resolved lighting changed (a light field, a light's world transform, the set of lights); work built from the reads above keys on it.
Identity:
- `M.lightKind(componentType: string, component: any?) -> string?` — the kind a light-role component names.
- `M.lightOfKind(entityId: string, kind: string) -> any` — the light-role component of that kind on one entity.
## Usage
```luau
local lighting = require("@builtin::modules.api.engine.lighting")
lighting.setSun({ direction = { 0.3, -1, 0.2 }, intensity = 2.0 })
lighting.setAmbient({ intensity = 0.3 })
lighting.applySetup({
sun = { direction = { 0.3, -1, 0.2 }, intensity = 2.0 },
ambient = { intensity = 0.3 },
sky = { timeOfDay = 14 },
})
local sun = lighting.sun()
print(sun.intensity, sun.entityId)
```
A reader takes no arguments and a setter takes the opts table, so `lighting.sun(opts)` is refused with the name of the call that applies it.
# renderer
GPU-resource factory plus CPU codec/store wrappers — the GPU/CPU half of the asset↔resource split. Moves a resource Disk → CPU → GPU in explicit steps and returns inert handles describing each live resource. assetType behaviours, components, and every other module call `renderer.*`.
A resource moves through three states, each an explicit call:
- `ref:load()` → `renderer.<res>.loadCpu(ref)` decodes the asset's primary content into the guid-keyed CPU store and returns a CPU handle (holds only a guid plus dims/counts and the read/encode/unload ops).
- `renderer.<res>.create(cpuHandle | rawData, guid?)` uploads CPU → GPU, keyed by guid, and returns a GPU handle. `create` never takes an `AssetRef` — load the CPU first.
- `renderer.destroy(handle)` frees the GPU resource; a CPU handle's `:unload()` frees the CPU copy.
A `MeshHandle` / `TextureHandle` / `MaterialHandle` is an inert data record (`{ kind, category, guid, name, ... }`) describing one live GPU resource. Every GPU op lives on `renderer.*` and takes the handle.
Anywhere a call names a resource it takes any of the forms you already hold — the handle `create` returned, the CPU handle `loadCpu` returned, the guid, or the `AssetRef` `asset.resolve` returned. Handles compose: what one call hands back, the next call accepts.
## Types
- `Aabb` — `{ min = {x,y,z}, max = {x,y,z} }`.
- `MeshHandle` / `MeshCpuHandle` / `MeshGeometry` / `MeshBuffers`.
- `TextureHandle` / `TextureCpuHandle` / `TexturePixels`.
- `MaterialHandle` / `MaterialContent`.
## renderer.mesh
- `encode(geom) -> string?` / `decode(zmsh) -> (geom?, errmsg?)` — the ZMSH CPU codec.
- `loadCpu(ref) -> MeshCpuHandle` — Disk → CPU load (called by `meshRef:load()`).
- `create(src, guid?) -> MeshHandle` — create or fetch a GPU mesh from a `MeshCpuHandle`, raw geometry `{positions, indices, normals?, uvs?, colors?}`, compute buffers `{vertexBuffer, indexBuffer, vertexCount, indexCount, aabbMin?, aabbMax?}`, or a `MeshHandle`.
- `geometry(mesh) -> MeshGeometry` — the mesh's vertex data, the read that pairs with `create`.
- `update(handle, src) -> MeshHandle` — overwrite the GPU resource in place under the same guid.
- `readback(mesh, into?) -> MeshCpuHandle`: GPU → CPU recovery of a runtime mesh's geometry. `into` lands the copy under a CPU-store key of the caller's own, which stays resident until the caller unloads it, whatever re-registers or unloads the mesh itself.
- `isResident(mesh) -> boolean` / `isCpuResident(mesh) -> boolean`.
- `clusters(mesh)` / `scheduleClusters(mesh, opts?)` / `clusterBakes()` — the mesh's level of detail. Every static mesh draws through clusters, and a baked hierarchy of them (`kind = "dag"`) is cut by the GPU per view and per instanced copy, so detail falls off continuously with distance with no authored LOD meshes; `kind = "lod0"` draws full detail at every distance until a bake lands. `guides { path = "topics/world-detail" }` covers which meshes bake on their own.
Geometry moves in four directions, two per axis — DATA the caller holds, and the geometry of a mesh the ENGINE holds:
| From | → bytes | → geometry |
|---|---|---|
| geometry (data the caller holds) | `encode(geom)` | — |
| ZMSH bytes (data the caller holds) | — | `decode(zmsh)` |
| a mesh the engine holds | `encodeCpu(mesh)` | `geometry(mesh)` |
`geometry(mesh)` reads the resident CPU copy when there is one and reads the geometry back off the GPU when there isn't (yielding a frame or two), so a mesh straight out of `create` answers it:
```luau
local h = renderer.mesh.create({ positions = P, indices = I, tangents = T })
local geom = renderer.mesh.geometry(h) -- { positions, indices, tangents, ... }
```
An optional stream is present only when the mesh carries one. The GPU vertex layout has no "unset" — it holds a zeroed tangent, a zeroed skin binding, and a second UV set copied from the texture UVs for every mesh — so a stream saying only what its absence already says is reported absent. `geom.tangents == nil` is therefore the answer to whether a mesh has a tangent basis, and `geom.uvs1 == nil` to whether it has a second UV set.
## renderer.texture
- `encode(rgba, width, height, opts) -> (string?, errmsg?)` / `encodeFromImage(bytes, opts) -> (string?, errmsg?)` / `decode(ztex) -> (rgba?, width?, height?)` — the ZTEX CPU codec.
- `withSampler(ztex, { filter?, wrapU?, wrapV?, anisotropy? }) -> (string?, errmsg?)` — the same payload with only its recorded sampler state changed; every level is byte-identical.
- `loadCpu(ref, encodeOpts?) -> TextureCpuHandle` — Disk → CPU load with per-pixel access.
- `create(src, guid?) -> TextureHandle` — from a `TextureCpuHandle`, raw pixels `{rgba, width, height, srgb?}`, a `TextureHandle`, or render-target dimensions `{width, height, name?}` (an empty GPU texture a render pass writes into).
- `update(handle, src) -> TextureHandle`, `destroy(handle)`, `capture(handle) -> string` (CPU readback result key), `readback(texture) -> TextureCpuHandle`, `isResident(texture) -> boolean`.
## renderer.material
- `create(content, key) -> MaterialHandle` — register or update a material's GPU record (`content = { shader, properties, textures, aliases?, name? }`) under its canonical registry key.
- `animatedTexture(texture, opts?) -> MaterialHandle` — a material that PLAYS a layered texture: its layers bound as the frames, its timing beside them, the built-in `animatedTexture` shader turning the clock into the layer showing now. One call from an imported GIF / APNG / animated WebP to a material an entity can wear. `guides { path: "topics/animated-images" }` is the whole surface.
- `setProperty(key, name, value)` — push one changed uniform.
- `setTexture(key, slot, ref)` — push one changed texture slot (the texture must already be GPU-resident).
- `destroy(key) -> boolean` — drop the definition filed under `key`, so `describe` and `list` stop answering for it. A surface already wearing the handle goes on drawing it.
A `MaterialHandle` and its `guid` are two different currencies. What a surface wears is the HANDLE — `Model:applySessionMaterial(handle)`, or a Model's `material` field. The handle's `guid` is the material's registry key, which is what `setProperty`, `setTexture`, `describe` and `destroy` take. A component field resolves an asset, so a bare registry key in one leaves the component waiting for an asset to register under that name.
## renderer.instanceData
Four `vec4` lanes of generic shader data per entity — the channel that lets ONE material serve many entities that differ in a value, instead of one material per entity. A surface shader reads lane `i` back as `input.shader_data[i]`, and the engine attaches no meaning to what a lane holds.
- `laneCount() -> number` — lanes per entity, so a lane index runs `0 .. laneCount() - 1`.
- `set(target, lane, x, y?, z?, w?)` — write one lane of an entity's block. `target` is an entity proxy or an entity-id string naming a live entity; `y` / `z` / `w` default to 0. The lane reaches the block where the call is made, and the draw on the next frame.
- `clear(target)` — drop the entity's whole block, so its draws read zero again. Takes an entity that has already gone, and does nothing for one holding no block.
A lane index outside the block, or a target no live entity answers to, is an error at the call rather than a write that lands nowhere. A feature picks the lane indices it owns and names them where it writes them: `@builtin::systems.globalIllumination.lightmap` holds lane 0 for a receiver's atlas rect and lane 1 for its layer and enable flag, which is the shape to copy.
The same lanes reach a GPU-driven population through `renderer.mesh.drawInstanced`'s `instanceDataBuffer`, on slots no entity owns.
## renderer.featureTexture
The texture analogue: a shared `rgba16f` 2D array every surface shader can sample as `zero_feature_texture(uv, layer)`, and the array a `SpotLight` projects a layer of through its cone via `cookieLayer`.
- `configure(width, height, layers)` — size the array. A call for the size it already has is left alone; one that changes the size reallocates, and the replacement is zeroed, so it empties every layer in the array — the layers other features and other cookies own along with your own.
- `setLayer(layer, textureKey, x, y)` — copy a GPU-resident `rgba16f` texture into one layer at that offset, GPU to GPU with no readback. Several small images pack into one layer at different offsets.
- `state() -> { width, height, layers, filled, fills }`: the extent the array carries and `filled`, the ascending 0-based indices of the layers a fill has landed in since it was last sized. One array is shared by every feature and every light cookie, and it has no allocator, so this is what a feature asks to tell whether the array it sized and filled is still the array it is writing into. A layer some other `configure` emptied leaves `filled` without it, which is what separates that from a fill that never landed. What it describes is the array a shader samples: the source texture a `setLayer` copied from is a GPU resource of its own and keeps the bytes it was written with, so `filled` is the reading that answers whether the layer behind a `cookieLayer` is live right now. `fills` counts the fills that have landed in each layer since the array was last sized, `fills[layer + 1]` for a 0-based layer: a fill of a layer already holding content leaves `filled` as it was and moves this count, so a feature re-filling its own layer reads its fill arriving here. Measured at the end of the last rendered frame, like every reader below.
```luau
renderer.featureTexture.configure(256, 256, 4)
renderer.featureTexture.setLayer(0, "my_gobo", 0, 0)
-- ... elsewhere in the scene, another feature sizes the array ...
local ft = renderer.featureTexture.state()
if ft.width ~= 256 or table.find(ft.filled, 0) == nil then
-- layer 0 was emptied under us: size it back and re-fill.
end
```
## Reading back what the renderer did
Every call above states an intention. What the renderer made of it is a separate
document, published once per frame and read through these:
- `drawDiagnostics() -> { DrawDiagnostic }` — every renderable that is NOT
drawing what its material says. A surface rendering as the magenta
placeholder, one the renderer could bind nothing for, and one drawing a
program whose most recent compile failed all land here, each naming the entity,
the program asked for, the program bound, and the one cause. It covers every
renderable the renderer holds, whether or not a camera reached it — a row with
`observed = false` and `outcome = "notDrawn"` is the renderer's own resolution
for one this frame drew nowhere, so a broken surface off-screen reads the same
as one in frame. An empty result means every renderable the renderer holds is
drawing the program its material named. **Start here when a surface looks
wrong.**
- `material.renderState(key) -> MaterialObservation?` — the blend / cull /
topology / queue / depth key the renderer holds a material under, and whether
a pipeline exists for it. `nil` means the renderer holds no material under
that key, which is what writes reaching nothing on screen look like. `index`
is the material index its row is filed under, and `textures` the texture key
each slot of that row names, so a `setTexture` the renderer has taken up
reads there.
- `materialCost() -> { MaterialObservation }` — draws, instances, placeholder
draws and material-owned bind groups (`binds` set, `bindsElided` skipped) per
material, over the published frame.
- `shaderCost() -> { ShaderCost }` — pipeline build time and permutation count
per program, summed since engine start, beside the compile gate's word.
- `observe() -> RenderObservation` — the whole document the four above read.
`/zero/runtime/generated_materials` serves the same document as files. Every
`notDrawn` row names why no pass reached it in `notDrawnReason`:
`meshNotResident`, `hidden`, `layer`, `culled` or `viewCull`.
## renderer.destroy
- `destroy(handle) -> boolean` — free the GPU resource behind a `MeshHandle` / `TextureHandle`, routing by the handle's `category`.
## Parts
The module is a folder of parts, each a module of its own that `init.luau` requires:
- `renderer.refs`: guid minting and the coercion from whatever names a material, mesh or texture to the key the renderer indexes it by.
- `renderer.sources`: the `src` shapes `renderer.mesh.create` / `update` and `renderer.texture.create` / `update` take, and the bounds and counts raw geometry implies.
- `renderer.shading`: the readings `renderer.shadingOf` builds out of the document the renderer publishes.
## Usage
```luau
local renderer = require("@builtin::modules.api.engine.renderer")
local gpu = renderer.mesh.create({ positions = { ... }, indices = { ... } })
renderer.destroy(gpu)
```
# asset Module
Public Luau surface over the `__asset` Internal FFI namespace —
asset resolver, ref envelope builder, sidecar metadata.
## Purpose
Wrap the raw `__asset.*` FFI namespace in a typed Luau table that
gets auto-injected as `_G.asset` via the prelude. Three families:
- **Lookup** — `resolve`, `ref`, `typeRef`, `inspect`, `source`,
`identity`, `guid`, `meta`, `deps`. Every op accepts any name an
asset has (handle, guid, identity, path, bare name) and returns
the requested view.
- **Discovery** — `categories`, `list`, `containing`.
- **Generic `.metadata` sidecar** — `metadata`, `set_metadata`,
field-level `get_field` / `set_field` / `remove_field` /
`has_field`, tag helpers (`tags`, `has_tag`, `add_tag`,
`remove_tag`), and `validate`.
The previously-FFI `bundle.*` namespace was dissolved into the
bundle assetType (see `@builtin::assetTypes.bundle`);
that's not exposed here. The prelude mints `bundle` separately as
a thin Luau table grafted from `bundle_update`.
## Usage
```luau
-- Lookup
local cam = asset.resolve("@builtin::components.Camera")
local ref = asset.ref("animations.idle", "animation")
print(asset.identity(cam), asset.guid(cam), asset.source(cam))
-- Discovery
for _, c in ipairs(asset.categories()) do print(c) end
for _, sceneRef in ipairs(asset.list("scene")) do print(sceneRef.identity) end
local s = asset.containing("/zero/source/scenes/main.scene/scene.json")
-- Metadata sidecar (agent-editable)
asset.set_field(ref, "category", "movement")
asset.add_tag(ref, "looping")
print(asset.has_tag(ref, "looping"))
-- Structural validation
local v = asset.validate(cam)
for _, p in ipairs(v.problems) do print(p.severity, p.message) end
```
## Exports
- Lookup: `resolve`, `ref`, `typeRef`, `inspect`, `source`,
`identity`, `guid`, `meta`, `deps`.
- Discovery: `categories`, `list`, `containing`.
- `.metadata` sidecar: `metadata`, `set_metadata`, `get_field`,
`set_field`, `remove_field`, `has_field`, `tags`, `has_tag`,
`add_tag`, `remove_tag`, `list_fields`, `list_field_values`.
- Validation: `validate`.
# ecs
Public, typed, discoverable API for native ECS components. Generic verbs (`insert`, `get`, `set`, `has`, `remove`, `query`, ...) operate on any component, while per-component typed constructors (`ecs.Mesh`, `ecs.Material`, `ecs.Transform`, ...) build the Rust-shaped value the verbs apply. Each constructor is minted at module load from a spec under `ecs.components.<Name>`.
## Typed constructors
`ecs.<Name>{...}` builds a component value: it runs the compiled conversion plan (asset-handle resolution, camelCase → snake_case field mapping, `vec3` expansion) and raises on an unknown field. The result is a value the upsert verbs accept.
```luau
local ecs = require("modules.api.engine.ecs")
local value = ecs.Transform{ position = { x = 0, y = 1, z = 0 } }
ecs.insertSync(id, value)
```
The constructor also takes every shape the component is read back as, so a read hands straight to the constructor it came from:
- the `ecs.get` handle — `ecs.Light(ecs.get(id, ecs.Light))`,
- the engine-side field table `handle:read()` and `ecs.snapshot(id).<Name>` give back,
- a value the constructor already built (copied, so the two are separately writable),
- a table keyed by public field names, engine-side field names, or both.
That makes changing one field a read, an assignment and a write back:
```luau
local h = ecs.get(id, ecs.Light)
h.intensity = 0
ecs.set(id, ecs.Light(h)) -- every other field keeps what it held
```
Each of those shapes names the component it holds, so handing one to another component's constructor says which component it is and which constructor takes it. The `ecs.get` handle writes its own fields as well — `h.intensity = 0` is already the whole write — so reach for the round trip when you want the component's value in hand.
## Verbs
Every verb accepts an entity proxy (what `entity.spawn` returns) or a raw id string.
- `ecs.insert(id, value) -> promise` — async upsert; await for same-tick visibility.
- `ecs.insertSync(id, value)` — upsert visible this tick; raises on failure.
- `ecs.insertMany(ids, value) -> number` — insert one value into many entities in a single crossing; returns the count applied.
The three insert verbs warn per field a component could not hold the value it was given, naming the component, the
entity, the field under its engine-side name and the value; the component holds that field's default and every other
field lands.
- `ecs.get(id, ecs.<Name>) -> handle?` — retained handle over a present component (`nil` when absent). See `handle`.
- `ecs.set(id, value) -> ok, rejected` — patch fields of an already-present component; raises if the component is absent.
`ok` is false and `rejected` lists the public field names that did not land when a field cannot hold the value it
was given (a string outside an enum field's set, a shape the field's type does not read). Each name appears once and
is warned once, with the component, the entity and every value that name refused — under the name you wrote it as,
where the insert verbs name the engine-side one. Every field is attempted, so one refusal leaves the rest applied.
- `ecs.has(id, ecs.<Name>) -> boolean`
- `ecs.findInSubtree(id, ecs.<Name>) -> string?` — the id of the entity itself, or else of the first of its descendants (depth-first, each entity before its children, children in `entity.getChildren` order), that carries the component; `nil` when none does. The walk runs in the engine and builds nothing in Luau, so asking it every frame of a subtree that holds no such component allocates nothing.
- `ecs.len(id, ecs.<Name>, field) -> number?` — element count of a collection-valued field (list/array/map/set), counted without building any element; `nil` when the component is absent or the field is not a collection. Reading the field to measure it converts everything in it — `#h.bones` on a 50-bone `Skeleton` costs ~1ms against one crossing here — so ask this whenever the question is how many, or whether any.
- `ecs.remove(id, ecs.<Name>)`
- `ecs.components(id) -> {string}?` — public component names present on the entity.
- `ecs.snapshot(id) -> table?` — every native component on the entity, nested and keyed by public name, each holding that component's fields under the names the component itself uses. A catalogued component's field table names the component it came from, so it goes straight to that constructor.
- `ecs.queryIds(...) -> {string}` — ids holding ALL the given `ecs.<Name>` types.
- `ecs.query(...) -> {proxy}` — like `queryIds` but returns entity proxies.
- `ecs.bind(id, component, field, mode?)` — retained component-field accessor by rust component name.
- `ecs.bindEntities(ids)`.
## Discovery
The engine is driven at runtime, so the catalog is introspectable in-engine:
- `ecs.types() -> {string}` — public component names available as `ecs.<Name>`.
- `ecs.describe() -> { schema, ... }` — the full catalog: every component with its fields. `ecs.describe(name | ecs.<Name>)` returns the schema for one component.
- `ecs.<Name>:schema() -> { component, rust, fields = { {name, type, rust}, ... }, methods?, accepts }` — runtime field discovery for a single component; `accepts` lists the calls the name is accepted by, the round trip among them; behavior-bearing components also list their handle `methods`.
```luau
for _, schema in ecs.describe() do
print(schema.component, #schema.fields)
end
```
## Saved native components
A saved record (a scene entity, a bundle `entity_template` entry) lists its native components in an `ecs` array beside `components`: `ecs = { { type = "Mesh", data = { mesh = "<mesh asset guid>" } }, { type = "Material", data = { id = "<material asset guid>" } } }`. `type` is the name under `ecs` and `data` the row `ecs.snapshot` answers, with every handle-typed field written as the guid of the asset the handle came from. The scene loader and `bundle:instantiate` resolve each guid to the handle the component holds (`ecs.handles`, see its README) and insert one value into every entity that states the same entry.
# Weather cover grid
`sample` casts one upward ray per grid cell and returns the packed underside heights and occupied-cell count for that contiguous range. The weather module uses it for both direct bakes and background refreshes.
# jobs
Substrate job registry. Wraps the `__jobs` FFI surface with a typed
Luau API and a JobHandle metatable. Every registered job returns a
stable handle; the `__index` lookup hits a small METHODS table, so each
operation makes exactly one FFI crossing — none of the methods
snapshot the full registry.
Exposed as the `jobs` Luau global via `--!global`. Authored scripts
call `jobs.register`, `jobs.list`, `jobs.find`, `jobs.inspect` directly
without a `require`.
## Exports
- `jobs.register(descriptor: table) -> JobHandle?` — register a job. Dispatches by `executor.kind`: `"kernel"` / `"stub"` → `__jobs.register` (JSON-only descriptor), `"luau"` → `__jobs.register_luau` so the run function survives the JSON crossing as a stable registry ref. Auto-fills `origin` with the calling script's VFS path.
- `jobs.list(phase: string?) -> { JobInfo }` — list registered job summaries, optionally filtered to a single phase.
- `jobs.find(name: string) -> JobHandle?` — look up a registered job by name; returns a handle or nil.
- `jobs.inspect(target: JobHandle | string) -> JobInfo?` — return a snapshot row by handle or by name.
- `jobs.dispatch(module: string, entry: string, args: any, opts?) -> PromiseHandle` — run the function `entry` of the module `module` (a require path, read from the calling line as `require` reads it) on a worker thread, and answer a promise of its result. `opts = { deadline: number?, name: string?, key: string?, supersede: boolean? }`: the key the item runs as and whether it supersedes the key's items that have not started (see "Keep state in a worker: keys" below), the deadline in seconds (default and at most the longest hold on one run, 60 seconds on every platform, native and browser alike: it may be lowered and never raised, and a larger one is refused at the call naming the cap; the longest one run of the item may take between a resume and the next yield, counted per run on monotonic time and never summed across runs) and what a rejection calls the item.
- `jobs.parallelFor(module: string, entry: string, over: number | { first, last } | buffer, args: any, opts?) -> PromiseHandle` — split a loop across the worker pool; the promise settles with the chunks' results in chunk order. `opts = { deadline: number?, name: string?, chunks: number?, stride: number? }`.
- `jobs.release(key: string) -> boolean` — end the binding of a key to its worker VM once the key's items dispatched before the call have settled; that VM's `jobs.onRelease` watchers run with the key. False for a key the pool does not hold.
- `jobs.onRelease(watcher: (key: string) -> ()) -> () -> ()` — hold a watcher in the calling VM that runs once per release of each key bound to it; answers the function that removes it.
- `jobs.warm(module: string, entry: string) -> PromiseHandle` — run `entry` of `module` once in every worker VM, before items need what it builds; the promise settles once every VM up at the call has run it.
- `jobs.context() -> { worker, key?, fresh }?` — on a worker, the running item's worker slot, key and whether it is the first of its key in this VM since the key bound; nil on the engine thread.
Handle methods (called via `:`):
- `job:pause()` / `job:resume()` — skip / resume the job on subsequent ticks.
- `job:status() -> JobStatus?` — `"pending"` / `"running"` / `"errored"` or nil.
- `job:valid() -> boolean` — whether the substrate still tracks this job.
- `job:info() -> JobInfo?` — full snapshot row.
- `job:cancel()` / `job:destroy()` — drop one refcount; last drop unregisters.
Types:
- `JobStatus = "pending" | "running" | "errored"`
- `ResourceAccess = { resource = { kind, id?, component?, field?, entity? }, mode? = "r"/"w"/"rw", type? }`
- `JobExecutor = KernelExecutor | StubExecutor | LuauExecutor | ComputeExecutor`
- `JobOrdering = { after? = { string }, before? = { string } }`
- `JobDescriptor = { name?, phase, reads?, writes?, executor, ordering?, pure?, origin?, metadata? }`
- `JobInfo = { id, name?, phase, executor, executor_detail, status, paused, refcount, last_error?, origin?, metadata, pure, ordering, reads, writes, key?, waited_for_vm_ms? }`
- `DispatchOptions = { deadline?, name?, key?, supersede? }`
- `JobContext = { worker?, key?, fresh }`
- `JobHandle = { id, pause, resume, status, info, valid, cancel, destroy }`
## Usage
```luau
local job = jobs.register({
phase = "main",
executor = {
kind = "kernel",
kernel = "copy_buffer",
},
reads = {{ resource = { kind = "buffer", id = src.id }, mode = "r" }},
writes = {{ resource = { kind = "buffer", id = dst.id }, mode = "w" }},
})
-- Luau-kind executor — the dispatcher invokes `run` once per frame.
local tick = jobs.register({
phase = "main",
executor = { kind = "luau", run = function() print("tick") end },
})
job:pause()
local rows = jobs.list("main")
local info = jobs.inspect("animation_blend_main")
```
### Work on a worker thread
`jobs.dispatch` runs one function of a module on a worker thread, so a
computation that would hold a frame for tens or hundreds of milliseconds
holds none. The module and the modules it requires run in a worker VM
that boots the prelude and `require`s modules as the engine thread's VM
does, so it has the same globals and `modules/api` modules; the entry
computes from its arguments and returns a value, and the code awaiting
the promise applies it to the world.
A call to a function only the engine thread serves (one that reads or
changes the ECS world, the component instances its VM holds, or a table
the engine thread has not published yet) is forwarded. The task that made
the call waits as it waits on a promise, the worker keeps serving its other
tasks, and the time parked never counts toward the deadline. The engine
thread runs the same function with the same arguments after every write the
job recorded before the call, as the principal the job runs as, and the
answer returns to the job; an error the call raises raises in the job. Each
forwarded call takes at least one engine frame to answer, so a loop of them
costs a frame each; tasks that wait at once are answered in the same frame.
Arguments and answers cross as copies (nil, booleans, numbers, strings,
buffers, vectors and tables of those). A call whose argument holds a function,
coroutine or userdata handle, whose answer holds an object of the engine
thread's VM, or that is made where the script cannot wait (a metamethod, the
top level of a module being required, a `batch` or `queue` body) raises an
error naming the function and the reason. `job:info().forwarded_calls` counts
a worker job's forwarded calls, and
`profiler.counters("system.schedule.frame.forwarded_calls")` and
`profiler.stats("system.schedule.frame.forwarded_call")` report the calls the
engine thread served each frame and the milliseconds they took.
A watcher the module registers (`engine.onModeChange`, `modules.watch`,
`world.on`, `vfs.watch` and the other engine events) is kept by the
worker VM and fires when that VM next starts an item, for the events
raised since it registered. `save.onMarksLanded` is refused on a worker,
because the engine reads the value its callback returns inside its own frame.
A function the module hands the engine through `renderfeature.setTick`,
`jobs.register` (the `luau` and `worker` kinds) or `httpserver.route` stays in
the worker VM that registered it, and that VM stays in service for it after
the item returns: the engine posts each call to the worker and never waits for
it, and reads the output of the latest call that completed. A tick or a job
body runs once per frame, and what a tick enqueues is drawn one frame after
the tick that made it; a job's `input` result is read, and its `apply` runs,
one frame after the call that made them. A frame whose call is still running
keeps the last completed output, and the call it would have made is a late
call, counted in the `workers` report, in `jobs.inspect(job).worker.lateCalls`
and in the profiler count `system.schedule.frame.worker_late_calls`. A route's
handler runs on the worker once per request and the request waits for its
value, as it waits on the engine thread. The function runs as the job that
registered it. The registration lives until it is unregistered, or the world
changes or the scripting state resets, whatever became of the job that made it;
the worker's thread serves it for that long. The entry is a task of the worker VM's own scheduler: it waits on time
(`task.wait`), on frames (`task.waitFrames`) and on promises
(`task.await`), starts tasks and scopes, and returns its result. The
promise settles once the engine thread has applied every write the entry
and the tasks it started made before it returned, so the code awaiting it
reads all of those writes, as it would after making the same calls on the
engine thread. An entry whose last write the engine thread applies in the
frame the entry returned settles as soon as one that writes nothing;
otherwise it settles one frame later. It waits as long as the writes do
(while no world is open, say) and then resolves with the entry's result. It
rejects only when the engine resets the scripting state or changes its world
first, and then none of those writes is applied.
The tasks it started keep running until they end or the item's deadline
ends them, or a run of one passes the deadline; the deadline is for one call, one run from a resume to the next yield, and time parked never counts. A write one of those tasks makes after the entry returned is not part of what the promise waits for. A promise the
worker makes settles on that worker (`delay`, `http.*` and
`jobs.dispatch` serve one), and a call whose promise an engine-thread
system settles (`queue`, `shell.run` of a command it would queue) is
refused, naming it.
An item runs as the task that dispatched it: its caller key and its whole
call context (the actor token of the agent whose call began the chain) are
captured at the dispatch, carried by the item's task and every task, watcher
callback, nested `jobs.dispatch` and `jobs.parallelFor` chunk it starts, and
nothing in Luau can state another. A write the item records is applied by the
engine thread as that caller, so a component it adds, a publish it makes and a
metered service call it issues belong to the dispatcher. A callback runs as the
caller that registered it (none when none did), from the worker's own loop and
never inside the call of another task, and one run of it is bound by the same
hold as an item's run. No run of Luau on a worker thread is unbounded: a task's
resume, a watcher or handler the worker's loop fires, and a call nothing routed
each have the hold, and a run that has not armed one is given it from its first
safepoint. A worker VM ends when the engine resets its scripting
state or its world changes: its tasks, watchers and handles end, the item it
serves fails naming the reset, and the next item runs on a new VM over the
modules the engine holds then. `/runtime/workers` names what a worker keeps
serving after its item returned (`serving`: the item, its owner tag, the caller,
and the tasks and watchers it holds).
The pool runs
several workers, each with a VM of its own, and an item dispatched without a
key runs on whichever worker takes it. A module's top-level state stays in the
VM that set it; items that keep state there for the next one run with a key
(below).
```luau
-- /source/terrain/noise.luau
local M = {}
function M.heights(args)
local out = buffer.create(args.size * args.size * 4)
for i = 0, args.size * args.size - 1 do
buffer.writef32(out, i * 4, math.noise(i % args.size / 16, i // args.size / 16, args.seed))
end
return out
end
return M
```
```luau
local heights = jobs.dispatch("@<library>::terrain.noise", "heights", { size = 256, seed = 7 }):await()
```
`<library>` stands for the library that holds the module: `root` for a
module of the caller's own world.
- The pool's size is its share of the engine's one thread budget (the
hardware threads less the engine thread, shared among the compute-task,
data-parallel, off-frame, luau-workers and pipeline-build pools by
weight, at least one thread each), so that many items run at once;
`/runtime/workers/pool` reads the number as `max_workers`, and
`__threads.budget()` lists every pool's share and size.
- The promise is a future (`core/scripting-and-tasks`): code that must not
wait, a component's `update` among it, reads `p:state()` (`"pending"`,
`"resolved"`, `"rejected"`, `"cancelled"`) each frame and takes the value
with `p:await()` once it has settled, which then returns at once.
- A promise settles when the engine thread takes in finished items, once a
frame, so a round trip lasts at least a frame however small the entry:
an item is worth sending when its work outweighs that frame.
- `args` and the result cross as copies: nil, booleans, numbers,
strings, buffers, vectors and tables of those. Any other value (a
function, an entity, a cyclic table) is refused at the call, naming
its key path (`args.fn`).
- The promise rejects with the entry's error and its stack, or names the
deadline when one run of the entry takes longer than `opts.deadline`; an entry that keeps yielding has no lifetime limit.
- `p:cancel()` halts a running entry, and keeps a queued one from
running; the awaiter raises the cancellation `task.isCancellation`
recognises.
- An edit of the module reaches the next dispatch.
### Keep state in a worker: keys
An item dispatched with `opts.key` runs in the worker VM its key is bound to,
so the state a module keeps for the key (a cache, a plan, a parsed asset, a
compiled rule set) is there for the key's next item:
```luau
-- /source/paths/graph.luau
local graphs = {}
local M = {}
jobs.onRelease(function(key)
graphs[key] = nil
end)
function M.route(args)
local ctx = jobs.context()
local graph = graphs[ctx.key]
if graph == nil then
graph = buildGraph(args.map)
graphs[ctx.key] = graph
end
return graph:route(args.from, args.to)
end
function M.loadTables()
loadSharedTables()
end
return M
```
```luau
jobs.warm("@<library>::paths.graph", "loadTables")
local route = jobs.dispatch("@<library>::paths.graph", "route", { map = map, from = a, to = b }, { key = "level3" }):await()
jobs.release("level3")
```
- The first item of a key binds the key to a worker VM: an idle worker holding
the fewest keys; when none is idle, a worker the pool starts for it while it
is under its cap, or else the worker holding the fewest keys. Every later
item of the key runs in that VM. A key holds no worker: between the key's
items the VM serves other items, keyed or not.
- The items of a key run one at a time, in the order they were dispatched: the
next starts once the one before it has settled and the writes it made have
applied, so it reads them, also when that one waits and its worker serves
other work meanwhile. An item that awaits an item of its
own key is refused at the await, naming the key: the awaiting item holds the
key's turn, and the awaited item starts only after it settles. Dispatching to
its own key without awaiting (queueing a next stage) runs that item after it.
A cycle through other keys (an item of `a` awaiting one of `b` that awaits one
of `a`) waits for itself in the same way and is not refused.
- A worker waiting inside an item takes queued work of the principal that item
runs as, and the queued entries of keys that item itself awaits, or that a
task of its VM belonging to no item (a watcher, a tick, a route handler)
awaits, whatever principal queued them, since an entry bound to the worker
can run on no other. An entry of a key none of those awaits waits for a
worker of its own.
- A key's item waits for its VM even while other workers are idle: that wait
is the price of the state it finds there. `/runtime/workers` reports
it per key (`keys[].waited_for_vm_ms`), and `job:info().waited_for_vm_ms`
for a keyed worker job.
- `opts.supersede = true` with a key rejects every item of the key that has
not started, each naming the item that replaced it; the running item is
untouched. An edit stream sends each request with it and runs only the
newest.
- `jobs.context()` answers, on a worker, `{ worker, key, fresh }`: the pool
slot of the worker, the running item's key (nil for an item dispatched
without one, and outside an item, as in a watcher), and `fresh`, true for the
first item a key runs in this VM since the key bound, so a module tells a
cold cache from a missing entry. On the engine thread it answers nil.
- A binding ends when `jobs.release(key)` reaches it (after the key's items
dispatched before the call have settled), when its VM ends (the world
changes, the scripting state resets, an item panics in the engine, a browser
worker is lost), or when the pool ends. The key's next item binds anew and
runs fresh; an item waiting for its turn when the VM ended is not lost with
it. A key with items queued or running, bound or not yet bound (the pool
binds a key to the worker that takes its first item), is released after
them, and `jobs.release` answers true; it answers false, doing nothing, only
for a key with no binding and no item queued or running (a key whose only
entry is a release under way among them). Items of a key queued before the world changes or the scripting
state resets are refused unrun, naming the reset, as every queued item is:
they belong to the state that was reset. The key's items dispatched after it
run.
- `jobs.onRelease(watcher)` holds the watcher in the VM of the module that
registers it, as a worker VM holds its `engine.on*` watchers: it runs as a
task of that VM's scheduler, once per release of each key bound to the VM,
and drops what the module keeps for the key. It answers the function that
removes it. Without a release, a VM keeps each key's state for as long as it
lives; `/runtime/workers` lists the keys each worker holds (`workers[].keys`).
- `jobs.warm(module, entry)` runs `entry` of `module` once in every worker VM,
to build the state the module keeps in its own VM (a registry, a parsed
asset, a table it loads) before an item needs it. The pool starts every
worker it may start, each VM up runs the entry as its next item, and a VM
made later runs it before its first item, whichever boot made it. The
promise settles once every VM up at the call has run it: it resolves when
every run ended well, and rejects naming each worker whose run raised,
panicked or ran past the warm bound, and its error. A second call for the same
module and entry, for the life of the scripting state, runs nothing more and
answers the same.
- A warm entry builds state in its own VM and does not wait on the pool. It runs
under the hold on one run (60 seconds from a resume to the next yield), and
its whole run, waits included, under the warm bound: 60 seconds of wall time
from its start to its end, on every platform. The bound is read between runs,
so a run in progress at the bound goes on to its next yield: an entry that
does not yield runs at most the bound plus one hold, about 120 seconds. It
may wait on time and frames (`task.wait`, `task.waitFrames`). An await of a
`jobs.dispatch`, a `jobs.parallelFor` or a `jobs.warm` promise by the entry or
a task it started, while the entry runs, raises, naming what it awaited,
whether or not the promise has settled; so does making a `future` combinator
over one, at the call. Tasks the entry leaves behind await freely once it is
over. Dispatching without awaiting is fine: the item runs once the VM is
warm, so an entry that waits for that item another way (polling a flag it
sets, popping a queue it fills) runs to the warm bound.
- No item starts on a VM until its warm pass is over, keyed or not. Tasks the VM
already holds, those of items that started earlier and its watchers, ticks and
route handlers, go on between the entry's waits, and their awaits are their
own.
- An entry that raises is logged with its module, entry and worker, and the VM
serves on. An entry that panics the engine, or runs past the warm bound, runs
on no later VM until the scripting state resets: it is logged once and ended,
and a VM it panicked is followed by one that runs the rest of the pass before
any item. A panic in code outside the entry while it runs (the VM's boot, a
watcher, a task another entry left behind) ends that VM, and the VM made next
runs the pass once more. These endings are counted per entry, across every
worker of the pool, for the epoch: the second one fails the entry for the
epoch, naming the panic. A VM that cannot be made is reported with that
reason, and an item that waited for it fails naming it when it cannot be made
a second time.
- An item may call `jobs.warm`, awaited or not, whatever principal it runs as:
its worker runs the warm job for its own VM before the item resumes. A module
calls it as it is first used in a world, so a world that never uses the module
pays nothing; the entry runs on workers only. `/runtime/workers` lists each
worker's warm runs with their milliseconds, and the failed ones with why, those
of a VM that ended included (`workers[].warm`); a keyed item that waited
behind a warm pass counts that time in `waited_for_vm_ms`.
- A `kind = "worker"` job takes `executor.key`: every item of the job runs as
that key.
- A key is a string of 1 to 256 bytes, and the pool holds at most 65,536 keys
at once; a dispatch past either bound is refused at the call, naming it. A
bound key stays until it is released or its VM ends, so a key names a thing
that persists (a graph, a map, an asset), and a module releases it when the
thing goes.
### Split a loop across the workers
`jobs.parallelFor(module, entry, over, args, opts?)` cuts a loop into
chunks that run on the pool's workers and answers one promise, which
settles when every chunk is done with the chunks' results in chunk order.
`over` is a count of indices (`1..over`), a `{ first, last }` range of
whole numbers, or a buffer whose elements are `opts.stride` bytes each
(default 1). Each chunk calls `entry` with one table:
```luau
-- /source/sim/reduce.luau
local M = {}
function M.sumChunk(chunk)
local sum = 0
for i = chunk.first, chunk.last do
sum += i * chunk.args.scale
end
return sum
end
return M
```
```luau
local sums = jobs.parallelFor("@<library>::sim.reduce", "sumChunk", 100000, { scale = 2 }):await()
local total = 0
for _, s in sums do total += s end
```
- `chunk` is `{ index, count, first, last, args, data }`: the chunk's
place among `count` chunks, the first and last index it covers (for a
buffer, element numbers from 1), a copy of `args`, and for a buffer
`data`, the chunk's slice of it. Every index is in exactly one chunk.
- `opts.chunks` is the number of chunks (default four per worker, at
most one per index or element, at most 4096); chunks are as even as the range
divides.
- `opts.deadline` (seconds, default and at most the hold on one run: 60 seconds on every platform) bounds one run of each chunk between a resume and the next yield;
`opts.name` is what a rejection calls the call.
- A chunk that raises or runs past its deadline rejects the promise,
naming the chunk (`chunk 3 of 8`) and its error, and cancels the other
chunks. `p:cancel()` cancels every chunk.
- It runs from the engine thread and from inside a worker entry. A worker
that awaits the promise runs queued chunks itself while it waits, so a
chunk may call `parallelFor` again and complete with every worker busy.
- The promise settles once every chunk has returned and the engine thread
has applied every write the chunks made before they returned.
- Everything else (the worker VM, copied values, module edits) follows
`jobs.dispatch`. Splitting is worth its cost when each chunk's work
outweighs the frame a round trip takes.
### Work every frame on a worker thread
A `kind = "worker"` job runs the same kind of module entry every frame,
pipelined: the engine thread pays only for `input` and `apply`.
```luau
local job = jobs.register({
name = "crowd",
phase = "main",
executor = {
kind = "worker",
module = "@<library>::crowd.sim",
entry = "step",
input = function() return snapshot() end, -- engine thread
apply = function(result) write(result) end, -- engine thread, the frame it lands
deadline = 2, -- seconds one run of an item may take between a resume and the next yield (default and at most the hold on one run: 60 seconds on every platform)
},
})
```
- At the job's phase each frame, a result that has landed goes to
`apply(result)`; then, when no item is in flight, `input()` runs and its
value is copied to a worker, where `entry` runs on it. An `input` that
returns nil queues no item that frame, so a job with work only some of the
time returns nil until it has some.
- One item is in flight at a time. A frame whose item has not returned runs
no `input`; `job:info()` reports `in_flight`, `frames_behind` (the frames
waited on the current item) and `last_ms` (how long the last item held its
worker) and `forwarded_calls` (the calls its items made to functions only
the engine thread serves).
- The module follows the `jobs.dispatch` rules: a worker VM that boots the
engine's prelude, copied values, and an edit reaching the next item.
- Without `executor.key`, two items of one job can run on different workers,
and module state stays in the worker VM that set it, so what one item hands
the next travels through the result and `input`: `apply` keeps it on the
engine thread and `input` sends it back. With `executor.key`, every item runs
as that key, in the VM the key is bound to, and finds the state the item
before it left there.
- An entry that raises, runs past its deadline, or whose `input` value
cannot be copied errors the job with the message (`job:info().last_error`,
and once in the engine's error log, naming the job);
`job:resume()` runs it again. An `apply` that raises errors its own job and
no other.
- Destroying, pausing or erroring the job stops its item, and `apply` never
runs for it. `input` and `apply` run as the principal that registered the
job, and so does each item.
- `/runtime/workers` reads the pool (`pool`) and each worker that has run an
item (`0`, `1`, ...): its state (`running`, `idle`, or `lost` for a worker
lost while it ran an item), the item it is running, its item count and busy
time.
- `__threads.pools()` reports the `luau-workers` pool: its workers, the
items queued and running, and the workers lost.
### Share state with the game while a job runs: `jobs.shared`
`jobs.dispatch` hands its result back when the entry returns. State that has to
cross *while* a job runs (progress, partial results, a flag the game sets, work
handed from one job to another) lives in `jobs.shared`: tables and queues that
the engine's VM and every worker VM read and write. Process memory, not
persisted and not replicated: `runtime_data` and synced component fields are
the persisted, replicated stores.
```luau
-- /source/terrain/build.luau (runs in a job)
local M = {}
function M.run(args)
local regions = jobs.shared.table("terrain.regions")
for index = 1, args.count do
regions[index] = buildRegion(index) -- a table of numbers, strings, buffers
jobs.shared.atomic(jobs.shared.table("terrain.progress"), "done", function(n) return (n or 0) + 1 end)
end
return true
end
return M
```
```luau
-- the game, each frame
local regions = jobs.shared.table("terrain.regions")
local progress = jobs.shared.table("terrain.progress")
local seen = 0
task.loop(function()
local now = jobs.shared.revision(regions)
if now ~= seen then
seen = now
for index, region in regions do showRegion(index, region) end
end
end)
```
- `jobs.shared.table(name)` is a table every VM reads and writes: `t.x = 1`,
`t.player.hp -= 5`, `#t`, `for k, v in t`, `pairs`, `ipairs`, `next`,
`table.insert`, `table.remove`, `table.sort`, `table.concat`, `table.find`,
`table.unpack`, `table.clone`, `table.clear`, `rawget`, `rawset`, and
`type(t) == "table"` behave as on an ordinary table. It holds nil, boolean,
number, integer, string, vector, buffer and tables of those. Assigning a
table copies it in: later edits of the local table are not seen. A function,
coroutine, userdata, or a table with a metatable raises, naming the key path.
- `t.a` where `t.a` is a table is that table, so `t.a.b = 1` writes through
and `t.a == t.a`. A table that was replaced or removed raises on any use,
naming where it was.
- Each access is atomic on its table. A loop walks the table as it stood when
the loop started: it never sees a torn table and never holds a writer up.
A change that spans keys is one `jobs.shared.atomic` on the parent key.
- `jobs.shared.atomic(t, key, fn)` reads, changes and writes one key without a
race. `fn(current)` returns the new value; if another write reached the table
meanwhile `fn` runs again on the newer value (up to 256 attempts, then the
call raises naming the table and key), so `fn` is quick, pure and does not
yield. A call that lost four attempts in a row takes its turn at the table:
the other `atomic` calls on a worker wait for it, so `atomic` calls never
starve one another, and the 256 attempts bound only a storm of plain writes.
Counters, flags and compare-and-set are this call.
- `jobs.shared.revision(t)` is one number that every write to the table or to
any table nested in it advances: game code that polls each frame reads the
table only when the number moved. `jobs.shared.snapshot(t)` is a plain deep
copy.
- `jobs.shared.queue(name, { capacity = 1024 })` is a bounded first-in-first-out
queue (at most 65,536 values). `q:push(v)` copies `v` in from anywhere;
`q:pop()` takes the front value and waits for one (a worker parks and uses no
cpu; on the engine thread only the calling task suspends, so no frame is held);
`q:tryPop()` never waits and answers nil when empty; `q:length()` counts. A full
queue raises naming the queue and its capacity: it never drops a value.
- Created on first use; it lasts until the world changes or the scripting state
resets (entering play keeps it). After that a held table or queue raises
naming the reason, and tasks parked on `pop` are rejected with it.
- Bounds: a table holds at most 1,048,576 entries and 64 MiB (32 MiB in the
browser), nested at most 64 deep; the process holds at most 4,096 names and
256 MiB (128 MiB in the browser). A write past a bound raises and changes
nothing.
- Reach: the engine's VM and worker VMs, not the trusted VM.
## Notes
- JobHandles are cached by id with weak values — looking the same id up
again returns the same handle table.
- `JobHandle` is sealed: `rawset` on the handle and `__newindex` both
raise. The id is the only field, exposed via direct access.
- `cancel` and `destroy` are aliases for symmetry with other resource
handles (`entity:destroy()`, `buffer:destroy()`); both drop one
refcount.
- `origin` is auto-filled by `register` with the calling script's VFS
path unless the descriptor already supplies one — surfaced under
`/zero/runtime/jobs/<phase>/<key>/origin.txt` for agent traceability.
- `register`'s `descriptor` parameter is typed `table` rather than
`JobDescriptor` because the LSP doesn't yet narrow string literals to
their literal types in record fields, which would reject the
tagged-union `executor` discriminator on every call site. Runtime
validation in `__jobs.register` enforces the actual structure.
# featureSlot
The render feature a module turns on and off. A slot holds the handle of the
feature it started, starts it again whenever it is not live, and destroys it
on demand, so a module that switches an effect with its settings writes the
switch and nothing else.
## Exports
- `FeatureSlot.new(ref, opts?) -> Slot` — a slot for one feature. `ref` is an
`AssetRef<renderFeature>`, a renderFeature identity, or a function answering
one; a function is called each time the slot creates or looks the feature up,
so an `asset.resolve` inside it resolves from the module that wrote it.
`opts.adopt = true` makes `ensure` hold a feature another caller already
runs on `ref` before creating one.
- `FeatureSlot.shared(ref) -> SharedSlot` — a slot for a feature several
callers share, holding only its guid. `shared.ensure()` answers at once while
that guid names a live feature, and otherwise takes the guid of a feature
already running `ref` or creates one; the feature's lifetime is the one its
own holders give it.
A `Slot` is:
- `slot.handle` — the `RenderFeatureHandle` it holds, or nil.
- `slot.live() -> boolean` — whether the handle names a live feature.
- `slot.ensure(prepare?, options?) -> boolean` — start the feature when it is
not live. `prepare` runs first; `options`, when given, answers the options
table `renderer.feature.create` takes. True when it started or adopted one.
- `slot.drop() -> boolean` — destroy the held feature and clear the handle.
True when it held one.
## Usage
```luau
local FeatureSlot = require("@builtin::modules.featureSlot")
local feature = FeatureSlot.new(function()
return asset.resolve("shutterBlur", "renderFeature")
end)
local function apply(strength: number)
if strength > 0 then
feature.ensure(pushParams)
else
feature.drop()
end
end
```
·computeshader · born here
❒asset # surface_weather
Weathers surfaces in place: wetness darkens and flattens, snow accumulates on what faces up.
## Bindings
| name | kind |
|------|------|
| `scene_color` | `texture2d` |
| `scene_depth` | `texture_depth` |
| `scene_normal` | `texture2d` |
| `frame_cam` | `buffer, read vec4<f32>` |
| `lights` | `buffer, read vec4<f32>` |
| `weather_params` | `buffer, read vec4<f32>` |
| `weather_cover` | `buffer, read f32` |
| `weather_out` | `storage2d (rgba16f)` |
`weather_out` holds linear light, which the wet sheen's additive reflections can carry past 1.0 — an 8-bit target would clamp it.
# assetType (asset type)
An asset type says what a kind of asset is: the files an asset of the kind is
made of, the code that gives it behaviour, the interface a person uses to work
with it, and how it is found, pictured and checked. A `<typename>.assetType/`
folder declares a type called `<typename>`, and every `<name>.<typename>/`
folder is an asset of it. `assetType` is itself a type, so a type is an asset
like any other: it is created, versioned, installed and contributed the same way.
## Making a type
`asset.create("assetType", "<typename>")` scaffolds a type. The type registers
the moment its folder is written, anywhere under `/zero/source/`, and from then
on `<name>.<typename>/` folders are its assets. An asset of a type that is not
registered yet is not an asset, so make the type first.
A type folder is a root: `~.x` in any file inside it names the type's own `x`,
wherever the type is installed. Keep the type's whole implementation inside its
folder and reach it that way.
What a type folder must hold is set by this type's own `type.yaml`, the same way
every type's `type.yaml` sets what its assets hold. `asset.validate` on a type
reports anything missing, and the scaffold produces a folder that passes.
## What sets your type's schema (`type.yaml`)
`type.yaml` is the structural contract every asset of the type is checked
against. The keys below are the ones the engine reads; a key not listed here is
ignored.
| Key | What it controls |
|---|---|
| `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. |
| `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. |
| `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. |
| `is_container` | Whether the suffix stays in the identities of what the asset holds. |
| `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. |
| `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. |
| `is_text_default` | Whether the asset's files are text unless stated otherwise. |
| `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. |
| `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. |
| `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. |
| `files: { required, optional }` | The files an asset holds (below). |
| `allow_unlisted` | `false` reports every file the type does not declare. |
| `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. |
| `settings:` | Typed per-asset settings (below). |
| `inspector:` | The interface people use for the type and its assets (below). |
| `preview:` | How an asset is pictured (below). |
| `references:` | Names of other assets the type's files carry (below). |
| `interfaces:` | The interfaces every asset of the type implements (below). |
| `indexing:` | What search reads for each asset (below). |
| `describe:` | How a missing description is generated (below). |
| `contexts:` | The environment the engine loads a file of the asset into, and what it holds (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?, export_optional? } }` 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.
## Computed output files
A type can declare files produced by its compiler. Each rule names an exact
asset-relative output path, an activation marker, and guidance for editing the
inputs:
```yaml
computed_files:
- path: "cache.json"
when_exists: "authoring/state.json"
edit: "Edit the recipe and run the asset compiler."
```
Once the marker exists, ordinary writes, removal and individual-file moves are
refused for that output. The marker and output paths stay within the asset.
Declare their folders in `files.required` or `files.optional` as usual.
Compilers commit their outputs with the input revisions through
`modules.sourceOperations.materialize`. A complete asset copy to a new
destination carries its inputs and computed files together. Copying individual
files into protected outputs and merging a tree over protected outputs are
refused before destination leaves change.
## 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. A type that lists `sceneInstantiable` under `interfaces:` guarantees it, and 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`, `implements`, `as`, `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`. |
| `validateCommitted` | `(folder, read) -> { { code, message, severity?, remedy? } }` | On every push, for each asset the push changes, over the asset as the commit the push publishes holds it. `read(file)` answers a file's committed text, relative to the asset's folder, or nil for a file the commit holds no text of. A problem of `error` severity (the default) refuses the push, whatever the working tree holds. |
### 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. |
| `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()`.
An asset whose picture is what it does to a scene rather than what it looks
like (a lighting setup) names a `subject` on an `instantiate` recipe: a
scene-instantiable asset stood in the studio in its place, while the asset
itself is applied to the world (`applicable`, owner `preview`) for the
shot and dropped after it. `studio_light: false` photographs the subject under
the world's lighting, which the applied asset states, instead of the studio's;
such a picture renders only on an explicit request (`preview.writePreview`,
`assets.generatePreviews`, staging), never from the preview queue or a live
preview.
```yaml
preview:
kind: instantiate
subject: "@builtin::preview.subjects.lookdev"
studio_light: false
```
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, or a list of categories: a name
there is recorded as the one asset of those categories it answers to, a name
two of them answer to is recorded as neither, and a name written as a path
ending in one of their suffixes is the asset at that path.
A key whose names are assets of any type implementing an interface is stated
under `interfaceKeys`, and is declared typed to the types that implement the
interface, again whenever a type or an interface changes:
```yaml
references:
interfaceKeys:
- { key: "members", implements: applicable, field: "source" }
```
`asset.declareReferenceKey`,
`asset.declareReferenceArg` and `asset.declareReferenceField` declare the same
from a script.
A JSON or YAML data file of your type is read whole for the references it holds:
every `{ __ref }` envelope, `@` identity and `components` entry in it. When a file
also keeps values that are data rather than links (an edit history holding the
asset a field used to name, say), `documents` names the fields that carry its
links, and the rest of the file is read as data:
```yaml
references:
documents:
- path: authoring/entities/ # every file under this folder of the asset
fields:
- [records, "*", references] # keys from the root; "*" is every entry of a list or mapping
- references
- path: authoring/settings.json # this one file
fields: [references]
```
`path` is inside the asset's folder; the longest `path` covering a file decides
it. Each value a field reaches is read whole. A file that holds none of the
fields is read whole, as is every file no `path` covers. An entry with no valid
`path` or `fields` is refused with a warning naming it.
## What your type guarantees (`interfaces:`)
An interface is an asset (`<name>.interface/`, see the `interface` type) that
states a guarantee: members with signatures, and properties. A type lists the
interfaces its assets implement in its `type.yaml`:
```yaml
interfaces: [sceneInstantiable]
```
Every asset of the type implements every interface the type lists; an asset of
a type that lists nothing never does. The key is a reference to `interface`
assets, so each name resolves like any asset name and is recorded by guid in the
type's reference table, which is where the engine reads the type's marks from.
The `indexing:` role named `interface` is a different thing: it names the file
that states the signatures a caller of an asset uses.
The type meets each member in its `behavior.luau`, implicitly with its own
`M.ref.<member>` of the member's name and signature, or explicitly when its own
method of that name means something else:
```lua
M.ref = { apply = function(self, into) ... end } -- the type's own meaning
M.interfaces = {
applicable = { apply = function(self, owner, values, opts) ... end },
}
```
`M.interfaces` is keyed by the interface's name as the type lists it. A property
the interface states is met by a value or a getter `(self) -> value` in the same
two places, else by the interface's default. A type whose own `<member>` is
shared by two interfaces with different signatures meets at least one of them
explicitly.
| Question | Call |
|---|---|
| Does this asset implement X? | `ref:implements("X")` (a name, identity or guid, or a list meaning any of) |
| Call a member through the interface | `ref:as("X"):member(...)`; `ref:as("X").property` reads a property |
`ref:as("X")` raises, naming the asset and `X`, when the type does not implement
it. A direct `ref:member(...)` reaches the type's own method of that name; when
the type meets the member implicitly, that method is the member and the call goes
through the interface's gate, which checks its inputs and its result. A generic
caller (one that knows only the interface) calls through `:as`.
A declaration that breaks a check is refused: it carries no marks, `asset.validate`
reports each problem as an error that refuses a push, and the engine log states
each once. The codes are `interfaces.shape`, `unknown`, `ambiguous`, `duplicate`,
`missing`, `arity`, `typeKey`, `explicitUnclaimed`, `explicitUnknown`,
`propertyMissing`, `propertyType`, `conflict` and `unloadable`; each message names
the type, the file, the fault and what to write instead. A type that defines
`instantiate` and lists no `interfaces:` (one written before the key existed, or
defined by its `behavior.luau` alone) implements `sceneInstantiable` with the
warning `interfaces.implied`, which names the line to add. `asset.inspect` of an asset lists the interfaces its type
implements, and of a type definition lists them under `detail.interfaces` with
`detail.interfaceProblems` when the declaration was refused. The type's
Inspector shows the same under **Interfaces**: one row per interface (its name,
the first line of its description, and whether the type declares it or it is
implied), then every problem the declaration raised. An interface's own
Inspector shows its guarantee, its contract module and conformance suite, every
member with its signature, inputs and output, and the types that implement it.
The asset browser's **Implements** filter narrows the list to the assets whose
type implements the interface chosen, each interface's description as its
tooltip.
## The environment a file runs in (`contexts:`)
A type whose assets hold a script the engine loads itself states the environment that script runs in, so the engine binds it and the language server checks the script against the same names:
```yaml
contexts:
- name: sceneBuild
file: "build.luau"
surface: "scene's `build.luau`"
globals:
build: "the build surface is bound in a scene's `build.luau`'s own environment, where `build.asset` authors ..."
hooks: [content, editorOnly]
modules: true
```
- `name` is the context's name.
- `file` is the file of the asset folder that runs in the context.
- `surface` names that file in a diagnostic, without an article.
- `globals` are the names the type's loader binds into each run of the file. Each carries the note an unknown-global message gives when the name is used in a file that lacks it.
- `hooks` are the functions the engine calls by name from the file, which the language server does not report as unused.
- `modules: true` says the loader binds the exports of the modules that join the context.
A module joins with `--!context <name>` in its leading comment block. The type's loader builds the environment with `ScriptContext.bind(env, path, values)` (the `script_context` module), which refuses a value the context does not declare. `asset.context(path)` reads the context a file runs in.
## 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.
# entityRef members
One table describing every member of the entityRef — the value `entity(id)`
returns.
```luau
--!members entityRef entity/proxy
local M: { [string]: Member } = {
id = { kind = "property", type = "string", doc = "This entity's id string." },
despawn = { kind = "method", type = "(self) -> ()", doc = "Remove this entity from the scene." },
component = { kind = "namespace", type = "{ [string]: any }", doc = "Script components attached to this entity." },
}
```
## Why one table
Three things need to agree about what an entityRef has, and they used to be
written separately:
| Consumer | What it takes from here |
|----------|------------------------|
| `ref.module` | The accepted-member set — a member not named here is refused, and the refusal lists these names. |
| The LSP | The `entityRef` type, generated from every entry's `type`. |
| `man` / `lsp.describe` | Each member's description and rendered signature. |
The `--!members entityRef` directive publishes the last two. Because all three
read this table, a member cannot be documented but unimplemented, or accepted
but undescribed.
## Declaring a member
`kind` says what the member IS, which is what a reader needs and what decides
how it renders:
- `property` — read as a value. Renders `entityRef.id -> string`.
- `method` — called. `type` is the whole signature, `self` first. Renders
`entityRef.rename(self, newName: string) -> ()`.
- `namespace` — carries its own members (`component`, `attribute`).
`type` is a Luau type expression. A type that does not parse degrades to `any`,
which answers every member access and quietly reverses the checking this exists
for — so prefer a shape that is true over one that is precise. Several
transform members are `{ [string]: any }` because the value really is a live
proxy answering `.x`, `[1]`, and `set`/`get`/`add`.
`doc` is one sentence, and `deprecated` names the path that supersedes it.
`example` is the line a reader copies, published on the member's page under
`Examples:`. A signature says what the call answers with; an example says what
to write with the answer, which is what a member answering a shape (an array
of identity strings, an array of records) needs beside its type.
## Where the members publish
The directive's second token is the doc path the surface is reached at, and
every member publishes there as well as under the subject's own name:
| Directive | A member lands at |
|-----------|-------------------|
| `--!members entityRef entity/proxy` | `entityRef/<member>` and `entity/proxy/<member>` |
| `--!members entityComponents entity/proxy/component` | `entityComponents/<member>` and `entity/proxy/component/<member>` |
| `--!members entityHierarchy globals/entity/hierarchy` | `entityHierarchy/<member>` and `globals/entity/hierarchy/<member>` |
The subject is a TYPE name, which is the spelling the checker and
`lsp.methods` use. The root is the spelling a reader who knows the CALL
writes. `entity(id).component.list()` reads at `entity/proxy/component/list`,
which is the page `man component.list` answers with and the entry
`/zero/docs/api/entity/` lists. A subject that declares no root publishes
under its own name alone.
## Adding one
Declare it here and implement it in `ref.module`. The member is then accepted
at runtime, typed by the checker, and documented — from this one edit.
# ref
Entity proxy metatable layer: a thin Luau metatable that calls into
the `__native_transform.*` / `__native_entity.*` flat FFI bindings and
serves the user-facing entity API:
`entity(id).localPosition = { x, y, z }`, `entity(id).despawn()`,
`entity(id).name`, etc.
After warm-up, steady-state allocation is **zero**: same `id` returns
the same proxy (weak-valued cache), sub-proxies are lazily allocated
once and cached on the proxy, and each method binding is a closure
created on first access and cached as `__m_<name>`.
## Exports
- `M.build(id: string) -> any` — entity proxy factory. Returns a cached proxy when one exists; otherwise allocates and caches a fresh one. Also bound as `_G.__build_entity_proxy`; its cache and metatable are bound as `_G.__entity_proxy_parts`, which the engine builds the proxies it hands scripts from, so both answer the same table for an id.
- `M.EntityProxyMT`, `M.PositionProxyMT`, `M.RotationProxyMT`, `M.LocalPositionProxyMT`, `M.LocalRotationProxyMT`, `M.LocalScaleProxyMT`, `M.LossyScaleProxyMT`, `M.TransformProxyMT`, `M.AttributeProxyMT` — exported metatables; consumers that want to extend the proxies can read them, but the proxies are sealed externally (every `__newindex` errors).
## Usage
```luau
local EntityProxy = require("@builtin::modules.api.engine.entity.ref")
local proxy = EntityProxy.build("some-entity-id")
proxy.localPosition = { 0, 1, 2 }
proxy.localRotation.eulerAngles = { 0, 90, 0 }
print(proxy.name)
proxy.despawn()
```
## Notes
- **World vs local space** (post Bevy hierarchy migration):
- `.position` / `.rotation` are world-space — engine back-computes
`Transform.{translation, rotation}` on set, decomposes the
world matrix on get.
- `.localPosition` / `.localRotation` / `.localScale` are
parent-relative direct reads/writes on `Transform.*`.
- `.lossyScale` is read-only world-space scale (approximate under
non-uniform parent scale + rotation; mirrors Unity).
- `.worldMatrix()` answers the whole composed object-to-world matrix as
16 column-major numbers, translation in elements 13, 14, 15 — the
placement the renderer draws the entity's geometry at, carrying the skew
a decomposition into position / rotation / scale folds away. Also
readable as `.transform.worldMatrix()`.
- Bare `.scale` was removed — accessing it raises an error pointing
callers at `localScale` / `lossyScale`.
- **Sealed proxies**: every proxy errors on `__newindex` (sealing). Mutations
go through `position.set` / `attribute.set` / etc., not direct field writes.
- **Caching**: the entity-proxy cache is keyed by `id` with weak values
(`__mode = "v"`), so dropped proxies are GC'd. Within one proxy, the
`M_PREFIX`-keyed cache survives until the proxy itself is collected.
- The `.component` sub-proxy is built by `__native_entity.component_subproxy`
— Rust-side helper that constructs the ~15-closure component-proxy
table once per entity. Subsequent `.component` accesses hit the
cached entry.
# renderFeature
A **render feature** inserts custom GPU passes into the frame pipeline. The engine
provides one generic capability — a per-frame render-pass queue and a set of
pipeline-phase insertion points — and a feature is the authored Luau that decides
what passes to enqueue, and where, every frame.
## Authoring contract
A `.renderFeature` folder holds an `init.luau` that returns a feature module:
```luau
return {
setup = function(ctx) -- optional; runs once when the feature goes live
-- A "fragment" pass's `shader` names a POST EFFECT, not a `.shader`
-- guid directly — postprocess.add compiles the shader asset under
-- that name once, here. Enqueueing a name never passed to
-- postprocess.add runs the pass as a no-op every frame (the log
-- reads "effect '<name>' not compiled — pass skipped").
postprocess.add("my_effect", asset.resolve("my.shader.guid", "shader"), { enabled = false })
end,
render = function(ctx) -- required; runs every frame
-- enqueue one or more passes. The spec shape depends on `kind` (see
-- "Pass kinds" below): this is a "fragment" pass (full-screen shader over
-- input textures); a mesh effect (outline, x-ray) is a "geometry" pass
-- with `material` + `select` (see "Geometry passes").
ctx.enqueue {
phase = "afterTransparent",
shader = "my_effect",
inputs = { src = "@scene.color" },
output = myRenderTargetGuid,
}
end,
teardown = function(ctx) end, -- optional; runs once when the feature is destroyed
}
```
Optional `materials/` and `shaders/` subfolders hold shader source the feature
constructs GPU programs from. A feature constructs its GPU programs (it does not
reference `.material` surface assets).
## `ctx`
Built fresh each frame and passed to `setup` / `render` / `teardown`:
| Field | Meaning |
|-------|---------|
| `ctx.enqueue(spec)` | Queue one render pass for the current frame. |
| `ctx.viewport` | `{ w, h }`: the size the **main viewport's** scene rasterized at, in pixels (`renderer.rasterSize()`: the viewport taken down by the render scale). |
| `ctx.time` | The instant this frame's per-frame fields are drawn at, in seconds: the running clock, or the instant a `renderer.temporal.hold` pins. Absent in a feature that states its inputs. |
| `ctx.frame` | The frame index beside that instant: it counts every frame of the loop, drawn or not, and reads 0 while a hold stands. Absent in a feature that states its inputs. |
| `ctx.renderPath` | `"forward"` / `"deferred"` / … — branch passes on the active path. |
| `ctx.settings` | The feature's knobs as they stand this frame — see "Settings". |
| `ctx.authored` | The same knobs as authored: a setting declared with `Field.scaled` reads its authored value here and the value of the quality level in force in `ctx.settings`; every other setting reads the same in both. |
### Per-frame values and a still picture
A buffer a feature's passes read is part of the picture: written with new words
between two frames, it is a change of the picture, and a renderer draws for as
long as such changes arrive. A field that animates with time (film grain, a
moving noise) seeds from `ctx.time` and draws while the clock runs. The jitter
an accumulation averages over (a ray offset, a rotated sample pattern) turns
with the renders of the view instead, so the feature's parameters hold the same
words on every frame of a still scene and the renderer stops drawing once the
accumulation settles: a history target's `state` buffer
(`renderer.texture.create { history = true }`) carries in `y` how many renders
in a row the view being drawn has carried, written as each render of the view
begins, and a pass that binds it reads its jitter frame there. While
`renderer.temporal.held()`, the passes take the frame from the held instant
`@frame.clock` carries instead (the feature states the hold among its inputs
and writes a flag into its parameters), so two renders under one hold agree.
`@builtin::systems.reflections.ssr` works this way.
## Stating what a feature depends on
A feature whose `render` gives the same passes while nothing it reads moved says
what it reads, and the engine stops running `render` on the frames where none of
it did. The module states the inputs with `dependsOn`, a list of names, with
`inputs`, a function returning a value, or with both:
```luau
return {
stage = "display",
dependsOn = { "settings", "viewport" },
render = function(ctx)
ctx.enqueue(specFor(ctx.settings, ctx.viewport)) -- a spec frozen all the way down
end,
}
```
| Input | Moves when |
|-------|-----------|
| `settings` | the feature's settings in force change: a `configure`, or a quality level that scales one. Every feature that states inputs holds this one, named or not. |
| `viewport` | the size the main viewport's scene rasterizes at changes (`ctx.viewport`). |
| `renderPath` | the active render path changes (`ctx.renderPath`). |
| `camera` | the camera drawing the viewport moves, turns or changes its projection (`ctx.camera`). |
| `camera.cell:<size>` | the camera's position crosses into another cell of `<size>` world units on a side, such as `camera.cell:2` (`ctx.camera`). |
| `assets` | an asset is created, changed or removed anywhere in the world. |
| `lights` | a light the renderer shades with changes: a field of a light component, a light entity's world transform (its own or an ancestor's), a light shown, withheld, spawned or removed, the sun or the ambient term (`lighting.revision()`). |
`inputs` is called with no arguments once a frame, and its value is compared with
the one of the frame before by `==`: a number or string that counts a revision, or
a table the owner replaces when its content changes (`debugViz` answers the batch
the debug module holds).
The first render, and a render after the feature restarts or the device rebuilds,
runs whatever the inputs say. Each later frame the engine reads the inputs: when
none moved, `render` does not run, and the passes the last render handed over
stand in the frame as they stood. A render's passes stand in the frame only while
every spec it enqueued is a table frozen all the way down (the engine reads such
a spec once and keeps it); a render that hands over any other spec runs on every
frame, whatever it states. `ctx.time` and `ctx.frame` are not there to read in a
feature that states its inputs, and `ctx.viewport`, `ctx.renderPath` and
`ctx.camera` are there only when an input names them: what changes on every frame
comes from the frame's own buffer, `@frame.clock`, which every pass binds. A
feature that states nothing runs `render` on every frame.
`renderer.feature.list()` and the profiler counts `renderFeature.renders` and
`renderFeature.replays` report how many features rendered and how many stood on
their kept passes in a frame.
## Settings
A feature declares the knobs it takes as `settings`, each a Field descriptor
with a default, the way a component declares its public fields. A feature that
declares no `settings` has nothing to tune: its schema is empty, and applying it
turns it on or off.
```luau
local Fields = require("@builtin::modules.field")
local Field, NoSync = Fields.Field, Fields.NoSync
return {
settings = {
intensity = Field.number(1.0, NoSync, "How much of the effect reaches the image."),
quality = Field.enum({ "low", "high" }, "high", NoSync, "How many samples the pass spends."),
},
render = function(ctx)
local s = ctx.settings -- { intensity = 1.0, quality = "high" }, or what a caller set
...
end,
}
```
The engine holds one settings table per live feature — every declared default,
overridden by what it was handed — and passes it as `ctx.settings` on every
`setup` / `render` / `teardown`. A feature reads its knobs there and nowhere
else, so any caller tunes any feature by name:
```luau
local h = renderer.feature.create(ref, { settings = { intensity = 0.5 } })
renderer.feature.configure(h, { quality = "low" }) -- lays over the rest
renderer.feature.settings(h) -- { intensity = 0.5, quality = "low" }
renderer.feature.find(ref) -- the live handle, or nil
renderer.feature.schema(ref) -- the declared knobs, unrun
```
A knob the feature does not declare, or a value of the wrong shape, is refused
by name. A scene authors its features on one `RenderFeatures` entity — a list
of features, each with its settings — which adopts a feature already live
rather than stacking a second, and takes every one down on disable and destroy.
Each entry is an application of its asset (`applicable`): the asset holds its
one live feature, every application joins it, the settings in force are those
of the application that last stated something new, and the last to leave stops
it. A feature already running when the first application comes is adopted, and
runs on with its own settings once the last leaves. A feature stopped from
outside the asset (`renderer.feature.destroy`, a
`render` that raised) stays stopped until an application is stated again.
`render` runs **once per frame**; the passes it enqueues run **once per render
target** drawn that frame — the live viewport, every offscreen capture, every
RTT camera — each at its own resolution. So `ctx.viewport` is the main
viewport's size, not the size of the target a pass ends up drawing into. Size a
full-screen scratch RT with `screen = true` and let the engine track the drawn
target (see "Screen-sized targets") rather than deriving it from `ctx.viewport`.
## Screen-sized targets
`renderer.texture.create { screen = true }` marks a feature RT as full-screen:
before each render target's feature passes, the engine resizes it to that
target's resolution. Create it once — the engine owns its size from then on:
```luau
myRt = renderer.texture.create {
width = ctx.viewport.w, height = ctx.viewport.h, -- initial size only
screen = true, format = "rgba16f", name = "my_effect",
}
```
A target that holds a picture of the scene is `rgba16f`, which is what the scene
target itself carries: linear light with headroom above the display's white and
no 256-step floor under a dark gradient. Omitting `format` on a screen-sized
target asks for the same thing. `format = "rgba8"` is for a mask, a weight or an
occlusion term, where 0..1 is the whole range — hand one of those back over
`@scene.color` and the frame loses every highlight and bands every gradient, and
the engine says so in the log.
`screenScale` (default `1.0`) takes a fraction of the drawn target's resolution,
for a scratch that runs below composite resolution (a half-res blur passes `0.5`).
A screen-sized RT is what makes a full-screen effect composite correctly at any
resolution. Deriving the size from `ctx.viewport` instead pins the RT to the main
viewport, and every differently-sized render target then composites a mismatched
scratch — the scene scaled into a corner with the rest black.
`screenSpace` names WHICH image a screen-sized RT follows:
| value | what it tracks |
|---|---|
| `"scene"` (default) | the scene render target, at whatever resolution the render scale asked for. Resized before EVERY render target's feature phases — the main frame and each offscreen one — and cleared to transparent before an offscreen render, so one sink never reads what another left behind |
| `"composite"` | the image the post-scene phases draw into. The presented frame's allocation is resized and drawn by the presented frame alone; an offscreen render that runs a post-scene phase (a capture, a render-to-texture camera whose picture goes through the `display` stage) draws in an allocation of its own at its own size, cleared to transparent before it draws |
The two carry the same size until the render scale drops below 1. From there,
while the renderer presents the viewport itself, the scene reaches the display's
resolution through an upscale that runs before `afterScenePost` — so a
composite-space RT is the display's size while a scene-space one is the smaller
rasterized frame. Under a UI viewport panel the panel draws the scene target at
its own rect, nothing upscales beforehand, and both spaces carry the scene's
size.
A scene-space target is scratch: whatever a pass does not rewrite this render is
transparent black. The presented frame's allocation of a composite-space target
survives every offscreen render untouched.
## History targets
An accumulation across frames (temporal antialiasing, a temporal denoiser, any
pass that reads what it wrote last time) lives in a history target:
```luau
history = renderer.texture.create {
width = ctx.viewport.w, height = ctx.viewport.h, -- initial size only
history = true, format = "rgba16f", name = "my_accum",
}
-- in render(ctx):
ctx.enqueue {
kind = "compute", program = myResolve,
inputs = { scene_color = "@scene.color", accum_previous = history.previous.guid },
buffers = { accum_state = history.state },
storage = { accum_out = history.guid },
phase = "afterLighting",
}
```
The passes a feature enqueues run once for every view the frame draws (the
viewport, each render-to-texture camera, each capture), so an accumulation has
to be one per view. A history target keeps one pair of images per view, sized to
that view: for the length of a view's render `history.guid` names the image the
render writes and `history.previous.guid` the image the same view's previous
render wrote. Another view never resizes, clears or overwrites them, and a
view's images are freed when it stops drawing. A capture drawing the picture
the viewport's latest render drew (its camera and lens, its size, the same of
the scene its layers admit, and its shading), while the viewport samples
where `renderer.setProjectionJitter`'s sequence places it, is the one render
that draws with another view's images: for the length of its render
`history.previous.guid` names the image the viewport's latest render wrote and
`history.guid` the viewport's other image, which the viewport's next render
writes over, and `history.state` reads as it would for that next render. A
viewport whose projection `renderer.setProjectionOffset` or a reconstructing
upscaler moves samples where no capture follows, and a capture then draws with
images of its own. It follows `screenSpace` and
`screenScale` like any screen-sized target; a composite-space one is kept for
every view that runs the post-scene phases: the viewport, a capture, and a
render-to-texture camera whose picture goes through the `display` stage.
Before each render of a view the engine writes `history.state`, one
`vec4<f32>` a pass binds through `buffers`:
| field | holds |
|---|---|
| `x` | 1 when `previous` holds this view's previous image; 0 on the view's first render, its first after a camera cut or a change of size, or after a render of the view that ran without the target, and `previous` then reads transparent black |
| `y` | how many renders in a row have carried the history |
| `zw` | this render's sub-pixel projection offset, in pixels (`renderer.setProjectionJitter`) |
`renderer.setProjectionJitter` is the matching per-view sample sequence: every
view walks it by its own count of renders, so the sequence a temporal pass
expects is the one each view's renders sampled.
## Post stages
A post effect belongs to one of the frame's named **post stages**, in frame
order, each stating what the picture holds there: the space an effect there
reads and writes (`light`, the scene's own light ahead of the display
transform's exposure and tone curve, `display`, code values, or `encoded`, the
presented surface's own values) and the size
the picture is held at (`raster`, the size the scene rasterized; `output`, the
size the frame is composed and shown at):
| Stage | Space | Resolution | Runs |
|-------|-------|------------|------|
| `lighting` | light | raster | screen-space lighting terms and what draws into the lit scene: occlusion, reflections, indirect light, contact shadows, decals, splats, outlines, diagnostic views. It spans every phase up to `afterLighting`, so a pass of a feature declaring it may name one of those phases |
| `medium` | light | raster | participating media: aerial perspective, fog, volumetric light |
| `preTemporal` | light | raster | effects reading the jittered raster before reconstruction: depth of field |
| `temporal` | light | raster | the one temporal reconstruction of the raster (TAA); the stage holds one feature at a time |
| `postTemporal` | light | raster | effects reading the reconstructed picture: motion blur |
| `meter` | light | reduced | measuring the picture: the exposure histogram, a fraction of the raster |
| `optics` | light | raster, then output | lens light: bloom, flare, streaks. Its render features run on the raster; the frame then carries the picture to the output size, and the post-process chain's `scene` layer runs there |
| `display` | display | output | the display transform, then on code values the temporal upscale, debanding, edge antialiasing and sharpening; the chain's `display` layer, the film grain last |
| `ui` | display | output | the UI, drawn over the finished picture, then what grades the picture with the UI on it: `afterUI` passes, the chain's `all` layer, then `afterPost` passes |
| `output` | encoded | output | the renderer's output stage alone: the one write of the presented surface, in the surface's encoding, rounded to its bit depth with a blue-noise dither (`renderer.output`). It takes no render feature and no chain effect |
A feature declares the stage it belongs to, and each pass it enqueues with no
`phase` runs in that stage, at the stage's phase and its band of orders plus the
pass's own local `order` (a whole number from 0 to 99):
```luau
return {
stage = "postTemporal",
render = function(ctx)
ctx.enqueue { kind = "fragment", shader = "my_effect", inputs = { src = "@scene.color" }, order = 0 }
end,
}
```
Passes sharing an order run in the order they were enqueued, so a chain of
passes over shared targets can run at one order, in sequence.
The `meter` and `optics` stages are the camera's film. A pass placed in one of
them, stating neither `postProcessing` nor `presented`, is part of the camera's
post-process chain (`postProcessing = true`): a camera running no
post-processing, such as a capture asking for the scene ungraded or an
environment cube face, skips it. A pass stating `postProcessing = false` runs on
every camera.
`render` runs once a frame, but each view the frame draws (the viewport, a
capture, a render-to-texture camera, an environment cube face) looks at the
world from its own camera, so an order that depends on where the camera stands
is stated per pass rather than chosen in `render`. A pass that composites
something standing in the world states the world point it stands at as
`sortPoint`: `{ x = .., y = .., z = .. }`, `{ x, y, z }` or a `vector`, so an
entity's `position` is one. Among the passes of one phase sharing one `order`
that run together (its fragment, compute and raster passes; its geometry
passes, which run ahead of those), the ones stating a point trade the places
they were enqueued in so that every view runs the one farthest from its own
camera first and the nearest last: composites laid over the frame by each of
them leave the nearest in front from wherever the view looks. Depth is
taken along the view (the distance in front of a perspective camera, the depth
into an orthographic one's box). Passes at the same depth keep the order they
were enqueued in, so the passes of one effect stating one point (a march into a
target and the composite reading it) stay together, and a pass stating no
point keeps its place:
```luau
for _, item in ipairs(items) do
ctx.enqueue { kind = "compute", program = march, storage = { out = scratch.guid }, order = 2, sortPoint = item.center }
ctx.enqueue { kind = "fragment", shader = composite, inputs = { src = scratch.guid }, blend = true, order = 2, sortPoint = item.center }
end
```
A draw or splat pass takes no `sortPoint`, and a value that is not three finite
numbers is refused by `ctx.enqueue`.
A pass may name a
`stage` of its own in place of the feature's, placed the same way: a feature
whose work spans two stages declares one and names the other on those passes,
the way temporal antialiasing declares `temporal` for its resolve and names
`display` on its sharpening passes. A pass naming both a `stage` and a `phase` is refused. A stage the
frame does not have is refused by `renderer.feature.create`, naming the stages
there are, and a second feature declaring the `temporal` stage while one stands
in it is refused naming both; the `temporal` stage takes the passes of the
feature declaring it alone. A pass that names a `phase` runs at that phase and
`order`, as below. `renderer.post.stages()` reports every stage and what stands
in it: a feature by the stage its passes' position falls in, marked `declared`
where that is the stage the feature declares or a pass names. Every built-in
render feature declares its stage; `postStages`'s README lists where each
built-in effect runs.
## Pass phases
`enqueue` runs a pass at a named pipeline boundary — a real seam between the
scene's discrete passes — ordered within a phase by `order`. Each phase is the
point where the scene colour holds a specific, nameable state:
| Phase | Scene colour there |
|-------|--------------------|
| `afterDepthPrepass` | the visibility raster written: `@scene.depth` holds this frame's complete opaque depth, and `@scene.motion` its opaque motion, before anything shades. Scene colour is not yet drawn; `@scene.colorHistory` holds the previous frame's lit colour, and the deferred g-buffer the previous frame's surfaces (`readsPrevious`) |
| `afterShadows` | shadow maps populated; scene colour not yet drawn. `@scene.depth` and `@scene.motion` hold what the visibility raster laid at `afterDepthPrepass` |
| `afterSky` | sky only. `@scene.depth` holds the frame's opaque depth, so a pass here tells the pixels the geometry pass draws over (depth above 0) from the ones that stay sky (depth 0) |
| `afterOpaque` | opaque drawn, before transparents. `@scene.depth` (and the deferred G-buffer) are populated. Forward: lit opaque. Deferred: lit opaque too, which the geometry pass shades straight into the scene colour, on a render no pass reads or writes `@scene.shaded` in; on one that does, the opaque surfaces are in the G-buffer's shaded channel, so the colour is still sky only until the composite (use `afterOpaqueLit`). Radiance stamped into `@scene.emissive` reaches the colour at the composite |
| `afterOpaqueLit` | the lit opaque scene, still before transparents, on **both** paths — the forward opaque draw, or the deferred geometry pass and composite. The background a refractive or transmissive surface samples: the one phase whose colour holds what is behind such a surface without holding the surface itself. A pass that lights or changes the opaque scene runs here, ahead of the air that hazes it (the aerial perspective at 98, the height fog at 100) and of the transparent phase: the built-in lighting terms (probe field, sky light, image-based environment, area lights, local contact shadows, surface weather, capsule occlusion, subsurface scattering, cached indirect, resampled direct, ray-traced shadows), the splat clouds and the outline shells stand at orders 1-96, so the haze covers their light and a see-through draw in front of a surface is not lit by that surface's light |
| `afterTransparent` | transparents drawn, before the OIT composite |
| `afterLighting` | deferred-lighting + OIT composite done — fully lit, final geometry on **both** paths. Where the air hazes the scene (aerial perspective, height fog), the opaque scene here is already hazed, so light a pass adds here lands over the fog and over every see-through draw |
| `afterScenePost` | the chain's `scene` layer and the display transform done: display code values, before the chain's `display` layer and the UI |
| `afterUI` | scene + UI composited |
| `afterPost` | the chain's `all` layer done — the finished picture in display code values, before the output stage writes it to the surface. A pass here reads that picture as `@scene.color` and draws over a copy of it |
The last three are the post-scene phases, and they work on the COMPOSITED image:
`@scene.color` there is the target the UI lands on, not the scene render target.
`@scene.depth` and `@scene.motion` still bind — they are the scene's own buffers
for the frame just drawn, which is what lets a pass at these phases reproject the
composite it is handed — and on the deferred path so do the G-buffer channels
(`@scene.normal`, `@scene.material`, `@scene.shaded`, `@scene.emissive`), the
surfaces of that same frame, so a look drawn over the finished picture reads
what each pixel's surface is without copying the G-buffer at an earlier phase.
All of them keep the SCENE's resolution. Whenever the
render scale is below 1 on the presented frame, that is smaller than
`@scene.color`, so a pass here maps between the two by uv rather than by texel
index, and takes its own output size from the target it writes.
**A texture is a texture.** A pass's sampled input names any texture the engine
holds by the handle that made it: a render target or a texture
`renderer.texture.create` returned (its guid), or a storage texture a compute
shader created (`ref:createStorageTexture2D`, its `key`). Which one it is decides
nothing about whether the pass accepts it. A pass sees the contents a texture
holds when the pass runs: a compute shader that wrote the texture in an earlier
pass of the same frame, or in a `dispatchEx` recorded at the start of the frame,
is read by a pass at any later point of the frame, and a pass that reads a
target an earlier phase of the frame draws sees that draw once the phase has run.
The `@scene.*` inputs (`@scene.color`, `@scene.depth`, …) bind the live frame
buffers; the deferred g-buffer channels (`@scene.normal`, `@scene.shaded`, …)
resolve only on the deferred path. Before the pass that shades has drawn — at
`afterDepthPrepass` — a g-buffer channel holds the previous frame's surfaces,
and a pass reading it there names the slot in `readsPrevious`
(`readsPrevious = { "scene_normal" }`); one that does not is held back rather
than handed a stale normal. `@scene.colorHistory` is the lit colour the target's
previous render ended with, kept by the engine per render target and never
cleared by a frame: what a pass tracing at `afterDepthPrepass`, against this
frame's depth, takes its light from — reprojected through the previous
view-projection `@frame.camera` carries. A capture drawn once, or a camera drawn
again after a pause, is drawn lit first when a pass reads the history, so its
first frame holds one.
Every `@scene.*` channel, what it holds, its format, the phase it is first
valid from, and the other names it answers to:
| Name | Holds | Format | Valid from | Also named |
|---|---|---|---|---|
| `@scene.color` | the scene's lit colour; the display composite at a post-scene phase | the scene target's format at a scene phase, the display composite's at a post one | every phase | — |
| `@scene.depth` | opaque depth, reversed (1.0 near, 0.0 far/empty sky) | `Depth32Float` — binds through a `texture_depth` compute slot, not `texture2d` | `afterDepthPrepass` on | — |
| `@scene.motion` | screen-space NDC velocity since the previous frame | `Rg16Float` | `afterOpaque` on | — |
| `@scene.normal` | world-space normal + the per-pixel surface-flag field | `Rgb10a2Unorm` | deferred path, `afterOpaque` through `afterPost` (previous frame's before — declare `readsPrevious`) | — |
| `@scene.shaded` | what a surface SENT — its shaded colour, linear and scene-referred | `Rgba16Float` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | `@scene.albedo` |
| `@scene.material` | what a surface IS — base colour (RGB565) + metallic + perceptual roughness | `Rgba8Uint` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | `@scene.mr` |
| `@scene.emissive` | radiance a pass stamped on the surface, added at the composite | `Rgba16Float` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | — |
| `@scene.ao` | scene occlusion a feature wrote, read back by shading: occlusion in r, the bent normal laid flat on the octahedron in g and b, and in a whether a bent normal was written | `Rgba8Unorm` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.sunOcclusion` | the share of the sun's direct light a feature found taken on the way to each pixel's surface (`.rgb`, 0 none to 1 all), read back by the sun's term alone | `Rgba8Unorm` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.reflection` | traced reflection radiance (`.rgb`) + confidence (`.a`) | `Rgba16Float` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.indirect` | the indirect diffuse light the surfaces closing each pixel's hemisphere send it (`.rgb`, in the ambient term's units) + the share of the closed hemisphere it answers for (`.a`), read back by the diffuse term through `zero_scene_indirect_here`; the second layer of the texture `@scene.reflection` is the first of | `Rgba16Float` | every scene phase (cleared at the top of every scene render) | — |
| `@scene.decal` | the base colour stamped over each pixel's opaque surface, premultiplied by its coverage (`.rgb`), with that coverage (`.a`); written at `afterDepthPrepass` (blend `premultiplied`), and every opaque surface takes it into its own base colour before it is lit (`zero_take_scene_decal`, which `zero_pbr_shade` calls), so the stamp is lit, shadowed and written to `@scene.material` with the surface; the third layer of the texture `@scene.reflection` is the first of | `Rgba16Float` | `afterDepthPrepass` through `afterSky` (cleared at the top of every scene render and again once the opaque surfaces have shaded, so a surface drawn after them takes none) | — |
| `@scene.colorHistory` | the lit colour the target's previous render ended with | `Rgba16Float` | every phase | — |
| `@scene.media` | the media trace's coverage by kind: what the participating media and the see-through draws laid in front of each pixel's opaque surface, as the share the cloud layer covers (`.r`), a volumetric medium (`.g`: a volume, smoke, fire, a volume sequence, a fog bank) and a see-through surface (`.b`: every blended draw, such as water, glass, particles and cards, and a fluid surface) cover, premultiplied, with their coverage in `.a`. A blended draw covers the share of the pixel its blend equation changes: its alpha under `alpha` and `premultiplied`, the strength of the light it adds (its brightest channel, saturating at 1) under `additive`, and how far its factor departs from 1 under `multiply`. Each producer blends its trace premultiplied source-over what stands behind it, so the nearer hold the larger share. A view keeps it only while a pass reads it; a pass writing it alone runs only on such a view. `@builtin::shaderModules.media_trace` reads and writes it | `Rgba16Float` | `afterSky` through `afterPost`, the post-scene phases included (cleared at the top of every scene render) | none |
| `@scene.mediaSurface` | the distance from the camera to what covers each pixel (`.r`, world units) and its world normal laid flat on the octahedron (`.gb`; a medium states the direction back toward the camera), premultiplied by the coverage in `.a`; the second layer of the texture `@scene.media` is the first of | `Rgba16Float` | as `@scene.media` | none |
| `@scene.lights` | the punctual-light storage buffer: 1024 light entries of eleven vec4s each (the light, then its projection, which names the shadow record it casts through), the light grid, then the virtual shadow map's region: a shadow record per casting light and their page tables. A loop runs over the first `@frame.camera[4].w` entries, the lights in use; the buffer's length counts the regions after the lights too, so `arrayLength` does not size a light loop | storage buffer | every phase | — |
| `@scene.shadowPool` | the depth pool every shadow-casting light renders its shadow pages into, read beside `@scene.lights` through `@builtin::shaderModules.light_shadows` (`zero_light_shadow`): the shadow a point, spot or area light casts at any world point, the one the surfaces take. A frame with a pass reading it keeps the coarsest page of every map of each casting light whose reach meets the view | `Depth24Plus` — binds through a `texture_depth` compute slot | scene phases only | — |
| `@scene.sunShadow` | the sun's virtual shadow map as the view being drawn reads it: its basis, depth range, clipmap levels and window origins and where its page table starts in `@scene.lights`, read beside `@scene.lights` and `@scene.shadowPool` through `zero::sun_shadow` (`zero_sun_visibility`): how much of the sun reaches any world point, past the occluders that shadow the surfaces. A frame with a pass reading it keeps the sun's pages under the air the view looks through | storage buffer (`ZeroVsmUniform`, a `kind: buffer` slot with `array: false`) | scene phases only | — |
| `@scene.environment` | the reflection-probe cube array | texture cube array | scene phases only | — |
| `@scene.environmentSampler` | the filtering sampler for `@scene.environment` | sampler | scene phases only | — |
| `@scene.reflectionProbes` | the environment buffer: the probe blend data naming which probe reaches a point, then the irradiance light-probe volumes | storage buffer | scene phases only | — |
The rendering and ray-tracing guides (`guides { path = "topics/rendering" }`,
`guides { path = "topics/raytracing" }`) point here rather than repeating this
table.
**What a full-frame pass reads, at each stage, on each path.** A full-frame
pass is a fragment or compute pass of a render feature, or an effect of the
post-process chain (`postprocess.add`). The G-buffer channels above are what the
deferred path knows about each pixel's surface, and they are the four the paths
differ on:
| Channel | Deferred path | Forward path |
|---|---|---|
| `@scene.color`, `@scene.depth`, `@scene.motion` | every stage (depth and motion from `afterDepthPrepass` and `afterOpaque` on, as the table states) | the same |
| `@scene.normal`, `@scene.material`, `@scene.shaded`, `@scene.emissive` | `afterOpaque` through `afterPost`: the `lighting`, `medium`, `preTemporal`, `temporal`, `postTemporal`, `meter`, `optics`, `display` and `ui` stages, and every layer of the chain. Before `afterOpaque` a pass naming one in `inputs` reads the previous frame's surfaces (`readsPrevious`), and the surface helpers read their stated substitute with `zero_scene_surfaces_drawn()` false | none: the forward path draws no G-buffer. A pass naming one as an input is skipped, and the log names the channel and the reason; every pass reading a render target that pass writes is held back in that view too, whatever the target holds from an earlier frame (`renderer.passSchedule().heldBack`), so a chain over the G-buffer composites nothing on the forward path. A shader reading one through the surface helpers reads its stated substitute (zero) and `zero_scene_surfaces_drawn()` reads false, so it draws a picture of its own there |
Two readers reach them. A pass names a channel in `inputs` (or a compute
binding), as above. A fragment pass's shader, or a chain effect's, reads them
by screen uv through the post framework's surface helpers (`zero_scene_normal`,
`zero_scene_material`, `zero_scene_shaded`, `zero_scene_emissive`; the shader
type README's post-process section has the table), which spend none of the
pass's input slots. Either way a render keeps a channel only when
something reads it: a queued pass naming it, a queued fragment pass whose
shader calls its helper, or a running chain effect that does. The channels
are at the scene's resolution, so a pass after an upscale reads them by uv.
A pass before the `temporal` stage reads each channel as the raster drew it,
with this render's sub-pixel offset. With temporal antialiasing running
(`@builtin::systems.antiAliasing.temporalAntiAliasing`), a reader after the
`temporal` stage reads `@scene.depth`, `@scene.normal` and `@scene.material`
restated at each pixel's centre, with no sub-pixel offset, so under a still
camera they hold still the way the resolved picture does: the restatements
run on a frame where a pass after them names the channel or a shader reads it
through its helper, and a chain effect reading the helpers is such a reader.
`@scene.shaded` and `@scene.emissive` keep the raster's sub-pixel offset at
every stage. `ctx.renderPath` names the path a feature's
`render(ctx)` runs on, and `postprocess.status()` lists, for each effect, the
channels it `reads` and, after a frame it drew with their substitute, the
`substituteReason`.
**Two g-buffer channels describe the surface, and they answer different
questions.** `@scene.shaded` is what a surface SENT — the colour the geometry
pass shaded it to, linear and scene-referred, so a surface lit above the
display's peak reads above 1 there. `@scene.material` is what the surface IS:
the base colour it reflects, its metallic and its perceptual roughness, each in
[0, 1] and each independent of how brightly the surface happens to be lit. A
pass that multiplies incoming light by a reflectance — a bounce multiplier, a
Fresnel tint, an ambient floor — reads `@scene.material`; a pass that filters
the picture reads `@scene.shaded`.
`@scene.material` is an `Rgba8Uint` channel packing all three into 32 bits, so
its slot declares `sample: uint` and the module unpacks it:
```yaml
# bindings.yaml
- { name: scene_material, kind: texture2d, sample: uint }
```
```wgsl
#include "@builtin::shaderModules.gbuffer_material"
let m = zero_gbuffer_material(scene_material, coord);
let bounce = incoming * m.base_color;
```
`@scene.albedo` is another name for `@scene.shaded` (the SHADED lit colour) and
`@scene.mr` for `@scene.material` (the material channel). The engine logs the
substitution once per name, naming the canonical one to write.
`@scene.motion` carries screen-space velocity: the NDC displacement each pixel's
surface underwent since the previous frame, so a still surface under a still
camera reads `(0, 0)`. Opaque geometry contributes it on both render paths:
the visibility raster writes it for every surface it records, and an opaque
surface whose depth state the raster cannot express writes its own where it
draws. A moving entity, a moving camera and an animated pose all reach it in
the viewport; transparents, particles and sky carry none. A surface a
material's `vertex()` hook displaces carries the displacement's own velocity. A render target's own camera and a
capture keep no view history, so velocity there is the entity's motion with no
camera term.
`@frame.camera` is a reserved **buffer** input carrying the camera CURRENTLY
being drawn: 18×`vec4<f32>` = the inverse view-projection (columns `[0..4)`,
column-major) + camera world position (`[4].xyz`, with the number of lights
`@scene.lights` holds in `[4].w`) + the previous render's view-projection
(columns `[5..9)`), which projects a point into the picture that render left +
the view-projection itself (columns `[9..13)`), which projects a world point
onto the view being drawn and is the matrix the scene rasterized with + the
sub-pixel offset that matrix carries (`[13].xy`, in NDC; zero without a
temporal upscale) + the view-projection with no sub-pixel offset (columns
`[14..18)`), the matrix the view's next render states as its previous one, so
a view drawn again from where its camera stands reads `[14..18)` word for word
equal to `[5..9)`. A compute pass declares a
`buffer` binding and binds it via `inputs = { name = "@frame.camera" }`, then
reconstructs a pixel's world position from `@scene.depth`:
```wgsl
let inv_vp = mat4x4<f32>(cam[0], cam[1], cam[2], cam[3]);
// ndc.z is the `@scene.depth` sample itself. Scene depth is reversed — 1.0 is
// the near plane, 0.0 the far plane and empty sky — and this matrix inverts
// that same range, so a sample goes in unmodified.
let wh = inv_vp * vec4<f32>(ndc, 1.0);
let world_pos = wh.xyz / wh.w;
```
Like `@scene.*`, the engine resolves it **per render target** — so the same pass
reconstructs against the live viewport's camera on screen and against an
offscreen capture's / RTT camera off screen. (Pack a camera matrix into your own
buffer instead and the offscreen render reconstructs against the wrong camera.)
> Render-feature passes run in the main viewport render **and** in offscreen
> captures / render-to-texture, each against its own camera. The `capture` tool's
> `source = "position"` / `"entity"` therefore run the pass queue too; using
> `@frame.camera` is what keeps those captures matching the live viewport.
### The view's matrices
`@frame.view` is a reserved **buffer** input carrying the view CURRENTLY being
drawn as the separate matrices a view-space algorithm is written against, which
`@frame.camera` states only as their product: 17×`vec4<f32>`, every matrix
column-major and none carrying a sub-pixel offset. Columns `[0..4)` hold
world-to-view; `[4..8)` hold view-to-clip, so `[4..8)` times `[0..4)` is
`@frame.camera`'s view-projection with no sub-pixel offset (`[14..18)`).
`[8..12)` and `[12..16)` hold the same two matrices as the view's previous
render drew with, the pair `@frame.camera`'s `[5..9)` is the product of; a view
with no previous render, or one that opens a new shot, states its own matrices
there. `[16]` holds the camera's near distance in `x` and its far distance in
`y` (both 0 where the view's projection is handed in whole, an environment
face, whose view-to-clip holds that whole matrix under an identity
world-to-view), and in `zw` the sub-pixel offset the render's projection
carries in pixels of the raster it is drawn at, along the NDC axes (x to the
right, y up; zero without a temporal upscale).
Like `@frame.camera` it is resolved **per render target**: the viewport, a
capture and a render-to-texture camera each read their own camera's matrices.
Its words differ from view to view and frame to frame, so a versioned pass that
binds it is refused. A pass that stands from frame to frame reads it on the
GPU like the other `@frame.*` buffers.
```yaml
# bindings.yaml
- { name: frame_view, kind: buffer, access: read, element: vec4<f32> }
```
```wgsl
let world_to_view = mat4x4<f32>(frame_view[0], frame_view[1], frame_view[2], frame_view[3]);
let view_to_clip = mat4x4<f32>(frame_view[4], frame_view[5], frame_view[6], frame_view[7]);
let near = frame_view[16].x;
let jitter_pixels = frame_view[16].zw;
```
```luau
inputs = { frame_view = "@frame.view" }
```
### The scene's light
`@frame.light` is a reserved **buffer** input carrying the scene's sun and
ambient term as the camera being drawn is shaded by them, the values the lit
passes read in the same frame: 3×`vec4<f32>` = the direction the sun's light
travels (unit, world space) with its intensity in `w`, the sun's colour with
`w` 1 while it casts shadows, and the ambient colour with its intensity in `w`.
A pass that lights a participating medium (clouds, haze, fog) reads its sun
here rather than carrying one of its own, so a day cycle, a scripted sun and a
sun switched off reach the medium in the frame they reach the surfaces, and a
scene with the sun and every light at zero leaves it black. `#include
"@builtin::shaderModules.frame_light"` reads it, and states the sun's light
either in the units the scene's lights are stated in
(`zero_frame_light_sun_irradiance`), for a medium that scatters those lights
too, or as the share of a medium's authored brightness the sun lights (its
intensity up to a unit sun, `zero_frame_light_sun_tint`):
```yaml
# bindings.yaml
- { name: scene_light, kind: buffer, access: read, element: vec4<f32> }
```
```wgsl
#include "@builtin::shaderModules.frame_light"
let light = zero_frame_light(scene_light[0], scene_light[1], scene_light[2]);
let toward_sun = zero_frame_light_toward_sun(light);
let sun = zero_frame_light_sun_tint(light) * authored_brightness;
```
```luau
inputs = { scene_light = "@frame.light" }
```
### The frame's clock
`@frame.clock` is a reserved **buffer** input carrying what the frame is doing:
3×`vec4<f32>`, the same for every view drawn in the frame. `[0]` holds the
shading time in seconds (the instant a `renderer.temporal.hold` pins while one
stands) in `x`, the seconds the frame advanced it by in `y`, that step in
sixtieths of a second in `z`, and the frame index in `w`, counted from the
engine's start and wrapping at 2^24 so a float holds it exactly (0 while a hold
stands, with a step of 0). `[1]` holds four values drawn uniformly from [0, 1)
by hashing the frame index: the seed a pass derives its per-frame random
rotation, jitter or sample offset from. `[2]` holds in `x` the wall-clock
seconds since the renderer drew its previous frame (at most 1), which runs in
every mode, paused play and a `renderer.temporal.hold` included: the step a
rate on the wall clock, such as an exposure adapting, advances by. A pass
reads these words, so a feature
whose passes stand from frame to frame writes none of them into a buffer of its
own, and states no `version`: a versioned pass that binds the clock is refused,
since the words differ on every frame.
```yaml
# bindings.yaml
- { name: frame_clock, kind: buffer, access: read, element: vec4<f32> }
```
```wgsl
let time = frame_clock[0].x;
let step_scale = frame_clock[0].z;
let frame = u32(frame_clock[0].w);
let seed = frame_clock[1];
let wall_step = frame_clock[2].x;
```
```luau
inputs = { frame_clock = "@frame.clock" }
```
### The environment
A compute pass reads the scene's captured surroundings — the reflection-probe
cube array, its sampler and the environment buffer (the probe blend data, then
the irradiance light-probe volumes) — through three reserved inputs, bound to
bindings of the shapes group(0) binds them in:
```yaml
bindings:
- { name: environment_map, kind: textureCubeArray }
- { name: environment_sampler, kind: sampler }
- { name: zero_environment, kind: buffer, access: read, element: ZeroEnvironment, array: false }
```
```luau
inputs = {
environment_map = "@scene.environment",
environment_sampler = "@scene.environmentSampler",
zero_environment = "@scene.reflectionProbes",
}
```
Named like that, `#include "zero::environment"` in the shader resolves the
environment at a world point along a direction — `zpbr_sample_environment(world_pos,
dir, lod)`, the probes whose radius reaches the point blended by rank and
proximity, each through its proxy volume, and the sky under them — exactly as a
material's environment term does, so a reflection a pass draws and one a
material draws agree about the room they are in. A pass that reads several
directions at one point selects the probes once, `let probes =
zpbr_select_probes(world_pos);`, and gathers each direction with
`zpbr_gather_environment_with_probes(probes, world_pos, dir, lod)`, which answers
the radiance in `rgb` and the share of it the probes and sky claimed in `a`.
The three bind at the scene phases; a post or UI phase carries none. A `textureCubeArray` binding takes
`@scene.environment` alone, and a fragment pass has no slot of that shape.
## Pass kinds
`enqueue` runs one of six kinds (the `kind` field; default `"fragment"`):
- **`"fragment"`** — a full-screen shader over input textures. The program is a
GPU **material** (or `shader`) the feature constructed; `inputs` bind live
textures (`@scene.*` or RT guids), `output` is the target RT (omit = the
phase's default scene target). Post-process, blur, edge effects.
**Writing named G-buffer channels (`outputs`).** Instead of the single `output`
RT, a fragment pass may declare an `outputs` array — one or more targets, each a
named engine channel (`@scene.shaded` / `@scene.normal` / `@scene.emissive` /
`@scene.color`) or an RT guid — each with its own blend mode:
```luau
ctx.enqueue {
kind = "fragment",
shader = myShaderKey,
outputs = {
{ target = "@scene.shaded", blend = "under" }, -- premultiplied dst-over-src
{ target = "@scene.emissive", blend = "additive" }, -- one fullscreen pass, two targets (MRT)
},
phase = "afterOpaque", -- deferred: G-buffer filled, before the composite
}
```
Blend modes — the keywords every pass's `blend` takes, `src` being what the
pass returns and `dst` what the target holds:
| Keyword | Result |
|---|---|
| `"replace"` | `src` — overwrites |
| `"alpha"` | `src.rgb * src.a + dst.rgb * (1 - src.a)` — straight-alpha source-over |
| `"premultiplied"` | `src + dst * (1 - src.a)` — source-over for a colour already multiplied by its alpha |
| `"additive"` | `src + dst` — sums |
| `"under"` | `src * (1 - dst.a) + dst` — premultiplied destination-over-source: what the target holds stays in front, which accumulates coverage-weighted contributions |
A keyword outside the table raises from `ctx.enqueue`, naming the field. A
`@scene.*` channel resolves only where it exists (the deferred
G-buffer at a pre-composite phase); a pass whose targets are all unavailable at
its phase is skipped (logged). `output` + `blend = true` remains the shorthand
for a single alpha-blended target. The shader's returned colour is written to
every target in the set.
A fragment shader returns `vec4<f32>`, so the channels it can target are the
float ones. `@scene.material` (also named `@scene.mr`) is
`Rgba8Uint`, which binds as `uint` — naming it as an output is refused by
name, with the channel's format and class in the log, and the rest of the
frame draws. A fragment pass's `inputs` reads through the same fixed float
slot, so naming `@scene.material` there is refused the same way; a compute
pass reads that channel through a `sample: uint` slot instead.
**What a pass with no `inputs` samples.** A fragment pass that declares no
`inputs` reads `@scene.color` — the shape of an effect that filters the scene
image. A pass that names `@scene.color` among its own `outputs` samples a 1x1
transparent texel instead, because the scene colour is that pass's render
target and one texture is a colour attachment or a sampled resource in a render
pass, never both. Declare `inputs = { src = "@scene.color" }` and write an RT
to read the scene image and write somewhere else in one pass.
- **`"compute"`** — a workgroup dispatch (`shader`, `storage`, `buffers`, `dispatch`;
see "Compute passes").
- **`"geometry"`** — draw scene geometry with a constructed pipeline. The program
is a **material** the feature built (`renderer.material.create`); the engine
draws the scene's render-objects with that material's pipeline + uniforms.
- **`"draw"`** — rasterize the feature's OWN geometry: `geometry` names a buffer
created with `usage = { "vertex" }`, `storage.index` one created with
`usage = { "index" }`, and `select` the one entity whose transform and
material the draw lands through. `params[0]` is how many indices to submit —
or name a buffer under `storage.indirect` (created with
`usage = { "indirect" }`, holding a `DrawIndexedIndirectArgs` block: index
count, instance count, first index, base vertex, first instance) and the count
comes from the GPU instead, so a compute pass that compacts geometry pays only
for what it kept and nothing waits on a read-back. `first_instance` must be 0;
the engine resolves the entity's per-instance data another way, because a
non-zero one needs a device feature WebGPU does not guarantee.
- **`"splat"`** — rasterize a compute buffer of particle records as instanced
camera-facing billboards into feature RTs (see "Splat passes").
- **`"raster"`** — draw geometry the feature makes itself with a `.rasterShader`
of its own: `vertexCount` vertices for each of `instanceCount` instances,
pulled from the buffers the pass binds, into the scene or the feature's
targets, depth-tested against the scene (see "Raster passes").
### Geometry passes
A geometry pass re-draws the scene's meshes with a material you supply — the
generic primitive for mesh-space effects (the engine names none of them):
```luau
ctx.enqueue {
kind = "geometry",
material = myMaterial, -- the HANDLE renderer.material.create
-- returned (or its registry-key string)
geometry = "@geometry.opaque", -- which drawables: "@geometry.opaque" |
-- "@geometry.transparent" | "@geometry.all"
select = { entityA, entityC }, -- OPTIONAL: restrict to these entities
-- (entity refs); omit = every matching mesh
phase = "afterLighting", -- afterLighting = lit scene + valid depth
}
```
`select` restricts the draw to the given entities — the per-instance signal that
turns a whole-scene pass into a chosen-meshes effect. A pass with no `select`
also draws the instanced populations (`renderer.mesh.drawInstanced`) its
`geometry` set takes, every copy at its own slot, so a whole-scene pass sees an
instanced forest as it sees the entities around it. The **material** decides how
those meshes are drawn; you control three things:
- **Pipeline render-state.** `renderer.material.create` takes a `render` block —
`cull` (`back`/`front`/`none`), `depthWrite` (bool), `blend`
(`opaque`/`alpha`/`additive`) — so the pass can rasterize differently from the
surface pass:
```luau
local myMaterial = renderer.material.create({
shader = myShaderKey, -- a .shader you authored (identity, not guid)
render = { cull = "none", depthWrite = false },
properties = { outline_color = { 1, 0.4, 0, 1 } }, -- seed the shader's uniforms
}, "my_pass_mat") -- pass `myMaterial` (or "my_pass_mat") as the pass `material`
```
- **The shader.** A geometry `.shader` is a surface shader: author `fn vertex(v:
VertexData) -> VertexData` to move vertices (object-local `v.position` /
`v.normal`) and `fn fragment(input: FragmentData) -> vec4<f32>` for the colour.
- **Its properties.** A shader reads ONLY the uniforms IT declares in
`properties.yaml`, via `material.<yourProp>`. Referencing a field it didn't
declare (e.g. a StandardMaterial `material.base_color`) fails to compile and the
mesh renders **magenta** — declare the property or use a constant.
What effect those three produce (outline, x-ray, wireframe, highlight, …) is
yours to design — the engine just draws the selected geometry with your pipeline.
#### What a pass starts its target from (`load`)
A geometry or draw pass with no `output` draws over the phase's own scene target,
which holds the frame as it stands. A pass naming an `output` render target begins
by setting that target's colour and depth to a starting state, and `load` says
which:
| `load` | the target starts as |
|---|---|
| `"clear"` (default) | empty: transparent colour and the far depth, so the target holds only what this pass draws |
| `"keep"` | what it holds: colour and depth as the last pass to draw into it left them, so this pass draws over that, depth-tested against it |
Two geometry passes naming one `output` therefore leave only the second one's draw
by default, since the second pass starts from an empty target. State `keep` on the
second to draw both, the way one camera draws many entities into one target:
```luau
ctx.enqueue { kind = "geometry", material = tagMat, output = mask.guid,
select = groupA, phase = "afterLighting", order = 0 } -- starts from empty
ctx.enqueue { kind = "geometry", material = tagMat, output = mask.guid,
select = groupB, phase = "afterLighting", order = 1,
load = "keep" } -- draws over groupA's
```
`keep` loads what the target holds when the pass begins: the draws of the passes
before it this frame, and the previous frame's picture where none drew it first
(and where a screen-sized target is made again, an empty one). The first pass to
draw a target each frame says `"clear"` so the target starts the frame empty; an
accumulation across frames is the one that says `"keep"` there too. `load` is
refused, naming the field, on a pass that is not a geometry or draw pass or that
has no `output`. A splat pass loads its targets with `blend = true`, and a raster
pass clears them with `clear = true`.
**How much of each mesh it draws.** A pass drawing into a small map (a
top-down cover or height map, a coarse occlusion mask) holds none of the
detail finer than a texel, and two fields keep it from paying for that detail:
- `detail = 1.0` states the world-space size of the finest detail its target
holds. Each static mesh then draws at the coarsest cut of its cluster
hierarchy whose error, placed at the object's scale, stays within that size,
the cut the scene's own draw takes for a distant object: a building keeps its
walls and roof and a tree its crown, in far fewer triangles than their full
detail. A mesh drawing from its own vertex streams (a skinned or morphing
mesh, one with no cluster set yet) and an instanced population draw in full.
- `rigid = true` leaves out every mesh a skeleton poses or morph targets blend,
so a crowd of characters costs the pass nothing.
`renderer.feature.drawn()` reads what each geometry pass drew on the last drawn
frame, as `{ objects, triangles }` keyed by its material, so the difference
either makes is a number.
**Where each surface stands.** A geometry pass draws every object through the
pass's own material, at that material's depth bias. `objectDepthBias = true`
adds to it the depth bias (`depthBias`, `depthBiasSlope`, `depthBiasClamp`) each
object's own material states, so a pass testing against the scene's depth meets
a decal or an overlay its material lifts toward the camera at the depth the
frame drew it at; the `zfighting` capture view counts surfaces this way. A clamp
either side states caps the sum, and a versioned pass stating it draws in every
view.
### Compute passes
A compute pass dispatches a `.computeShader` program over a workgroup grid:
```luau
ctx.enqueue {
kind = "compute",
program = myComputeShader,
storage = { outTex = myStorageRtGuid }, -- slot -> storage-texture RT guid
buffers = { particles = "my_particle_buf" },-- slot -> named compute buffer
inputs = { camera = "@frame.camera" }, -- slot -> @frame.*/@scene.* buffer
dispatch = { x = 64, y = 1, z = 1 },
}
```
**`dispatch` is optional.** Omit it and the pass is dispatched over what it
WRITES: a grid covering its first `storage` texture, at the `@workgroup_size` the
shader's entry point declares. With a screen-sized storage target that grid
tracks the render target being drawn, so a screen-space effect covers the live
viewport, an offscreen capture and an RTT camera without the feature knowing any
of their resolutions:
```luau
ctx.enqueue {
kind = "compute",
program = myComputeShader,
inputs = { scene_color = "@scene.color", cam = "@frame.camera" },
storage = { outTex = myScreenSizedRt.guid }, -- screen = true
phase = "afterLighting",
}
```
State an explicit `dispatch` for a grid that is not one thread per output texel
(a reduction, a particle sim), or when the shader's `@workgroup_size` is an
override/const expression the engine cannot read.
**`dispatch = { indirect = <buffer>, offset = <bytes> }`** takes the grid from the
GPU: the pass runs the workgroup counts (x, y, z, three `u32`) found `offset`
bytes into the named compute buffer (default 0; a multiple of 4), which a pass
earlier in the frame wrote. A scheduling pass counts the work that exists this
frame, writes the counts, and the passes after it dispatch over exactly that
work, so a pass that touches one object in ten costs the one in ten:
```luau
-- the buffer is created with usage = { "indirect" }; the first pass writes its
-- three counts, the second dispatches over them
local args = schedule:createBuffer("args", { type = "f32", len = 3, usage = { "indirect" } })
ctx.enqueue { kind = "compute", program = schedule, buffers = { args = args }, dispatch = { x = 1, y = 1, z = 1 }, order = 1 }
ctx.enqueue { kind = "compute", program = work, buffers = { items = items }, dispatch = { indirect = args }, order = 2 }
```
`indirect` takes the buffer's handle or its name. A pass naming a buffer that does
not exist, was created without `usage = { "indirect" }`, or holds fewer than
three `u32` from `offset`, is skipped with a warning naming the buffer. A count
of zero in any dimension runs no workgroups. The pass that dispatches from a
buffer does not bind that buffer as a writable storage binding (the GPU reads
the counts while the pass runs); each count stays within the device's
`max_compute_workgroups_per_dimension` (65,535 on the WebGPU baseline), so a
count past it is split over x and y by the pass that writes it. `dispatch` states
either `x`, `y`, `z` or `indirect`, not both. Native and the web build dispatch
the same way.
Each WGSL storage-buffer binding in the shader resolves its bound slot in this
order: an explicit `buffers` mapping (the handle a buffer's owner holds, or a
name), then `inputs` (`@frame.camera` / `@frame.view` / `@frame.light` / `@scene.lights` /
`@scene.reflectionProbes`), then — when a slot has neither — a buffer whose
engine-side name equals the slot's own name. `buffers`
is the seam a pass binds through: the buffers a shader works over are the ones
handed to it, whatever each is called. `storage` binds storage TEXTURES (RT
guids) the same way, one map per resource kind.
**A table built from a few settings.** A compute pass whose targets follow
from inputs that rarely change (a lookup table, a baked noise volume) states
the version of those inputs as `version`, a string or a number. The pass runs
in a view only while some render target it writes holds no picture this
program recorded at this version, so the table is built in the first view
after the version moves and skipped in every later view and frame:
```luau
ctx.enqueue {
kind = "compute", program = bakeLut,
buffers = { settings = settingsBuf },
storage = { lut_out = lutRt.guid },
phase = "afterSky",
version = string.format("%.17g,%.17g", density, falloff),
}
```
A pass reading the table later in the frame reads the picture it holds. The
table is built again when the version changes, when the pass's own
`params`, `dispatch`, `buffers` or `storage` change, when the program's
pipeline is rebuilt (an edit to its source), when a render target it reads
through its `inputs` holds a new picture (so a table built from another table
is built again whenever that one is, and one built from a camera's target or a
video target whenever that target draws), when another texture it reads there
holds new texels, when a pass of any other version or none writes the target,
when the target is reallocated or cleared, and when the device reports an error
after the build was recorded. What the build reads from a buffer's contents or
from a value its program holds (`ref:setParam`) belongs in the version. A pass reading a
texture a GPU producer outside the texture cache writes, a 3D texture, or the
scene's acceleration structure and hit tables is built in every view.
**A table built from the view being drawn.** A table that follows the camera
too (a sky seen from the camera's altitude) binds `@frame.camera`, and names
what its program reads of the view in `viewReads`: `"@frame.camera.position"`
(the camera's world position, `@frame.camera[4].xyz`) and `"@frame.light"`
(the whole light buffer). The engine names the build by those values as each
view holds them, so the table is built in a view drawn from where it was not
built and stands in every view and frame drawn from where it was. `render`
runs once a frame and states what follows from the frame alone in `version`;
the engine adds what each view holds:
```luau
ctx.enqueue {
kind = "compute", program = skyTable,
inputs = { cam = "@frame.camera", lut = transmittanceRt.guid },
buffers = { settings = settingsBuf },
storage = { sky_out = skyRt.guid },
phase = "afterSky",
version = string.format("%.17g,%.17g,%.17g", sun.x, sun.y, sun.z),
viewReads = { "@frame.camera.position" }, -- built again when the camera moves
}
```
Every view of a frame shares the target, so a capture or a render-to-texture
camera standing elsewhere builds the table for its own camera, and the next
view drawn from the viewport builds it again for the viewport's. The program
reads nothing else of the camera buffer: its orientation, its projection and a
temporal upscale's sub-pixel offset move from frame to frame and name n
# 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.coverAt(x, z) -- the undersides the field holds over a place
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.
Cover is geometry that casts a shadow. A model with `castsShadows = false` lets
the sun through, and the field lets the weather through it the same way: a
mist layer, a sheet of falling rain or a water surface stands over nothing, and
the field's extent is measured over the models that cast one.
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
```
# renderer.atmospherics
`renderer.atmospherics`: the share of the air between the camera and a surface that reaches the image, and the holds that pin it.
# renderer.baseline
The renderer a caller began with: `renderer.markBaseline`, `renderer.resetToBaseline` and `renderer.releaseBaseline`.
# renderer.bounds
`renderer.bounds`: the extent a render feature publishes for a renderable it draws from its own buffers.
# renderer.captureView
`renderer.captureView`: the named camera passes a render feature publishes, each under a debug channel a capture selects.
# renderer.core
The renderer table every `renderer.*` namespace is defined on, the engine surfaces those namespaces call, the runtime registry a create files a resource in under the holder its scope names, and the handles each create hands out, held weakly so a resource nothing reaches any more is let go.
# renderer.debugPass
`renderer.debugPass`: resolves a debug-pass name to and from the channel it selects, for the built-in passes and the capture views.
# renderer.destroy
`renderer.destroy`: releases the runtime texture, material, mesh or render feature a handle, or a kind and an id, names.
# renderer.feature
`renderer.feature`: the registry of live render features, the context each one's `render(ctx)` runs with every frame, and their settings; `renderer.post`: the post stages; `renderer.output`: the output the frame is presented in.
# renderer.featureInputs
What a render feature's `render` reads, and whether any of it moved. A feature that states its inputs (`dependsOn`, `inputs`) has `render` run only on a frame one of them moved; on every other frame the engine runs the passes the last render handed over. Its settings in force are always one of those inputs.
- `settingsInForce(feat, levels)` answers a feature's settings at the quality levels in force, kept on its row until the authored settings or a level change.
- `NAMES` names each input a feature may state in `dependsOn` and what it stands for.
- `compile(mod, identity)` answers the inputs a feature module states, or nil for one that states none, and refuses an input it does not know by name.
- `holdsStill(feat, levels, frame)` answers whether every input stands as it stood at the feature's last render, so its passes can be replayed.
```luau
local FeatureInputs = require("@builtin::modules.api.engine.renderer.featureInputs")
local inputs = FeatureInputs.compile({ dependsOn = { "viewport", "camera.cell:2" } }, "example")
assert(inputs.viewport == true and inputs.cell == 2)
assert(FeatureInputs.compile({}, "example") == nil)
assert(not pcall(FeatureInputs.compile, { dependsOn = { "weather" } }, "example"))
assert(FeatureInputs.NAMES.lights ~= nil)
```
# renderer.featureTexture
`renderer.featureTexture`: sizes the shared feature-texture array a surface shader reads through `zero_feature_texture(uv, layer)`, sets its layers and reports its state.
# renderer.frameStats
What each frame submitted (culling, draws, skinning, morphs, uploads) and how the frames are paced: the frame pacing and activity readings, frames in flight, the present mode, the spectator mode, local layers and the frame-rate cap.
# renderer.holds
The reads every renderer cell a hold pins answers the same way. A hold on a cell such as `renderer.temporal` (the per-frame clock) or `renderer.atmospherics` (the share of the air that reaches the image) names who took it and the key it was taken under, so a caller reads who holds the cell, an exclusive hold is refused for every other key, and a hold whose task ended is handed back.
- `statedOwner(options)` answers the key `options.owner` states, or nil.
- `actor()` answers the id and display name of the caller the call is attributed to.
- `ownerLabel(owner, ownerName)` answers how a refusal names the holder.
- `holderIsGone(holder)` answers whether the task that took a hold was cancelled or died; `holdingTask()` answers the task taking a hold now.
```luau
local Holds = require("modules.api.engine.renderer.holds")
assert(Holds.statedOwner({ owner = "shot" }) == "shot")
assert(Holds.ownerLabel("abc", "Ada") == "Ada (abc)")
assert(Holds.holderIsGone(nil) == false)
```
# renderer.instanceData
`renderer.instanceData`: the per-entity lanes of the per-instance block a shader reads as `input.shader_data`, set and cleared by entity.
# renderer.letGo
The watch that releases a runtime texture, material, mesh or render feature mid-session once no script reaches a handle to it and nothing else holds it. It reads the renderer's handle sets every few dozen frames: a resource whose last handle the garbage collector took joins the watch and is judged against the runtime resource census, by the holders `renderer.collect` reads, and released once nothing holds it. A resource kept only by the component or scene load that created it stays while that owner does, and the log names an owner once it holds 64 of one kind that way, and again each time that count doubles. A render feature holds what it created through the handles it keeps and the passes it queues, which the census names as references, so a target whose handle the feature dropped and that none of its passes names any more is released while the feature stands. A texture or mesh the asset path uploaded under its asset's guid waits on the watch while that asset stands, and is judged from its holders once the asset index changes and the asset no longer answers. A texture a released material record named goes on the watch with it, the one the device holds for an asset included: that asset is the path the texture is read back by, so it is released once nothing else names it, the way a collection releases it.
- `new(host)` makes the watch over the handle sets, census and release the renderer hands it in `host`, and answers `{ start, rejudge, letGo }`: `start()` starts the task that reads the sets unless it is running, `rejudge(kind, guid)` marks a watched resource due a judgement at the next reading, and `letGo(kind, guid)` puts a resource a holder other than a handle let go of on the watch.
# renderer.lifetime
Runtime resource lifetime: `renderer.hold`, `renderer.release` and `renderer.references`, `renderer.collect`, and the let-go watch that releases a runtime resource once nothing holds it.
# renderer.material
`renderer.material`: the material records (a shader key, property overrides and texture-slot references) the renderer builds a bind group from, and what each one draws with.
# renderer.memory
The render device and what its memory holds: the GPU memory reading, the device generation, state, limits and errors, shadow memory and pages, the reflection environment, render targets and the pass schedule, texture memory, the texture budget and streaming, memory pressure, the material table and the texture bucket slack.
# renderer.mesh
`renderer.mesh`: the ZMSH codec, the guid-keyed CPU mesh store, the GPU meshes created from it, their clusters and level of detail, and the instanced draws of a mesh.
# renderer.observation
The renderer's readings of its pipeline and shader caches, its pending work, the frame it last drew (`renderer.observe`), the draw diagnostics, how a subject shades, what materials and shaders cost, and the material identity table.
# renderer.postStages
The frame's post stages: the ordered list of named seams every post effect runs at. Each stage states the colour space of the picture it holds (`light`, scene-referred light the display transform has yet to fit to the screen, or `display`, display-referred code values) and its resolution (`raster`, `output`, `reduced`, or `rasterToOutput` for a stage that starts on the raster and carries the picture to the output size). A render feature declares `stage = "<name>"` and a post-process chain shader `stage: <name>` in its `properties.yaml`; the engine schedules each from this list, a feature's passes inside the stage's band of orders at its pipeline phase and a chain effect at the stage's chain layer. `renderer.post.stages()` reports the list with the effects standing in each stage.
Inside a stage a feature's pass takes a local order from 0 up to `BAND`, and passes sharing an order run in the order they were enqueued, so a feature whose passes depend on one another (a chain over shared targets) can run them at one order, in sequence. A pass may name a stage of its own (`stage = "display", order = 2`): a feature whose work spans two stages, such as temporal antialiasing (its resolve in `temporal`, its sharpening in `display`), declares one and names the other on those passes. A chain effect takes its place among the chain effects of its stage by `priority`, a number, or `"last"`, after every numbered chain effect of the stage; chain effects sharing a priority, two `"last"` among them, run in the order they registered. The `ui` stage runs `afterUI` feature passes, then its chain effects, then `afterPost` feature passes, so an `afterPost` pass runs after every chain effect of the stage.
The presented frame (`renderer.presentedFrames`, a `capture` of `source = "presented"`) runs every stage. An offscreen render (a capture from a camera or a station, a render-to-texture camera) runs the render features of every stage up to `optics`, the film stages among them (`meter`, `optics`) only when its camera runs post-processing; when it fits the picture to the display it runs the `display` stage too: the display transform, the stage's render features and the chain's `display` layer. It runs the `ui` stage as well (its `afterUI` render features, the chain's `all` layer and its `afterPost` render features) when it renders the picture as the screen presents it: a capture does, and so does a render-to-texture camera with `textureColorSpace = "presented"`. Any other texture camera's picture takes the `ui` stage from the frame that shows it, and one with `textureColorSpace = "linear"` holds the scene's light and runs neither the `display` stage nor the `ui` stage.
Where the built-in effects run:
| stage | built-in effects |
|---|---|
| `lighting` | occlusion, reflections, indirect light, contact shadows, subsurface scattering, area lights, decals, splats, outlines, debug draws and diagnostic views |
| `medium` | aerial perspective, height fog, volumetric light |
| `preTemporal` | depth of field |
| `temporal` | temporal antialiasing |
| `postTemporal` | motion blur |
| `meter` | the exposure meter |
| `optics` | lens flare (render feature), bloom (chain) |
| `display` | the display transform, then the temporal upscale, debanding, edge antialiasing (FXAA) and sharpening (RCAS, CAS), then the chain's looks and the film grain (`lensFx.grain`, `priority = "last"`) |
| `ui` | the UI, then the cutscene fade and letterbox (`priority = "last"`) |
| `output` | the surface encoding |
The stages, in frame order: `lighting`, `medium`, `preTemporal`, `temporal` (one effect at a time), `postTemporal`, `meter`, `optics`, `display`, `ui` and `output`.
- `list()` answers every stage in frame order, each a copy: `{ name, film, space, resolution, single, runs, feature, phases, chain?, chainFirst }`.
- `isFilm(name)` answers whether a stage is one of the camera's film, the exposure meter and the lens light (`meter`, `optics`): a pass a render feature places there, naming no `postProcessing` and no `presented` of its own, is part of the camera's post-process chain, so a camera running no post-processing (a capture asking for the scene ungraded, an environment face) skips it, and `postProcessing = false` on the pass keeps it on every camera.
- `get(name)` answers the stage a name names, or nil and a message listing the stages there are.
- `index(name)` answers where a stage stands in the frame, 1 for the first.
- `chainLayer(name)` answers the chain layer (`scene`, `display` or `all`) a post-process effect declaring that stage runs at, or nil and the reason.
- `stageOfLayer(layer)` answers the stage a chain layer's effects run in.
- `stageOfPosition(phase, order)` answers the stage a render-feature pass placed by phase and order stands in.
- `BAND` is how many orders one stage's band at a phase spans: a declared feature's local order counts from 0 up to, and short of, it.
# renderer.rayTracing
Ray tracing: `renderer.setRaytrace` and the readings of the scene acceleration structure a ray-tracing render feature traces against, transmission shadows, and the main camera's view.
# renderer.refs
How `renderer.*` names a live resource. A runtime resource is filed under a v4 guid, minted from OS entropy or given by the caller; and each call that names a resource takes whatever the caller already holds (the key or guid, the handle `create` returned, the CPU handle `load` returned, or an `AssetRef`) and coerces it to the key the renderer's stores index it by.
- `makeGuid()` mints a guid; `validateGuid(guid, what)` answers `guid` when it is a v4 guid and raises at the caller's line when it is not.
- `materialKey(value, what)`, `meshKey(value, what)` and `textureKey(value, what)` answer the registry key or guid a value names, and raise a rejection that lists the accepted forms.
- `refField(t, name)`, `declaredCategory(value)` and `shapeName(value)` read a ref-like table the way the coercions do.
- `primaryBytes(ref)` answers an asset's primary content bytes, waiting for them under a coroutine when they are still on their way; `textureRefOf(value, what)` answers the ref a texture asset's content is read through.
```luau
local Refs = require("modules.api.engine.renderer.refs")
local guid = Refs.makeGuid()
assert(Refs.validateGuid(guid, "example") == guid)
assert(Refs.meshKey({ kind = "MeshHandle", category = "mesh", guid = guid }, "example") == guid)
```
# renderer.sampling
Anisotropic texture filtering, and where in a pixel the projection samples: its offset and jitter.
# renderer.shaderSources
The programs the engine compiled for each feature set a shader was asked for, and the WGSL the compiler received for a shader.
# renderer.shading
The readings `renderer.shadingOf` builds out of the document the renderer publishes every frame.
- `shadingSubject(value, what)` answers the id a shading question names: an entity proxy's id, an entity-id string, or the registry key of a material in any form a material answers to.
- `publishedRenderable(doc, id)` answers the row that answers for a subject: the entity's own row, or a row drawing with the material, a fault wherever there is one.
- `materialRow(doc, id)` answers the renderer's record for one material.
- `shadingFault(state, means, row)` builds the fault reading a row carries.
```luau
local Shading = require("modules.api.engine.renderer.shading")
local doc = { renderables = { { entity = "e1", material = "m1", substituted = false } }, materials = {} }
local row = Shading.publishedRenderable(doc, Shading.shadingSubject("e1", "example"))
assert(row.material == "m1")
```
# renderer.shadows
Shadow caching and its page breakdown, the skinned and blended batching switches and the skinning pose hold, the shadow configuration and sizing, the caster cutoff, shadow proxies, the shadow views and the shadow hero.
# renderer.sources
The `src` shapes `renderer.mesh.create` / `update` and `renderer.texture.create` / `update` take.
- `classifyMesh(src)` answers which mesh src it is (`SRC_GPU`, `SRC_CPU`, `SRC_GEOMETRY` or `SRC_BUFFERS`), and raises for a src that is none of them or a geometry src whose indices address a vertex its positions do not carry.
- `vertexRecordsToArrays(src)` turns geometry written as per-vertex records (`vertices = { { pos, normal?, uv?, uv1? }, ... }`) into the parallel flat arrays the upload takes.
- `boundsFromPositions(positions)`, `vecToAabb(min, max)` and `ZERO_AABB` are the bounds a mesh is created with; `geometryCounts(src)` answers the vertex and index counts raw geometry implies.
- `classifyTex(src)` answers which texture src it is (`TSRC_GPU`, `TSRC_CPU`, `TSRC_PIXELS` or `TSRC_TARGET`).
```luau
local Sources = require("modules.api.engine.renderer.sources")
local src = { positions = { 0, 0, 0, 1, 0, 0, 0, 1, 0 }, indices = { 0, 1, 2 } }
assert(Sources.classifyMesh(src) == Sources.SRC_GEOMETRY)
print(Sources.boundsFromPositions(src.positions).max.x) -- 1
```
# renderer.specShapes
The shapes a render feature's passes are held in. A spec frozen all the way down reads the same on every frame, so the engine keeps it as it read it. A spec a render hands over unfrozen is held as a frozen copy when it reads the same as one handed at the same place in an earlier render, so a feature that builds its specs afresh every frame costs the engine what one handing over frozen specs costs.
- `wholeFrozen(spec)` answers whether a spec and every table inside it is frozen and carries no metatable.
- `heldShapeOf(row, spec)` answers the spec to hand over at the feature row's next place: the held copy the spec reads as, a new held copy, or the spec itself once the place's specs keep moving.
- `placed` holds the placed copy of each frozen spec a stage placed, by the spec it was placed from, with weak keys.
```luau
local SpecShapes = require("@builtin::modules.api.engine.renderer.specShapes")
assert(SpecShapes.wholeFrozen(table.freeze({ kind = "fullscreen" })))
assert(not SpecShapes.wholeFrozen({ kind = "fullscreen" }))
local row = { shapes = {}, handedN = 0 }
local first = SpecShapes.heldShapeOf(row, { kind = "fullscreen", order = 1 })
assert(table.isfrozen(first))
row.handedN = 0
assert(SpecShapes.heldShapeOf(row, { kind = "fullscreen", order = 1 }) == first)
```
# renderer.splat
`renderer.splat`: decodes a Gaussian splat capture into the GPU-ready byte pools a render feature uploads.
# renderer.temporal
`renderer.temporal`: the clock a per-frame effect draws itself against, and the holds that pin it.
# renderer.texture
`renderer.texture`: the texture codec, the guid-keyed CPU texture store, the GPU textures created from it, the render targets, and the readings of a texture's pixels.
# renderer.visibility
What the renderer decides to draw before it draws it: the resolution scale and its mode, the quality tier, the upscaler, the viewport and picture sizes, the screen-size and cluster-error cutoffs, occlusion culling, raster shading, the scene's lighting, and the ray cast against the geometry it draws.
# result
The handle `asset.list` returns.
A query result **is** the array of matched `AssetRef` handles. Entry `1` is the
first match, `#rows` is the count, `ipairs(rows)` walks it, and anything that
accepts a list of refs accepts it unchanged. The handle adds methods on top of
that array through a metatable, so reading the result stays one expression.
```lua
local hero = asset.list({ type = "mesh", fields = { tags = "hero" } }):first()
local prop = asset.list({ type = "mesh", path = "/zero/source/props" }):random()
asset.list("material")
:filter(function(m) return m.name:find("rust") ~= nil end)
:each(function(m) print(m.identity) end)
```
## Methods
| Method | Returns |
|---|---|
| `:first()` / `:last()` | One entry, or nil when the query matched nothing. |
| `:random()` | One entry chosen at random, or nil. |
| `:count()` | How many entries matched. |
| `:isEmpty()` | Whether nothing matched. |
| `:each(fn)` | The same result, after calling `fn(entry, index)` in order. |
| `:map(fn)` | A new result holding `fn(entry, index)` per entry. |
| `:filter(predicate)` | A new result holding the entries kept. |
| `:searchable()` | A new result without the deprecated assets, the ones a search or a picker offers. |
| `:sort(comparator?)` | A new, ordered result; ordered by identity when the comparator is omitted. |
| `:toArray()` | The entries as a plain table, without the handle. |
`:map`, `:filter`, and `:sort` return new results carrying the same methods, so
they chain. `:sort` leaves the result it was called on as it is.
## Ordering
`asset.list` already returns its matches ordered — by identity unless the query
asks for another field with `order` — so `:first()` names the same asset on
every call. `:sort` is for orders the query cannot express, such as one computed
from an entry's fields.
## What the handle does not change
The metatable carries `__index` alone. Length, `ipairs`, `pairs`, `next`,
`table.*`, and serialisation all read the array part, so a result behaves
exactly as a plain array everywhere those are used.
# asset_warmup
`asset.warmup` — a **read-only closure inspector**.
Returns the transitive set of assets that the CPU-residency system *would* load
when the given asset enters `/runtime/` — i.e. the asset plus everything
reachable through its declared content references. It does **not** itself change
residency or touch bytes:
```lua
local closure = asset.warmup("@builtin::meshes.cube")
-- → the asset + every texture/material/mesh it transitively references
```
Residency is owned by the engine's reference-counted CPU-residency system, which
acquires the closure on a `/runtime/` enter (usage 0→1) and releases it on the
last drop (→0), loading/unloading bytes at the per-node 0↔1 boundaries so a
texture shared by two materials stays resident until BOTH are gone. This helper
just lets scripts and agents **inspect** that closure (debugging, "what would loading
X pull in?") without any side effect — it avoids `asset.resolve` (which fires the
BlobStore prefetch) and uses the side-effect-free `asset.guid` / `asset.deps` /
`asset.identity`.
The closure is the generic `.refs` graph, so this is fully type-agnostic —
material/mesh/user-types all resolve the same way with zero per-type knowledge.
By default it follows `asset_ref` / `component` (content) edges and skips
`asset_type` (structural) / `require` (code); `opts.vias` overrides. Deduped by
guid via an explicit work-stack so diamonds appear once and cycles terminate.
Installed onto the FFI `asset` namespace by the prelude.
# blobs
Generic binary staging for handing bytes to native components. Content reads a file's bytes (`vfs.read`, binary-safe, yields until the blob is resident), stages them with `set`, and passes the returned handle through a component field; the native consumer takes the bytes back by that handle and owns its copy. Staged bytes stay while a component field names their handle; bytes no component names are dropped once the frame after the one they were staged in ends, so a handle goes into its component in the frame it is staged. Writes a `queue()` body defers hold every staged payload until they land. Component field values travel as JSON (UTF-8 only), so a raw binary payload rides as a staged handle — the CPU-side analogue of the mesh/texture GPU upload.
## Methods
- `blobs.set(bytes) -> handle` — stage a binary payload, get a short string handle to pass through a component field.
- `blobs.get(handle) -> bytes?` — read back a copy of the staged bytes without removing them; nil for an unknown or already-cleared handle.
- `blobs.clear(handle)` — drop a staged payload at once, freeing its memory before the engine would drop it unnamed.
## Usage
```luau
local bytes = vfs.read(clipPath .. "/data.zaud")
local handle = ecs.blobs.set(bytes)
ecs.insertSync(id, ecs.AudioSource { clip = clip, bytesHandle = handle })
```
# ecs.components
Component-spec namespace — re-exports every native ECS component spec under `ecs.components.<Name>`. Each spec describes one native component: its public name, the Rust type it maps to, and the per-field entries the generic `ecs` verbs use to build and read Rust-shaped values. The sibling `ecs` module registers each spec to mint its typed constructor (`ecs.Mesh`, `ecs.Transform`, ...).
## Spec shape
Each spec is a table with:
- `name` — the public component name (`"Mesh"`).
- `rust` — the native type it maps to (`"MeshInstance"`).
- `entries` — per-field descriptors `{ luau, rust?, kind, expand? }`. `luau` is the camelCase field a caller writes; `rust` is the underlying snake_case field; `kind` is the conversion kind (`string`, `bool`, `number`, `vec3`, `meshHandle`, `materialHandle`, `textureHandle`, `assetRef`, `struct`); `expand` lists the rust scalars a `vec3` expands into.
- `behavior(id) -> { method = fn }` — optional per-entity imperative methods the `ecs.get` handle exposes.
- `static = { fn = function(id, ...) end }` — optional component-level operations that take an explicit entity id.
## Members
`Mesh`, `Material`, `Transform`, `Physics`, `Light`, `Collider`, `CollisionGroups`, `PlaneHold`, `GravityField`, `Force`, `FluidForces`, `LiftSurface`, `PhysicsJoint`, `PhysicsLatch`, `WheelCollider`, `ShaftNetwork`, `SoftBody`, `AudioSource`, `Camera`, `Sky`, `PlayerOwned`, `Skeleton`, `TransformConstraints`, `VisibilityRange`. Each lives in its own `.module/` folder.
## Usage
```luau
local Specs = require("modules.api.engine.ecs.components")
for name, spec in Specs do
print(name, spec.rust)
end
```
# handle
Lazy handle over a present component, returned by `ecs.get(id, ecs.<Name>)`. It retains a bind accessor per field (resolved once, reused, revalidated) and closes over the component's compiled conversion plan, so reads and writes stay live without re-crossing into the native substrate.
## Reads
Index the handle by the public (mapped) field name you construct with — `h.castsShadows`, `h.tint` — or by the underlying rust field name — `h["casts_shadows"]`, `h["tint_r"]`. Public names win when both resolve. A `vec3` field recomposes into `{ x, y, z }` (also mirrored to `[1]`, `[2]`, `[3]`). Reads are live, never stale.
## Writes
Assign to the same names you read: `h.castsShadows = false`, `h.tint = { 1, 0, 0 }`. The assignment writes the component's row, so the read after it answers what the component holds. `handle:set(key, value)` is the same write in method form.
The component's row is the handle's only store — a name the component does not have raises, and a value the field will not take leaves the field as it was and warns, naming the component, the field under the name you wrote it as, and the value refused.
## Methods
- `handle:set(key, value) -> handle` — write a field by public or rust name; resolves and coerces handle-typed fields, and expands a `vec3` into its three scalars. Returns the handle.
- `handle:read() -> table` — batch-read every rust field in one pass (point-in-time copy keyed by rust field name).
- `handle:release()`: destroy the retained bind accessors now. A handle nothing reaches gives them back on its own once the collector frees it.
A behavior-bearing component (e.g. `Physics`) also attaches its per-entity imperative methods directly on the handle, each bound to this entity's id.
## Usage
```luau
local body = ecs.get(id, ecs.Mesh)
local visible = body.visible
body.castsShadows = false
body:set("tint", { 1, 0, 0 })
```
# handles
Loads the native components a saved record lists. A record (a scene entity, a bundle `entity_template` entry) states its native components beside its script components as `ecs = { { type = "<public name>", data = <row> } }`: `type` is the name the component answers to under `ecs`, and `data` is the row `ecs.snapshot` answers for it. Every field that holds a GPU handle is written as the guid of the ASSET the handle came from, because the guid outlives the session and the handle does not.
Loading resolves each of those guids to the handle the component holds (`ref:handle()`, the call a `Model` makes, which puts the asset on the GPU) and inserts one value into every entity that states the same entry.
## Exports
- `M.handleFields(typeName) -> { { rust, category } }?` - the fields of a native component that hold a GPU handle, each with the asset category its guid names (`mesh`, `material` or `texture`). nil for a name `ecs` does not hold.
- `M.value(entry, site?) -> value` - the component value one `{ type, data }` entry states, ready for `ecs.insert`. A guid that names no asset of the field's category raises, naming the component and field. `site` is the path or identity of the asset the entry was read from: a site inside a carried mount reads each guid within that mount's closure (`asset.tryResolve(guid, category, site)`).
- `M.insertAll(specs, site?) -> failures` - inserts `{ id, type, data }` specs, one `ecs.insertMany` per distinct `(type, data)`, reading every guid at `site` the way `M.value` does. Answers one `{ type, ids, message }` per entry that did not land.
## Usage
```luau
local handles = require("modules.api.engine.ecs.handles")
local failed = handles.insertAll({
{ id = a, type = "Mesh", data = { mesh = meshGuid } },
{ id = b, type = "Mesh", data = { mesh = meshGuid } },
{ id = a, type = "Material", data = { id = materialGuid } },
})
for _, failure in ipairs(failed) do
log.error(failure.type .. ": " .. failure.message)
end
```
The scene loader and `bundle:instantiate` call `insertAll` after a record's script components are added.
# plan
Compiles a per-component spec into a reusable conversion plan and formats Luau input into the Rust-shaped payload the `ecs` verbs apply. A plan is compiled once per component at module load; `format` is the only per-call work.
## Exports
- `M.compile(spec) -> plan` — builds a plan from a spec's `entries`: `{ rust, entries, byLuau, rustFields }`, where `byLuau` maps each public field name to its entry and `rustFields` is the set of underlying rust field names.
- `M.format(plan, input) -> table` — converts Luau input to the rust-shaped payload. Expands `vec3` fields into their three rust scalars (reading `{r,g,b}`, `{x,y,z}`, or array form), resolves handle fields to their guid, passes scalars through, and raises on an unknown field.
- `M.resolveMeshHandle(value) -> string` — reads the live GPU registry guid off a `MeshHandle`, raising on a category mismatch or a missing guid.
- `M.resolveMaterialHandle(value) -> string` — reduces any of the forms that identify a material to the one string rust holds: a `MaterialHandle` (its guid), a registry key or asset guid string (passed through), or an `AssetRef` (its `__ref`). These are the forms `renderer.mesh.drawInstanced` takes for the same job. A handle or envelope naming another category raises — a handle names its category in `category`, an `AssetRef` names it in `type`, and both are read.
- `M.resolveTextureHandle(value) -> string` — accepts a typed `TextureHandle` (returns its guid), a bare guid string (passed through), or `nil` / `""` to clear.
## Usage
```luau
local plan = require("modules.api.engine.ecs.plan")
local compiled = plan.compile(spec)
local payload = plan.format(compiled, { visible = true, tint = { 1, 0, 0 } })
```
# watch
A watch over the entities holding a set of components. `w:changed()` answers whether anything a reader of those entities could see is different from the last time it was asked, so a system that derives something from them every frame (an overlay, a validation, a cache) derives it again only when it has to.
## Exports
- `M.new(...) -> Watch`: a watch over the entities holding any of the terms. A term is a native component type (`ecs.Light`) or the name of a script component (`"PlayerSpawn"`); anything else raises.
- `watch:changed() -> boolean`: true when, since the previous call, a native component the watch names was added to or written on an entity, an entity holding one left that set (despawned, or the component removed), or an entity holding any of its terms moved. For script terms it is also true when a component was added to or removed from any entity, or any component's public field was written. The first call answers true.
## Usage
```luau
local EcsWatch = require("modules.api.engine.ecs.watch")
local lights = EcsWatch.new(ecs.Light, "ReflectionProbe")
task.loop(function()
if lights:changed() then
rebuildOverlay()
end
end)
```
# Compute shader (asset type)
A `.computeShader` is a GPU compute (GPGPU) program with a **zero-scaffolding**
authoring contract: you write only `@compute fn main(...)` plus a declarative
`bindings.yaml`, and the engine GENERATES every `@group/@binding` declaration —
storage buffers, textures, samplers, storage textures, and a `params:` uniform —
expands `#include`s, naga-validates the result, and registers it. The single
source of truth for the binding layout is `bindings.yaml`; there are no
hand-written `@binding` lines to keep in sync.
> New to how content lives across the CPU and GPU? Read `core/resource-model`
> first: it covers the asset / CPU / GPU forms every resource takes, the upload
> path, and how compute fits the performance ladder (`core/performance`).
## Folder shape
A `.computeShader` is a folder asset:
```
<name>.computeShader/
shader.wgsl # the WGSL body — only `@compute fn main` + helpers (required)
bindings.yaml # the binding + params schema (required)
README.md # a one-paragraph description of THIS shader (required)
.metadata # asset metadata
```
Each file carries a committed `.meta` sidecar pinning its stable guid. The
identity is `<name>` (the `.computeShader` suffix strips).
Resolve the shader once, then dispatch through the reference:
```lua
local carve = asset.resolve("carve", "computeShader")
carve:dispatch({ buffers = { heights }, workgroups = { 64 } })
```
`asset.resolve` is what records your script's dependency on the shader, so the
shader travels with the world your script lives in — packed, pulled, or
published. It compiles on first dispatch, and on the first frame a render
feature's compute pass names it; there is no setup step.
## bindings.yaml
One ordered `bindings:` list — the binding index is the list position
(0, 1, 2, …) — plus an optional `params:` scalar-uniform block. `kind` defaults
to `buffer` when omitted.
```yaml
bindings:
- { name: clouds, kind: storage3d, format: rgba16f } # texture_storage_3d<rgba16float, write>
- { name: occupancy, kind: texture3d } # texture_3d<f32>
- { name: smp, kind: sampler } # sampler
- { name: out_tex, kind: storage2d, format: rgba16f } # texture_storage_2d<rgba16float, write>
- { name: U, kind: buffer, access: read, element: f32 } # var<storage, read> U: array<f32>
- { name: Uniforms, kind: buffer, access: read, element: VolumeUniforms, array: false } # var<storage, read> Uniforms: VolumeUniforms
params:
- { name: scale, type: float, default: 2.0 }
- { name: count, type: int, default: 0 }
```
| `kind` | extra keys | generated WGSL declaration |
|---|---|---|
| `buffer` (default) | `access: read \| read_write` (default `read_write`), `element: <wgsl type>` (default `f32`), `array: true \| false` (default `true`) | `var<storage, ACCESS> NAME: array<ELEMENT>;` (or `… NAME: ELEMENT;` when `array: false`) |
| `texture3d` | — | `var NAME: texture_3d<f32>;` |
| `texture2d` | `sample: float \| uint \| sint` (default `float`) | `var NAME: texture_2d<f32>;`, or `<u32>` / `<i32>` for the other classes |
| `texture_depth` | — | `var NAME: texture_depth_2d;` — the one sampled shape with no `sample:` of its own; a depth-aspect channel (`@scene.depth`) binds here, not through `texture2d` |
| `storage3d` | `format`, `access: write \| read \| read_write` (default `write`) | `var NAME: texture_storage_3d<FMT, ACCESS>;` |
| `storage2d` | `format`, `access: write \| read \| read_write` (default `write`) | `var NAME: texture_storage_2d<FMT, ACCESS>;` |
| `sampler` | `filter: linear \| nearest`, `mipmap: linear \| nearest`, `address` (or `addressU` / `addressV` / `addressW`): `clamp \| repeat \| mirror`, `anisotropy: 1..16` (with `filter` and `mipmap` linear), `compare: never \| less \| less-equal \| equal \| greater \| greater-equal \| not-equal \| always`; none stated is the engine's linear, clamped sampler | `var NAME: sampler;`, or `var NAME: sampler_comparison;` when it states `compare` (for `textureSampleCompare` on a `texture_depth`) |
| `textureCubeArray` | — | `var NAME: texture_cube_array<f32>;` — the environment cube array, bound to `@scene.environment` by a render feature's pass |
| `vertices` | `access: read \| read_write` (default `read_write`) | `var<storage, ACCESS> NAME: array<u32>;` plus the mesh's layout uniform and the `zeroVertex*` accessors |
| `acceleration_structure` | — | `var NAME: acceleration_structure;` (hardware ray tracing) |
- **Eight storage buffers per shader** — the WebGPU guarantee, and what the
engine asks every device for. `buffer` and `vertices` bindings spend that
budget; textures, samplers, storage textures and `params:` do not. An
`acceleration_structure` brings engine-owned buffers with it — **three** where
the device has hardware ray query (the tables `zeroHitSurface` / `zeroMaterial`
read) and **five** on the software backend (those, plus the scene triangles and
the hierarchy over them) — so a traced pass has three slots of its own on the
backend web users get. Over budget, the engine refuses the shader and logs
which buffers it declared.
- A `buffer` defaults to `array<ELEMENT>`. Set `array: false` for a single
NON-array storage buffer — a struct binding (e.g. `element: VolumeUniforms`,
`array: false` → `var<storage, read> NAME: VolumeUniforms;`). The struct
definition itself lives in `shader.wgsl`, not `bindings.yaml`.
- **A sampled texture binds under the class its FORMAT puts it in**, so
`sample` states that class and the generated `texture_2d<..>` matches it. An
integer channel — `@scene.material`, which is `Rgba8Uint` — is `uint`;
everything else is the `float` default. Bind an integer channel to a `float`
slot and the engine refuses the pass and names both classes, because the
device would otherwise reject the bind group and invalidate the pipeline.
- **A float texture binding filters where the shader samples it.** Each
`texture2d` / `texture3d` binding is laid out from what the shader does with
it: one the shader reads through a sampler (`textureSample*`,
`textureGather*`, in the entry point or any function it calls) is filterable,
and one it reads with `textureLoad` alone is unfilterable and takes every
float texture. `r32f`, `rg32f` and `rgba32f` filter only on a device that
grants 32-bit float filtering, which many mobile GPUs do not; there a pass or
dispatch binding one at a sampled binding is refused and logged, naming the
binding and the format. Read a 32-bit float texture with `textureLoad`, or
keep a texture the shader samples at `rgba16f`.
- A storage texture's `access` decides both the generated declaration and the
layout the engine registers, so the two always agree. It defaults to `write`,
the access every target grants every storage-compatible format. `read_write`
is granted on `r32f` and `r32u` alone; declaring it on any other format is refused at
the compile, with the reason on `compute.programState`. A pass that needs to
read a wider target reads it through a separate `texture3d` / `texture2d`
binding, or through a second storage binding declared `read`.
- `format` tags (storage textures): `r8`, `r16f`, `r32f`, `r32u`, `rg32f`,
`rgba8`, `rgba8u`, `rgba16f`, `rgba32f`. Storage textures only allow
storage-compatible formats (`r32f` / `r32u` / `rg32f` / `rgba8` / `rgba8u` /
`rgba16f` / `rgba32f`). `r32u` holds one unsigned 32-bit word a texel and
`rgba8u` four unsigned 8-bit lanes (the format `@scene.material` is kept in):
the shader loads and stores either as a `vec4<u32>`, and the texel is never
filtered, so a texture bound to a `texture2d` slot reads it with
`sample: uint`. `rg32f` holds two 32-bit floats a texel, each stored and
read back as written and never filtered.
- An `acceleration_structure` binding resolves to the scene acceleration
structure when the shader runs as a render-pass with ray tracing enabled
(`renderer.setRaytrace(true)`). Declaring one makes the engine emit the helper
functions the body can call:
`zeroTraceClosest(origin, dir, t_min, t_max) -> ZeroHit` (struct: `hit, t,
instance, primitive, bary, attr`, where `instance` is the hit object's render
slot), `zeroTraceAny(origin, dir, t_min, t_max) -> bool`
(terminate-on-first-hit over every traced surface, for occlusion rays),
`zeroTraceShadow(origin, dir, t_min, t_max) -> bool` (the same over the
surfaces that cast shadows, for a shadow ray toward a light: a surface with
`castsShadows = false` lets the light through), and
`zeroHitSurface(hit) -> ZeroSurface` (`normal, uv, material`) +
`zeroMaterial(index) -> ZeroMaterial` (`base_color, emissive, metallic,
roughness`) to shade what a hit landed on; its `base_color.rgb` is the
material's `base_color` times the mean colour of its `base_color_texture`. The same surface works on both backends — hardware
ray query and the software/compute path — so the shader doesn't branch on
`renderer.raytraceCapability()`. Both trace helpers pass through the
cut-away texels of an alpha-tested surface (a texel stays where
`base_color.a * base_color_texture.a` reaches the material's `alpha_cutoff`),
read from the engine-owned coverage texture `zeroHitCoverage` bound beside
the hit tables. Bind it from a render-pass, which is where
the scene acceleration structure exists.
`params:` declares scalar uniforms (`type: float | int`). When non-empty the
engine appends a `ZeroComputeParams` uniform as the trailing binding (read it in
WGSL as `params.<name>`) and tunes its values at runtime with
`shaderRef:setParam(prop, value)`.
## The kernel ABI: `columns`, counted and appended outputs, `specialize`, `determinism`
One shader asset can serve many shapes of data. `bindings.yaml` states the shape
with these extensions, and the engine's compile path lowers them to the plain
bindings and WGSL above (`modules/compute_abi`, whose README has the whole
surface):
```yaml
workgroup: 64 # the size the body declares (default 64)
bindings:
- { name: cols, kind: columns, access: read } # a table of columns in one binding
- { name: src, kind: buffer, access: read, element: T }
- { name: dst, kind: buffer, access: read_write, element: T, count: "len(src)" }
- { name: hits, kind: buffer, access: read_write, element: vec4<f32>, capacity: "n * 4", append: true }
specialize:
- { name: T, options: [f32, i32, vec2<f32>, vec3<f32>, vec4<f32>] }
- { name: FOLD, options: [add, min, max] }
- { name: BODY, kind: source, default: "0.0" } # text that replaces the identifier
determinism: exact # or float_order
```
- A `buffer` of a scalar or vector element gets `NAME_get(i)`, `NAME_len()` and
(unless `access: read`) `NAME_set(i, v)`. A `vec3` element is stored as a flat
scalar array, so a column of vec3 keeps its 12-byte stride. `zero_n()` is the
dispatch size.
- `columns` binds a table of columns (`compute_abi.table`) as one storage buffer;
`cols_f32(c, i, lane)`, `cols_vec3(c, i)` and the rest read it.
- `count` / `capacity` give the size, in elements, of an output the run
allocates. `append: true` adds a live counter binding, `NAME_count`, with
`NAME_store(slot, v)`, `NAME_set_count(n)` and, under `determinism: float_order`,
`NAME_append(v)`.
- `specialize` parameters are compile-time: type options become `alias NAME`,
named options become `const NAME` and `NAME_<option>`, `kind: source` text
replaces the identifier. Each specialization compiles once.
- `determinism: exact` refuses `NAME_append`: an exact output is written at ranks
the kernel computed.
Dispatch such a shader through its program:
```lua
local variant = shaderRef:program():variant({ specialize = { T = "vec3<f32>" } })
local run = variant:run({ n = 64, inputs = { src = srcBuffer } })
local values = require("@builtin::modules.compute_abi").read(run.outputs.dst.buffer)
```
`shaderRef:program()` answers the same program, with the variants it has lowered and compiled, for as long as
`shader.wgsl` and `bindings.yaml` hold the bytes they held when it was made. A write to either file, from any origin
(`vfs.contentVersion` moves), makes the next `program()` a new one, and a dispatch through it runs the new text. The
schema `getBindings()` answers is the one the program was made over.
## Writing a mesh's vertices — `kind: vertices`
A mesh's vertices are raw bytes on the GPU, and the engine stores a mesh in one
of two layouts: 92 bytes a vertex with every attribute a `f32`, or 32 bytes a
vertex with normals and tangents quantized to bytes and UVs to shorts. Which one
a mesh got depends on the mesh.
Declare `kind: vertices` and the shader is handed both the buffer and the layout
that mesh is in, plus accessors that address it:
```yaml
bindings:
- { name: verts, kind: vertices } # the mesh, writable
- { name: heights, kind: buffer, access: read, element: f32 }
params:
- { name: lift, type: float, default: 1.0 }
```
```wgsl
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
if (id.x >= zeroVertexCount()) { return; }
var p = zeroVertexPosition(id.x);
p.y = p.y + heights[id.x] * params.lift;
zeroSetVertexPosition(id.x, p);
zeroSetVertexNormal(id.x, vec3<f32>(0.0, 1.0, 0.0));
}
```
```lua
carve:dispatchOnVertices({ model = meshRef:handle().guid, buffers = { heights }, workgroups = { 64 } })
```
The accessors, over a binding declared `read_write`:
| read | write |
|---|---|
| `zeroVertexCount() -> u32` | — |
| `zeroVertexPosition(i) -> vec3<f32>` | `zeroSetVertexPosition(i, vec3<f32>)` |
| `zeroVertexNormal(i) -> vec3<f32>` | `zeroSetVertexNormal(i, vec3<f32>)` |
| `zeroVertexTangent(i) -> vec4<f32>` | `zeroSetVertexTangent(i, vec4<f32>)` |
| `zeroVertexUv(i) -> vec2<f32>` | `zeroSetVertexUv(i, vec2<f32>)` |
| `zeroVertexColor(i) -> vec4<f32>` | `zeroSetVertexColor(i, vec4<f32>)` |
| `zeroVertexNodeIndex(i) -> u32` | — |
| `zeroVertexWord(i, offset) -> u32` | — |
`access: read` gives you the readers only — a `var<storage, read>` binding
cannot be assigned to, so the writers are left out rather than handed to you
broken.
Once a pass has written a mesh's vertices, the engine bounds that mesh by what
the pass wrote: it reduces the vertices to an AABB every frame and culls against
that, so geometry a pass moves across the scene needs no oversized placeholder
to survive culling. `renderer.mesh.boundsSource(guid)` reports `"compute"` for
such a mesh and `"geometry"` for one still bounded by what it was created with.
A shader declares at most one `vertices` binding; the accessors are generated
for that mesh. It can be declared anywhere in the list — the mesh is bound by
the dispatch, and `buffers` fills the other storage slots in declaration order.
The tangent's `w` carries handedness, and quantized normals/tangents come back
in -1..1 while quantized UVs and colours come back in 0..1, so the values are
the same ones a surface shader sees whichever layout the mesh is in.
## shader.wgsl
Write only `@compute fn main` (and any helpers / `#include`s). The names declared
in `bindings.yaml` are in scope — `data`, `out_tex`, `params.scale`, … — with no
`@group`/`@binding` lines of your own.
```wgsl
// @domain: compute
// Bindings are declared in bindings.yaml — do NOT write @group/@binding here.
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
if (id.x < arrayLength(&data)) {
data[id.x] = data[id.x] * 2.0;
}
}
```
## Dispatch & runtime
Everything a compute shader does, it does through its reference:
| method | what it does |
|---|---|
| `ref:dispatch(opts)` | `{ buffers, workgroups, params? }` — bind one buffer per declared storage binding, in order |
| `ref:dispatchOnVertices(opts)` | `{ model, buffers?, workgroups, params? }` — bind the mesh `model` names to the `vertices` binding, `buffers` filling the rest |
| `ref:dispatchEx(opts)` | `{ resources, workgroups, params? }` — for shaders mixing textures, samplers and storage textures: one `{ kind, name }` per declared binding, in order; `params = { name = value }` gives the shader's `params:` fields values for this dispatch alone, as `ref:dispatch` takes them. Any other key is refused, naming it |
| `ref:setParam(prop, value)` | write one `params:` scalar uniform |
| `ref:createBuffer(name, opts)` | `{ type, len, usage? }` — a GPU buffer owned by this shader |
| `ref:buffer(name)` | the buffer this shader last made under `name` |
| `ref:getBindings()` | the parsed `bindings.yaml` schema, read and parsed again only after the file is written |
| `ref:getSource()` / `ref:setSource(wgsl)` | read / overwrite `shader.wgsl` |
| `ref:compile()` | compile now instead of on the first dispatch or the first frame a feature pass names it |
| `ref:withIncludes(replacements)` | `{ [module as the shader's WGSL includes it] = shaderModule }` — a program of this shader in which each named `#include` reaches the compiler as the module its value names; answers the key a render pass's `program` or a dispatch takes, compiled again under a new key when the shader, a replacement module or any module the program reaches through its includes is edited (`compute.programState(key)` reads where it stands) |
| `ref:status()` | what the engine did with this shader's dispatches, one record per target |
The `params:` uniform is engine-owned and takes no entry in `buffers` or
`resources`, and neither does a `vertices` binding's layout.
`setParam` writes the uniform every later dispatch reads. A dispatch that
passes `params = { name = value }` reads those values instead, in a copy of the
uniform only it binds, with every name it leaves out at the value the shader
holds — so one shader dispatched twice in a frame over different data reads
different values each time:
```lua
lift:dispatch({ buffers = { a }, workgroups = { 4 }, params = { height = 1.0 } })
lift:dispatch({ buffers = { b }, workgroups = { 4 }, params = { height = 3.0 } })
```
A name the shader does not declare fails that dispatch, and the failure names
what it does declare.
### `dispatchEx` resources
Each `resources` entry fills the binding at its position. Its `kind` says what
the resource is, in the words `bindings.yaml` uses, and the binding decides how
it is read. A slot takes the kind it is declared with; a `texture2d` slot also
reads a storage texture, a side of a history pair or the scene depth, and a
`storage2d` slot also writes this frame's side of a history pair:
| binding's `bindings.yaml` kind | `resources` entry | `name` |
|---|---|---|
| `buffer` | `{ kind = "buffer", name = buf }` | a buffer handle from `ref:createBuffer` |
| `texture3d` | `{ kind = "texture3d", name = vol }` | a 3D texture handle from `ref:createTexture3D` |
| `storage3d` | `{ kind = "storage3d", name = vol }` | a 3D texture handle from `ref:createTexture3D` made with `storage = true` |
| `storage2d` | `{ kind = "storage2d", name = target }` | a storage texture handle from `ref:createStorageTexture2D` |
| `storage2d` | `{ kind = "history_curr", name = history }` | a history pair from `ref:createTextureHistory`: this frame's side |
| `texture2d` | `{ kind = "texture2d", name = tex }` | a handle `ref:copyBufferToTexture` returns, a texture asset's guid once `texRef:handle()` has made it GPU-resident, or a `renderer.texture.create` handle: a render target a render feature draws into, or a texture made from pixels |
| `texture2d` | `{ kind = "storage2d", name = target }` | a storage texture handle, read as a texture |
| `texture2d` | `{ kind = "history_prev", name = history }` / `{ kind = "history_curr", name = history }` | a history pair: the previous frame's side or this frame's |
| `texture2d` | `{ kind = "scene_depth" }` | none: the frame's scene depth |
| `sampler` | `{ kind = "sampler", name = smp }` | a sampler handle from `ref:createSampler` |
A `dispatchEx` is recorded at the start of the frame, ahead of the frame's render
passes, so a render target it reads holds what the previous drawn frame's passes
wrote into it; a pass of a render feature reads what a `dispatchEx` of the same
frame wrote.
`texture3d` and `storage3d` name the same resource, a 3D texture, so either one
fills either slot. The engine's own spellings name the same resources and keep
working: `texture_3d` for `texture3d` and `storage3d`, `texture_2d` for
`texture2d`, and `storage_2d` for `storage2d`. Any other `kind` is refused at the
call, naming every kind it accepts. A `vertices` binding is filled by
`ref:dispatchOnVertices`, and `texture_depth`, `textureCubeArray` and
`acceleration_structure` bindings by a render feature's pass.
```lua
local march = asset.resolve("volume_march", "computeShader")
-- bindings.yaml: density (storage3d), out_tex (storage2d), U (buffer)
march:dispatchEx({
resources = {
{ kind = "storage3d", name = density },
{ kind = "storage2d", name = target },
{ kind = "buffer", name = uniforms },
},
workgroups = { 8, 8, 8 },
})
```
`workgroups` is `{ x, y, z }`, `{ x }`, or a bare `x`, and every dimension it
leaves out is 1. A zero in any dimension is refused: the dispatch is dropped and
recorded as a failure, so it surfaces in `ref:status()` and `compute.failing()`
with the reason. A count derived from how much data there is passes through
`math.max` first, so an empty set dispatches one workgroup rather than none:
```lua
carve:dispatch({ buffers = { heights }, workgroups = { math.max(1, math.ceil(#points / 64)) } })
```
### Buffers and readback (the CPU side)
A buffer is created through the shader that owns it and comes back as a handle.
Pass the handle to a dispatch — including another shader's — to bind it there:
```lua
local double = asset.resolve("@builtin::shaders.compute_double", "computeShader")
-- `type` is the element the shader declares, `len` how many of them.
local data = double:createBuffer("data", { type = "f32", len = 4, usage = { "readback" } })
data:write({ 1.0, 2.0, 3.0, 4.0 }) -- :writeU32 for integer words, :writeBytes for packed bytes
double:dispatch({ buffers = { data }, workgroups = { 1, 1, 1 } })
local pending = data:read() -- starts an async GPU->CPU readback
-- a frame or two later, drain it (nil until it has arrived):
local out = pending:result() -- :resultU32 / :resultBytes read the same bytes another way
data:destroy() -- free it when done
```
`type` is one of `"f32"`, `"vec3"`, `"vec4"`, `"quat"`, `"mat4"`, and `usage`
adds `"readback"`, `"vertex"`, `"index"` or `"indirect"` on top of the storage a
buffer always has. An `"indirect"` buffer holds a draw's arguments where the GPU
reads them, so a shader that compacts geometry writes the drawn count into the
same dispatch that produced it and a render feature's `kind = "draw"` pass
submits exactly that — the `renderFeature` asset type's README documents that
pass and the `storage.indirect` name it reads.
An `"indirect"` buffer also holds the three workgroup counts a compute pass
dispatches over: a render feature pass stating `dispatch = { indirect = buffer }`
runs the counts a pass before it wrote there (`renderFeature`'s README, "Compute
passes").
The handle's key is the shader's guid plus the name you gave it and
a serial, so two shaders that both want a buffer called `data` get one each —
and so do two callers asking this same shader for one. `ref:buffer(name)`
returns the last one made under that name, which is how two callers share one
on purpose.
A buffer that no shader computes — a vertex or index run that is only ever
drawn — is allocated straight from the primitive instead:
`substrate.createBuffer({ name = ..., type = ..., len = ..., kind = "gpu", usage = { "vertex" } })`.
The first dispatch of a shader compiles it, so the very first readback can still
reflect the un-run shader; dispatch again once it is compiled, or `ref:compile()`
to pre-warm. This create/write/dispatch/readback loop is the CPU side of the
resource model in `core/resource-model`.
### Is it compiled?
`ref:compile()` queues the compile; the pipeline is built on the render side
frames later, so that call cannot say whether it produced a program.
A shader whose program the engine holds (`ready`) or is building (`pending`),
compiled again while its `shader.wgsl`, its `bindings.yaml` and every module it
includes hold the content the program was made from, queues nothing and
leaves the program as it is; an edit to any of those files queues the compile
again. A shader that includes a module some code filed under a key of its own
(`shader.registerModule`; the engine's `zero::` names aside) queues the compile
each time, since no file says when that text changed. `compute.programState(ref)` is where that lands:
```lua
if compute.programState(carve) == "ready" then carve:dispatch(opts) end
local state, reason = compute.programState(carve)
if state == "failed" then print(reason) end
```
- `"absent"` — the engine holds nothing under this key and nothing is in
flight: never asked for, or released.
- `"pending"` — a compile was asked for and has not reached the device. A
recompile of a resident program reads pending too, because what it produces
is a different program from the one bound now — which is what makes this the
precondition to wait on after an edit.
- `"ready"` — compiled and resident, so a dispatch naming it binds it.
- `"failed"` — the most recent compile produced no program, and the second
return says why.
A dispatch issued while the program is `"pending"` is held behind the compile
and dropped if it never lands, so a readback taken before `"ready"` reports the
buffer as it was. Wait for `"ready"`, not for a count of frames.
### Did it run?
A dispatch is recorded into a command encoder frames after the call that asked
for it returned, so that call's `true` means "queued", not "ran". `ref:status()`
is where the outcome lands — one record per target, cumulative:
```lua
for _, d in ipairs(carve:status()) do
print(d.target, d.ok, d.dispatches, d.failures, d.lastError)
end
```
`target` is the mesh guid for a `dispatchOnVertices` and the buffers it bound
for a dispatch that writes only those, so two systems driving one shader over
their own buffers read as the two passes they are. `ok` is the most recent outcome; `lastError` says
why the last failure failed and is kept after a recovery. An empty result means
nothing has dispatched this shader at all. `compute.failing()` answers the same
question across every shader at once.
A failing dispatch also posts a notice, so a pass that stops running reports
itself rather than waiting to be found.
### Running one every frame
A `kind = "compute"` substrate job queues one dispatch per frame:
```lua
jobs.register({
phase = "main",
executor = {
kind = "compute",
shader = asset.resolve("carve", "computeShader"),
buffers = { "heights" },
workgroups = { 64 },
},
})
```
### Many dispatches as one call: compute lists
Work that issues many dispatches every frame (a solver's passes, the levels of a
pyramid, a chain of blurs) registers them once as a compute list and queues them
all with one call, so a frame pays for one call rather than one per dispatch:
```lua
local advect = asset.resolve("~.advect", "computeShader")
local project = asset.resolve("~.project", "computeShader")
local key = velA.key .. ":step" -- named from something this system owns
compute.list(key, {
{ write = params, values = { 0, 0, 0, 1 / 60 }, slots = { [4] = "dt" } },
{ program = advect, resources = {
{ kind = "texture3d", name = velA }, { kind = "sampler", name = smp },
{ kind = "storage3d", name = velB }, { kind = "buffer", name = params },
}, workgroups = { 16, 16, 16 } },
{ program = project, resources = {
{ kind = "texture3d", name = velB }, { kind = "storage3d", name = velA },
}, workgroups = { 16, 16, 16 }, slots = { strength = "strength" } },
})
-- every frame:
compute.runList(key, { dt = dt, strength = 0.5 })
```
An entry is a dispatch, binding `buffers` as `ref:dispatch` does or `resources`
as `ref:dispatchEx` does, or a buffer `write` (`offset` in 32-bit words,
`values` as f32, or u32 with `unsigned = true`). `slots` names the values a run
supplies: a `params:` name to a slot on a dispatch, a value's place (from 1) to
a slot on a write. `when = "<slot>"` leaves the entry out of a run that gives
that slot 0, so one list holds the variants a run picks between. Everything
else is fixed when the list is registered, so a list that alternates between two
textures (a ping-pong) is two lists, or one list whose two halves are guarded by
`when`. The entries run in the order the list states them, and runs in the order
they were queued: a write lands after the dispatches before it and ahead of the
ones after it, so a list may write a buffer between two dispatches that read it,
and two runs in one frame each read their own writes.
`compute.list` resolves every reference and handle when it is called and raises
on a malformed entry, naming it; `compute.runList` answers that the run was
queued, and `ref:status()` and `compute.failing()` say what each dispatch did.
Registering again under the same key replaces the list; `compute.dropList(key)`
forgets it when the system is torn down. `fluidSim` steps its whole solver this
way.
## Registration & hot reload
Writing `shader.wgsl` or `bindings.yaml` fires the `.computeShader` assetType's
`onChange`, which compiles it: the binding declarations are generated,
`#include`s expanded, the WGSL validated, and the shader registered. This happens on
create and on every edit, so saving recompiles with no world reload. A shader
with invalid WGSL (a type mismatch, an undefined name) **fails to compile** with
the reason logged (`[compute] Compile of '<name>' failed: …`) and is **not**
registered. You don't need to register a shader before dispatching it — the first
dispatch auto-compiles it on use. `ref:compile()` remains as an optional explicit
pre-warm, only to avoid the one-frame first-dispatch warm-up in a
latency-critical spot.
## What compute is holding, and why a key names nothing
Every buffer, volume, storage target, history pair and sampler a dispatch can
bind is filed under a key, and `compute.observe()` lists all of them with what
each costs:
```lua
local r = compute.observe()
print(r.totals.count, r.totals.bytes)
for _, res in ipairs(r.resources) do
print(res.key, res.kind, res.bytes, res.owner.name)
end
```
A row carries the key verbatim — the same string a dispatch names it by and a
dispatch-failure message prints — plus its `kind`, its `bytes`, its extent and
`format` where it has them, the `usage` bits it was created with, and the frame
it was created on. `owner` is read back out of the key
(`<shader-guid>::<name>#<serial>`), so a resource nothing has ever dispatched
over still names the shader that made it. `compute.resources(ref)` narrows to
one shader's — including the `<shader-guid>::__params` uniform the compile
created for a `params:` block, which the shader owns like any other resource.
`r.totals.bytes` is the `compute` figure of `renderer.gpuMemory()` — the two are
read off the same registries, so a listing accounts for the category exactly.
The same reading is served at `/zero/runtime/compute`.
When a key names nothing, `compute.diagnose(key)` says which of the states the
inventory distinguishes it is in, from the closed set `compute.absentReasons()`
enumerates:
| reason | what the inventory read |
|---|---|
| `resident` | a resource is filed under exactly this key; the row is on `resource` |
| `replaced` | the owner holds the same name at a different serial — `current` names the live key |
| `nameUnused` | the owner holds resources, none under this name |
| `ownerAbsent` | no live resource carries this key's owner |
| `unowned` | the key carries no owner segment, and nothing is filed under it |
| `notPublished` | no renderer has published an inventory, so no key can be answered for |
So a key out of `[compute] dispatch '…' failed` resolves against what exists,
and a typo reports which part of it the engine could not match rather than
coming back empty.
A reason is the inventory at the moment the call read it. The reading is
republished on a frame where a registry gained or lost an entry, so a resource
created and diagnosed inside one script sees the reading from before it was
made; wait a frame and ask again.
## Discovery
- `asset.list("computeShader")` — every registered compute shader.
- `asset.inspect("<name>")` — status, source, parse errors, this README.
- `computeRef:getBindings()` — the parsed `bindings.yaml` schema
(`{ bindings, params }`).
- `compute.programState(ref)` — whether the program is compiled, still
compiling, or failed, and why.
- `compute.observe()` — every GPU resource compute holds, and what it costs.
- `compute.diagnose(key)` — whether a key names a live resource, and why not.
- `profiler.gpuFrame()` — what each dispatch of this shader spends on the GPU.
A dispatch is timed under `compute.<identity>` — the same identity
`asset.resolve` takes, so a timing row names the shader that produced it.
## Common pitfalls
- **Compute shaders don't render** — verify output via a buffer readback or a
debug pass, not a screenshot.
- **`ref:compile()` returns before the program exists** — the pipeline is
built on the render side; `compute.programState(ref)` says when it is
`"ready"`. A dispatch issued before that is held behind the compile and
dropped only if the compile never lands.
- **A dispatch call returning true means queued** — ask `ref:status()` whether
it ran.
- **A destroyed buffer is refused where it is bound** — a handle outlives its
storage, and `buf:alive()` reports which.
- **Binding order is the contract** — `buffers` and `resources` bind in
`bindings:` list order; reordering the list reorders the bindings.
- **Don't write `@group`/`@binding` in `shader.wgsl`** — the engine owns them;
re-declaring is the fastest way to a layout mismatch.
- **Don't infer a mesh's vertex stride** — declare `kind: vertices` and use the
accessors. A wrong stride writes positions correctly and normals into the
wrong word, which renders as flat lighting rather than as broken geometry.
- **Storage-texture format must be storage-compatible** — `r32f` / `r32u` / `rg32f` /
`rgba8` / `rgba8u` / `rgba16f` / `rgba32f`; others are rejected at compile.
- **A key that comes back empty is not the same as one that failed** —
`compute.diagnose(key)` separates a name never used from a generation that
was replaced, and names the live key in the second case.
## Related types
- `.shader`: render-domain shaders (surface, sky, post-process, screen).
## In the Inspector
Selecting a compute shader opens its **Compute** section: whether its program is ready (and why not), how many dispatches it has run and failed in this session (and the last error), tables of the bindings and params its `bindings.yaml` declares, and openers for `shader.wgsl` and `bindings.yaml`.
# transform
Math helpers for positions, rotations, and directions on transforms.
Exposed as the global `Transform` table via `--!global Transform` — no
explicit require needed in user code. Functions that take an entity
accept either an entity ID string or an entity proxy table from
`entity("id")`.
## Exports
Look-at and entity-aware helpers:
- `Transform.lookAtQuat(fx, fy, fz, tx, ty, tz) -> (qx?, qy?, qz?, qw?)` — quaternion from origin toward target. Nil when degenerate.
- `Transform.lookAt(entity, txOrTarget, ty?, tz?) -> (boolean, string?)` — make an
entity face a world position or another entity. Both slots read world space:
the subject and an entity target are read as `entity(id).position` and the aim
is written as `entity(id).rotation`, so a parent under either one still leaves
the aim on the point named. Returns whether the rotation was written, and the
reason when it was not.
- `Transform.distance(x1, y1, z1, x2, y2, z2) -> number` — Euclidean distance between two points.
- `Transform.distanceBetween(entityA, entityB) -> number?` — distance between two entities' world positions. Nil when either is unresolvable.
- `Transform.direction(fromX, fromY, fromZ, toX, toY, toZ) -> (dx, dy, dz)` — unit direction vector.
- `Transform.directionBetween(entityA, entityB) -> (dx, dy, dz)` — unit world-space direction between two entities' world positions.
Rotation shapes:
A quaternion **constructor** here returns the four components as four separate
values, so a caller either names them or braces the call to make one table:
```lua
local qx, qy, qz, qw = Transform.quatFromAxisAngle(0, 1, 0, math.rad(90))
entity("cam").localRotation = { Transform.quatFromAxisAngle(0, 1, 0, math.rad(90)) }
```
A rotation-taking **surface** reads that table through
`Transform.toQuaternion`, which also takes euler DEGREES — so
`{ qx, qy, qz, qw }`, `{ x =, y =, z =, w = }`, `{ pitch, yaw, roll }` and
`{ pitch =, yaw =, roll = }` all mean the same thing wherever a rotation is
assigned: `entity(id).rotation` / `.localRotation`, `entityOps.spawn`,
`entityOps.transform`, and the capture viewpoints.
- `Transform.toQuaternion(rotation, label?) -> { qx, qy, qz, qw }` — the shared reading of a rotation a caller wrote. Raises when the value matches no form, naming what arrived; a value that is one of the shapes a quaternion helper returns is named as such along with the packing it goes in as.
- `Transform.tryQuaternion(rotation, label?) -> ({ qx, qy, qz, qw } | nil, message?)` — the same reading without raising, for a surface that wants to raise the message at its own caller's line.
- `Transform.readVec3(value, label?) -> { x, y, z }` — the same for a vector.
- `Transform.snapVec3(v, step) -> { x, y, z }` — quantize a vector to a step grid.
Quaternion construction / conversion:
- `Transform.quatFromYaw(yaw)`, `Transform.quatFromYawPitch(yaw, pitch)`, `Transform.quatFromAxisAngle(ax, ay, az, angle)` — quaternion constructors.
- `Transform.quatIdentity()` — identity quaternion.
- `Transform.euler(qx, qy, qz, qw) -> (yaw, pitch, roll)` and the named alias `Transform.quatToEuler`.
- `Transform.eulerToQuat(yaw, pitch?, roll?)` — euler-to-quaternion in YXZ order.
Lerps and interpolation:
- `Transform.lerp(ax, ay, az, bx, by, bz, t) -> (x, y, z)` — vec3 lerp.
- `Transform.lerp1(a, b, t) -> number` — scalar lerp.
- `Transform.normalizeAngle(a) -> number` — wrap angle into `[-pi, pi]`.
- `Transform.lerpAngle(a, b, t) -> number` — shortest-arc angle lerp.
- `Transform.slerp(ax, ay, az, aw, bx, by, bz, bw, t) -> (qx, qy, qz, qw)` — quaternion slerp with shortest-path and near-parallel fallback.
Quaternion operations:
- `Transform.quatMul(...) -> (qx, qy, qz, qw)` — `qa * qb` composition.
- `Transform.quatInverse(qx, qy, qz, qw) -> (qx, qy, qz, qw)` — inverse (= conjugate for unit quats).
- `Transform.quatRotateVec(qx, qy, qz, qw, vx, vy, vz) -> (x, y, z)` — rotate a vec3 by a quaternion.
Pose helpers:
- `Transform.orbit(centerX, centerY, centerZ, radius, height, angle) -> (x, y, z, qx, qy, qz, qw)` — orbital pose facing the center.
- `Transform.worldToLocal(...)` / `Transform.localToWorld(...)` — pose-space conversions.
Nested `Transform.vec.*` namespace (component-wise vec3):
- `Transform.vec.add`, `sub`, `scale`, `dot`, `cross`, `length`, `normalize`.
Types:
- `Vec3 = { x: number, y: number, z: number }`
- `EntityRef = string | { entityId: string }`
## Usage
```luau
-- Look-at by coordinates or by target entity:
Transform.lookAt("cam", 0, 1, 0)
-- an entity target resolves to that entity's world position
local aimed, why = Transform.lookAt("cam", "box")
-- Orbit pose around a point:
local x, y, z, qx, qy, qz, qw = Transform.orbit(0, 1, 0, 5, 2, t)
entity.find("cam").localPosition = { x, y, z }
entity.find("cam").localRotation = { qx, qy, qz, qw }
-- Quaternion math:
local qx, qy, qz, qw = Transform.quatFromYawPitch(math.pi / 4, 0)
local sx, sy, sz, sw = Transform.slerp(0, 0, 0, 1, qx, qy, qz, qw, 0.5)
-- Component-wise vec3 helpers:
local nx, ny, nz = Transform.vec.normalize(1, 1, 0)
```
## Notes
- The `--!global Transform` directive promotes the module's typed
functions onto the runtime universe's globals bucket, so `Transform.*`
is available without any per-source `require`.
- Entity-aware functions (`lookAt`, `distanceBetween`,
`directionBetween`) report a missing entity or a missing transform in
their return value rather than raising: `lookAt` answers
`false, "unresolved"` / `"no-transform"` / `"incomplete-target"` /
`"degenerate"`, `distanceBetween` answers `nil`, and
`directionBetween` answers zeros.
- Quaternion APIs operate on raw `(qx, qy, qz, qw)` tuples for parity
with the entity proxy's `localRotation.get`/`set`. Use
`Transform.quatIdentity()` rather than hand-rolling `(0, 0, 0, 1)`.
- `Transform.slerp` flips the second quaternion if `dot < 0` to take
the shortest path, and falls back to lerp+normalize when the inputs
are within `dot > 0.9995` to avoid `1/0` near-parallel issues.
# vfs Module
Public Luau surface over the `__vfs` Internal FFI namespace — the
engine's virtual filesystem.
## Purpose
Wrap the raw `__vfs.*` FFI namespace in a typed Luau table that gets
auto-injected as `_G.vfs` via the prelude. The standard read / write /
move / remove / mkdir / list / exists / readAsync / reload / evict
surface, plus trusted-only `watch` / `unwatch` for the bootstrap VM.
`vfs.read` yields on a byte-cache miss: the module's last step installs
the `vfs_async_read` fallback over the synchronous read, so every VM that
holds this namespace, the trusted VM included, reads a path through the
same two steps and gets the same bytes for it.
## Usage
```luau
-- Read / write
local src = vfs.read("/zero/source/libs/@builtin/components/Camera.component/init.luau")
vfs.write("/zero/source/notes.md", body)
-- What a write landed: where the bytes went, and what the static passes
-- read in the Luau among them
local ok, report = vfs.write("/zero/source/game/Vent.component/init.luau", code)
if report.diagnostics then
for _, d in report.diagnostics do
print(d.severity, d.path, d.line, d.message)
end
end
if not report.durable then
log.warn(report.warning)
end
-- Listing
for _, e in ipairs(vfs.list("/zero/source")) do
print(e.isDirectory and "[d] " or " ", e.name)
end
-- Async fetch
local png = task.await(vfs.readAsync("/zero/runtime/screenshots/last.png"))
-- Reclaim RAM after processing a big binary
vfs.evict("/zero/source/textures/imported_huge.png")
-- Reload a module after editing its source on disk
if vfs.reload("@builtin::modules.json") then
local m = require("@builtin::modules.json") -- sees the new source
end
```
`vfs.reload(identity)` answers whether a module was cached under that name
and has now been dropped. A `false` says the name matched nothing — either a
misspelled identity or a module this VM never required — so the next
`require()` returns whatever it would have returned anyway.
A module that caches state derived from OTHER files keeps serving the old
value when those files are rewritten, since only its own source is watched.
Reload it by identity to make the next `require()` recompute.
## How a write reaches disk
A native engine's `vfs.write` returns once the engine holds the bytes and the
session's journal holds the record of the write, its bytes with it. The record
is in the operating system's hands before the call returns, so an engine
process that ends right after a write, however it ends, leaves the write for
the next session on the same machine to owe and make again. The blob a binary
write stores by content is written and flushed by a worker thread (`vfs-io`) in
the order the writes were made, so a script that writes a thousand files pays
for handing them over and for their journal records, not for the flush of
each. A read of a blob still waiting for its file answers from memory, so a
write reads back the moment it returns. A queue holding more than its byte
budget (256 MiB) makes the next write wait for it and write inline, which
bounds the memory the queue pins. The queue is flushed when the engine exits
normally. `world.syncStatus()` reports nothing owed once the writes have also
reached the world.
## Exports
- `vfs.read(path, opts?) -> string?`
- `vfs.write(path, content, opts?) -> (boolean, WriteReport | string)`
- `vfs.move(src, dst, opts?) -> (boolean, WriteReport | string)`
- `vfs.copy(src, dst) -> (boolean, WriteReport | string)`
- `vfs.remove(path, opts?) -> (boolean, string?)`
- `vfs.mkdir(path, opts?) -> boolean`
- `vfs.list(path?) -> { VfsListEntry }`
- `vfs.exists(path, opts?) -> boolean`
- `vfs.readAsync(path, opts?) -> promiseId`
- `vfs.reload(modulePath?) -> boolean`
- `vfs.evict(path, opts?) -> boolean`
- `vfs.mutationSeq() -> number`
- `vfs.contentClock() -> number`
- Trusted-only: `vfs.watch(path, callback) -> number` /
`vfs.unwatch(watcherId) -> boolean`.
# luau_introspect (module)
Parses Luau/asset source TEXT into structured declarations. Pure
string/pattern parsing (`string.find` / `string.match` / `string.gmatch`)
over the literal source — no compiling, no VM spawn, no runtime state, no
engine FFI. Given source text, it extracts what is written in the file.
This is the shared parser every per-assetType `M.ref.inspect` hook uses to
turn a component/module/tool's own source into the structured record
`asset.inspect` returns.
## Exports
- `docstrings(src) -> DocMap` — scans `--!desc` / `--!arg` / `--!return` /
`--!example` comment runs and binds each run to the name of the
declaration on the next non-comment line (the identifier after
`function`, `public:`, `local function`, or `M.`).
- `publicFields(src) -> { FieldEntry }` — parses `public = { name =
Field.<kind>(default, mode), ... }` table-literal entries and
module-scope `public.<name> = Field.<kind>(...)` assignments.
- `events(src) -> { EventEntry }` — parses `events = { name =
Event(payloadSchema?, syncMode?), ... }` table-literal entries.
- `methods(src) -> { MethodEntry }` — parses `function public:<name>(...)`
/ `typed function public:<name>(...)` declarations (params + optional
return type).
- `lifecycleHooks(src, catalog) -> { string }` — top-level `function
<name>(` declarations whose name is in the caller-supplied `catalog`
array.
- `moduleExports(src) -> { ExportEntry }` — parses `M.<name> = function`
assignments, `function M.<name>(...)` declarations, and a trailing
`return { foo = foo, ... }` export table.
- `forSource(src, computeFn) -> any` — memoises `computeFn(src)` keyed on
`src` itself in a module-local table. The same source text returns the
cached result without re-running `computeFn`; different source text
recomputes. Keyed on the source content (not an asset checksum) because
composite/container assets (component folders, scene folders, etc.) all
hash to the empty-string checksum — a checksum-keyed cache collapses
every such asset's detail onto whichever one was inspected first.
## Usage
```luau
local Introspect = require("modules.luau_introspect")
local src = self:getInitScript()
local detail = Introspect.forSource(src, function(s)
return {
fields = Introspect.publicFields(s),
events = Introspect.events(s),
methods = Introspect.methods(s),
hooks = Introspect.lifecycleHooks(s, lifecycleCatalog),
}
end)
```
## Notes
- Every function is a pure string→table transform: same source text in,
same structured table out, every time. No reads of live component
state, no entity/world queries.
- Structural scanning runs over a comment- and string-aware **mask** of
the source (a same-length copy where comment bodies and string-literal
contents are blanked to spaces, delimiters and newlines preserved).
Pattern matches and brace/paren balancing run on the mask — so a brace,
`Field.`, `Event(`, or a whole entry that appears inside a comment or a
string literal never registers — while captured values are sliced from
the original source at the same (aligned) indices. This makes the
parser robust to apostrophes in comments, commented-out entries, string
defaults containing `}` / `Field.` / `Event(`, and `[[ ]]` long
strings.
- `default` / `category` are raw trimmed source-text slices (with any
trailing comment stripped), not evaluated values.
- For a **ref constructor** (`Field.assetRef` / `dataRef` / `resource`
/ `componentRef`) the FIRST positional argument is the category /
contract / componentType selector, captured under `category`; the
SECOND argument is captured under `default`.
- For every **other** Field kind the first argument is the `default`
and `category` is nil.
- A trailing `Sync` / `NoSync` identifier is captured as `sync`,
tolerating a trailing comma or a trailing comment after the last
argument.
- Field/Event entries whose key is a computed or indirect expression
(`[expr] = Field.number(...)`) are omitted — only literal identifier
keys are recognised.
- `methods` captures a `...` variadic parameter (as `name = "..."`), with
its `: <type>` annotation when present.
- A `--!desc` written above a field/event declaration (`<name> =
Field.<kind>(...)` / `<name> = Event(...)`) or a `public.<name> =`
assignment binds to that name in `docstrings`, and is folded into the
corresponding `publicFields` / `events` entry's `desc`.
- `lifecycleHooks` never hardcodes the lifecycle-callback catalog; the
caller passes the list of names to match against.
- `forSource`'s memo is bounded (oldest-key eviction) so a long session
touching many distinct asset versions can't grow it without limit.
# assetType.shared.ref
Builds the metatable every `AssetRef` (the `{ __ref, type, name, guid, identity, path }` envelope returned by `asset.resolve` / `asset.ref`) carries: the default methods every ref answers and the per-type behaviour its asset type defines.
## Public API
```lua
local assetRef = require("@builtin::assetTypes.assetType.shared.ref")
-- Called by the Rust factory (push_asset_ref_handle) via
-- _G.__build_asset_ref_proxy after the envelope fields are set.
assetRef.build(envelope) -- attaches AssetRefMT, returns the table
```
The module exposes no invalidation surface — discovery is registry-driven and hot-reload is transparent (see "Discovery and hot-reload" below).
## Method dispatch order
`ref.foo` is resolved in this order:
1. **Default methods** — `getSource` / `getBytes` / `getText` / `exists` / `inspect` and the lazy `meta` property. Per-type definitions cannot override these (an engine contract).
2. **Per-type `ref` table** — discovered through `asset.resolve(<typename>, "assetType")` + `require(<identity>.behavior)`. The lookup resolves to whichever `<typename>.assetType/` folder is currently registered for the typename (built-in, user, or library-vendored) and pulls its `ref` methods.
3. **Nil** — unknown key, same shape as the original C metatable.
## Adding methods for a new asset type
Drop a `behavior.luau` into the type folder:
```
assetTypes/<typename>.assetType/
├── type.yaml -- structural spec (existing)
├── behavior.luau -- ref + global behaviour (new)
└── template/ -- placeholder body (existing)
```
`behavior.luau` returns:
```lua
return {
ref = {
--!desc Per-instance method on every `<typename>` AssetRef.
myMethod = function(self, ...) ... end,
},
global = {
-- Reserved for the asset.<typename>.* surface — not consumed
-- yet; reserved for that surface.
},
}
```
Within `ref` methods, `self` is the AssetRef envelope: `self.path`, `self.identity`, `self.guid`, `self.type`, `self.name` are available. Engine-required fields (`guid`, `path`, `identity`, `type`) must not be redefined.
## Discovery and hot-reload
Type discovery uses the asset registry, so it doesn't matter where a `<typename>.assetType/` folder lives — engine built-ins under `@builtin::assetTypes.<X>`, user types dropped under `/zero/source/<X>.assetType/`, or types vendored inside an imported library all resolve identically. The dispatcher walks `asset.resolve(<typename>, "assetType")` → canonical identity → `require <identity>.behavior` on every miss; the asset registry is the cache for the resolve half and Luau's `_LOADED` is the cache for the require half.
Hot-reload is transparent. When a `<typename>.assetType/behavior.luau` is rewritten through VFS, the engine's `invalidate_require_cache_for_state` re-runs the module and mutates the cached `_LOADED[<identity>.behavior]` table in place. Dispatch reads `mod.ref` on every access (rather than caching a sub-pointer), so existing AssetRefs see the new methods on the very next access — no Rust-side hook into this module is needed, and no invalidation API is exposed for callers to call.
The same registry-driven path also handles type **registration** correctness: dropping a new `<typename>.assetType/behavior.luau` updates the asset registry, the next `asset.resolve(<typename>, "assetType")` returns the new ref, and AssetRefs of that type immediately gain the new methods.
## Why Luau, not Rust
The asset surface needed per-category behaviour (`material:getProperties()`, `bundle:instantiate(entityId)`, `tool:run(args)`) and the old shape couldn't grow without an FFI change per method. Owning the proxy in Luau means:
- Type-specific methods ship as content (the `<typename>.assetType/` folder), not engine code.
- Adding a new asset type drops in a new folder; no Rust rebuild.
- Methods can call any other Luau global (`vfs`, `asset`, `Material`, `entity`, etc.) directly, instead of going through narrow FFI primitives.
## Consumers
- The engine's asset bindings — the factory that pushes envelopes invokes `_G.__build_asset_ref_proxy` once per push.
- Every Luau call site of `asset.resolve` / `asset.ref` / `entity(id).component.X.material` / any binding declared `AssetRef<...>` — they all receive envelopes built through this module.
# i18n
The player's language: which of a world's languages to show them, the
languages their platform says they read, the locale the engine chose for its
own text, the locales the engine offers, their own choice, and a signal when
any of it changes. The same `i18n` global in every VM.
```lua
local lang = i18n.pick({ "en", "pt", "es" }) -- "pt" for a Brazilian player
i18n.emulate({ "es-MX" }) -- try the world as a Mexican visitor; nil puts this machine's back
print(i18n.locale()) -- "en"
print(i18n.preferred()[1]) -- "pt-BR" on a device set to Portuguese (Brazil)
for _, l in i18n.offered() do print(l.tag, l.nativeName) end
local r = i18n.choose("pt-BR") -- refused unless pt-BR is offered
if not r.ok then log.warn(r.reason) end
local id = i18n.onChange(function(locale, preferred)
log.info(("now %s; platform %s"):format(locale, table.concat(preferred, ",")))
end)
i18n.offChange(id)
```
## How the locale is chosen
One chain, the first link that matches an offered locale deciding:
1. the player's choice (`i18n.choose`), kept on the device for their ZeroMind
account, or for the signed-out player;
2. the language ZeroMind shows the player (the `zeromindLocale` boot argument
ZeroMind's page passes, or the desktop `--zeromind-locale`), and the one
the page names when its reader picks another language while the browser
engine runs;
3. the platform's preferred languages, most preferred first;
4. `en`, the engine's source language.
A link matches an offered locale with the same tag, then one its tag
truncates to (`pt-BR-x-abc` to `pt-BR`), then one with the same language
(`pt` to `pt-BR`). The engine offers a locale once its manifest is launched,
and it offers `en` and `pt-BR`; a player none of whose links matches either
gets `en`. `i18n.sources()` names every link and the one that decided.
The chosen locale is also the one the engine names to ZeroMind on its requests
(`x-zeromind-locale`) and the one the text system picks fallback fonts for.
## API
- `i18n.pick(available) -> string`: which of the content's languages the
player reads (the first of `available` when none matches).
- `i18n.emulate(tags?) -> { ok, locale?, platform?, reason? }`: stand a
visitor's language list in; nil reads the platform's own again.
- `i18n.locale() -> string`: the chosen locale.
- `i18n.fallback() -> {string}`: the chosen locale's fallback chain.
- `i18n.preferred() -> {string}`: the platform's preferred languages.
- `i18n.offered() -> {Locale}`: `{ tag, name, nativeName, fallback }` per
offered locale.
- `i18n.choice() -> string?`: the player's own choice.
- `i18n.choose(tag?) -> { ok, locale?, decidedBy?, reason?, offered? }`:
choose, or clear with nil.
- `i18n.sources() -> Sources`: `{ locale, decidedBy, matched, choice,
zeromind, platform, signedIn, choiceKept }`; `choiceKept` is `device`, or
`run` in an offline engine, which keeps a choice for that run alone.
- `i18n.onChange(fn(locale, preferred)) -> id` / `i18n.offChange(id)`.
## Where the platform list comes from
| platform | source | changes reach the engine |
|----------|--------|--------------------------|
| Linux | `LANGUAGE`, `LC_ALL`, `LC_MESSAGES`, `LANG` | at boot |
| Windows, macOS | the user's language list | at boot and when the window regains focus |
| browser | `navigator.languages` | on `languagechange` |
| Android | the activity's configuration locales (the per-app language when set) | on the configuration change, without restarting the app |
# yaml.module
YAML decode + encode for authored engine content. Pure Luau, no engine
dependencies — a general parsing library, not data-system plumbing.
```luau
local Yaml = require("@builtin::modules.yaml")
local doc = Yaml.decode(vfs.read(path))
vfs.write(path, Yaml.encode(doc))
```
## Supported subset
- Block mappings (`key: value`) and block sequences (`- item`), nested
to any depth.
- Compact sequence-of-mapping entries (`- path: x` / ` kind: y`).
- Flow collections — `{ a: 1, b: 2 }` and `[1, 2, 3]` — single line.
- Plain scalars with type inference: `~` / `null` → nil, `true` /
`false` → boolean, numeric literals → number, everything else →
string.
- Single- and double-quoted strings (`''` escapes a literal quote
inside a single-quoted string; `\n` `\t` `\r` `\\` `\"` inside a
double-quoted one). A quote opens a quoted scalar where a scalar
begins — after `key:`, after a `- ` entry marker, or inside a flow
collection — so a plain scalar carries an apostrophe as data
(`note: the world's rules`). Quoted keys are read in flow mappings.
- `#` comments — honored outside quotes, so a `#` inside a quoted
string is kept as data.
- Literal (`|`) and folded (`>`) block scalars, with a chomping
indicator (`-` strips the final newline, `+` keeps every trailing
blank line, none keeps one newline) and an indentation indicator
(`1`-`9`: the content's indent past the parent's), in either order
(`|-`, `>+`, `|2`, `>1-`). A block scalar's content is literal text:
quotes (balanced or not), `#`, `key: value` and `---` inside it are
data.
- An optional leading `---` document marker.
## Loud-error contract
Constructs outside the subset above raise instead of misparsing:
anchors/aliases (`&`, `*`), tags (`!`), directives (`%`),
multi-document streams (a second `---`), a block-scalar header
it cannot read (`|x`, `|-+`, `|0`), tab indentation, and inconsistent indentation (both block structure and
block-scalar bodies). Every error carries the offending line number
(`yaml: line N: ...`), so a bad config points straight at the line to
fix.
Tab indentation is rejected everywhere — including block-scalar body
lines whose leading whitespace contains a tab. A tab after the first
non-space character of a line is content and passes through.
## API
- `Yaml.decode(text: string): any` — decode a YAML document into a
Luau value (table, scalar, or nil for an empty document). Raises on
malformed input or an unsupported construct.
- `Yaml.decodeWithComments(text: string): (any, boolean)` — decode as
`decode` does, and report whether the text carries a comment by the
decoder's own rule: a `#` at a line's start or after whitespace, outside
a quoted scalar and outside a block scalar. Re-encoding the value drops
such comments, so an editor that writes a document back reads this first.
- `Yaml.stripComment(line: string): string` — one line of YAML text less
its comment and the spaces before it, by the same rule. A reader that
takes a document apart line by line reads each line through it, so
`roughness: 0.5 # polished` reads as `roughness: 0.5`.
- `Yaml.encode(value: table): string` — encode a Luau table as YAML
(block style, two-space indent, alphabetically sorted keys). Raises
on values YAML can't represent (functions, userdata, non-string
mapping keys).
A top-level empty table encodes to an empty document, which decodes
back to `nil` (the YAML empty-document ambiguity).
# json
JSON encode/decode library for Luau. Encodes Lua values to JSON
strings and decodes JSON strings back to Lua values. Used for
communication with the Rust side of the engine, the VFS read/write
bridge, and any wire-format that needs JSON.
Pure Luau, no engine dependencies. Compact and pretty-printed
encoders, plus a hand-rolled decoder that streams the input by position
so it works under WASM as well as native.
## Exports
- `Json.encode(value: any, indent?: string, currentIndent?: string) -> string` — compact encode. Functions / unknown types and NaN/Inf encode as `null`.
- `Json.encodePretty(value: any, indentStr?: string) -> string` — pretty-printed encode with sorted object keys (diff-friendly).
- `Json.encodeArgs(...: any) -> string` — encode varargs as a JSON array.
- `Json.null` — the value that stands for JSON `null` inside a table. A key set to nil is left out of the encoded object; a key set to `Json.null` is written `"key":null`, which is how a request names a field it clears. `decode` answers `null` as nil.
- `Json.decode(str: string) -> any` — decode a JSON string. Returns the decoded value, or `nil` + error message on failure. The string is one JSON value with optional whitespace around it; anything else after the value is a failure naming the character and its position.
## Usage
```luau
local Json = require("@builtin::modules.json")
local widget = { type = "button", text = "Click Me" }
local compact = Json.encode(widget) -- '{"text":"Click Me","type":"button"}'
local pretty = Json.encodePretty(widget, " ")
local decoded = Json.decode(compact)
local v, err = Json.decode("oops") -- v = nil, err = error message
```
## Notes
- Object keys are sorted alphabetically in both encoders for consistent
output across runs.
- Numeric keys on objects are stringified at encode time (JSON has no
numeric keys). Pure-integer key sets get detected as arrays via
`isArray` and encoded with brackets.
- NaN, +Inf, -Inf encode as `null` — JSON has no representation. Round
trips through `decode` recover `null` (Lua `nil`), so they don't
preserve.
- Unicode `\uXXXX` escapes decode to UTF-8 by hand to stay WASM-safe.
Only the BMP is covered; supplementary planes via surrogate pairs
are not.
- Functions encode as `null`.
- Decode is character-streamed — no regex, no `string.match` patterns
on the whole input — so the line-and-column information needs to be
reconstructed from the position offset.
# assetType runtime
The machinery that reads a `<typename>.assetType/behavior.luau` and turns its
declarations into live behaviour.
A `behavior.luau` is a table of declarations — `ref` methods, `modules` shared
code, an `events` schema, a `namePattern`, `refShapes`, and the `onCreate` /
`onRegister` / `onChange` / `onDelete` / `validate` / `settingsDefaults` /
`settingsCorrections` hooks. None of it runs itself. This is the code that
runs it, and it lives here because reading a type's declarations is the
**assetType type's own behaviour** — the same way `material.assetType` owns
what a `.material` does.
## Sub-modules
| Module | Reads | Responsibility |
|---|---|---|
| `ref.module` | `ref`, `modules` | Builds every `AssetRef` envelope, attaches the shared metatable, and dispatches per-type methods and shared modules onto it. Also owns edit-mode write-behind persistence. |
| `create.module` | `onCreate`, `namePattern`, `validate` | Backs `asset.create`: resolves the type, checks the name against its pattern, runs `onCreate` (or clones `template/`), and writes the instance. `validate.module` beside it checks a creation `opts` table against the type's `createSchema`. Before running `onCreate`, resolves the type's settings chain (below) and hands the result to the hook as `opts.settings`. |
| `settings.module` | `settings`, `settingsDefaults`, `settingsCorrections` | A type's declared settings schema and where its values live (`type.yaml`'s `settings:` block). `Settings.resolveForCreate` layers the schema's own defaults, the type's own `settingsDefaults(name, opts, asked)` hook (a DEFAULT the schema can't express — a name-derived convention, a fact read off a payload the caller handed it, a value following a field `asked` shows a higher layer naming; any later layer overrides it), the Preset Manager, an importer's settings, the caller's `settings` table, then the type's own `settingsCorrections(values, name, opts)` hook (a CROSS-FIELD CONSTRAINT the schema can't express, applied last over the fully merged values). A correction over a default/preset/importer value lands silently; a correction that would override what the caller's own `settings` table explicitly asked for refuses the creation instead, naming the field and why. Neither hook is ever handed a table to mutate; each returns what it wants changed (`settingsCorrections` may also return a `{ [field]: reason }` table for that refusal message). `Settings.cloneValues` deep-copies a values table — `create.module` hands `onCreate` a copy, never the table it stamps. `Settings.valuesOf` / `writeValues` read and write an asset's own values file. |
| `typeYaml.module` | `type.yaml` | The folder a type lives in and its parsed `type.yaml`, decoded once per content version of the file. `settings.module` and `inspector.module` read their blocks through it. `about` / `aboutAt` read a type's `about.yaml` (`intent`, `function`, `usage`), leaving out any key that is empty or still starts with `[[describe]]`; `aboutRows` and `aboutMarkdown` lay the texts out for the Inspector and the `types/<name>` guide. |
| `inspector.module` | `type.yaml`'s `inspector:` block | Which inspector a type declares for its assets (`inspector: { type: ... }` or `{ instance: ... }`), and the declaration that file returns — the sections it adds, the generic ones it replaces, and their order — or the problem that kept it from loading. |
| `onRegister.module` | `onRegister` | Fires an instance's once-only registration hook — on arrival, on world load, and for `@builtin` library instances. |
| `changeDispatch.module` | `onChange`, `onDelete`, `refShapes` | Routes a VFS source write or a folder delete to the enclosing typed asset's type hooks. |
| `refShapes.module` | `refShapes`, `ref` | Publishes what every `AssetRef<category>` answers to, so a member read on an asset-typed value is checked against that category's real surface. |
| `events.module` | `events` | The per-asset event runtime behind `ref.events`. |
| `instantiable.module` | `ref.instantiate` | The instantiation contract an asset type opts into: `root` stands the root entity, `place` applies the base placement opts to one the type adopted, and `result` shapes the `(root, idMap)` every `instantiate` returns. Also registers the `sceneInstantiable` field-constraint validator. |
| `interfaces.module` | `type.yaml` `interfaces:`, `interfaces`, `ref` | The interfaces a type implements: reads each `interface` asset, reads a type's marks from the references its `type.yaml` records under `interfaces`, runs every check and refusal of the declaration, and answers `implements`. |
| `declaration.module` | `type.yaml` | The type's decoded declaration, read once and held until a write inside an `.assetType` folder; what every question about a type as a whole reads. |
| `previewRecipe.module` | `type.yaml` `preview:` | How an instance's `preview.png` is produced: which of the four recipes (`instantiate`, `image`, `surface`, `custom`) the type declares, and what that recipe needs. |
## Reaching it
```luau
local rt = require("@builtin::assetTypes.assetType.shared")
rt.ref.loadTypeBehavior("material")
```
Fields resolve lazily. The prelude requires the sub-modules directly, in
dependency order (`ref`, then `changeDispatch`, `onRegister.install()`,
`refShapes.install()`) — a table that required all six on load would take that
ordering away from it.