# Buoyancy
Floats the entity's rigid body on the sea.
```lua
entity.find("barrel").component.add("Buoyancy", { density = 0.4 })
```
The entity needs a dynamic `Physics` body. Position and orientation stay the
physics world's — this component only adds the forces water exerts, so a
floating body still collides, still takes impulses, and still falls when it is
lifted clear of the water.
| Field | What it does |
|---|---|
| `density` | Relative to water: the lower it is the higher the hull rides, and a body denser than water sinks. A hull settles a little deeper than the number alone asks for, so trim it until the waterline sits where it should. 0 releases the body. |
| `damping` | How hard water resists the hull moving through it, as a fraction of the damping that settles it without overshoot. 1 is that critical value, 0 bobs indefinitely. Applied per column, so it steadies rolling as well as heaving. |
| `angularDamping` | The same, for a hull turning. The rigid body carries it as its own angular damping while the hull is in the water, and it is the only thing that damps a spin about the hull's own vertical axis, which the per-column damping cannot see. |
| `columns` | Grid resolution per horizontal axis over the footprint. 1 floats but cannot right itself; 2 is the smallest grid that produces a righting moment. |
| `sizeX`/`sizeY`/`sizeZ` | The box that displaces water, in the hull's own space. All three at 0 measures it from what the entity draws. |
`barrel:submersion()` reads how much of the hull was under water on the last
step, and `barrel:waterline()` reads the world Y the surface stood at under it,
wave motion included.
Forces reach a rigid body only while the scene is playing, so a hull sits where
it was placed in edit mode and settles onto the water when play starts.
# Ocean
Puts a live sea on an entity. The component's fields ARE the sea state — wind
speed and direction, choppiness, swell, foam, extent and detail — and the wave
simulation, the GPU surface mesh and the material bound to the simulation are
all rebuilt from them whenever the component wakes.
That rebuild is what makes the ocean persistable. The simulation lives entirely
in GPU buffers and a runtime mesh, none of which survive an engine restart; the
component's settings do, and the whole sea is reconstructed from them. A scene
with an ocean in it reloads into the same sea.
The surface follows the viewer and covers `extent` metres around them, so one
ocean is the whole sea however far anyone sails. `sampleHeight(x, z)` and
`sampleDisplacement(x, z)` report where the water is — the same waves that are
drawn — which is what a boat, a buoy or a swimmer floats on.
Start from a `preset` (`calmClear`, `darkChop`, `darkRolling`, `heavySwell`,
`whitecapped`, `murkyGrey`, `paleSwell`, `glassyDark` and `gale`) and override
whatever the scene needs. Wind speed does most of the work:
significant wave height goes as its square.
·computeshader · born here
❒asset # ocean_assemble
Unpacks one cascade's two transformed fields into the `(dx, height, dz)`
displacement field the surface mesh reads, applying the `(-1)^(x+z)` sign
alternation that undoes the centred-on-zero wave-vector grid the spectrum was
built on. Height and horizontal displacement carry independent gains, so crest
pinching (`choppiness`) can be dialled without changing wave height.
·computeshader · born here
❒asset # ocean_displace
Displaces the ocean surface mesh by one cascade, once per cascade per frame. The
first cascade writes each vertex from the rest position stored in its UV and the
rest accumulate onto it, so the mesh is rebuilt from a clean grid every frame
instead of drifting. Cascades are sampled at the vertex's true world position —
the mesh follows the camera, so its rest grid sits at a moving origin. The vertex
normal accumulates each cascade's surface gradient (the ratio `n.xz / n.y`),
which is how independent wave fields actually combine; per-fragment normal detail
comes from the cascade normal maps in the surface shader, since the mesh is far
too coarse near the horizon to carry it.
·computeshader · born here
❒asset # ocean_evolve
Advances one cascade's static spectrum to the current time — `h(k,t) = h0(k)
e^{iwt} + conj(h0(-k)) e^{-iwt}` at the deep-water dispersion `w = sqrt(g|k|)` —
and emits the two complex fields the inverse FFT consumes. The frequency is
quantised to a multiple of `2*pi / loop_period` so the whole sea state repeats
seamlessly instead of drifting as elapsed time grows. Field A packs the height
and X-displacement spectra into one complex field (`H + i Dx`), which the
Hermitian symmetry of both lets a single inverse transform separate again — two
FFTs per cascade instead of three.
·computeshader · born here
❒asset # ocean_fft
Transforms one axis of an ocean cascade's complex field in place, as one
dispatch per axis: a workgroup per line runs every Stockham auto-sort radix-2
butterfly stage against workgroup-shared memory, so a 256-wide transform costs
one dispatch rather than eight butterfly passes and needs no bit-reversal
permutation. Supports grids up to 512 per side. The axis, direction and scale
arrive through the bound `plan` buffer rather than a `params:` uniform, because
same-frame dispatches are chained into one submission and a uniform rewritten
between them would not be seen per-dispatch.
·computeshader · born here
❒asset # ocean_floor_displace
Raises the seabed's flat grid into terrain: one gradient-noise field over world
XZ, written into each vertex's height, with the analytic slope written into its
normal.
Runs when the mesh recentres rather than every frame. The terrain is still in
the world; only the grid under it moves.
It is a compute pass rather than the surface shader's `vertex()` hook so that
every pass that draws the mesh, and everything that reads its vertex buffer,
meets the same displaced geometry.
The normal is the derivative of the noise rather than a difference of
neighbouring vertices, so it stays correct where the grid is coarse — which,
over a clipmap, is nearly everywhere.
## The collision patch
The threads past the mesh write a square patch of the same field into `heights`
as plain metres, row-major with the column along world X and the row along world
Z — the layout a heightfield collider indexes. `plan[2]` gives the patch its
world centre, its samples per side and its world span.
It is the same call to the same function that raised the vertices. A second
evaluation of the noise, in Luau or in a pass of its own, is a copy free to
drift from the one that is drawn, and ground stood on a metre from where it is
drawn is worse than ground with no collision at all — nothing reports it.
## Bindings
| Buffer | Access | Contents |
|--------|--------|----------|
| `plan` | read | lane 0: `xy` mesh world origin, `z` vertex count, `w` noise period (m). lane 1: amplitude, lacunarity, persistence. lane 2: `xy` patch centre, `z` samples per side, `w` patch span (m). |
| `vertices` | read_write | The mesh's vertex buffer, engine 23-word layout. |
| `heights` | read_write | The collision patch, `side * side` f32 metres. |
Dispatch `vertexCount + side * side` threads.
·computeshader · born here
❒asset # ocean_floor_texture
Grows the three tiling maps the seabed is built from: sand, rock, and the
caustic web the sun draws on both of them. Albedo goes in `rgb` and height in
`a`; the caustics map carries two independent phases in `r` and `g`.
Generated rather than shipped as images. A stored texture is a binary,
content-addressed asset, and a material blocked on a texture reference that
never resolves never prepares — which leaves its entire uniform block unwritten
and the surface black. Generating keeps the seabed on the same compute-texture
path the cascade maps and the foam patterns already use.
Run once per map at startup, each with its own seed. Every map tiles: each
octave hashes its lattice modulo a period that divides the texture size.
The caustics are constructed rather than painted. Sunlight refracting through a
wavy surface lands as the light a patch gathers divided by the area it spreads
over — the reciprocal Jacobian determinant of the refraction map. Writing the
surface as a height field makes that map `p + k grad h`, so the determinant is
that of `I + k H`; inverting it produces the sharp filaments and their crossing
cusps, which are the places the determinant approaches zero and a finite bundle
of light lands on almost nothing.
·computeshader · born here
❒asset # ocean_foam
The persistent whitecap field: a world-space region, following the viewer, in
which foam accumulates where the sea folds and drains everywhere at a fixed
half-life.
Shading foam directly from the instantaneous fold makes it blink with the wave
that caused it. This field is what gives a broken crest a wake of white behind
it, and what the surface's `waves` foam layer is actually gated on.
Run once per frame, after every cascade's `ocean_normals`. The two history
buffers swap roles each frame; the caller binds whichever holds last frame's
result as `previous`.
·computeshader · born here
❒asset # ocean_foam_texture
Grows the tiling greyscale pattern the three foam layers stamp on the water.
It is generated rather than shipped as an image. A stored texture is a binary,
content-addressed asset, and a material blocked on a texture reference that
never resolves never prepares — which leaves its entire uniform block unwritten
and the surface black, not merely un-foamed. Generating the pattern keeps foam
on the same compute-texture path the cascade maps already use.
Run once per layer at startup, each with its own seed. The noise tiles: every
octave hashes its lattice modulo a period that divides the texture size.
·computeshader · born here
❒asset # ocean_normals
Differentiates one cascade's displacement field into a shading normal and a foam
mask. Normals come from central differences of the displaced positions (so crest
pinching is accounted for, unlike a height-only gradient), with wrap-around
neighbours because the cascade tiles. Foam comes from the smaller eigenvalue of
the horizontal displacement Jacobian: where it goes negative the surface has
folded over itself, which is what a breaking wave is — so whitecaps appear from
the same displacement that raised the crest rather than from a painted-on noise
threshold. Fresh foam replaces the stored value immediately while old foam fades
at `foam_decay` per second, leaving streaks behind broken crests.
·computeshader · born here
❒asset # ocean_probe
Resamples every cascade onto one small grid that the CPU reads back, so gameplay
can ask where the water is without stalling a frame on the full simulation.
Dispatched once per cascade: the first overwrites the grid, the rest add to it.
`xyz` is the summed displacement in metres and `w` the strongest folding, so a
caller can also ask whether the water at a point is breaking.
The swell bank is deliberately absent — it is analytic and longer than the tile
this grid covers, so `ocean.module` evaluates it directly on the CPU instead.
·computeshader · born here
❒asset # ocean_spectrum
Builds one ocean cascade's time-independent complex wave amplitude `h0(k)` from
a JONSWAP directional spectrum: a Phillips energy core, Donelan–Banner
directional spreading around the wind, a JONSWAP peak enhancement, and a
`k_min`/`k_max` band limit that keeps each cascade to its own disjoint range of
wave numbers. The result is randomised into a complex Gaussian so the same sea
state produces a real random surface rather than a deterministic ripple. Runs
when the sea state changes, not per frame — `ocean_evolve` animates the field it
writes.
# islandLagoon
The island the `island_lagoon` demo scene stands in, as a terrain graph.
A flat lagoon bed at -14 m with a broad dome rising through sea level at
roughly 1:21, carrying two surfaces: sand from the lagoon floor up past the
waterline, grass over the dry crown. The gentle slope is the point — it puts a
continuous range of water depth in front of the camera, which is what makes
the ocean's shoaling, absorption and shoreline wash readable in one shot.
## Inputs
None. Every dimension is authored in the graph; edit `init.luau` to move the
waterline, widen the beach or change the relief.
## Outputs
- `land`: the landscape as one element carrying `Terrain`, which the graph
shows through `io.output`: the ground, its colliders and its water, standing in
the scene.
## Consumers
- `@builtin::systems.oceans.demo.island_lagoon` instantiates it as the demo's
terrain and binds the ocean's `ground` to the entity it produces.
# Island lagoon
The spectral ocean against a shore: an island rising out of a lagoon at a
beach's slope, so one view holds every water depth from the waterline to open
blue.
Load `@builtin::systems.oceans.demo.island_lagoon` with the `scene.load` tool, then
walk down to the water.
## What it shows
- **Depth as colour.** The water column's absorption is per-channel, so the
sea reads turquoise where the sand is a metre or two down and turns blue as
the bed falls away. The gradient is the ground's own slope seen through the
water, not a painted ramp.
- **The seabed through the surface.** The bed is refracted, attenuated over
the real path the light travelled, and lit by the caustic web the surface
focuses onto it.
- **Shoaling.** Chop dies as the bottom comes up — geometry and shading
together — so the shallows are glassy while the open water stays crisp.
- **The shoreline.** Wash along the waterline, foam that clings to breaking
crests, and a sea that meets the sand instead of ending at it.
- **A sun path over water.** The glitter track is the surface's own slope
statistics under this scene's directional light.
## Things to try
```luau
local Presets = require("@builtin::systems.oceans.modules.oceanPresets")
Presets.names() -- nine sea states, calm to gale
entity("lagoonSea").Ocean.preset = "gale" -- the same shore under a gale
entity("lagoonSea").Ocean.seaLevel = 2.0 -- flood the beach
```
A preset is a whole sea — spectrum, swell, colour, all three foam layers and
the seabed — so swapping one changes the water and leaves the island, the
light and the sky exactly where they are.
## What it is made of
- `@builtin::systems.oceans.demo.islandLagoon` — the terrain graph the island
is baked from.
- `Ocean` — the sea, bound to that landscape through its `ground` field.
- A directional sun, an ambient fill, a `ProceduralSky` and a
`PhysicalAtmosphere`. The ocean carries no light of its own: every
reflection, the glitter and the foam's shading come from these.
# oceans guide
The walkthrough for building a sea with the oceans package: putting an ocean in
a scene, choosing a sea state and understanding which control does what, floating
things on the waves, and what the simulation costs.
# oceanSeabed
The ground under the sea: one gradient-noise field mixed between sand and rock,
lit by the scene's own sun and ambient, with the caustics the waves above focus
onto it added on top. The simulation drives the cascade displacement map, the
sand and rock maps the compute pass generates, and the terrain's world origin on
this material as the clipmap recentres; the blend threshold, the tiling and the
caustic strength are authored here. Sea-state presets in
`~.modules.oceanPresets` override these values.
# oceanWater
The default open-ocean material the `Ocean` component applies: deep blue with
per-channel absorption tuned for clear seawater, a near-mirror surface, and
breaking-wave foam. The simulation drives the cascade normal maps, the cascade
patch sizes and the scene-depth map on this material every frame; everything
else is authored here. Sea-state presets in `~.modules.oceanPresets` override
these values for paleSwell, gale and the rest.
# buoyancy
Floats a rigid body on the sea the simulation is already drawing.
```lua
local buoyancy = require("@builtin::systems.oceans.modules.buoyancy")
buoyancy.attach(barrel, { density = 0.4 })
```
Or attach a `Buoyancy` component next to the entity's `Physics` body and author
`density` / `damping` / `angularDamping` / `columns` on it — the component calls
this module every frame.
## A hull is a bundle of columns
A grid is laid over the hull's footprint, and each cell stands for a vertical
prism spanning the hull's full height. Every column measures the water above its
own base, and carries the share of the displaced volume that implies, applied at
its own position.
That is what the grid is for. One force at the centre of mass can only push a
body up and down; forces spread over the footprint push harder on the side that
is deeper, which is what rights a hull that has been tipped over and what makes
it pitch as a wave rolls under it. `columns = 1` is a single central column: it
floats, but it cannot right itself.
## Density sets the waterline
`density` is relative to water: the lower it is, the higher the hull rides, and a
body denser than water sinks. `buoyancy.restingY(waterY, height, density)` gives
the height at which a hull of that density displaces its own weight.
A hull settles somewhat deeper than that height, and how much deeper moves with
how long the frames are — a force applied from a script acts over a frame, while
gravity is integrated by the physics step, so the two balance a little below
where the arithmetic puts them. Densities up to about a half float on every frame
time measured; above that a hull rides progressively lower and sinks outright on
a long frame. Trim the number until the waterline sits where it should.
The body's own mass comes from its rigid body, whether `Physics.mass` sets it or the solver derives it from the collider volume, and the buoyant force is scaled
against it, so a hull floats at the same waterline whatever mass it was authored
with — mass changes how briskly it gets there, not where it ends up. `mass` and
`gravityScale` may be passed to `attach` / `configure` for a body whose rigid
body says something else.
## Damping is measured against the hull's own spring
Buoyancy is a spring: push a hull under and the water pushes back in proportion
to how far, so it has a natural frequency of its own, set by how deep it has to
sink to displace its own weight. `damping` is a fraction of the damping that
would return it to its waterline without a single overshoot — 1 is that critical
value, lower values let it bob on the way, 0 bobs indefinitely.
Reading it as a ratio rather than an absolute rate is what keeps a dinghy and a
barge equally steady at the same setting. It is applied per column against that
column's own velocity, so it steadies rolling as well as heaving; a body spinning
about its own vertical axis moves every column but their forces cancel in pairs,
so `angularDamping` damps the hull's turning on top of it. That one is handed to
the rigid body as its own angular damping rate for as long as the hull is in the
water, so the physics step takes the spin down itself and can never overshoot
the rest it is bringing the body to.
Both scale with how much of the hull is actually in the water, so a body lifted
clear of the sea falls freely.
## The hull's box
The hull is measured from what the entity draws, in the entity's own space, so
it stays the same box however the body is turned. Where that box sits comes with
it, so a model drawn off its own pivot — a keel-pivoted boat, an offset child
mesh — displaces water where it draws and carries its columns over that
footprint. What an entity draws arrives over the frames after it is spawned, so
the measurement is retried until it lands and a body keeps its place while it
waits.
`sizeX`/`sizeY`/`sizeZ` name a box explicitly — for a body whose visible mesh is
not what displaces water, or one that draws nothing at all. That box is centred
on the entity's origin, and it belongs at the size of the body that is actually
there: the water pushes on the rigid body's own inertia, so a footprint much
wider than the collider rocks a hull the body has no weight to steady.
## What it reads
The water height comes from `ocean:sampleHeight`, the same wave field the
surface renders, so a hull rides the waves that are on screen. With no ocean in
the scene there is nothing to float on and the body is left to the physics
world; pass `ocean` to pick one when a scene has several.
# ocean
The oceans package's substrate. One `Ocean.create` call brings up a live sea: the
GPU wave simulation, the surface mesh that renders it, the material bound to the
simulation's output, and the coarse readback gameplay queries.
The simulation is spectral and runs in cascades — independent wave fields over
different patch sizes, each band-limited to its own range of wavelengths, summed
into one surface. That is what gives detail at every scale (swell, wind waves,
chop) while keeping each transform small.
The surface is one mesh whose vertices a compute pass rewrites every frame, so no
wave data crosses to the CPU for rendering. It is graded radially and follows the
viewer, snapped to a wave-patch multiple so the sea stays put in the world while
the mesh slides under it.
`sampleHeight` / `sampleDisplacement` answer where the water is, from a small
grid read back off the GPU a few times a second — enough to float a boat on the
same waves that are drawn without stalling a frame on a round-trip. Both invert
the horizontal wave displacement, so they return the surface point that actually
ended up above the position you asked about.
Use the `Ocean` component to place a sea in a scene; use this module directly to
drive one from code.
# oceanClipmap
Builds the ocean's geometry: concentric rings that double in extent and halve in
density outward, the stitch strips that remove the T-junctions between them, and
the skirt that carries the water out to the horizon.
Returns the vertex and index data as Luau buffers, ready to upload straight into
the compute buffers `ocean_displace` rewrites each frame.
# oceanFloor
The ground the water is seen through. It spans the same extent as the clipmap,
follows the viewer the way the surface does, and is shaded by
`~.shaders.oceanFloor`.
One noise field is the whole terrain: scaled it is the relief the seabed's
vertex stage raises the grid into, and read again unscaled it picks between sand
and rock. Over both moves the sun's caustic web, displaced by the horizontal
displacement of the water directly above it.
The seabed applies no absorption of its own. The water column belongs to the
surface shader, which knows the real distance light travelled through water;
attenuating here as well would darken the ground twice.
Its three tiling maps are grown once by `ocean_floor_texture` — the same
compute-texture path the cascade maps take — so the seabed carries no binary
asset and no content reference that could fail to resolve.
```luau
local Floor = require("@builtin::systems.oceans.modules.oceanFloor")
local floor = Floor.create({
config = cfg, -- a resolved ocean config
extent = 12800, -- the clipmap's own extent, metres
prefix = "ocean1_floor_",
name = "Seabed",
})
floor:bindWave(cascadeDisplacementTexture, cascadeTile)
floor:step(elapsed, viewerX, viewerZ)
floor:destroy()
```
`Ocean` creates and drives one of these itself whenever the sea state's `floor`
block is enabled, so a scene that uses the `Ocean` component gets a seabed
without naming this module at all.
# oceanPresets
Named sea states for the oceans package — `calmClear`, `darkChop`, `darkRolling`,
`heavySwell`, `whitecapped`, `murkyGrey`, `paleSwell`, `glassyDark` and `gale`.
Each name says what the water does, so a sea can be picked off the list without
reading its values. A state is an `OceanConfig` fragment applied underneath
whatever the caller passes to `Ocean.create`, so any single field can be
overridden without giving up the rest.
The states are laid out along the Beaufort scale, because wind speed is what
determines wave height in a spectral ocean — the remaining fields shape
character: how long the swell runs, how readily crests break, and what colour the
water body is. `materialProperties` returns the appearance half of a preset,
ready to apply to an ocean material.
# oceanQuality
The four quality tiers: how finely the sea is resolved, as distinct from what
sea it is.
A tier owns the FFT grid per cascade, the clipmap's ring density, the swell band
count, the whitecap field's resolution and whether screen-space reflections run.
It never touches wind, spectrum shape or colour — those come from the preset, so
the same named sea looks like itself on any machine.
# oceanScene
The seam between the `oceanScene` render feature, which captures the colour and
depth behind the water, and the ocean materials that sample them.
`renderer.feature.create` hands back a handle rather than the feature module, so
a shared module is how the half that fills the textures reaches the half that
reads them.
·computeshader · born here
❒asset # ocean_copy
Copies the ocean's rendered surface into the scene target.
## Bindings
| name | kind |
|------|------|
| `scene_depth` | `texture_depth` |
| `scene_color` | `texture2d` |
| `depth_out` | `storage2d (r32f)` |
| `color_out` | `storage2d (rgba16f)` |
# oceanCalmClear
The "Calm Clear" sea state, offered as `calmClear` in the ocean's preset list (slot 1 in the calm-to-gale progression). The lightest wind in the catalogue, at 4 m/s, over the brightest and clearest water it holds, above a shallow shoal. A complete `oceanPreset` configuration: spectrum and swell, colours, fresnel, all three foam layers, the seabed and its caustics, subsurface scattering, screen-space reflections and the sun sparkle.
# oceanDarkChop
The "Dark Chop" sea state, offered as `darkChop` in the ocean's preset list (slot 2 in the calm-to-gale progression). A brisk wind chopping the darkest water in the catalogue, with almost no swell running underneath it. A complete `oceanPreset` configuration: spectrum and swell, colours, fresnel, all three foam layers, the seabed and its caustics, subsurface scattering, screen-space reflections and the sun sparkle.
# oceanDarkRolling
The "Dark Rolling" sea state, offered as `darkRolling` in the ocean's preset list (slot 3 in the calm-to-gale progression). Dark water rolling under a long swell, on the least choppy surface in the catalogue. A complete `oceanPreset` configuration: spectrum and swell, colours, fresnel, all three foam layers, the seabed and its caustics, subsurface scattering, screen-space reflections and the sun sparkle.
# oceanGale
The "Gale" sea state, offered as `gale` in the ocean's preset list (slot 9 in the calm-to-gale progression). The strongest wind in the catalogue, at 38 m/s, raising a fully wind-driven sea under the heaviest surface foam. A complete `oceanPreset` configuration: spectrum and swell, colours, fresnel, all three foam layers, the seabed and its caustics, subsurface scattering, screen-space reflections and the sun sparkle.
# oceanGlassyDark
The "Glassy Dark" sea state, offered as `glassyDark` in the ocean's preset list (slot 8 in the calm-to-gale progression). No swell at all and the highest standing-wave ratio in the catalogue: a still, strongly refracting surface over near-black water. A complete `oceanPreset` configuration: spectrum and swell, colours, fresnel, all three foam layers, the seabed and its caustics, subsurface scattering, screen-space reflections and the sun sparkle.
# oceanHeavySwell
The "Heavy Swell" sea state, offered as `heavySwell` in the ocean's preset list (slot 4 in the calm-to-gale progression). The largest and longest swell in the catalogue, running through mid teal-green water. A complete `oceanPreset` configuration: spectrum and swell, colours, fresnel, all three foam layers, the seabed and its caustics, subsurface scattering, screen-space reflections and the sun sparkle.
# oceanMurkyGrey
The "Murky Grey" sea state, offered as `murkyGrey` in the ocean's preset list (slot 6 in the calm-to-gale progression). Grey, murky water whose reflections fall away close to the eye and which carries no glitter at all. A complete `oceanPreset` configuration: spectrum and swell, colours, fresnel, all three foam layers, the seabed and its caustics, subsurface scattering, screen-space reflections and the sun sparkle.
# oceanPaleSwell
The "Pale Swell" sea state, offered as `paleSwell` in the ocean's preset list (slot 7 in the calm-to-gale progression). A big swell under one of the lightest winds in the catalogue, through the palest blue subsurface transmission it holds. A complete `oceanPreset` configuration: spectrum and swell, colours, fresnel, all three foam layers, the seabed and its caustics, subsurface scattering, screen-space reflections and the sun sparkle.
# oceanPreset
A complete sea state for the ocean system: everything `ocean.create` needs to
stand up a specific sea, from the wave spectrum to the seabed under it. Each
`.data` instance is one named preset offered in the ocean's preset list.
## Fields
- `key` — the name the preset answers to in `ocean.create({ preset = ... })`
and the presets API. Stable; world content refers to it.
- `label` — the human-readable name shown in pickers.
- `order` — the preset's slot in the calm-to-gale progression the list is
offered in (1 = flattest).
- `seed` — the spectrum's random seed.
- `waves` — the FFT spectrum: wind speed and direction, choppiness, gravity,
JONSWAP gamma, spectral sharpness, standing-wave ratio, animation speed,
and a global amplitude on top.
- `cascades` — the three simulation bands: per-band enable, amplitude and
world-space tile scale in metres.
- `gerstner` — the analytic long swell layered under the FFT bands:
wavelength and its spread, amplitude, wave count, directional spread.
- `clipmap` — the surface mesh: base tile size in metres and ring count.
- `color` — the water column: absorption rates authored as a hex triple
(decoded to per-channel 1/m extinction), transmission and body colours,
and the depth assumed where nothing stands behind the water.
- `fresnel` — the mirror: distance fade start/power, index-of-refraction
ratio, normal strength, screen-space refraction strength.
- `foam` — the three layers: `surface` lace, `waves` whitecaps (with
persistence, optional `breaking` window and `placement` mask), and the
`shoreline` wash.
- `floor` — the procedural seabed and its `caustics` web.
- `shore` — how deep the bottom starts taking the waves (`shoalDepth`,
metres); omitted, the ocean's default shoaling band applies.
- `sss` — subsurface scattering through backlit crests.
- `ssr` — screen-space reflections.
- `sparkle` — the sun's specular glint.
Colour-valued fields are authored as `#rrggbb` strings and decoded to linear
RGB by `Presets.color` on the way to the GPU — including `absorptionColor`,
whose channels are extinction rates rather than a colour.
# oceanWhitecapped
The "Whitecapped" sea state, offered as `whitecapped` in the ocean's preset list (slot 5 in the calm-to-gale progression). A hard wind raising the steepest crests in the catalogue, whose foam is the heaviest and the slowest to fade. A complete `oceanPreset` configuration: spectrum and swell, colours, fresnel, all three foam layers, the seabed and its caustics, subsurface scattering, screen-space reflections and the sun sparkle.
·renderfeature · born here
❒asset # oceanScene
Copies the colour and depth of everything drawn behind the water into textures
the ocean surface material can sample.
A surface shader cannot bind the frame's own depth buffer or colour target while
drawing into them, and the water needs both: depth gives the length of the water
column, and colour is what refraction bends and what screen-space reflections
march through.
Both copies run at `afterOpaque` and are published through
`~.modules.oceanScene`, which is where the ocean materials pick them up.
# oceanFloor
The seabed under the spectral ocean: sand where the ground has settled, rock
where it has not, lit through the water by a moving web of focused sunlight.
One noise field decides the whole terrain. Scaled, it is the relief the vertex
stage raises the mesh into and the normal that shades it; unscaled, the same
field picks between sand and rock — so rock outcrops stand on the high ground
and sand fills the hollows, because the two are readings of one surface rather
than independent patterns laid over each other.
Both ground maps carry albedo in `rgb` and height in `a`. The height is
differenced into a detail normal that rides on the terrain's own slope as a
gradient, so relief accumulates rather than one normal replacing the other.
The caustics are two layers of the caustics map scrolling against each other at
slightly different scales and in opposite directions, displaced by the
horizontal displacement of the water directly overhead — which is what makes the
web ripple with the surface instead of sliding across the ground as one rigid
sheet. Each colour channel is read at its own small offset, giving the chromatic
fringe focused light through a dispersing medium has.
The seabed applies NO absorption of its own. The water column above it belongs
to the water surface, which knows the real distance the light travelled through
water; attenuating here as well would darken the ground twice.
The mesh follows the viewer, so `floor_center` carries where it currently sits
and every terrain and texture lookup is made in world space. That is what keeps
the ground still while the mesh slides beneath it.
# oceanSurface
The water surface of the spectral ocean. Geometry arrives already displaced by
`ocean_displace`, so this shader only decides what the surface looks like: the
normal summed across cascades as gradients (which is what adds when wave fields
overlap), a water column shaded by per-channel Beer–Lambert extinction over the
distance to whatever lies behind it, Fresnel reflection from the scene's own
reflection probes, subsurface scattering through backlit crests lit by the
scene's directional light, a sharp sun-glitter lobe, and foam
from the simulation's own breaking-wave mask plus a shoreline band. Opacity is
the extinction rather than an authored constant, so colour and transparency stay
consistent from a turquoise shallow to a near-black deep. Works from below as
well as above.
# Package (asset type)
A package is an asset — a `<Name>.package/` folder that bundles
components, modules, scenes, presets, tools, and any other typed
sub-assets under one identity, installed into a world as one unit.
Packages are how authoring sets get distributed across worlds.
A **library** is the addressable root scope content resolves under
(`@builtin`, `@<name>`) — a whole world mounted into this one under a
namespace, via `zeromind.installLib` / `world.installLibrary`. A package is
an asset that lives inside such a root, and one library holds as many
packages as its author put there. A package is installed by guid the
way every asset is (`zeromind.install`, `zeromind.installAsset`).
## When to use one
- You're authoring a coherent feature suite (character controller
stack, voxel engine, UI kit, animation library) and want to ship
it as one install target.
- You want a stable identity worlds can install and resolve sub-assets
against (`@<lib>::pkg.sub_module`).
- You want versioning + a per-package metadata layer that travels with
the contents.
If you're authoring inside a single world and don't need a separate
install lifecycle, you don't need a package — drop your `.component`
/ `.module` / etc. directly in `/zero/source/`. Packages are for
cross-world distribution.
## Where it lives
- Source: `/zero/source/.../<Name>.package/` (or, for legacy
packages, a folder containing `package.yaml` at its root).
- Identity: `<Name>` (the `.package` suffix collapses in identity —
mirrors `.module`). A file at `<Name>.package/<sub>/init.luau`
resolves under the same identity it would at `<Name>/<sub>/init.luau`.
- Folder shape (container-style — open child set):
- `package.yaml` — metadata (name, version, description).
**Required.**
- `README.md` — instance documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
- Sub-asset folders: any combination of `.component/`,
`.module/`, `.scene/`, `.preset/`, `.tool/`, `.toolbox/`,
`.material/`, `.shader/`, etc.
The validator permits unlisted children (`allow_unlisted: true`) by
design — packages are open containers.
## How to create one
```luau
asset.create("package", "<Name>")
-- Creates: /zero/source/<Name>.package/
-- package.yaml (metadata scaffold)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source instead of the root:
asset.create("package", "<Name>", { folder = "systems" })
```
Then scaffold sub-assets inside it:
```luau
local pkg = asset.resolve("<Name>.package")
asset.create("component", "Spinner", { into = pkg })
asset.create("module", "util", { into = pkg })
```
## How it operates
1. **Registration.** Writing `package.yaml` indexes the package with
the package registry.
2. **Install.** A package is read before it is installed: `zm ls-tree
@<guid>` in the shell lists what it contains, and `zm show
@<guid>:<path>` and `zm grep <pattern> @<guid>` read it, so candidates
are compared by what they do. The one that fits is installed by guid,
the way every asset is: `zeromind.install` from the shared library, or
`tools.use("zeromind", "installAsset", <guid>)` inside the engine. The
install writes the package's files (and the deps its `.refs`
record) into this world's source, so its sub-assets resolve here.
`tools.use("zeromind", "preview", <guid>)` reports what an install would
write before it writes anything.
3. **Sub-asset resolution.** Because `.package` collapses in
identity, sub-asset paths work whether the package folder is
suffixed (`<Name>.package/<sub>`) or not (`<Name>/<sub>`).
4. **Updates.** `tools.use("zeromind", "updates")` lists installed content
with upstream changes available; re-running the install pulls them.
5. **Metadata.** `package.yaml::name` overrides the folder stem if
present (rare); `version` + `description` are surfaced in the
package index.
6. **Hot reload.** Edits to sub-assets hot-reload as normal; edits to
`package.yaml` reload package metadata.
## Discovery
- `asset.list("package")` — every registered package.
- `asset.inspect("<name>")` — sub-asset catalog, source, this type
README.
- `ls /zero/source/<Name>.package` lists the files the folder holds.
- `library.list()` — the library assets registered in this world,
including the ones packages under an installed library contribute.
## Authoring conventions
- Name packages by their feature (`voxels`, `cameraRigs`,
`dialogSystem`), not by their owner — the host library is the
`@<lib>::` scope prefix.
- Cluster cohesive sub-assets together. A "character controller"
package should ship the controller component, its preset configs,
its supporting modules, and a demo scene — not just the component.
- Document the package's surface in `README.md` — what install
installs, what each sub-asset does, how they relate. Agents reading
`cat /zero/source/<Name>.package/README.md` get the full picture in one shot.
- Version conservatively — breaking a package means breaking every
world that installed it. Use semantic version bumps.
## Common pitfalls
- **Missing `package.yaml`.** Without it the folder isn't recognized
as a package even if it has a `.package/` suffix.
- **Dependency installs.** A package that depends on another package
must declare it (in `package.yaml::dependencies` once supported)
and the parent world must install dependencies in order.
- **Identity collapse.** Sub-asset paths skip the `.package` suffix.
Don't include `.package` in `require` strings.
## Referencing inside a package: the `~` rule
`~` means **this package**, resolved structurally from the referring file's own
location. It is the only package-specific syntax. It is rename-safe (no package
name is ever written) and library-agnostic (it never names the host library, so
it survives `@builtin` being renamed or the package being mounted elsewhere).
`~.tail` maps to `<pkg>.package/tail` from anywhere inside the package.
| Referencing from | Use | Example |
|---|---|---|
| An asset/module **inside this package** | `~.tail` | `require("~.modules.myThing")`, `shader: "~.shaders.myThingBlend"` |
| A **different package** under the same root | root-relative identity | `require("@root::systems.otherPkg.modules.x")` |
| A **different library's** public API (a deliberate external dependency) | `@otherlib::…` | `require("@physics::modules.rigidbody")` |
**Never write `@builtin::` (or any host-library name) to reference your own
package** — that couples the package to the library it currently lives in and
breaks if the library is renamed or the files move. Use `~.`. It works from
Luau `require()` and from asset-reference strings in data files (a material's
`mat.yaml` `shader:` field, a component's default asset ref); the engine
resolves it against the referring file's own package. `asset.resolve` takes a
`~.` name the same way, against the package of the file that calls it:
`asset.resolve("~.materials.myThingStandard", "material")`.
`~.` is the package-relative self-reference; `@root::` is the root-relative one
(the library root, or the world source tree for non-library content). The
`core/requiring-modules` guide covers the root model in full.
A package that ships substantial functionality should include a `.guide` asset
(a `<name>.guide/guide.md` folder anywhere under the package); the `guides` tool
discovers it live, so collaborators find the system the way they find built-in
guides. A package's test suite reaches the shared `Test` framework through its
enclosing asset: `local Test = asset.containing(__FILE__).modules.shared`
(`asset.containing` returns the deepest enclosing typed asset, the `.testSuite`,
not the outer `.package`).
## Related types
- Any of `.component`, `.module`, `.scene`, `.preset`, `.tool`,
`.toolbox`, `.material`, `.shader`, `.style`, `.service`,
`.importer` — packages bundle these.
## In the Inspector
Package: the name, version and description package.yaml declares, how many things the package holds and what they are, and **Open** for package.yaml. A package.yaml that does not decode is listed under Problems with the decoder's error.
# Component (asset type)
A component is a reusable behavior + data unit attached to an entity.
The component file declares public fields, methods, and lifecycle
callbacks; the engine instantiates one per attachment and drives its
hooks every frame. Components are the primary unit of gameplay code —
movement, AI, animations, UI panels, network sync, and per-entity state
all live here.
## When to use one
- You need per-entity state that survives across frames.
- You need per-entity behavior driven by engine lifecycle hooks
(`start`, `update`, `destroy`).
- You want to expose configurable fields to designers / `entity.spawn`
callers / scenes without code changes.
If you need a global service that outlives any entity, use a `.service`
instead. If you need a stateless pure-function library, use a `.module`.
## Where it lives
- Source: `/zero/source/.../<Name>.component/`
- Identity: `<Name>` (the `.component` suffix strips from the
identity, but the folder retains the suffix on disk).
- Folder shape:
- `init.luau` (or `init.lua`) — declares the component. **Required.**
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
The structural contract is enforced by `asset.validate` against this
type's `type.yaml`.
## How to create one
Always start with the scaffold — it guarantees the folder shape
matches `type.yaml` from the moment it's on disk:
```luau
asset.create("component", "<Name>")
-- Creates: /zero/source/<Name>.component/
-- init.luau (canonical declare + public block + hooks stubbed)
-- README.md (instance README template)
```
After scaffolding, edit `init.luau` to fill in the actual fields and
behaviour. The component registers as soon as the file is written —
hot-reload is automatic; no engine restart required.
## How it operates
1. **Registration.** Writing `init.luau` into a `.component/` folder
indexes the asset, mints a guid (in the `.meta` sidecar), and
surfaces the type to the engine's component registry. Same-frame
visible to `entity.component.add`.
2. **Attachment.** `entity(id).component.add(name, data)` (or the
batch form `tools.use("entityOps", "addComponents", targets,
{ [name] = data })`) attaches an instance.
The `data` table's fields override the component's declared
defaults; omitted fields take the declared default. The `data`
values are copied into `public.*` BEFORE `awake()` runs.
3. **Lifecycle.** The hooks run in this order:
- `awake()` — same frame as attach, immediately after the data
copy. Initialise state, set up native bridges, register with
other systems. Other components on the same entity may not have
awoken yet.
- `start()` — the next frame. Every component on the entity has
completed `awake()` by then, so cross-component setup is safe
here.
- `update(dt)` — same frame as `start()`, then every frame after,
for as long as the gameplay clock is running. `fixedUpdate(dt)`
runs beside it on the fixed timestep; `editorUpdate(dt)` runs
while the clock is held. Which of them ticks is decided by
`engine.mode` AND `engine.paused` together — see **Per-frame
hooks and the two axes** below, and `man modes`.
- `onDestroy()` — when the component is removed via
`component.remove` or when the owning entity is despawned.
Release resources, drop native ECS components.
For the full list (`onEnable`, `onDisable`, `fixedUpdate`,
`editorUpdate`, `onPropertyChanged`, `onAssetReload`,
`onModuleReload`,
`onBeforeSave`, …) and the timing details, **read `man components`
— that is the canonical lifecycle reference. Generic component
patterns (declare blocks, public fields, sync, ECS bindings,
typed methods) all live there.**
4. **Public surface.** Fields declared in `public` are inspectable,
editable in the inspector, and persist with the entity. Methods are
declared on that same table with a colon —
`typed function public:method(args)` — and every one of them takes
the component ref as `self`, so a caller invokes it with a colon
too: `entity(id).component.get(name):method(args)`. That is the one
calling convention a component ref answers to: the reflection
methods `ref:fields()` / `ref:getField(name)` /
`ref:setField(name, value)` take the same spelling. A function the
chunk declares at file scope (`function helper()`) is the
component's own, reachable from its hooks under its bare name;
`public` is what the ref carries.
5. **Settings and the Inspector card.** `type.yaml` names the component's
settings schema as `settings: { schema: { instance: "init.luau",
export: "public" } }`: the `public` table IS the schema, and its values
live on each entity the component is on, so `asset.schema(componentRef)`
answers the Field descriptors and no values file exists. On an entity
the Inspector shows the component as a card whose generic `settings`
section edits those fields as typed controls, each edit checked against
the schema and written to the live component as one undoable operation.
`type.yaml` also names `inspector: { instance: "inspector.luau" }`: a
component that ships an `inspector.luau` beside its `init.luau` shapes
its card — the file returns `{ sections, replace, order }` (see
`assetTypes/README.md`, "`inspector:`"), each section's `build(ctx)`
reading `ctx.component` (the live component) and `ctx.selection.id` (the
entity). `SceneModule.component/inspector.luau` replaces `settings` with
the bound module's declared inputs.
6. **Events.** An `events` block declares typed moments the component
fires from inside — `events = { onHit = Event({ dmg =
Field.number(0, NoSync) }) }`. The owner fires with
`events.onHit:fire({ dmg = 10 })`; outside code subscribes through
the proxy's subscribe-only facade,
`entity(id).component.get(name).events.onHit:connect(fn)`
(`:once` / `:wait` too). Pass `Sync` as the event's second argument
to replicate a fire to other peers. Events let one component react
to another's moments without polling. Full reference: **`man
components`**, Events section.
7. **Hot reload.** Editing `init.luau` reloads the component
definition; live instances are reconciled with the new declaration
in-place, and each crosses one lifecycle boundary: `onDestroy()`
ends the running life, then `awake()` and `start()` construct the
one that replaces it, and `update()` resumes on the next frame.
`public` and `private` values carry across; module-level `local`s
belong to the chunk, so the new life starts with them at their
initial values and its `awake`/`start` are what fill them in.
Whatever the old life handed elsewhere — a subscription, a shared
registration, a spawned entity — is released in `onDestroy`, the
call that pairs with the construction about to run. An edit that
leaves the source byte-identical crosses no boundary at all.
A field carries its value across when something stated it: a key of
the `data` table the instance was attached with (a scene record's
data is that table), or a write made since. Every other field takes
the edited source's declared default, so changing a default reaches
every instance that left the field to it. An instance that states
its own value for a field whose default the edit changed keeps that
value, and the reload logs a `[HotReload]` warning naming the field,
the entity, the value kept and both defaults.
## Discovery
- `asset.list("component")` — every registered component (engine +
world + libraries).
- `asset.inspect("<name>")` — identity, scope, public fields,
lifecycle methods, source path, and this type README. `detail`
carries the component's declared `fields`, `methods`, and `events`,
parsed from its source — `tools.use("assets","describe", "<name>")`
renders it as markdown, so a component's events are visible without
opening its source.
- `ls /zero/source/<Name>.component` lists the files the folder holds.
- `entity(id).component.list()` — components attached to an entity.
## Per-frame hooks and the two axes
`engine.mode` (`"edit"` / `"play"`) and `engine.paused` (the gameplay
clock) are independent, and the per-frame hooks read them separately:
- `update(dt)` / `fixedUpdate(dt)` tick while **the gameplay clock is
running** — whichever mode the engine is in.
- `editorUpdate(dt)` ticks while **the clock is held** — because the
mode is `edit`, or because play is paused — and also alongside
`update` whenever edit is running.
Which gives four states, and this table is the contract:
| `engine.mode` | `engine.paused` | hooks that tick |
|---|---|---|
| `edit` | `true` | `editorUpdate` |
| `edit` | `false` | `update`, `fixedUpdate`, `editorUpdate` |
| `play` | `false` | `update`, `fixedUpdate` |
| `play` | `true` | `editorUpdate` |
Entering edit sets `paused = true` and entering play sets it back to
`false`, so a session that never writes `engine.paused` only ever sees
rows 1 and 3 — which is where the shorthand "`update` is the play tick,
`editorUpdate` is the edit tick" comes from. It is the two default rows
of a four-row table, not the rule.
**Row 2 is the one that surprises.** With `engine.paused = false` in
edit — set by hand, or by a tool that advances the gameplay clock to
sample it, such as a `capture.collage` given a `duration` — `update` and `editorUpdate`
both fire, once each, every frame. A component that declares both and
routes them to one body therefore runs that body **twice per frame**:
```luau
local function drive(dt) ... end
function update(dt) drive(dt) end
function editorUpdate(dt) drive(dt) end -- twice per frame in row 2
```
Nothing reports the doubling; it reads as an animation running at twice
its intended speed. To get exactly one tick per frame in every row, ask
which axis you meant and answer it in the body:
```luau
function update(dt) drive(dt) end
function editorUpdate(dt) if engine.paused then drive(dt) end end
```
A scene `entrypoint.luau` declaring the same two hook names is dispatched
by the scene loader, not by this table: there `update` needs play AND
running, `editorUpdate` needs edit, and play-paused ticks neither. Read
`man scenes` before carrying a component's rule to an entrypoint.
## Authoring conventions
- Annotate public fields with `--!desc` so the inspector + LSP show
documentation alongside the field name.
- Declare lifecycle hooks (`start`, `update`, `destroy`) explicitly
rather than relying on engine defaults — readers can see at a glance
what runs when.
- Keep `update(dt)` cheap — it runs every frame per instance. Move
heavy work to `start`, to a service, or behind a job (`man jobs`).
- For multi-entity batching, prefer
`tools.use("entityOps", "addComponents", targets, components)` over
a loop of `entity(id).component.add` — it takes many targets and
many components in one call.
## Common pitfalls
- **Naming.** The component identity is the folder stem with
`.component` stripped (e.g. `<Spinner>.component/` → identity
`Spinner`). Don't repeat the suffix in the identity passed to
`component.add`.
- **`init.lua` vs `init.luau`.** Either is accepted (it's a
`one_of_group: "entrypoint"`), but `.luau` is canonical. Mixing both
in one folder is invalid.
- **`update` in edit mode.** It runs whenever the gameplay clock is
running, and entering edit stops that clock — so `update` is idle in
a freshly-entered edit session and ticks again the moment anything
sets `engine.paused = false`. Use `tools.use("wld", "play")` to test
update logic under the mode it ships in; `tools.use("wld", "edit")`
to return. See **Per-frame hooks and the two axes** above.
- **Renaming.** Renaming the folder changes the identity. Update
every `component.add(<oldname>, ...)` call and the scene JSON
entries that reference it.
## Related types
- `.module` — pure-function library, no per-entity state.
- `.service` — globally-scoped behavior, no per-entity state.
- `.preset` — a captured component configuration, replayable into
`component.add` without re-typing fields.
- `.bundle` — entity hierarchies that may carry component attachments
as part of the bundle.
## In the Inspector
Fields: its execution order, hooks, and how many methods and events it declares, then the fields its `public` table declares as read-only typed controls holding their defaults, with **Check** and **Open** for its entry file. Instances: a link to every entity carrying it. What its card shows on an entity comes from the component's own `inspector.luau`.
# 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; 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` | — | `var NAME: sampler;` |
| `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 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` 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`, `rgba8`, `rgba16f`,
`rgba32f`. Storage textures only allow storage-compatible formats
(`r32f` / `rgba8` / `rgba16f` / `rgba32f`).
- 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, for shadow/occlusion rays), and
`zeroHitSurface(hit) -> ZeroSurface` (`normal, uv, material`) +
`zeroMaterial(index) -> ZeroMaterial` (`base_color, emissive, metallic,
roughness`) to shade what a hit landed on. The same surface works on both backends — hardware
ray query and the software/compute path — so the shader doesn't branch on
`renderer.raytraceCapability()`. 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 }` — for shaders mixing textures, samplers and storage textures: one `{ kind, name }` per declared binding, in order |
| `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 |
| `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, or a texture asset's guid once `texRef:handle()` has made it GPU-resident |
| `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` |
`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.
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.
`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 },
},
})
```
## Registration & hot reload
Writing `shader.wgsl` or `bindings.yaml` fires the `.computeShader` assetType's
`onChange`, which calls `__compute.compile` — that generates the binding
declarations, expands `#include`s, naga-validates, and registers. 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"`, and a dispatch issued before that is dropped.
- **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` / `rgba8` /
`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) and the
legacy `@domain: compute` fallback.
## 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`.
# procGraph (asset type)
A `.procGraph` asset is a **procedural graph**: a description of how to make
something, written as code, that can be evaluated over and over with different
numbers. Its `init.luau` returns `proc.define(...)` — that source IS the asset,
the way a `.procNode`'s `init.luau` is.
## Shape
A `<name>.procGraph/` folder containing:
- `init.luau`: the graph's definition. Returns `proc.define(function(g) … end)`, the graph named by its asset folder.
- `graph.json` — the compiled form (`proc.graph.v1`), written by this type from
`init.luau`. Generated, never hand-edited.
- `README.md`, `.metadata` — the universal asset files.
## Authoring
Edit `init.luau`. The type recompiles on the write, rewrites `graph.json`, and
every live `Generator` bound to the asset re-cooks from it — there is no build
step between saving and seeing the result.
A recompile is cheap however large the graph: node results are keyed by content,
so recompiling an unchanged node reuses its cooked output, and an edit
invalidates only that node and the ones downstream of it. Changing the last step
of a landscape does not re-run the erosion above it.
Two words worth keeping apart, because both happen here:
- **compile** — `init.luau` → `graph.json`. Produces the graph.
- **cook** — each node performing its operation to produce a value. Runs the
graph. Driven by a `Generator`, reported by `procgen.cooks`.
## Using one
Through the ref rather than a path string: `ref:eval("mesh")` evaluates an
output, `ref:inputs()` lists the knobs a Generator can override by name,
`ref:outputs()` the values it produces, `ref:validate()` type-checks it, and
`ref:asOp()` wraps it so another graph can composite it as a node.
Generated outputs (meshes, materials, textures, bundles) are persisted through
their own asset types.
## Related
- `@builtin::systems.procgen.proc` — the authoring + evaluation model.
- `procgen.toolbox` — `preview`, `spawn`, `bake`, `validate`, `ops`, `schema`
and the wider tool family.
## In the Inspector
The Inspector shows the graph as nodes and wires, and edits it there. Every graph input,
op, graph used as a node and output is a node; each input port that nothing is wired into
carries the value that drives it, and a click on a value edits it where it stands (typing,
dragging a number, flipping a switch, choosing from a list). Drag a node to move it, drag
from a port to another port to connect, drag a connected input away to take its wire off,
Delete removes the selection. A node is added from the op search under the graph, or from
the procGraph assets, which stand as nodes that open their own asset on a double click. The
graph's inputs and outputs are nodes too: their name, type, default and range, and an
output's domain, are values on them, and the Inputs and outputs section declares new ones.
Describes is the sentence search finds the graph by.
Every edit is written into `init.luau` with `proc.saveSource` and compiled by the type, so a
live Generator re-cooks on it; the node positions are kept beside the graph in `layout.json`.
The Result section scrubs the timeline of a graph that has one and shows what the selected
node makes (`procgen.preview` with the target `node:<id>`), and the Preview section above it
shows what the graph makes, live. **Compile** and **Open** for its source stay as they were.
# Scene (asset type)
A scene is a saved, loadable snapshot of an entity scenegraph inside a
world: the entity hierarchy, transforms, components, lighting, and a
declared `player` intent, plus an auto-discovered startup script. A scene
is the unit of "level" or "screen" — a title screen, a lobby, a gameplay
area, and an end-of-game summary each get their own scene.
Scenes load as **layers**. One root scene is active at a time; additional
scenes can load additively as overlays on top of it. Each scene owns its
own multiplayer relay room. Switching scenes is a local call: the client
that makes it leaves the old scene's room and joins the new scene's room.
## When to use one
- You want a savable, re-loadable snapshot of an entity scenegraph plus
its lighting and player setup.
- You want a runnable starting state for a level or screen.
- You want a scenes-as-data flow: `layers.load("lobby")`, edit live, then
`layers.active:save()` to publish the edits back to the scene.
For a reusable entity assembly (a prop, a vehicle, a UI panel) that many
scenes spawn into themselves, use a `.bundle`. A scene is a whole-world
snapshot; a bundle is one prefab that lives inside scenes.
## Folder shape
A scene asset is a folder ending in `.scene`. Its identity is the folder
name with the suffix stripped (`Lobby.scene` → `Lobby`).
- `scene.json` — the scenegraph: `entities[]`, lighting, and the
top-level `player` intent. **Required.** Written by the engine — a build,
a save, a human dragging something in. Not hand-edited.
- `build.luau` — what the scene is made of, written as code. Runs while you
author; saving bakes its result into `scene.json` (see Building a scene).
- `entrypoint.luau` — the startup script. Auto-discovered as a sibling of
`scene.json`; define lifecycle callbacks here (see The entrypoint).
- `<name>.<type>/` — an asset the build makes, authored here by `build.asset`
(see The assets a build makes), alongside `.build.assets`, which records
which `build.luau` produced each of them.
- `prefabs/` — optional subfolder for scene-local bundles.
- `scripts/` — optional subfolder for scene-local Luau helpers, required
from `entrypoint.luau`.
- `README.md` — optional per-scene notes about THIS scene. Author one only
when there is scene-specific detail worth recording; the general scene
model lives here, in `guides { path: "types/scene" }`.
`scene.json` is version 7. It carries `"format": "scene"`,
`"version": 7`, an `entities[]` array, and a top-level `"player"` string
intent.
## The `player` intent
Every scene declares how it handles players with a top-level `player`
field in `scene.json`:
- `"spawns"` — the scene carries an authored player setup, and the engine
spawns a player for each connecting user from it. This is the default
for a freshly created scene.
- `"none"` — the scene spawns no player and authors no camera. Author your
own Camera entity for the view (menus, UI-only screens, cinematics).
### How `"spawns"` works
A `"spawns"` scene authors two things in `scene.json`:
1. A **PlayerPrototype** — an entity carrying the `PlayerPrototype`
component, whose `body` field names a child entity (the body). The
body carries an avatar (an `Asset` pointing at an avatar, e.g.
`@builtin::avatars.humanoid`). A `CameraRig` child carries a `Camera`
with a camera behavior (e.g. `orbital_follow`). The prototype root is
authored `PrototypeOnly` so it exists as a clonable template.
2. A **PlayerSpawn** — an entity carrying the `PlayerSpawn` component,
whose `prototype` field names the PlayerPrototype to instantiate and
whose transform is where players appear.
The scaffolded scene groups these under two organizing entities,
`PlayerSetups` (holding the prototype) and `Spawns` (holding the spawn),
so the authoring tree stays legible.
On each user join — entering play, and each subsequent connect — the
engine runs the spawn for that user:
- It clones the PlayerPrototype subtree.
- The clone root becomes the user's **internal identity** — a registry-only
entity named `user` carrying the `UserIdentity` component. The identity
is the anchor for who the player is; it has no world presence.
- The body named by `PlayerPrototype.body` is adopted as the user's
**avatar** — their visible presence in the world — and placed at the
PlayerSpawn's world transform. Move the PlayerSpawn (or drag it in the
editor) to set where players appear.
- The `CameraRig`'s Camera follows the bound avatar.
The player prototype is live in edit mode so you can see and adjust it. In
play mode it is deactivated and marked internal — it stays a clonable source while
each user gets their own clone.
### Reaching the live player
The player surface lives on the root scene's registry,
`layers.active.players`:
- `players.localPlayer` — this client's player, a curated handle.
- `players.localReady` — `true` once the local player's avatar is bound
(or the scene opted its avatar out).
- `players:list()` / `players:count()` — the players connected in this
scene's room.
- `players:get(userId)` — a connected player by account id.
- `players:ownerOf(avatar)` — the player whose body is a given avatar.
A player handle is a data record about who the player is, plus a link to
their body:
- `player.avatar` — the body's entity ref. Act on the body through it
(`player.avatar.position`, raycasts, rig access).
- `player.isLocal` — whether this client owns the player.
- `player.ready` — whether a live avatar is bound.
- `player.userId` / `player.identity` / `player.displayName` — the
player's account identity.
- `player.avatar = ref` — bind a live body entity as the player's body
(assign nil to clear). To use a `.bundle` / `.avatar` asset, spawn it
into the world first, then bind the resulting entity.
The player's identity entity is the internal anchor; the handle exposes the
body (`player.avatar`) and the player's data, and reaching for
`.entity` / `.id` / `.component` raises with a redirect to `player.avatar`.
## Building a scene
`build.luau` declares what the scene holds. It is ordinary engine code —
`entity.spawn`, `component.add`, transform writes, `for` loops, a `require`
of a module that computes a layout — and what it creates is what ends up in
the scene.
```lua
function content()
for i = 0, 4 do
local crate = entity.spawn("crate")
crate.localPosition = { i * 2, 0.5, 0 }
crate.component.add("Model", { model = asset.resolve("cube", "mesh") })
end
end
```
The build runs while you author, in **edit** mode, and what it created lands in
the live scene. Saving the scene bakes it into `scene.json`, which is what makes
the entities durable content: a human can select and inspect them, they
replicate, and they are there when the world opens without `build.luau` running
at all. Play mode never runs it — in play the entities load from `scene.json`
like anything else the scene holds.
**Editing the file rebuilds the scene in place.** Writing `build.luau` is the
signal; there is nothing to reload, and the rebuild saves. An entity keeps the
id it had, so a reference to it — a spawn naming a prototype, another entity's
component naming this one — survives every rebuild. Add a crate to the loop and
the other four do not move.
The write returns as soon as the file is on disk and the rebuild finishes behind
it, so what it landed comes back as a notice:
```
[info] a write to build.luau rebuilt the scene { content="6", scene="scenes.main",
editorOnly="1" }
```
An edit saved while a rebuild is still running is an edit to code that rebuild
has already read, so it gets a rebuild of its own once that one finishes, and
says which it was:
```
[info] a write to build.luau arrived during a rebuild and was rebuilt after it
{ content="7", scene="scenes.main", editorOnly="1" }
```
Several edits saved during the same rebuild get the one run after it, which
reads the file as it stands then.
A scene that declares a build also runs it when it **loads** in edit, so the
scene shows what the code says now, including an edit made while the world was
closed. A load whose `.build.state` records the current script reads
`scene.json` as the build and runs nothing. When the load does run it, a
world's own scene saves the result, unless the scene holds unsaved edits: those
stay the author's to keep or discard, and the file write waits for their save.
A library scene (one under `/libs/`, the `@builtin` library included) is read
by its load: the build lands in the live scene and its files stay as the
library states them. Play reads `scene.json`, so it comes up without that build
until `:build()` saves it.
### The two surfaces
- `content()` — the scene's own entities. Present in play.
- `editorOnly()` — entities present while authoring and absent in play. They
carry the `EditorOnly` participation the runtime deactivates and hides when
play begins, and they are baked too, so a collaborator opening the world sees
the same ones. Anything an author needs to see and a player does not goes here
— an alignment guide, a spacing marker, a debug volume.
Both are optional. A scene with neither has no build.
### What a rebuild touches
Only the entities the build itself placed. Anything a human dragged in, or a
tool placed directly, is invisible to a rebuild and never moved or removed.
Within what it owns, the build is authoritative: an entity the code stopped
emitting is despawned, a component it stopped adding is removed.
The build writes its own name and each entity's place in the hierarchy onto the
entity, and `scene.json` records that pair beside the entity's name and
transform — which is why a rebuild after a reload, in a later session, lands on
exactly the entities it placed the first time without anything having been
remembered.
### When the file did not change
`:build()` runs the build against what it resolves right now — for the case
where something the builder *reads* changed and the file did not: a module it
requires, an asset it resolves. After a write it is unnecessary; the write has
already run it.
```lua
layers.active.asset:build() -- rebuild and save
layers.active.asset:build({ save = false })
```
It answers with how many entities each surface placed —
`{ content = 6, editorOnly = 1 }` — and with nil for a scene that has no
`build.luau`. Called while a build for that scene is already running, it returns
at once with `{ inFlight = true, scene, trigger, startedBy, message }` naming
that build instead of starting a second one; `inFlight` is what tells the two
answers apart.
An operation the bake cannot hold is **refused** rather than applied. A build
accepts what its records carry: entity lifecycle, transforms, hierarchy, names,
visibility, active state, participation mode, network scope, attributes, and
components with their public data. Anything else raises while the build runs,
naming the operation and the build it answered to, instead of leaving the scene
depending on something no reload brings back. When that happens the previous
build stays exactly as it was. A runtime resource a build needs — a mesh it
generates, a texture it writes — is made as an asset instead, below. Everything
else a refusal names goes outside the builder, or into a component the builder
attaches, which runs at play.
### The assets a build makes
`build.asset(type, name, produce)` makes an asset the build's content names — a
mesh a lathe produces, a texture a pattern writes. `produce` takes nothing and
returns the creation parameters `asset.create` takes for that type; the call
returns the asset's `AssetRef`, which is what a component field holds.
```lua
function content()
local tower = build.asset("mesh", "tower", function()
local positions, indices = lathe(profile, 16)
return { positions = positions, indices = indices }
end)
entity.spawn("tower").component.add("Model", { model = tower })
end
```
The asset is authored inside the scene's own folder — `Lobby.scene/tower.mesh`
— and the scene records which `build.luau` produced it in `.build.assets`. So
`produce` runs when the build script changed and never otherwise: a reload
re-runs the build and reuses the asset, while editing the profile re-authors
`tower.mesh` **in place**, keeping its path and its guid. That is what holds the
reference — `scene.json` names assets by guid.
For a part of a scene that several scenes place — or that one scene places many
times with different settings — see `guides { path: "types/sceneModule" }`,
which is the same idea with declared `inputs` a placement sets.
`guides { path: "core/scenes-as-code" }` covers both.
## The entrypoint
`entrypoint.luau` is the scene's **runtime** — what happens while the game is
being played. What the scene *is* comes from `build.luau` above; nothing here
has to construct it.
`entrypoint.luau` is auto-discovered as a sibling of `scene.json`. The
loader runs it in a fresh environment and folds its top-level
`function name(...)` declarations into the matching scene lifecycle event.
Define the callbacks the scene needs — the recognised set:
- `onLoad()` — the scene loaded in **play** mode. Gameplay-start hook,
runs on every connected client.
- `onHostLoad()` — the scene loaded in **play** mode, on the client that
owns the scene's synced content (the relay room creator; offline and
single-player count as host). Fires once. Entities spawned here — and
anywhere downstream — become synced automatically, so this is where
shared world content is spawned: it runs on exactly one peer, and every
other peer receives the entities from the relay snapshot.
- `onEditLoad()` — the scene loaded in **edit** mode. Custom per-scene
authoring tools. Writing this file while the scene is loaded in edit mode
reloads its layer, so the new `onEditLoad` runs after the previous load's
`onUnload`.
- `onUnload()` — before the scene's entities are torn down. Extra cleanup;
engine-managed teardown (entity despawn, resource release) runs
separately.
- `update(dt)` — per frame in play mode, while the gameplay clock
runs.
- `editorUpdate(dt)` — per frame in edit mode, running or paused.
Play-paused ticks neither hook. The scene loader partitions these
strictly on mode; a component's hooks of the same name read
`engine.paused` instead, so the two rules differ — `man components`
has that table.
- `localPlayerReady(player)` — once the local player's avatar is ready.
Gameplay wiring for the local player: attach state, bind UI, swap the
avatar. The avatar is already placed at the PlayerSpawn, so this is for
behavior, not positioning.
- `playerJoined(player)` — a remote player joined this scene's room. Use
for per-player UI (nameplates, greetings). The local player arrives
through `localPlayerReady`.
- `playerLeft(eid)` — a remote player left this scene's room. Receives the
departed entity's id (the entity is already despawned).
Each scene's entrypoint runs in its own environment, so two scenes can
declare the same top-level names without clashing. Keep each callback
short; push per-scene logic into `scripts/` modules and `require` them.
## Layers
Scenes load through the `layers` namespace.
- `layers.load(ref, opts?)` — load a scene. `ref` is a scene AssetRef or
identity string. Without `opts.additive`, this is a **root** load: it
replaces the current root scene. `opts`:
- `additive` — load as an overlay alongside the current root instead of
replacing it.
- `persistent` — keep an additive overlay mounted across mode flips and
root swaps.
- `origin` — a `{x, y, z}` world offset for the overlay's entities.
- `deferred` — spread the entity spawn across frames (for
thousand-entity scenes); the load signals complete only once the
scene has settled.
- `layers.active` — the current root scene proxy (nil before any load).
- `layers.list()` — every loaded layer (root + additive overlays).
- `layers.find(ref)` / `layers.is_loaded(ref)` — look up a loaded layer by
ref.
- `layers.onLoad(cb)` / `layers.onUnload(cb)` / `layers.onBeforeLoad(cb)` —
subscribe to every scene load / unload (distinct from a scene proxy's
own `:on_load` / `:on_unload`, which fire only for that scene).
A root scene carries the `players`, `camera`, and `settings` surfaces;
additive overlays inherit the root's players and lighting and do not carry
their own.
### The scene proxy
`layers.active` (and `layers.find` / `layers.list` entries) returns a
scene proxy:
- Fields: `.guid` (canonical identity), `.name`, `.path`, `.asset`,
`.additive`, `.visible`, `.state` (`"loading"` → `"loaded"` → `"ready"`
→ `"unloading"`), `.ready`, `.players`, `.camera`, `.settings`,
`.entrypoint`.
- `.camera` — a proxy over the scene's primary camera entity; read and
write the live Camera component through it, and
`.camera.behaviors._list()` enumerates the available camera behaviors.
- `:save(opts?)` — publish the live scenegraph to canonical `scene.json`
(see Saving). A convenience that forwards to the scene ASSET's `save`
(`self.asset:save(opts)`): the proxy is the runtime view and owns nothing
on disk, so persistence lives on the asset.
- `:reload()`: unload and reload the same scene (a runtime respawn). A scene
with a `build.luau` runs its build again and saves the scene, so `scene.json`
holds what the reload built and the next play loads it; a library scene's
rebuild lands in the live scene alone.
- `:clearDirty()` — discard unsaved edits and respawn from canonical.
Forwards to the scene asset's `discard` (`self.asset:discard(opts)`).
- `:sceneAsset()` — the durable `AssetRef<scene>` this live layer maps to.
- `:promoteDirty()` / `:writeDirty()` / `:hasDirty()` — manage the dirty
overlay directly.
- `:unload()` — despawn the layer and free its slot.
- `:onReady(cb)` — fire once the scene reaches `ready` (latched: a late
subscriber fires immediately).
## Multiplayer & relay rooms
Every scene has its own relay room, keyed by the world guid, the boot
profile, the mode, and the scene guid. Switching scenes with
`layers.load` runs a room transition — leave the old room, tear down,
join the destination scene's room — all on the client that made the call.
Teardown of the old scene never leaks to peers in the new one.
In play mode connected to a relay, the scene's entities are
host-authoritative: only the room creator instantiates them (marked
synced), and every joiner receives them from the relay snapshot rather
than spawning their own. This is why shared world content belongs in
`onHostLoad` — spawning it in `onLoad` would run on every peer and
duplicate it. Each player's own avatar spawns per-user from the
PlayerSpawn on every client.
Edit mode and offline boots spawn locally and never auto-sync.
## Loading and saving
**Loading** — `layers.load(ref)` for a root scene:
1. Despawns the current root scene's non-persistent entities.
2. Instantiates the entities from `scene.json` (including the player
prototype and spawn for a `"spawns"` scene).
3. Applies lighting and sky.
4. Runs `entrypoint.luau` and fires lifecycle callbacks as their events
occur.
**Saving** — persistence lives on the scene ASSET. `sceneRef:save()`
writes the scene's current state back to canonical `scene.json`; when the
scene is loaded it captures the live scenegraph, and when it is not loaded
it promotes the pending dirty overlay. `layers.active:save()` is the
convenience form — it forwards to the active layer's mapped asset
(`layers.active.asset:save()`). Writing canonical is the only path that
does so: edit ↔ play cycles never save, so hitting play to test never
overwrites the scene. Between saves, live edits accumulate in a per-scene
dirty overlay that the loader merges on top of canonical.
`sceneRef:discard()` throws the overlay away and restores the saved state
— deleting the overlay, and respawning the live layer when the scene is
loaded. It works whether or not the scene is loaded, because the overlay
belongs to the asset, not the runtime layer. `layers.active:clearDirty()`
forwards here. Saves capture entity data, not the entrypoint script —
edits to `entrypoint.luau` and `scripts/` are always preserved.
`opts.to` on `save`/`discard` targets a different scene ("save as"),
taking either a bare name (`"level_2"`) or a full VFS path.
**What a record states.** A component's record in `scene.json` holds the
fields that instance's configuration states: the keys of the table it was
added with (a `build.luau` call's own init table, or the record it was
loaded from) and every field written since, through code, a tool or the
inspector. A field nothing set stays out of the record and takes the
component's declared default each time the scene loads, so changing that
default reaches every entity that left the field to it. To have an entity
follow the default again, remove the field from its record. A field set on a
live entity after its record was made is a change the scene review names
(`sceneAuthoring.changes` lists it as `+ Type.field = value`), and accepting it
writes the field into the record. A scene saved
before records were stated this way holds every field; those values load
and save as they are, since a stored value cannot be told apart from one an
author chose, and a hot reload that changes a default one of them shadows
names it. A stored field the component no longer declares is named by a
`[component.add]` warning when the record loads and left out of the next
save.
## Lighting
Lights are ordinary entities: a directional light, an ambient light, and
a sky are entities carrying `Light` / `ProceduralSky` components in
`scene.json`. Author, move, and tune them like any other entity. If a
scene is missing any of {directional light, ambient light, sky}, the
loader adds a temporary default for the absent one so a scene never loads
dark or skyless; the defaults are never saved into the scene.
Scene-level lighting state that is not an entity — clear color and sky
descriptor — lives under `layers.active.settings.lighting` (`clear_color`,
`sky`); writing those fields updates the engine live.
## Modes
Scenes load in both edit and play mode (see `man modes`). The mode
governs behavior:
- An entrypoint's `update(dt)` runs in play while the gameplay clock
runs, and its `editorUpdate(dt)` runs in edit. A component's hooks of
the same name follow the clock rather than the mode — `man
components` has the four states that produces.
- Player prototypes are live in edit and deactivated + internal in play,
where each user instead gets a clone. `EditorOnly` entities follow the
same edit-live / play-internal toggle.
- `onLoad` / `onHostLoad` fire on a play-mode load; `onEditLoad` fires on
an edit-mode load.
## How to create one
```luau
asset.create("scene", "<Name>")
-- Creates /zero/source/<Name>.scene/ with:
-- build.luau where this scene's content is written. A new one starts
-- with the sun / ambient / sky lighting and the "spawns"
-- player setup, commented for editing — everything else the
-- scene comes to hold is written here too.
-- scene.json what that code produces, baked.
-- entrypoint.luau commented lifecycle-callback stubs.
```
A freshly created scene has a player with a following camera on the first press
of play. It carries no ground, so the first thing to author is what the player
stands on — a `content()` line away in `build.luau`.
## Discovery
- `asset.list("scene")` — every registered scene.
- `asset.inspect("<name>")` — entity count, lighting summary, source path,
and this type README.
## Authoring conventions
- Keep static layout in `scene.json` — geometry, lights, props, the player
prototype and spawn.
- Keep dynamic setup in `entrypoint.luau` lifecycle callbacks — event
listeners, gameplay state, services attached to spawned entities.
- Spawn shared, synced world content from `onHostLoad`; spawn each
player's own gameplay wiring from `localPlayerReady`.
- Set the world's startup scene in `/.world_settings` — that is the scene
the world boots into.
- Y is up; +Z is forward.
- Renaming the folder changes the scene's identity — update every
`layers.load` callsite and the world's startup-scene field.
## Related types
- `.bundle` — reusable entity hierarchies that scenes spawn into
themselves.
- `.service` — cross-scene background work that outlives a scene load.
- `.world_settings` — picks the startup scene and world-level renderer /
physics options.
## In the Inspector
Selecting a scene opens its **Scene** section, read from `scene.json` without loading the scene: how many entities it holds, how many of them are roots (and their names), how players join and the file's format version when it states them, and whether the scene has edits not yet saved.
# guide
A guide is a single-file documentation asset: a `<name>.guide/` folder whose body is `guide.md`, surfaced through the `guides` MCP tool, the `man` shell builtin and the Docs panel. Drop one anywhere under `/zero/source/`, a `.package` included, and it shows beside the built-in guides.
## In the Inspector
Guide: the guide's word count, its headings, and **Open in Docs**, which opens it in the Docs panel.
# Material (asset type)
A material is a named, configured instance of a `.shader`. The shader
defines the surface look (lighting model, available property fields,
texture slots); the material picks values for those fields and a
shader to bind to. Renderable entities reference materials, not
shaders, so the same geometry can wear different materials and the
same material can be reused across many entities.
Entities sharing one material can still differ in a value: every drawn
object carries four `vec4` lanes of its own that a surface shader reads
as `input.shader_data[lane]` and `renderer.instanceData.set` writes. Use
that for a dissolve at its own progress per subject, a hit flash at its
own age, a fill level per instance — a material per entity is for when
the LOOK differs, not when a number does.
> New to how a material relates to its shader, its textures, and the live GPU
> material behind it? Read `core/resource-model` first. It also covers the
> difference between an authored `.material` asset (this type) and a runtime GPU
> material made with `renderer.material.create`.
## When to use one
- You want a named surface configuration an entity wears by referencing it
from its `Model` component (`material = "@.../<Name>"`).
- You want runtime property tweaks (`asset.resolve(ref):setProperty(...)`) to
affect every entity using the material at once.
- You want to publish a curated look (`Gold`, `RedGlow`,
`BrickWall`) other authors can reuse without re-typing shader
bindings.
If you need a brand-new lighting model or a custom visual effect, you
need a `.shader` first; the material wraps it.
## Where it lives
- Source: `/zero/source/.../<Name>.material/`
- Identity: `<Name>` (the `.material` suffix strips).
- Folder shape:
- `mat.yaml` — canonical material spec (shader + property values).
**Required.**
- `preview.png` — the material's rendered shader-ball still, its
persisted visual description. **Required.** Rendered when the
material is staged (`zm add`) with its preview missing or stale, and
by `generatePreviews`; it syncs, publishes, feeds image-based search,
and gives browsers a thumbnail.
- `README.md` / `.metadata` — optional prose + tags, indexed when an
author writes real ones.
- `textures/` — optional folder for embedded textures. Validator
allows the folder; its interior is unrestricted.
- `shaders/` — optional folder for a co-located custom shader.
Same rule.
## How to create one
```luau
asset.create("material", "<Name>")
-- Creates: /zero/source/<Name>.material/
-- mat.yaml (shader binding + property scaffold)
-- preview.png (rendered when the material is staged with `zm add`; the
-- picture lands as a change the next `zm add` stages)
-- `folder` places it in a subfolder of /source instead of the root:
asset.create("material", "<Name>", { folder = "materials" })
```
Pass the shader and initial values through `asset.create`, then tune with
`setProperty` and keep what you tuned with `saveDefinition`:
```luau
local mat = asset.create("material", "<Name>", { shader = "@builtin::shaders.pbr" })
mat:setProperty("base_color", { 0.8, 0.6, 0.1, 1 })
mat:setProperty("roughness", 0.3)
mat:saveDefinition() -- writes the tuned values into mat.yaml
```
This mints the `.material` asset and returns a handle you tune with
`setProperty`. A set is a runtime change: it reaches the GPU material and every
entity wearing it, and `saveDefinition` is the call that writes it into
`mat.yaml`, so a property driven every frame costs no file write and leaves the
authored file as its author wrote it. A purely runtime `asset.create` lives only
for the session.
For an ephemeral, runtime-only GPU material that is not an asset at all, use
`renderer.material.create` instead (see `core/resource-model`).
## How it operates
1. **Property reflection.** The bound shader's uniform struct fields
become the material's configurable properties — no manual property
declarations needed. `naga` introspects the shader at load.
2. **Property values.** `mat.yaml` groups values by type, each block
keyed by the shader's field names: `properties:` holds scalars and
colors/vectors, `ints:` holds integer-typed fields, `bools:` holds
boolean-typed fields, and `textures:` holds texture slots. Omitted
fields take the shader's default. A scalar is a bare number
(`roughness: 0.5`); a color or vector is an array
(`base_color: [1, 1, 1, 1]`). `shader:` is the shader's identity
string. This is the shape every material the engine writes uses. A
`saveDefinition` writes the changed values into the file where they
already stand and leaves the rest of it — its comments, the order of
its keys and blocks, the spelling of its literals — untouched. The older
`floats:` / `colors:` blocks (with `{ r, g, b, a }` map colors) still
load for materials hand-authored that way.
3. **Render state.** `render:` holds how the mesh is drawn rather than
what the shader reads: `blend` (the equation the fragment composites
with, also spelled `type`), `cull`, `depth_write`, `depth_compare`,
`topology` and `queue` (the draw order, a whole number: `2000` opaque,
`3000` transparent, `4000` overlay). The `.shader` type README's "The
render block" section lists every value each key takes, and
`asset.create`'s `render` argument takes the same keys and values.
4. **Application.** An entity wears a material by referencing it from its
`Model` component (`material = "@.../<Name>"`). Materials affect every entity
that references them; runtime `asset.resolve(ref):setProperty(...)` changes
propagate to all of them immediately, and last until the next mode change
unless `saveDefinition` writes them into `mat.yaml`.
5. **Texture binding.** Texture slots accept `color:r,g,b,a` for
solid colors, `default:white` / `default:black` / `default:normal` for the
engine's own fallback texels, `@builtin::textures.<name>` for builtins,
`path/to/image.png` for file textures, or a render-target handle
for camera renders. The GPU texture cache reads the `color:` and
`default:` forms from the string itself, so a slot written in one names no
asset and carries nothing with the material when it travels; every other
form names a texture asset the slot depends on.
A texture in `base_color_texture` is multiplied by `base_color`: every
built-in surface shader declaring both draws the texture's colour times
`base_color`, channel by channel. Under the default white `base_color` the
texture shows as itself, and a coloured `base_color` tints it. The two
read a colour differently: `base_color` is linear, and the slot reads its
texels as sRGB-encoded, a `color:` value's included, the way it reads an
image. A colour stated in both places is therefore multiplied by a darker
copy of itself: `color:0.62,0.14,0.05,1` in the slot decodes to
`0.34, 0.017, 0.0039`, so beside `base_color` `0.62, 0.14, 0.05` the
surface draws `0.21, 0.0024, 0.0002`, far darker than either. State a
solid colour once, as `base_color`, and leave the slot at its default
white.
6. **Hot reload.** Editing `mat.yaml` repacks the GPU uniform buffer
on the next frame; visible immediately.
7. **Inspector.** `type.yaml` names `inspector: { type: "inspector.luau" }`,
and `inspector.luau` declares the material's sections beside the generic
ones: `shader` (the bound shader, swappable), `properties` (each shader
field as its typed control) and `textures` (each texture slot as an asset
chip). They read the material through `mat:getShaderRef()` (the bound
shader's ref, `~` expanded) and `mat:getTextures()` (slot name →
`{ ref, name }`: the bound texture's guid and the id the material names
it by). An edit there is an authoring write: `mat:writeProperty(name,
value)` and `mat:writeTexture(slot, texture)` write the value into
`mat.yaml` (and drop the session's own value for it, so the material
reads what the file holds), and `setShader` rewrites the file; inside an
undo operation each file write is recorded, so undo puts `mat.yaml` back.
`setProperty` / `setTexture` stay runtime writes that last until the next
mode change.
## Discovery
- `asset.list("material")` — every registered material.
- `asset.inspect("<name>")` — shader binding, property values,
source path, this type README.
- `ls /zero/source/<Name>.material` lists the files the folder holds.
- `asset.resolve("<name>"):getProperties()` — the property fields exposed by
the bound shader, each at the value it currently holds: what `mat.yaml`
authored until something writes to the material, and the written value from
then on, whichever call wrote it. That is the value the surface is drawn
with. Read them back rather than guessing names; which fields exist comes
from the shader.
- `asset.resolve("<name>"):getDefinition()` — the authored `mat.yaml` bytes,
the value the material rests at.
- `asset.resolve("<name>"):getShader()` — the shader the material binds.
## Authoring conventions
- Use lowercase, descriptive names (`brushed_steel`, `red_glow`,
`tarmac_wet`). Avoid shader-name suffixes in the material name —
the binding lives in `mat.yaml::shader`.
- Drive every property the shader exposes; defaults are a fallback,
not a contract for which fields exist.
- Embed textures alongside the material (`textures/` subfolder) when
they're used only by this material; reference shared textures from
`@builtin::textures.*` or a library.
## Common pitfalls
- **Property names must match the shader's uniform struct exactly**
(case-sensitive). Misnamed properties silently get the shader's
default.
- **`base_color_texture` multiplies `base_color`.** A `color:` texture holding
the same value as `base_color` multiplies the colour by its own
sRGB-decoded value, so the surface renders far darker than the value
written. Write a solid colour as `base_color` alone.
- **Broken shaders break the material.** A material whose shader has a
parse error renders as the magenta checkerboard. Inspect the shader
first if the material looks wrong.
- **`setProperty` targets the material, not the entity.** Changes affect
every entity that references the material.
- **`setProperty` is a runtime change.** It reaches the GPU, not the file:
call `saveDefinition` to write the current values into `mat.yaml`. For a
per-entity override that no other entity sees, give the entity its own copy
with `Model:applySessionMaterial(renderer.material.create(...))`.
- **Renaming the folder changes the identity.** Update every `Model`
component and `asset.create` callsite that references it.
## Related types
- `.shader` — defines what properties exist; required before a
material can bind to it.
- `.preset` — captures a component configuration; conceptually
similar to a material, but for components instead of shaders.
# Module (asset type)
A module is a reusable, stateless (or globally-stateful) Luau library
that other code pulls in with `require()`. Modules are the unit of
factored-out logic in a world: helpers, math libraries, format
parsers, registries, shared algorithms.
## When to use one
- You have logic you want to share across multiple components,
services, scenes, or tools.
- You have a registry, lookup table, or shared cache that callers all
read from / write to.
- You want a stable API surface (`M.fn`) other code can depend on.
If the logic is bound to one entity, use a `.component`. If you want a
named UI of fields rather than functions, use a `.preset`.
## Where it lives
- Source: `/zero/source/.../<name>.module/`
- Identity: the source path with `/` written as `.` and each segment's
type suffix dropped — `/zero/source/demo/beats.module` is
`demo.beats`, and `/zero/source/kit.package/beats.module` is
`kit.beats`, the container's name kept and its `.package` suffix
gone. `asset.create` returns this string, `asset.resolve(...).identity`
reads it back, and the `require` forms below write it as
`<identity>`.
- Folder shape:
- `init.luau` (or `init.lua`) — module body. **Required.** Returns
a table (conventionally named `M`).
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
```luau
asset.create("module", "<name>")
-- Creates: /zero/source/<name>.module/
-- init.luau (canonical `local M = {} … return M`)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source, and that subfolder
-- leads the identity: `{ folder = "lib" }` produces `lib.<name>`.
-- `into` authors it inside a resolved container (a package, a toolbox),
-- whose own identity leads the same way:
asset.create("module", "<name>", { folder = "lib" })
asset.create("module", "<name>", { into = asset.resolve("myPkg.package") })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.module/` folder
indexes the asset and registers the module path with the resolver.
2. **Loading.** The first `require("<identity>")` runs
the file's body and caches the returned table. Subsequent requires
from anywhere return the **same table** — this is the
shared-state lever for "module-local" registries. The body runs in
an environment of the module's own: a name it declares without
`local` is readable by the module's own functions and by no other
script, so an export reaches its callers through the returned table
and nothing else. Requiring a component's folder runs its chunk the
same way, once, and its `update`, `start` and `public` stay in that
environment; a component runs on an entity through
`entity(id).component.add(name)`.
3. **Hot reload.** Editing the file re-runs the module body and folds
what it returns into the table already loaded, so that table keeps
its identity: a caller that captured it with `require` reads the new
source's functions and values through the reference it already
holds, and a later `require` returns that same table. A key the new
source drops goes away; a key something set at runtime stays. The
body's own `local`s start again from their initial values, so state
that must outlive an edit lives in `modules.state()`
(`guides { path: "core/scripting-and-tasks" }`).
4. **Identity resolution.** A module is reached by its `<identity>`,
and where the caller lives decides which spelling of it resolves.
For a module in a **world**, from a caller in that same world —
another module, a component, a scene entrypoint, or an `execute`
chunk:
- `require("<identity>")` — the identity on its own, resolved
against the caller's own root. It carries every folder segment,
so a module created with `{ folder = "demo" }` is
`require("demo.beats")`.
- `require("@root::<identity>")` — the same root-relative
resolution, written out.
- `require(".sibling")` — a module in the same folder, by its bare
name; `..name` steps up one folder, `...name` two.
Logs, stack traces and hot-reload notices name that same module
`@local.source.<identity>` — its key under the world source root.
The `<identity>` tail of that key is the form above, so a trace
reading `@local.source.demo.beats` is `require("demo.beats")`.
For a module in a **library** — content under
`/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's
root from anywhere: `require("@builtin::modules.transform")`.
Mounting a world as a library moves its files under such a root and
flips the caller root to `@<lib>::`, which is what keeps the
root-relative forms above resolving across the move.
## Discovery
- `asset.list("module")` — every registered module.
- `asset.inspect("<name>")` — public functions, source path, this
type README.
- `ls /zero/source/<name>.module` lists the files the folder holds.
## Authoring conventions
- Return a single `M` table from `init.luau`. Top-level statements
with side effects run on first require — useful for one-time
initialization, dangerous if they touch the engine before it's
ready.
- Write exported functions as `typed function`, not `function`: the
argument types are enforced at the call and the checker knows the
signature, so a caller's mistake is reported where they made it.
- Annotate exported functions with `--!desc` / `--!arg` / `--!return`
/ `--!example` so the LSP, `tools.list`, and `asset.inspect`
surface them. A function with no `--!desc` is reachable only by
someone already reading this file.
- Declare a VALUE with `Field.<kind>(default, mode, description)`, and
a table whose members are reached through a metatable with
`--!members <TypeName>` — the latter gives the surface its accepted
member set, its type, and its documentation from one table. See
`guides { path: "core/authoring" }` for all four rules and
`modules/api/engine/entity.module/members.module` for a worked
member table.
- Keep module state in module-local upvalues or in `modules.state()`.
A name the body declares without `local` lives in the module's
environment, which every run of the module shares: a function the
previous run left in place reads what the reload assigned. Module-locals start again from their
initial values with each hot reload; the table `modules.state()`
returns is the same table on both sides of every reload.
- Prefer focused modules over kitchen-sink modules. If two halves of a
module have no shared state, split them.
## Common pitfalls
- **Cyclic requires.** A `require` chain that loops will return the
partial table (the half built before the cycle was detected).
Design for one-way dependencies.
- **Engine-time side effects.** Don't `entity.spawn` at module
top-level — the engine may not be ready. Expose an `M.init` and
call it from a scene entrypoint.
- **Hot-reload + module-local cache.** A module that caches
expensive computation in upvalues loses that cache on reload —
fine for dev, but be aware in performance work.
- **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical.
- **Writing one while play runs.** A `/source` write made while play is
running lands on the play shadow, and a guarded play-exit discards it
unless it is kept. One `.module` write shadows `init.luau`, the
`README.md` and the `.metadata` together.
`vfs.write(path, bytes, { durable = true })` skips the shadow, and
`vfs.promotePlayShadow` keeps what is already on it — the `core/vfs`
guide has the model and what each route costs.
## Related types
- `.component` — for entity-bound state + lifecycle hooks.
- `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider.
- `.tool` — for a single agent-callable function with a YAML schema.
- `.package` — to group several modules + components + scenes into
one shippable folder.
## In the Inspector
Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
# data (asset type)
A `.data` instance is a configured value binding to a `dataType`
contract: `values.yaml` names the contract and supplies the field
values the contract's schema declares. Instances carry values only —
structure (field types, constraints, defaults) and behavior live on the
bound contract, never on the instance. Think of it as the
ScriptableObject *asset* to `dataType`'s ScriptableObject *class*.
## When to use one
- You have a `dataType` contract (e.g. `weapon`, `questObjective`) and
need one or more concrete, named configurations of it (`smg`,
`rifle`, `sniper`).
- You want the configuration to persist as authored content, discovered
by `asset.list("data")` / `contractType:instances()`, and validated
against the contract on every edit.
- Mutable *runtime* state (ammo remaining, cooldown timers) belongs on
a component, not here — a `.data` instance is configuration, not
simulation state.
If you don't have a contract yet, author one first
(`asset.create("dataType", ...)`).
## Where it lives
- Source: `/zero/source/.../<Name>.data/`
- Identity: `<Name>` (the `.data` suffix strips).
- Folder shape:
- `values.yaml` — `contract: <dataTypeName>` plus a `values:` map of
the contract's fields. **Required.**
- `.metadata` — description + tags for search. **Required.**
Play-mode edits fork a runtime copy (`runtime_copy: true`) — tweaking
values while gameplay runs never writes back to the source instance.
## How to create one
```luau
asset.create("data", "<Name>", { contract = "<dataTypeName>" })
-- Creates: /zero/source/<Name>.data/
-- values.yaml (contract binding + the contract's declared defaults)
-- .metadata (empty description/tags — fill both to publish)
```
`opts.contract` is required — creating without it, or naming a
contract that isn't a registered `dataType`, errors loudly and names
`contract` in the message. The seeded `values.yaml` fills every field
the contract declares a default for, so a fresh instance is immediately
valid wherever every required field has a default.
## Ref surface (`AssetRef<data>`)
- `ref:contract()` — the bound `AssetRef<dataType>`.
- `ref:satisfies(wanted)` — `(ok, reason?)`: whether this instance's
contract chain includes `wanted` (the bound contract itself, or any
contract it extends). `reason` is a string explaining a `false`
result (unrelated contract, unresolvable binding, invalid values).
- `ref:validate()` — `(ok, violations)` against the bound contract's
merged schema. `violations` is an array of `{ path, message }`.
- `ref:data(wanted?)` — the resolved, read-only value object: this
instance's `values.yaml` with the bound contract's schema defaults
filled in, `assetRef` / `dataRef` fields materialized (`assetRef` →
`AssetRef`, `dataRef` → a nested value object resolved the same way),
and the bound contract chain's `behavior.luau` methods reachable by
field-style call — `v:someMethod()` alongside `v.someField`. Method
resolution is **child-first**: the bound contract's own methods win
over an inherited one of the same name, and either loses to an
explicit instance value of that name (values always shadow methods).
A contract with no `behavior.luau` simply contributes no methods —
it still inherits its ancestors' via the chain.
Pass `wanted` to assert the instance's bound contract satisfies that
contract before resolving (same semantics as `:satisfies`) — it's an
assertion of intent, not a filter: the returned object still carries
the full bound schema and full method chain, not a view scoped to
`wanted`.
Raises when the instance's values violate its contract (same
violations `:validate()` reports), when `wanted` doesn't appear
in the bound contract's chain, and when `dataRef` fields form a
circular chain (instance A referencing B referencing A).
The object is read-only at the top level — assigning a field raises;
change configuration by editing `values.yaml` instead. Nested plain
tables (struct and array values) are private copies of the resolved
snapshot: mutating them changes only your snapshot, never the source
instance or any other caller's resolve.
Generalized iteration (`for k, v in w do`) walks the resolved value
fields (explicit values + filled defaults); methods are reachable by
name but never appear in iteration.
```luau
local w = smg:data() -- resolved value object
print(w.damage, w.fireMode) -- schema values (with defaults)
print(w:dps()) -- a behavior.luau method, if the contract ships one
local weapon = smg:data("weapon") -- asserts smg's contract chain includes "weapon"
```
## Discovery
- `asset.list("data")` — every registered instance, as `AssetRef`s.
- `<contractRef>:instances()` — every `.data` instance bound to that
contract or to a contract that extends it (see `dataType`'s ref
surface).
- `asset.inspect("<name>")` — the instance's files, bound contract,
values, and this type README.
- `ls /zero/source/<Name>.data` lists the files the folder holds.
## Authoring conventions
- Name instances for the specific thing they configure (`smg`,
`rifle`), not for the contract they bind (that's `values.yaml::contract`).
- Keep `values.yaml` limited to configuration; anything that changes
during gameplay belongs on a component instead.
- Say what this specific configuration is tuned for in the `description`
of its `.metadata` — the contract's own README documents field meaning.
## Common pitfalls
- **Missing or unknown contract at creation.** `opts.contract` must
name an existing `dataType`; both a missing `opts` and an unknown
contract name error before any file is written.
- **Values drifting from the contract.** Editing `values.yaml` re-runs
validation immediately; a violation warns rather than silently
passing through.
- **Confusing configuration with runtime state.** A `.data` instance
never mutates during play — components own live state.
## Related types
- `.dataType` — the contract this instance is bound to; owns
structure, validation, and (optional) behavior.
- `.preset` — a named set of values for one declarer's settings schema
(an assetType, an importer, a component), not a contract of its own.
## In the Inspector
Values: a link to the contract this instance is bound to, every contract field as a typed control (`data_schema`'s `toFields`), and the values that break the contract. An edit is checked against the contract and written through `dataRef:setValues`, one undoable step. `setValues` re-encodes values.yaml with `Yaml.encode`, so comments in the file are not kept; a values.yaml that carries comments is therefore shown read-only, with **Open** for the file.
`dataRef:setValues(patch)` replaces the named top-level fields and checks the result against the contract. A change is refused (one error naming each violation, nothing written) when it introduces a violation or leaves one standing at or under a value it set. A list item is known by what it holds rather than where it sits, so removing or reordering items sets none of the rest. A violation the file already held anywhere else stays listed and does not stop the change, so an instance that does not yet satisfy its contract fills in one field at a time, and a value beside a key the contract does not declare stays editable. It writes values.yaml, recorded into the open undo operation when there is one. An Inspector edit writes only the leaves it changed: every other value keeps its stored value and form, including a colour held as numbers, a map-form vector, and keys the contract does not declare.
# dataType (asset type)
A dataType is a user-authored typed-data contract: it declares a set of
fields — names, types, constraints, defaults — that any bound `.data`
instance must satisfy. A contract can carry an optional `behavior.luau`
of methods its instances expose. Think of it as a ScriptableObject
schema: the contract defines structure and behavior, `.data` instances
supply the values.
## When to use one
- You want a typed, validated configuration shape (a weapon's damage /
fire mode / recoil profile, a quest's objectives, a loot table's
entries) that many `.data` instances can be authored against.
- You want field-level validation (required, numeric ranges, enums,
references to other assets or data instances) enforced the same way
everywhere the contract is used.
- You want shared structure across related contracts without
duplicating field declarations — `extends` factors common fields
into a parent contract.
If you only need a named set of values for settings something already
declares, use a `.preset` instead. If you need executable shared logic rather than
typed configuration, use a `.module`.
## Where it lives
- Source: `/zero/source/.../<Name>.dataType/`
- Identity: `<Name>` (the `.dataType` suffix strips).
- Folder shape:
- `schema.yaml` — the field declaration (`fields:`, optional
`extends:`). **Required.**
- `README.md` — instance documentation: what the contract models,
what each field means. **Required.**
- `.metadata` — description + tags for search. **Required.**
- `behavior.luau` — optional ref methods this contract's `.data`
instances expose beyond the built-in `:contract` / `:satisfies` /
`:validate` surface.
## How to create one
```luau
asset.create("dataType", "<Name>")
-- Creates: /zero/source/<Name>.dataType/
-- schema.yaml (`fields: {}`, a valid contract with no fields yet)
-- README.md (instance README template)
-- .metadata (empty description/tags — fill both to publish)
```
Then edit `schema.yaml` to declare the contract's fields.
## `schema.yaml` field-spec vocabulary
```yaml
extends: "item" # optional: parent contract identity
fields:
damage:
type: number
required: true
min: 0
max: 100
fireMode:
type: string
enum: ["semi", "burst", "auto"]
default: "semi"
muzzle:
type: vec3
default: [0, 0, 0]
tint:
type: color # "#rrggbb"/"#rrggbbaa" or {r,g,b[,a]}
fireSound:
type: assetRef
assetType: soundClip # required for assetRef fields
recoil:
type: dataRef
contract: recoilProfile # required for dataRef fields
required: true
falloff:
type: array
items:
type: struct
fields:
distance: { type: number }
multiplier: { type: number }
```
Field types: `number`, `string`, `boolean`, `vec3`, `color`, `assetRef`,
`dataRef`, `array`, `struct`.
- `required` — a boolean; a field with a `default` is never "missing"
even when `required` is set.
- `default` — must itself satisfy the field's own constraints (checked
at declaration time).
- `min` / `max` — apply only to `number` fields.
- `enum` — apply only to scalar fields (`number` / `string` /
`boolean`); the value must equal one of the listed entries.
- `assetRef` — needs an `assetType`; validated against
`asset.resolve(identity, assetType)`.
- `dataRef` — needs a `contract`; validated against whether the
referenced `.data` instance's contract chain includes it
(`:satisfies`).
- `array` — needs an `items` field spec every element must satisfy.
- `struct` — needs a `fields` map of nested field specs; struct values
reject unknown keys the same way top-level values do.
## `extends`
A contract may declare `extends: "<parentContract>"` to inherit the
parent's fields. The child adds new fields — it never redeclares a
field the parent (or any ancestor) already declared; doing so is a
schema error. Behavior is optional at every level: a contract may
carry `behavior.luau` or not regardless of whether its parent does.
Chains are single-inheritance and acyclic — a cycle raises loudly the
moment the chain is resolved (`:schema`, `:validate`, `:defaults`,
`:chain` all resolve the chain). Editing a parent's schema does not
re-warn its child contracts at edit time; validation stays loud where
the chain is used — `:schema` / `:validate` calls and the publish gate.
## Ref surface (`AssetRef<dataType>`)
- `ref:schema()` — the merged field map (own fields + every field
inherited through `extends`).
- `ref:validate(values)` — `(ok, violations)` against the merged
schema. `violations` is an array of `{ path, message }`.
- `ref:defaults()` — the default value table the merged schema
declares (a fresh, mutable table).
- `ref:parent()` — the parent contract ref (`extends`), or nil for a
root contract.
- `ref:chain()` — the full extends chain as refs, root parent first,
this contract last.
- `ref:instances()` — every `.data` instance bound to this contract or
to a contract that extends it, as `AssetRef`s. A full scan over the
world's data assets — a discovery surface for authoring and tooling,
not a per-frame call.
## Discovery
- `asset.list("dataType")` — every registered contract, as `AssetRef`s.
- `asset.inspect("<name>")` — the contract's files, declared schema
body, instance README, and this type README.
- `ls /zero/source/<Name>.dataType` lists the files the folder holds.
## Authoring conventions
- Name contracts for the concept they type (`weapon`, `questObjective`,
`lootTable`), not for a specific instance.
- Factor genuinely shared fields into a parent contract via `extends`;
don't duplicate a field declaration across sibling contracts.
- Document every field's meaning and units in `README.md` — the schema
only carries types and constraints, not intent.
## Common pitfalls
- **Redeclaring an inherited field.** `extends` merges parent fields
in; a child that re-declares a field name the parent already
declared is a merge error, not a silent override.
- **Cyclic `extends`.** Contract A extending B extending A raises
loudly the first time the chain is resolved — fix the chain, there
is no partial result to fall back to.
- **assetRef/dataRef without existence checks.** `assetType` and
`contract` on ref fields are declaration-time requirements; the
referenced asset or data instance is checked at validation time, not
declaration time.
## Related types
- `.data` — a configured value instance bound to a dataType contract.
- `.preset` — a named set of values for one declarer's settings schema
(an assetType, an importer, a component), not a contract of its own.
- `.component` — executable entity behavior, versus this type's typed
configuration data.
## In the Inspector
Contract: the contract it extends (a link), every field across the extends chain with its type, whether it is required, its default and its bounds or allowed values, and **Count instances**, which scans every data asset for the ones that satisfy it (a count taken before a data asset was made or removed says so).
# 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 **main viewport's** size in pixels. |
| `ctx.time` | Seconds since boot. |
| `ctx.frame` | Monotonic frame index. |
| `ctx.renderPath` | `"forward"` / `"deferred"` / … — branch passes on the active path. |
| `ctx.settings` | The feature's knobs as they stand this frame — see "Settings". |
## 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:
```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.
`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. Resized on the presented frame only, and never cleared for an offscreen render, since none of those phases run there |
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. A composite-space target survives an offscreen render
untouched, but it follows the presented frame alone.
## 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. It follows `screenSpace` and
`screenScale` like any screen-sized target; a composite-space one is kept for
the viewport, the one view that draws the post-scene phases.
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.
## 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/depth not yet drawn |
| `afterSky` | sky only; depth empty |
| `afterOpaque` | opaque drawn, before transparents. `@scene.depth` (and the deferred G-buffer) are populated. Forward: lit opaque. Deferred: opaque is in the G-buffer, so the colour is still sky only until the composite (use `afterOpaqueLit`) |
| `afterOpaqueLit` | the lit opaque scene, still before transparents, on **both** paths — the forward opaque draw, or the deferred lighting 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 |
| `afterTransparent` | transparents drawn, before the OIT composite |
| `afterLighting` | deferred-lighting + OIT composite done — fully lit, final geometry on **both** paths |
| `afterScenePost` | scene-layer post (DoF/MB/…) done, before UI |
| `afterUI` | scene + UI composited |
| `afterPost` | all-layer post done — the final image, before present |
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 — but they 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.
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 earlier spellings still bound to it:
| Name | Holds | Format | Valid from | Aliases |
|---|---|---|---|---|
| `@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` on (previous frame's before — declare `readsPrevious`) | — |
| `@scene.shaded` | what a surface SENT — its shaded colour, linear and scene-referred | `Rgba16Float` | deferred path, `afterOpaque` on (previous frame's before) | `@scene.albedo` |
| `@scene.material` | what a surface IS — base colour (RGB565) + metallic + perceptual roughness | `Rgba8Uint` | deferred path, `afterOpaque` on (previous frame's before) | `@scene.mr` |
| `@scene.emissive` | radiance a pass stamped on the surface, added at the composite | `Rgba16Float` | deferred path, `afterOpaque` on (previous frame's before) | — |
| `@scene.ao` | scene occlusion a feature wrote, read back by shading | `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.colorHistory` | the lit colour the target's previous render ended with | `Rgba16Float` | every phase | — |
| `@scene.lights` | the punctual-light storage buffer: 64 light entries of twelve vec4s each (the light, then its punctual shadow record), followed by the virtual shadow map's region. A loop runs over the first `@frame.camera[4].w` entries, the lights in use; the buffer's length counts the shadow region too, so `arrayLength` does not size a light loop | storage buffer | every phase | — |
| `@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 | — |
`docs/topics/rendering.guide/guide.md` and `docs/topics/raytracing.guide/guide.md`
both point here rather than repeating this table.
**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;
```
The earlier spellings still bind: `@scene.albedo` resolves to `@scene.shaded`
(the SHADED lit colour) and `@scene.mr` resolves to `@scene.material` (the
material channel), so a feature written against either keeps resolving. The
engine logs the substitution once per spelling, naming the canonical one to
write going forward.
`@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: 10×`vec4<f32>` = the inverse view-projection (columns `[0..4)`,
column-major) + camera world position (`[4].xyz`) + the previous render's
view-projection (columns `[5..9)`), which projects a point into the picture
that render left. 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 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. 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 three 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 lighting composite
}
```
Blend modes: `"replace"` (overwrite), `"alpha"` (source-over), `"additive"`
(sum), `"under"` (premultiplied dst-over-src — accumulates coverage-weighted
contributions). 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` (and its earlier spelling `@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").
### 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. 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.
### Compute passes
A compute pass dispatches a `.shader` compute program over a workgroup grid:
```luau
ctx.enqueue {
kind = "compute",
shader = myComputeShaderKey,
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",
shader = myComputeShaderKey,
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.
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` / `@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.
### Splat passes
A splat pass draws every record of an f32 buffer as a camera-facing billboard —
the raster primitive behind screen-space particle surfaces (the `fluidSurface`
system is built entirely on it):
```luau
ctx.enqueue {
kind = "splat",
phase = "afterLighting",
output = depthRt.guid, -- or `outputs` for the thickness+color MRT
splat = {
buffer = "my_particles", -- compute-buffer name
stride = 12, -- floats per record
posOffset = 0, -- float offset of the position
count = 200000, -- records to draw
radius = 0.3, -- world particle radius
channel = "depth", -- "depth" | "thickness" | "sprite" | "gaussian"
velOffset = 4, -- optional: velocity → screen-space stretch
stretch = 0.04, -- seconds of motion elongating the billboard
colorOffset = 8, -- optional (thickness): + per-particle RGB → MRT
weightOffset = 7, -- optional (sprite): per-particle intensity
minY = -60.0, -- records below this y collapse (parked/dead)
maxRadiusPx = 120, -- optional: cap on the projected pixel radius
},
}
```
The `"gaussian"` channel draws the engine's packed splat records — what
`renderer.splat.components` decodes a `.spz` or `.ply` capture into — as
elliptical-weighted-average Gaussians, and takes fields of its own:
```luau
splat = {
buffer = "cloud_records",
stride = 6, -- the packed record is six u32 words
posOffset = 0,
count = 1200000,
radius = 1.0, -- multiplies each splat's stored scale
channel = "gaussian",
orderBuffer = "cloud_order", -- back-to-front permutation; "over" needs one
shBuffer = "cloud_sh", -- optional: quantized higher-order SH
shStride = 24, -- u32 words of SH per record
shDegree = 3,
transform = model, -- object -> world, column-major, 16 floats
prevTransform = prevModel, -- where `transform` stood last frame
opacityScale = 1.0,
}
```
`transform` places the cloud: each Gaussian's covariance is conjugated by its
upper-left 3×3, so a non-uniform scale shears the cloud the way it shears a mesh.
`prevTransform` plus a second entry in `outputs` makes the channel write an MRT
pair — the colour into the first target, and the screen-space displacement each
splat underwent between the two placements into the second, premultiplied by the
same alpha the colour composites under. That second target therefore resolves to
`(coverage-weighted mean displacement, coverage)`, which is what folds a moving
cloud into `@scene.motion`. Naming one target, or leaving `prevTransform` out,
renders the colour alone.
The other three channels write different fragments: `"depth"` writes nearest-surface
linear view depth (R32Float, hardware-depth-tested on the target's own depth
buffer), `"thickness"` accumulates additive optical thickness (with
`colorOffset` and a two-entry `outputs` list it also accumulates
thickness-weighted color into the second target), and `"sprite"` accumulates a
soft additive disc scaled by `weightOffset`. Every channel discards fragments
behind opaque scene geometry by sampling the scene depth at the fragment's own
NDC. `maxRadiusPx` scales down billboards whose projected major radius would
exceed that many pixels, so particles crossing the near plane stay
droplet-sized instead of filling the screen. Targets clear at the pass;
`blend = true` on the spec loads them instead to accumulate over a prior
splat pass.
`renderer.feature.create(featureRef)` instantiates a feature and returns a live
handle (`featureRef` may be an `AssetRef<renderFeature>` or its identity string).
The handle appears under `/zero/runtime/generated_features/<guid>/`. Re-creating
the SAME feature asset replaces the live one (hot-reload after editing
`init.luau`) rather than stacking a duplicate.
- `renderer.feature.list()` → `{ {guid, identity} }` for every live feature.
- `renderer.feature.destroy(handleOrGuid)` (or `renderer.destroy(handle)`) tears
one down — by handle OR by guid string, so you can stop a feature even after
losing its handle (e.g. across separate `execute` calls).
## In the Inspector
Selecting a render feature opens its **Feature** section: whether the feature runs in this session, an Enable or Disable action, and its settings as typed controls. While it runs, the controls hold its live values and an edit reconfigures the running feature (`renderer.feature.configure` checks it against the schema first). Those edits are session state: they change the running feature only, they are not undoable (Ctrl+Z never reaches them), and Disable or a restart ends them; the feature's declared defaults are what the next Enable starts from. While it does not run, the controls show the declared defaults, read-only, and a write reaching it then is refused. A feature enabled, disabled or reconfigured from a script shows in the section as it happens. A feature that declares no settings says so.
# Shader (asset type)
A shader is a WGSL program that runs on the GPU. Materials reference shaders and
supply property values; renderable entities reference materials, not shaders
directly. This README is the canonical reference for writing **every** kind of
shader — it covers all domains, the surface authoring contract, the material
property schema, the engine library functions you can call, and how a shader
registers and compiles.
> New to how shaders, materials, meshes, and textures relate as assets and live
> GPU resources? Read `core/resource-model` first.
## Folder shape
A `.shader` is a folder asset:
```
<name>.shader/
shader.wgsl # the WGSL body (required)
properties.yaml # the material property schema (optional; surface shaders)
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 `.shader` suffix strips).
A shader's material properties are exactly the ones its `properties.yaml`
declares: a shader with no `properties.yaml` declares none, and the engine
reads no property from the WGSL body. A `.wgsl` file standing on its own,
outside a `.shader` folder, is WGSL source rather than a shader: a material
draws with the `.shader` folder that holds it as `shader.wgsl`. Materials and other assets
reference a shader by **AssetRef** (a typed, guid-backed handle), never by a raw
string.
## Domains
The first line of `shader.wgsl` declares the domain:
```wgsl
// @domain: surface
```
| Domain | What it is | You write |
|---|---|---|
| `surface` | A material on a mesh (the common case). | `fragment()` (+ optional `vertex()`/`vertex_clip()`). The engine generates everything else. |
| `post-process` | A full-screen pass over the rendered frame, in the space it declares (bloom, vignette, grade). | `fragment(in: PostInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `screen` | A standalone full-screen visual (UI background, procedural). | `fragment(in: ScreenInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `sky` | The sky background (a fullscreen material). | `fragment(in: SkyInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `compute` | GPU data processing, no rasterization. | *(legacy)* An `@compute @workgroup_size(...)` entry over storage buffers — you write the `@group/@binding` lines yourself. **The canonical path is now the separate `.computeShader` assetType** (see below); `.shader` + `// @domain: compute` still compiles for back-compat. |
`// @domain:` resolves the names above and `postprocess` / `screenspace` / `ui`
as further spellings of `post-process` and `screen`. A body carrying no
`@domain:` line is `surface`. `shaderRef:domain()` answers the domain a body
declares, a further spelling as the domain it names. Any other name is refused where the shader
registers, with an error naming the spellings that resolve, so a shader reaches
the renderer only under a domain the compiler scaffolds.
Particles are drawn and simulated through these domains like anything else: the
particle package's `particle_sprite` and `particle_mesh` are `surface` shaders,
and its simulation, culling and sorting steps are `.computeShader` assets.
## Texture coordinate space
A shader that samples a texture through a coordinate it builds itself declares
which space that coordinate lives in, on a line beside `@domain:`:
```wgsl
// @domain: surface
// @uv_space: world
```
| Value | The coordinate | A material's `uv_scale` means |
|---|---|---|
| `mesh` (the default) | The mesh's own UV attribute, `input.uv`. | How many times the texture repeats across a surface. |
| `world` | The fragment's world position, as a triplanar projection samples. | How many times the texture repeats per world unit, so a larger surface carries more. |
Texture residency reads the declaration to work out how finely a frame samples
each texture: a material laying eight copies of its texture across a surface
samples each copy at an eighth of the surface's size, and the mip level that
serves it is three levels coarser than the surface's own footprint implies.
Leaving the line out puts the shader in mesh space, which is what sampling
`input.uv` is. `renderer.textureStreaming().textures` reads back the span each
texture was measured at and the level that span asked for.
**Compute shaders are now their own assetType.** A `.computeShader/` folder gives compute the same zero-scaffolding contract surface/sky/post/screen get: you write only `@compute fn main` (+ helper fns/structs, **no `@group/@binding` lines**) and declare bindings in a sibling `bindings.yaml` (storage buffers, textures, samplers, storage textures, plus a `params:` uniform); the engine generates the `@group(0)/@binding(N)` declarations. Dispatch it through a resolved reference (`asset.resolve("name", "computeShader"):dispatch(...)`). See the `.computeShader` assetType README and `man compute`. The `.shader` compute domain above remains only for back-compat.
**Surface**, **sky**, **post-process**, and **screen** shaders all get
engine-generated scaffolding — you write only `fragment()` and declare properties in
`properties.yaml`; the engine generates the entry points and the group(1) material
interface. (Each domain's `fragment` takes a domain-specific input instead of
`FragmentData`: `SkyInput`, `PostInput`, or `ScreenInput` — see "Sky shaders" and
"Post-process & screen shaders" below.) Compute shaders get the same treatment via
the separate `.computeShader` assetType (write only `@compute fn main`, declare
bindings in `bindings.yaml`). The legacy `compute` domain here writes its own
entry points directly — see `man compute`.
## Surface shaders
A surface shader writes **only** the parts that are unique to it. The engine owns
all the scaffolding — the vertex stage, every render-mode entry point
(`vs_main` / `fs_forward` / `fs_gbuffer`), group(0) (camera, transforms, lights,
shadows, and the material rows), and the material interface generated from
`properties.yaml` (`material` and your texture slots). Adding a render path never
touches your shader.
Inside `fragment()` you have access to exactly four things — nothing is hidden:
1. **`input: FragmentData`** — the interpolated per-fragment surface data the
engine hands you: world position, world normal, uv, view direction, vertex
colour, and more. Every field is in the `FragmentData` table below.
2. **`material.*` and your textures** — the material inputs **you** declare in
`properties.yaml`. The mapping is mechanical: a scalar property named `foo`
becomes `material.foo`; a texture property named `bar` becomes `bar` (the
texture) and `bar_sampler` (its sampler). `material` has **exactly** the fields
your `properties.yaml` declares and no others — to add an input, add a property.
List what a shader exposes with `shaderRef:getProperties()` or
`asset.inspect("<name>")`.
3. **Engine state** — the scene's camera, lights, time, and shadows that the
renderer binds for every surface shader. `uniforms.*` (sun direction/colour,
ambient, `camera_pos`, `time`) and the punctual lights (`zero_point_light(i)`)
are always in scope; the shadow functions come from `#include "@builtin::shaderModules.shadows"`. This is how
you light a surface **without** the prebuilt PBR — see "Engine state" and
"Writing your own shading" below.
4. **Library functions** you `#include` (see "Library includes").
A shader and its property schema go together. The two files below are a complete
surface shader:
`properties.yaml` — declares the material inputs:
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
- { name: roughness, type: float, default: 0.5, min: 0, max: 1 }
- { name: metallic, type: float, default: 0.0, min: 0, max: 1 }
- { name: base_color_texture, type: texture, default: white }
```
`shader.wgsl` — those declarations are now `material.base_color`,
`material.roughness`, `material.metallic`, and the `base_color_texture` /
`base_color_texture_sampler` pair:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.pbr_shading" // the PBR helpers — see "Library includes"
fn fragment(input: FragmentData) -> vec4<f32> {
var s = zero_pbr_default_surface(input);
s.albedo = material.base_color.rgb
* textureSample(base_color_texture, base_color_texture_sampler, input.uv).rgb;
s.perceptual_roughness = material.roughness;
s.metallic = material.metallic;
return vec4<f32>(zero_pbr_shade(input, s), material.base_color.a);
}
```
`fragment()` returns the final colour. The engine forces no lighting model on
you — flat, toon, PS1, dithered, or PBR are all just different `fragment()`
bodies. Calling `zero_pbr_shade` is opt-in.
### The two surface bodies, and what each gives up
A surface shader exposes one of two entry points, and which one decides how
much of the shader the engine can see:
| Body | The engine gets | PBR debug passes read |
|---|---|---|
| `fn fragment(input: FragmentData) -> vec4<f32>` | the finished pixel, and the `PbrSurface` too when the body hands one to `zero_pbr_shade` | the real channel where a surface was handed over; magenta, the "no data here" marker, where the body shades by its own math |
| `fn surface(input: FragmentData) -> PbrSurface` | the surface (albedo, roughness, metallic, emissive, normal, occlusion), which the engine then lights | the real channel |
Both are first-class: `fragment()` is what you want when the shader owns its
own look, `surface()` when you want engine lighting. `capture { pass = "albedo" }`
(and `roughness` / `metallic` / `ao` / `emissive`) answers about your material
for either body wherever the engine has the surface — writing the same
`PbrSurface` behind `surface()` or behind `fragment()` + `zero_pbr_shade` gives
one answer per channel. A body that lights itself by its own math draws those
channels magenta. `pbr.shader` exposes `surface()`.
`capture { pass = "normal" }` is a geometry read rather than a material one, so
it answers for every shader: the normal of the surface where one was handed
over, and the interpolated normal of the triangle where none was. It is the same
normal the frame's normal buffer carries, which is what a screen-space pass
reading `@scene.normal` sees.
`shaderRef:shadingModel()` reports which one a shader ended up with —
`"engine-lit"` for `surface()`, `"self-shading"` for `fragment()`.
### Optional vertex hooks
```wgsl
// Displace geometry in OBJECT space. Runs on skinned meshes too (it sees the
// already-skinned, morph-applied local position). Return the modified vertex.
// The `v` parameter is immutable (WGSL function params are), so copy it into a
// `var` first and modify that.
fn vertex(v: VertexData) -> VertexData {
var out = v;
out.position += out.normal * sin(out.time) * 0.1;
return out;
}
// Post-transform vertex hook (runs AFTER the engine's world/skin/projection). Two
// things you can do here, separately or together:
// * move `clip_position` — vertex jitter, PS1 snapping, render-resolution lowering;
// * write `color` — PER-VERTEX (Gouraud) shading: light the vertex from its
// world_normal + the light context and the engine forwards the result into the
// interpolated `vertex_color` the fragment reads.
fn vertex_clip(v: ClipVertex) -> ClipVertex {
var out = v;
// Gouraud: Lambert sun + ambient, evaluated once per vertex (flat-banded shading).
let n_dot_l = max(dot(v.world_normal, -normalize(v.light_direction)), 0.0);
let lit = v.ambient_color * v.ambient_intensity + v.light_color * v.light_intensity * n_dot_l;
out.color = vec4<f32>(v.color.rgb * lit, v.color.a);
out.clip_position = round(out.clip_position * 80.0) / 80.0; // PS1 snap
return out;
}
```
#### Declaring how far a hook moves geometry: `vertexBoundsDilation`
Static geometry is culled per cluster against its bounds as authored. A hook that moves vertices — wind sway, an outline hull, a vertex wave — can move them outside those bounds, and the cull then drops clusters whose displaced triangles are still on screen. Declare the farthest the hook moves any vertex, in world units, as a `vertexBoundsDilation` float property, with a default that covers the shader's own properties across their ranges:
```yaml
properties:
- { name: sway, type: float, default: 0.5, min: 0, max: 4 }
# 0.4 x sway, at sway's largest value.
- { name: vertexBoundsDilation, type: float, default: 1.6, min: 0, max: 100 }
```
Each material sets its own value — a material that sways less can set less, one moved farther sets more — and a material that sets none takes the default. The cull adds the material's value to every bound in its frustum and occlusion tests (not to the level-of-detail cut). A shader with a hook and no `vertexBoundsDilation` property is named once in the engine log when it compiles; its geometry is culled against its undisplaced bounds.
### Structs the engine passes you
`FragmentData` (input to `fragment()`):
| Field | Type | Meaning |
|---|---|---|
| `world_position` | `vec3<f32>` | fragment world-space position |
| `world_normal` | `vec3<f32>` | interpolated geometric normal (normalized) |
| `world_tangent` | `vec4<f32>` | xyz = world tangent, w = handedness (mikktspace) |
| `uv` | `vec2<f32>` | primary texture coordinates (perspective-correct) |
| `affine_uv` | `vec2<f32>` | the same UVs interpolated **without** perspective correction — the PS1 texture "swim". Always available; sample with it instead of `uv` for affine texture mapping |
| `vertex_color` | `vec4<f32>` | interpolated per-vertex colour (white if unset; carries per-vertex lighting if `vertex_clip()` wrote it — see Gouraud below) |
| `view_position` | `vec3<f32>` | camera world position |
| `view_direction` | `vec3<f32>` | normalized world-space direction to the camera |
| `light_direction` | `vec3<f32>` | directional (sun) travel direction, unit length; surface→sun is `-light_direction`. Where no sun reaches the camera it points straight down |
| `light_color` | `vec3<f32>` | sun colour |
| `light_intensity` | `f32` | sun intensity; 0 where no sun reaches the camera |
| `ambient_color` | `vec3<f32>` | ambient colour |
| `ambient_intensity` | `f32` | ambient intensity |
| `frag_coord` | `vec4<f32>` | framebuffer pixel coords (xy) + depth (z) — for screen-space dither |
| `receives_shadows` | `f32` | per-instance: > 0.5 if this surface receives shadows |
| `material_index` | `u32` | per-instance: the index standing for the material this surface draws with — the number `renderer.materialIdentity()` maps to a name |
| `shader_data` | `array<vec4<f32>, 4>` | per-instance: this entity's own four `vec4` lanes — its `ecs.ShaderData` component's `lane0`..`lane3`, or what `renderer.instanceData.set` put in them (zero until something does). A procedural graph's elements set them through the `data0`..`data3` attributes |
| `front_facing` | `bool` | true for front faces (double-sided shading) |
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
`shader_data` is the per-instance channel, and it is what lets ONE material serve
many entities that differ in a value — a dissolve at its own progress per subject,
a hit flash at its own age, a fill level per instance. The alternative is a
material per entity, which is a separate pipeline binding and a separate row in
the material table for every one of them.
```wgsl
const DISSOLVE_LANE: u32 = 0u;
fn fragment(input: FragmentData) -> vec4<f32> {
let progress = input.shader_data[DISSOLVE_LANE].x;
...
}
```
```lua
-- one material on twenty entities, each at its own progress
renderer.instanceData.set(subject, 0, progress)
renderer.instanceData.clear(subject) -- back to zero lanes
```
The engine attaches no meaning to a lane: a shader and whatever writes it agree
what each one carries. Name the indices in the module that writes them.
`renderer.instanceData.laneCount()` is how many there are. The same lanes reach a
hardware-instanced population through `renderer.mesh.drawInstanced`'s
`instanceDataBuffer`, on slots no entity owns.
`VertexData` (in/out of `vertex()`): `position` (object-local, model-scale + morph
applied), `normal`, `uv`, `color`, `time`.
`ClipVertex` (in/out of `vertex_clip()`) — the post-transform vertex. Read context:
`clip_position`, `world_position`, `world_normal`, `uv`, `view_position`,
`view_direction`, `light_direction`, `light_color`, `light_intensity`,
`ambient_color`, `ambient_intensity`, `time`, `view_proj` (the view-projection of
the frame being evaluated), and where the vertex stands on its instance:
`local_position` (its position in the mesh, after `vertex()` and before the
instance's world transform), `object_origin` (the world position of the instance's
origin), `object_scale` (the world length of the instance's x, y and z axes) and
`object_axes` (`mat3x3<f32>`, the world direction of those axes, unit length) —
what a camera-facing card, a shard grown about its own base, or anything placed
per instance is built from. **Writable:** `clip_position` (snap /
jitter) and `color` (write a lit colour here for per-vertex Gouraud shading; the
engine forwards it to the interpolated `vertex_color` — left untouched, the mesh's
own vertex colour passes through).
`vertex()` and `vertex_clip()` run in the vertex stage, which reads the frame
uniforms (`uniforms.*`, and the `ClipVertex` members built from them), the scene
buffer (`zero_object_data`, `zero_object_visuals`, the node transforms), the
material interface and a `read` buffer property. The point, spot and area lights
(`zero_point_light`, `zero_punctual_projection`), the shadow maps, the
environment and light probes, the feature textures, the scene depth, colour and
reflection copies and a `@group(2)` buffer the shader declares `read_write` are
visible to the fragment stage alone: read them in `fragment()` or `surface()`. A
shader whose vertex hook reaches one fails to compile, and the error names the
stage, the binding and the calls that reach it.
### Each hook runs twice: this frame and the one before it
A vertex hook decides where the surface IS, so it also decides where the surface
WAS. The engine runs every hook a shader declares a second time, over the same
vertex standing one frame back — the previous-frame position stream, with
`time` = the clock that frame was drawn at and (for `vertex_clip()`)
`view_proj` = the view-projection it was drawn with. The motion vector the
renderer publishes is taken between the two results, so a displacement that
moves with time reports the velocity of the displaced surface, and a
displacement that does not move reports the motion of the transform alone
because the identical offset appears on both evaluations and cancels.
What that asks of a hook:
- **Take the frame from the argument.** `v.time` is the clock of the evaluation
being run; `uniforms.time` is always this frame's. A displacement built on
`uniforms.time` is identical on both evaluations, so its motion vector cancels
to exactly zero. The same holds for `v.view_proj` against
`uniforms.view_proj`: a clip hook that rebuilds its position from world space
through `uniforms.view_proj` reprojects the previous frame with this frame's
camera, and reports no camera motion at all. The wind helpers come in both
shapes for this reason — `zero_wind_sway_at_time(world_pos, stiffness, v.time)`
inside a hook, `zero_wind_sway(world_pos, stiffness)` outside one.
- **Anchor a wrap to `uniforms.time`.** A displacement that jumps discontinuously
— a falling drop that restarts at the top, a looping offset — differences its
jump as velocity on whichever frame it wraps. Compute the wrap COUNT from
`uniforms.time` and the position within the cycle from `v.time`, and both
evaluations share the same cycle, so the surface reports the speed it fell at.
`@builtin::shaders.rain_material` and `snow_material` do exactly that.
The per-vertex attributes (`world_normal`, `uv`, `color`) and the lighting and
camera-position context are this frame's on both evaluations, so a hook that
displaces along its normal reports the motion of the transform plus this frame's
displacement.
## Engine state — point lights & shadows
The common lighting state — the sun (`input.light_direction` / `light_color` /
`light_intensity`), the ambient (`input.ambient_color` / `ambient_intensity`), the
camera (`input.view_position` / `view_direction`), and `input.time` — is already on
`FragmentData`, so most shaders never touch the raw engine state. The one thing not
on `FragmentData` is the punctual-light array (its length varies), which is always
in scope:
| Expression | Type | Meaning |
|---|---|---|
| `uniforms.point_light_count` | `u32` | number of active point/spot lights |
| `zero_point_light(i)` | `PointLightData` | one point or spot light (fields below) |
| `zero_punctual_projection(i)` | `PunctualProjection` | a spot or area light's projection: `view_proj`, the frustum its cookie and shadow are placed by, and `cookie_layer` |
`PointLightData`: `position`, `radius`, `color`, `intensity`, `direction`,
`cone_outer_cos`, `cone_inner_cos`, `kind` (0 = point, 1 = spot).
Shadows come from `#include "@builtin::shaderModules.shadows"`:
- `compute_directional_shadow_factor(world_pos, normal, light_dir) -> f32` — 1.0 lit, 0.0 fully shadowed.
- `compute_spot_shadow_factor(...)` / `compute_point_shadow_factor(...)` / `compute_area_shadow_factor(...)` — one shadow shape each.
- `compute_punctual_shadow_factor(light_index, world_pos, normal) -> f32` — the row's own shape, read off its `kind`, for a loop that walks the punctual lights and does not want the switch.
- `zshadow_light_reach(light_index, world_pos, normal, object_channels) -> f32` — how much direct light that row puts on a surface on those light channels: the channel mask, falloff, cone or rect orientation, and the cosine, times intensity. Zero exactly where the light contributes nothing.
## Writing your own shading
The engine forces no lighting model — `zero_pbr_shade` is just one option. You can
light a surface yourself from the state above. Here is a complete custom-lit
(Lambert diffuse) surface with no PBR:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.shadows" // exposes compute_directional_shadow_factor
fn fragment(input: FragmentData) -> vec4<f32> {
let n = normalize(input.world_normal);
let albedo = material.base_color.rgb;
// Directional (sun) light: Lambert N·L, attenuated by its shadow.
let sun = normalize(-input.light_direction); // surface -> sun
let sun_shadow = compute_directional_shadow_factor(input.world_position, n, input.light_direction);
var lit = input.light_color * input.light_intensity * max(dot(n, sun), 0.0) * sun_shadow;
// Point + spot lights (the punctual-light array, varying length).
for (var i = 0u; i < uniforms.point_light_count; i = i + 1u) {
let pl = zero_point_light(i);
let to_light = pl.position - input.world_position;
let dist = length(to_light);
let l = to_light / max(dist, 1e-4);
let atten = max(1.0 - dist / max(pl.radius, 1e-4), 0.0);
lit += pl.color * pl.intensity * max(dot(n, l), 0.0) * atten;
}
// Ambient fill.
lit += input.ambient_color * input.ambient_intensity;
return vec4<f32>(albedo * lit, material.base_color.a);
}
```
- **Unlit:** skip the lights and return your colour directly.
- **Toon / PS1 / custom:** start from the loop above and band, quantize, or warp
it however you like.
- **PBR:** build a `PbrSurface` and call `zero_pbr_shade` (see "Library includes")
instead of writing the BRDF by hand.
## Material properties — `properties.yaml`
A surface shader declares its material properties in a sibling `properties.yaml`.
The engine GENERATES the entire group(1) interface from it — the uniform struct
(`material.<name>`) plus a texture/sampler pair per declared texture. You write
no `@group`/`@binding` lines.
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
- { name: roughness, type: float, default: 0.5, min: 0, max: 1 }
- { name: metallic, type: float, default: 0.0, min: 0, max: 1 }
- { name: emissive, type: color, default: [0, 0, 0, 1] }
- { name: base_color_texture, type: texture, default: white }
- { name: normal_texture, type: texture, default: flat_normal }
```
| `type` | WGSL field type | Notes |
|---|---|---|
| `float` | `f32` | optional `min`/`max` for editor sliders |
| `float2`/`float3`/`float4` | `vec2/3/4<f32>` | |
| `color` | `vec4<f32>` | sRGB colour, default is `[r,g,b,a]` |
| `int` | `i32` | |
| `bool` | `u32` | |
| `texture` | `texture_2d<f32>` + `sampler` | `default:` is a built-in texture name (`white`, `black`, `flat_normal`) |
In the shader you read scalars as `material.<name>` and sample textures as
`textureSample(<name>, <name>_sampler, uv)`. A texture slot with no bound texture
samples its default, so a shader can always sample — no presence flag needed.
`vertex()` reads the same material interface, so a height or deformation map
drives displacement from the slot it was bound to. A vertex stage has no implicit
derivatives, so sample it at an explicit mip there:
`textureSampleLevel(<name>, <name>_sampler, uv, 0.0)`.
## Sky shaders
A `// @domain: sky` shader draws the sky as a fullscreen pass. You write **only**
`fn fragment(in: SkyInput) -> vec4<f32>` — the colour along the view ray for each
pixel — and declare tunables in `properties.yaml` exactly like a surface shader
(read as `material.<name>`, textures via `textureSample(<name>, <name>_sampler, uv)`).
The engine generates the fullscreen `vs_main`/`fs_main`, the group(1) interface,
and reconstructs the world-space ray; there is no separate sky renderer — a sky
material runs through the same material pipeline, just on a fullscreen triangle.
A sky pipeline binds group(0) and the group(1) interface alone, so a sky that
reads a `buffer` property or any other `@group(2)` binding fails to compile, and
the error names the binding and the calls that reach it.
`SkyInput` (the only argument) carries:
| Field | Type | Meaning |
|---|---|---|
| `ray_dir` | `vec3<f32>` | normalized world-space ray through this pixel |
| `ndc` | `vec2<f32>` | screen position in NDC `[-1, 1]` |
| `sun_direction` | `vec3<f32>` | unit vector TOWARD the sun (from the directional light) |
| `camera_pos` | `vec3<f32>` | world-space camera position |
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
```wgsl
// @domain: sky
fn fragment(in: SkyInput) -> vec4<f32> {
let up = max(in.ray_dir.y, 0.0);
let col = mix(material.horizon_color.rgb, material.zenith_color.rgb, up);
return vec4<f32>(col * material.exposure, 1.0);
}
```
Day/night comes from `sun_direction.y` (the directional light's elevation), so a
sky shader never needs a time-of-day uniform — orient the light and the sky
follows. The builtin sky shaders (`procedural_sky`, `solid_sky`, `cubemap_sky`,
`equirect_sky`) are all authored this way; author a custom sky material and point
a `Skybox` component at it.
## Post-process & screen shaders
`// @domain: post-process` and `// @domain: screen` shaders are authored exactly
like surface and sky — you write **only** `fn fragment(in: PostInput) -> vec4<f32>`
(post) or `fn fragment(in: ScreenInput) -> vec4<f32>` (screen) and declare tunables
in `properties.yaml` (read as `material.<name>`, textures via
`textureSample(<name>, <name>_sampler, uv)`). The engine generates the fullscreen
`vs_main`/`fs_main` and the group(1) material interface. **There are no
`uniforms.params[i]` slots** — that convention is retired; every input is a named
property.
A **post-process** shader's `properties.yaml` carries one further, top-level key
beside `properties:` — `space`, either `light` (the default) or `display`:
```yaml
space: display
properties:
- { name: amount, type: float, default: 1.0, min: 0, max: 1 }
```
`light` is the scene's linear radiance — what every surface, the sky and every
`afterLighting` feature write, unbounded above 1.0. `display` is the code values
the `__display__` pass leaves behind after applying exposure and its tone curve
— the 0-1 range a colourist's tool and a dithered or quantized effect expect.
`postprocess.add`'s `opts.space` overrides what the asset declares for one
registration. The chain converts at both ends of an effect that runs on a
segment in the other space, so a light-space vignette still darkens a frame
graded after `__display__`, and a lookup table built from a `.cube` export
always sees the code values it was authored against, wherever the chain
runs it.
`space` also decides which layer a registration that names none lands on: a
`light` shader grades `scene`, the segment holding the scene's own light, and a
`display` shader grades `all`, the picture after `__display__` with the UI on
it. So `postprocess.add("glow", asset.resolve("~.shaders.bloom", "shader"))`
thresholds highlights that still stand above 1.0, and a lookup table registered
the same way reads the code values it was built for. `opts.layer` names one
explicitly — `"all"` is what an effect that must grade the interface says.
A **post-process** shader's `properties.yaml` carries a further, optional
top-level key — `passes:`, the pass list the frame draws through, in order:
```yaml
space: light
passes:
- { name: bright, entry: bright, scale: 0.5, inputs: [scene] }
- { name: down1, entry: downsample, scale: 0.25, inputs: [bright] }
- { name: up0, entry: upsample, scale: 0.5, inputs: [down1, bright] }
- { name: composite, entry: composite, inputs: [scene, up0] }
```
Every pass's entry — `fn <entry>(in: PostInput) -> vec4<f32>` — lives in the
one `shader.wgsl` the assetType recompiles on. `scale` is the fraction of the
view a pass draws at; the LAST pass takes none, since it draws at the view's
size and writes the chain's output. `inputs` names what a pass reads —
`"scene"`, the chain's input for this effect, or the name of an EARLIER pass —
and `inputs[0]` is what `zero_sample_scene(uv)` reads inside that pass's body;
every input, `inputs[0]` included, is also reachable by index through
`zero_pass_input(i, uv)` and `zero_pass_input_size(i)`, below. The one place
the two reads of `inputs[0]` disagree: in an effect whose declared space
differs from the segment it draws on, `zero_sample_scene` converts a `scene`
input into that space while `zero_pass_input(0, uv)` hands back the segment's
own, unconverted value. A shader declaring no `passes:` is one pass whose
entry is `fragment`, and its generated WGSL is byte-identical to what it is
without the key.
A pass that is not the last writes a scratch target the effect owns — in the
space the shader declared, view-sized times its own `scale` — allocated on the
first draw and replaced whenever the size changes. `engine.params`, below,
carries the drawing pass's own index, its scale, and its first input's texel
size, so one shader body serves every level of a chain built this way.
The worked example is the bloom: `@builtin::shaders.post.bloom` declares
twelve passes — a threshold pass, five downsamples, five tent upsamples and a
composite — out of four entries, since the five downsamples share one and the
five upsamples share another, each level reading the one below it through
`zero_pass_input` and telling itself apart by `engine.params`. Its own README
walks the declaration.
A declaration is refused at compile time — reported through `compileStatus()`,
`postprocess.add`'s second return value, or a live effect's
`status()[i].error` — for: an entry `passes:` names that `shader.wgsl` does
not define; an input naming a later pass, or naming neither `scene` nor an
earlier pass; a `scale` outside `(0, 1]`; a `scale` declared on the last pass;
a `buffer` property (group(2) carries the pass inputs now); or a shader whose
group(0) plus declared texture slots plus widest pass's inputs ask for more
than the 16 FRAGMENT sampled textures one shader stage has.
A **post-process** shader runs as a full-screen pass over the already-rendered
frame. Its `fragment` argument and framework helpers:
`PostInput`:
| Field | Type | Meaning |
|---|---|---|
| `frag_coord` | `vec4<f32>` | framebuffer pixel coords (`@builtin(position)`) |
| `uv` | `vec2<f32>` | screen UV, `(0,0)` top-left … `(1,1)` bottom-right |
Framework helpers (always in scope — no include needed):
| Call | Returns | Meaning |
|---|---|---|
| `zero_sample_scene(uv)` | `vec4<f32>` | the rendered scene colour at `uv`, converted into the space this effect declared (`zero_scene_light` is the same call, for content that reads it by that name) |
| `zero_scene_depth(uv: vec2<f32>)` | `f32` | scene depth at `uv` — a screen UV here, where the surface domain's `zero::scene_depth` module takes a pixel coordinate under the same name (exact texel — an R32Float copy). Reversed: 1.0 is the near plane, 0.0 the far plane and empty sky, so a nearer surface reads GREATER and `d > 0.0` means "a surface was drawn here" |
| `zero_linear_depth(d, near, far)` | `f32` | that sample as a distance in metres — the one inversion of the reversed range |
| `zero_scene_motion(uv)` | `vec2<f32>` | per-pixel screen-space motion vector at `uv` |
| `zero_pass_input(i, uv)` | `vec4<f32>` | the pass's declared input `i`, at `uv`. Input 0 is what `zero_sample_scene` reads |
| `zero_pass_input_size(i)` | `vec2<f32>` | that input's size in texels, so one entry serves every level of a chain |
Engine data uniform `engine` (a `PostEngineData`):
| Field | Type | Meaning |
|---|---|---|
| `resolution` | `vec4<f32>` | `x`=width, `y`=height, `z`=1/width, `w`=1/height |
| `time` | `vec4<f32>` | `x`=elapsed seconds, `y`=dt, `z`=frame index |
| `view_proj` | `mat4x4<f32>` | this frame's view-projection |
| `prev_view_proj` | `mat4x4<f32>` | last frame's view-projection (motion) |
| `inv_view_proj` | `mat4x4<f32>` | inverse view-projection (world-space reconstruction) |
| `params` | `vec4<f32>` | `x`=this pass's own index, `y`=the scale it draws at, `zw`=1/size of its first input — for a pass the post-process chain draws. A pass a `renderFeature` fragment pass draws carries that feature's `spec.params` here instead; a shader declaring `passes:` is always drawn by the chain, so the two never meet in one shader. |
The engine fills all of it **per render target**. A registered effect runs over
the live viewport's frame AND over every offscreen one — a `capture` from a
world-space station or orbiting an entity, a capture of a named camera, a
render-to-texture camera — and in each of those, `view_proj`, `prev_view_proj`
and `inv_view_proj` are the camera THAT render was drawn from, while
`resolution` is that target's own pixel size. So a pass reconstructing world
space from `zero_scene_depth(uv)` reconstructs against the station and lens the
capture asked for, and an offscreen frame is a picture of the effect as it
stands at that station. (A render feature's passes reach an offscreen render the
same way, against the same camera — the `renderFeature` assetType README carries
that half, including `@frame.camera`, its own per-target camera input.)
An offscreen render keeps no view history of its own, so `prev_view_proj` there
holds that same matrix rather than the frame before it, and a pass taking camera
motion from the two reads none. On the viewport the pair is a frame apart, so
camera motion is the one reading a capture answers differently from the screen.
`postProcessing = false` on a capture is the one control that takes the chain
off the frame it returns; it names the camera property the ephemeral capture
camera is built with, so it scopes to that one capture. What a capture opts out
of is the registered effects; `__display__` still runs on it, so the exposure
and tone curve that turn the scene's light into a picture are on what a capture
returns.
A diagnostic capture (`albedo`, `normal`, `motion_vectors`, …) bypasses
`__display__` itself, since a channel like that is a reading of the scene
rather than a graded picture of it. The environment-cube capture bypasses it
too, and for the same reason: a probe face carries radiance into the cube
array, and `__display__` would fit that radiance to a display's code values —
a picture of it rather than the value the PBR indirect term multiplies into
its lighting.
A complete post-process effect — a vignette via `fragment()` + `properties.yaml`:
`properties.yaml`:
```yaml
properties:
- { name: intensity, type: float, default: 0.5, min: 0, max: 1 }
- { name: radius, type: float, default: 0.75, min: 0, max: 1 }
- { name: softness, type: float, default: 0.45, min: 0, max: 1 }
```
`shader.wgsl`:
```wgsl
// @domain: post-process
fn fragment(in: PostInput) -> vec4<f32> {
let color = zero_sample_scene(in.uv);
let intensity = max(material.intensity, 0.01);
let radius = max(material.radius, 0.01);
let softness = max(material.softness, 0.01);
let center = in.uv - vec2<f32>(0.5);
let dist = length(center);
let vignette = smoothstep(radius, radius - softness, dist);
let darkened = color.rgb * mix(vec3<f32>(1.0), vec3<f32>(vignette), intensity);
return vec4<f32>(darkened, color.a);
}
```
The asset above **defines** the effect. It enters the frame when something
registers it:
```luau
postprocess.add("vignette", asset.resolve("~.shaders.vignette", "shader"), { priority = 200 })
```
The registration names no layer, so the effect grades the layer its `space`
belongs to: this vignette reads light, so it runs on `scene`, over the picture
before the UI reaches it. Registering it is the one step that makes it render,
so a world's chain holds exactly the passes its content asked for. Editing the shader body afterwards
recompiles every effect registered from it, in place — the pass keeps its enabled
state, priority, layer, tuned property values and bound textures, and draws the
new pixels on the next frame. `postprocess.remove(name)` takes it back out of the
chain and leaves the asset alone.
Drive the named properties at runtime with `postprocess.setProperty(name, prop,
value)` and bind texture properties with `postprocess.setTexture(name, prop, path)`
(both keyed by the **property name**, never a slot index — see the post-process
section of `man shaders` / the `postprocess.*` API).
Read them back with `postprocess.describe(name)`: it carries the chain state
`postprocess.status()` lists for that effect, the `properties` schema it was
registered with, and the `values` each of those properties currently holds. Before
the effect exists, `shaderRef:getProperties()` on the asset names the same schema,
so what a pass takes is answerable either side of the registration.
A **screen** shader is a standalone full-screen visual (UI background, procedural
pattern). `ScreenInput` mirrors `PostInput` (`frag_coord` + `uv`); there is no scene
to sample, so it has no `zero_sample_scene` helpers. Its `engine` uniform is a
`ScreenEngineData`:
| Field | Type | Meaning |
|---|---|---|
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
| `scroll` | `f32` | UI scroll offset |
| `resolution` | `vec2<f32>` | render-target size in pixels |
| `mouse` | `vec2<f32>` | mouse position |
| `velocity` | `f32` | scroll velocity |
```wgsl
// @domain: screen
fn fragment(in: ScreenInput) -> vec4<f32> {
let t = engine.time * 0.5;
let col = vec3<f32>(
sin(in.uv.x * 3.14159 + t) * 0.5 + 0.5,
sin(in.uv.y * 3.14159 + t * 0.7) * 0.5 + 0.5,
material.brightness
);
return vec4<f32>(col, 1.0);
}
```
## Library includes
A library module is a **`.shaderModule` asset**: it only EXPOSES functions and
structs and does nothing on its own (exactly like a Unity `.cginc`). You must
call what you include. Include one by its identity, the same string you would
hand `asset.resolve`:
| Include | Exposes |
|---|---|
| `@builtin::shaderModules.pbr_shading` | `struct PbrSurface { albedo, normal (world), metallic, perceptual_roughness, emissive, occlusion }`; `zero_pbr_default_surface(FragmentData) -> PbrSurface`; `zero_pbr_shade(FragmentData, PbrSurface) -> vec3<f32>` (the full forward PBR lighting) |
| `@builtin::shaderModules.shadows` | `compute_directional_shadow_factor(...)`, `compute_spot_shadow_factor(...)`, `compute_point_shadow_factor(...)`, `compute_area_shadow_factor(...)`, `compute_punctual_shadow_factor(...)`, `zshadow_light_reach(...)` |
| `@builtin::shaderModules.engine_bindings` | the group(0) declarations (camera, transforms, lights, shadow maps) — surface shaders get this implicitly; include it directly only for advanced raw access |
| `@builtin::shaderModules.shadow_bias` | `zshadow_offset_receiver(...)`, `zshadow_directional_depth_bias(...)` and the rest of the bias math, as pure functions |
| `@builtin::shaderModules.texturing` | `ztex_stochastic(...)` (tile without a visible repeat grid), `ztex_blend_normals(...)` (reoriented normal blending) |
| `@builtin::shaderModules.depth` | `zero_linear_depth(depth, near, far)` — the one reading of a stored depth |
| `@builtin::shaderModules.gbuffer_material` (`zero::gbuffer_material`) | `struct ZeroGbufferMaterial { base_color, metallic, perceptual_roughness }`; `zero_gbuffer_unpack_material(texel: vec4<u32>) -> ZeroGbufferMaterial`; `zero_gbuffer_material(t: texture_2d<u32>, coord: vec2<i32>) -> ZeroGbufferMaterial`, `zero_gbuffer_base_color`/`zero_gbuffer_metallic`/`zero_gbuffer_roughness(t, coord)` — the one unpacking of `@scene.material`'s `Rgba8Uint` texel into what a surface reflects |
| `zero::scene_depth` | `zero_scene_depth(px: vec2<f32>)`, `zero_scene_depth_uv(uv: vec2<f32>)`, `zero_scene_depth_texel(px: vec2<i32>)`, `zero_scene_depth_size()`, `zero_scene_depth_is_sky(d: f32)`, `zero_scene_world_position(px: vec2<f32>)`, `zero_scene_world_normal(px: vec2<f32>)`, `zero_scene_depth_fade(px: vec2<f32>, world_position: vec3<f32>, fade_distance: f32)` — every `px` is a pixel coordinate in two components, so a surface fragment passes `input.frag_coord.xy`, not the `vec4<f32>` `FragmentData.frag_coord` holds. The depth already drawn UNDER a surface fragment, and the world position and geometric normal of the surface standing there. What a decal projector box, a soft particle, a forcefield or water intersection foam shades against. Surface domain; the depth belongs to the view being drawn |
| `zero::scene_color` | `zero_scene_color(px: vec2<f32>)`, `zero_scene_color_uv(uv: vec2<f32>)`, `zero_scene_color_texel(px: vec2<i32>)`, `zero_scene_color_size()`, `zero_scene_color_refract(px: vec2<f32>, offset_px: vec2<f32>)`, `zero_scene_color_refract_uv(px: vec2<f32>, offset_fraction: vec2<f32>)` — every `px` is a pixel coordinate in two components, so a surface fragment passes `input.frag_coord.xy`, not the `vec4<f32>` `FragmentData.frag_coord` holds. The scene colour already composed BEHIND a surface fragment, and the displaced read that bends it. What heat haze, a refraction shockwave, a cloaking or shield warp, glass and ice shade with. Surface domain; the colour belongs to the view being drawn, and is the lit opaque scene as it stood immediately before the transparent pass — so a `blend`-queue surface reads this frame's, an opaque one reads the previous frame's, and two overlapping blended surfaces both read the same picture and do not bend each other |
`asset.list("shaderModule")` enumerates the `.shaderModule` assets in this
engine, builtin and world-authored alike, and each one's README says what it
exposes. Those are the `@builtin::shaderModules.*` rows above; a module you
write is included exactly the same way, by its own identity or by the
package-relative `~.name` form.
The `zero::`-named rows come from the renderer itself. Their WGSL is baked into
the engine binary and registered under those names before any asset exists, so
they answer an `#include` in every engine and appear in no asset index. A shader
that includes one records no dependency on it: the engine reading the shader is
the engine that already holds the module.
Two spellings reach the same `.shaderModule`: an earlier name is kept working
through the module's declared alias, so a shader written against `zero::pbr`
still compiles and still pins the asset that name resolves to. Newly written
shaders should use the identity — it says which asset travels with the content.
Whichever punctuation an include is written with — `#include "name"`,
`#include 'name'` or `#include <name>` — names the same module and records the
same dependency.
The engine's own scaffolding — `zero::surface`, `zero::sky`, `zero::post`,
`zero::screen` — is injected by the compiler around the matching domain and is
never written by hand. The surface framework puts `safe_normalize`,
`mat3_from_mat4` and `apply_normal_map(FragmentData, tangent_normal)` in scope
for every surface shader.
## Shader features — compile-time variants
A **property** is runtime uniform data (a colour, a float, a texture): set per
material, read as `material.<name>`, no recompile. A **feature** decides which
code is in the program at all. Use a property when the value changes at runtime,
a feature when it changes what the shader is.
Declare features in `properties.yaml`, alongside the properties:
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
features:
- { name: PARALLAX, default: false, description: silhouette parallax march }
- { name: DETAIL, default: true, description: detail-normal overlay }
```
Guard the code each feature owns with `#ifdef`:
```wgsl
fn surface(input: FragmentData) -> PbrSurface {
var s = zero_pbr_default_surface(input);
#ifdef PARALLAX
s.normal = parallax_normal(input); // absent when PARALLAX is off
#else
s.normal = input.world_normal;
#endif
return s;
}
```
`#ifdef` / `#ifndef` / `#else` / `#endif`, one per line, and they nest. The
directives resolve before the WGSL reaches the compiler, so the program holds
exactly the lines its feature set selected and every other line is an empty one,
which keeps a compiler message on the line number the file shows. An unbalanced
block is a compile error naming its line.
A material is what chooses a feature set, so `features:` shapes the shaders a
material draws with — the surface, sky and screen-space domains.
A material names the features it wants in its `mat.yaml`:
```yaml
name: worn_rock
shader: "@builtin::shaders.pbr_layered"
features:
PARALLAX: true # on, over the shader's default
DETAIL: false # off, against the shader's default
```
or through `asset.create`:
```lua
asset.create("material", "worn_rock", {
shader = "@builtin::shaders.pbr_layered",
features = { PARALLAX = true, DETAIL = false },
})
```
### A property that switches a feature on
A feature can also be switched on by a material's property values. List the
properties under the feature's `properties:`, and the feature is on for every
material whose value for one of them stands away from that property's declared
default:
```yaml
properties:
- { name: clearcoat, type: range, default: 0.0, min: 0, max: 1 }
features:
- { name: CLEARCOAT, properties: [clearcoat], description: the coat lobe }
```
```wgsl
#ifdef CLEARCOAT
s.clearcoat = material.clearcoat;
#endif
```
A material at `clearcoat: 0` draws a program holding none of the coat's code; one
that sets `clearcoat: 0.6`, in its `mat.yaml`, through `asset.create` or with
`renderer.material.setProperty`, draws the `CLEARCOAT` variant, and setting it
back to 0 returns it to the base program. The property stays a runtime value the
program reads; the feature decides only whether the code reading it is there.
This is how a shader with costly optional parts keeps every material that leaves
them at rest on the cheap program without each material having to name a
feature. A material naming the feature off under `features:` keeps it off
whatever the property holds. Write the guarded code so that, with the feature
off, the shader computes what it would with the property at its default: the
material sees one look either way, and pays for the part only where it shows.
Each distinct set of switched-on features is a program to compile the first time
a material reaches it. A material keeps the programs its values switched it onto
compiled while it lives, so a property crossing back and forth reuses them; when
the shader's variant budget is spent, the ones no material draws with are given
back first. A `properties:` entry is a value property (`float`, `range`, `int`,
`bool`, `color`, `float2` to `float4`) the shader declares; one naming no declared
property, or a texture or buffer, is refused by name.
The engine compiles one program per feature set its materials ask for, named
`<shader>#<features>`. Materials sharing a set share that program. A feature the
shader does not declare selects nothing, so a stray name cannot make the engine
compile anything, and the compile names both halves of a mismatch: a guard on a
name `features:` does not declare, and a declared name no guard tests.
**Permutations are the cost.** A shader with n features can express 2^n
programs, each its own compile and pipeline. One shader holds at most 32
variants; a material asking for a set past that draws with the shader's default
features and the engine logs which shader ran out. Read what a scene is
spending:
```lua
for _, s in renderer.shaderVariants() do
print(s.shader, #s.variants, "of", s.budget)
print(renderer.variantSource(s.base.program)) -- what it ships as
for _, v in s.variants do
print(v.program, renderer.variantSource(v.program)) -- what one asked for
end
end
```
A shader registers under every key it answers to — its identity, its guid, each
alias — and each key is a row. A variant lands on the row for the key the
material named, which for authored content is the guid, so take a program name
from the report rather than composing one.
## Materials reference shaders
A `.material` applies a shader to entities. Its `mat.yaml` references the shader by
its identity string and supplies property values:
```yaml
name: my_material
shader: "@builtin::shaders.pbr"
render:
blend: alphaBlend
cull: back
depth_write: false
floats:
roughness: 0.5
colors:
base_color: { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }
textures:
base_color_texture: { ref: "default:white" }
```
`shader:` is a plain identity string, and each `colors:` entry is an
`{ r, g, b, a }` map — the two forms `mat.yaml` accepts for those keys. A key's
value is the rest of its line, so every value above stands alone on one.
### The render block
Render behaviour that used to be material "flags" — the blend equation, alpha
cutout, which faces are drawn — lives in the `render:` block and drives the
pipeline, not the fragment. These are the keys that reach the pipeline from both
authoring routes, and the values each one takes:
| Key | Values | Sets |
|-----|--------|------|
| `blend` | `opaque` `transparent` `alpha` `alphaBlend` `additive` `add` `cutout` `alphaCutout` `premultiplied` `premultipliedAlpha` `multiply` | the equation the fragment composites with |
| `cull` | `back` `front` `none` `off` `disabled` | which faces the rasterizer keeps |
| `depth_write` | `true` `false` | whether the draw writes depth |
| `depth_compare` | `less` `lessEqual` `lequal` `equal` `greater` `greaterEqual` `gequal` `always` `never` | the test a fragment's depth passes |
| `topology` | `triangleList` `lineList` `lines` `line` | what consecutive vertices assemble into |
| `queue` | a whole number: `2000` opaque, `3000` transparent, `4000` overlay | the draw order of the material; a number inside a queue orders within it |
`blend` is also spelled `type`, and the two name one key. Its equations, over
the fragment the shader returned (`src`) and the value already in the target
(`dst`): `opaque` is `src`; `transparent`, `alpha` and `alphaBlend` are
`src * src.a + dst * (1 - src.a)`; `additive` and `add` are `src + dst`, the
mode a glow, a light shaft or a spark card is written for; `premultiplied` and
`premultipliedAlpha` are `src + dst * (1 - src.a)`, taking a source that already
carries its own coverage; `multiply` is `src * dst`, which is how a soot, grime
or shadow card darkens what stands behind it. `cutout` and `alphaCutout` keep
the fragment or discard it on its alpha and go on writing depth.
The same block is what `asset.create`'s `render` argument takes, key for key and
value for value, so one material named in Luau and the same material standing on
disk ask for their pipeline with the same words. `depth_write` is the one key
whose value takes the shape of its route: the word `false` on a `mat.yaml` line,
the boolean `false` in the Luau table.
```lua
asset.create("material", "heat_plume", {
shader = "@builtin::shaders.pbr",
render = { blend = "alphaBlend", cull = "none", depth_write = false },
})
```
Where a value outside a key's set is reported is what the two routes differ on.
`asset.create` refuses the call on any of these keys and names the set it
measured the value against, or for `queue`, that it takes a number. A
`mat.yaml` standing on disk registers either way, each key falling back to a
value of its own: `blend` to `opaque`, `cull` to `back`, `depth_write` to
`true`, `depth_compare` to `less`, `topology` to `triangleList` and `queue` to
`2000`. The engine log carries the blend fallback, naming the value and
the set it was measured against, so a `mat.yaml` value is worth putting through
`asset.create` once — that is where every key answers with its set.
## Registration & hot reload
A `.shader` is compiled by the asset system, not by the renderer: writing
`shader.wgsl` or `properties.yaml` fires the `.shader` assetType's `onChange`,
which calls `shader.compile` — that reads the body + the property schema, generates
the group(1) interface and (for surface) every render-mode entry point, expands
`#include`s, **validates the result with naga**, and registers it. Validation
happens at this compile step — the whole point of "compile". A shader with invalid
WGSL (an unknown field, a type mismatch, an undefined function) **fails to compile**
with the real reason — readable directly from Luau via
`shaderRef:compileStatus()` (`{ status = "compiled" | "failed" | "pending",
error?, pending? }`), and also in the author log and `asset.inspect`; it is **not**
registered. This fires on create and on every edit, so saving a `.wgsl` recompiles
with no world reload; the change is visible on the next frame. Compilation is
async, so a `compileStatus()` of `"pending"` immediately after a write means check
again next frame.
A surface shader is also checked for the material resolve, the pass that
shades each pixel of the visibility buffer through the shader's own code. That
check reaches its verdict a few frames after the raster compile. Until it
does, `compileStatus()` reads `"pending"` with `pending` saying so, and the
shader already draws. A shader the check refuses reads `"failed"`, and `error`
names the construct the resolve cannot evaluate and where it sits; its pixels
resolve through the error shader until it changes.
The stage the compile checks comes from one of two places: the hook the engine
scaffolds entry points around (`fragment()`, or `surface()` for an engine-lit
surface), or the `vs_main` / `fs_main` pair the body writes itself. The pair is
a pair: a body that writes its own entry points owes both stages. A body
carrying neither route — a hook whose name is a letter off, say, or half a pair
— holds no stage the rasterizer can enter, so the compile **refuses it** and
names both the entry point it looked for and what the body carries, in the same
`compileStatus()` error every other compile failure reads back through.
### Reading a compile error against the text it is about
What the compiler reads is not the file you wrote. The engine generates the
group(1) material interface from `properties.yaml`, wraps the body in its
domain's framework and every entry point that domain needs, expands every
`#include`, and resolves every `#ifdef` — so a 100-line body reaches naga as
tens of thousands of lines. **Every line number in a compile error, and every
`[N]` handle index naga prints where it has no name to print, is a position in
that composed module.** A fault at module scope (`no definition in scope for
identifier: 'zero_scene_depth'`) reads fine without it; a fault inside a
function body does not.
`renderer.compiledSource(name)` returns that composed module, and
`shaderRef:compiledWgsl()` returns it for a ref you already hold. Both answer
for a shader that declares no features, needs no material, entity or draw, and —
the case they exist for — **answer for a shader whose compile failed**, holding
the text the compiler was refused over for as long as `compileStatus()` reports
that failure. `renderer.compiledShaders()` lists every name they answer for.
```lua
local ref = asset.resolve("myShader", "shader")
local status = ref:compileStatus()
if status.status == "failed" then
print(status.error) -- the line, the caret, and the cause
local wgsl = ref:compiledWgsl() -- the text those positions are in
local line = tonumber(string.match(status.error, "wgsl:(%d+):"))
print(string.split(wgsl, "\n")[line])
end
```
The composed text carries every `zero::*` module the shader included, so the
signature a call was rejected against is in the same text as the rejection —
which is the whole of what a "wrong argument type" error needs to be actionable.
A material bound to a broken (or missing) shader renders with the **magenta error
shader** — never invisibly — so a shader problem is impossible to miss on screen as
well as in the log. **Fixing the shader and re-saving recovers it live**, with no
engine restart: the recompile clears the failed-shader state and the object returns
to normal on the next frame.
## Discovery
- `asset.list("shader")` — every registered shader.
- `asset.inspect("<name>")` — domain, status, source, parse errors, this README.
- `shaderRef:compileStatus()` — did it compile? `{ status, error?, pending? }`, no
log needed. `"pending"` with `pending` set means the material resolve check
is still reaching its verdict; a resolve refusal reads as `"failed"`.
- `shaderRef:compiledWgsl()` / `renderer.compiledSource("<name>")` — the WGSL the
compiler received, which is what a compile error's positions index into.
Answers for a failed compile too.
- `renderer.compiledShaders()` — every name that call answers for.
- `shaderRef:getProperties()` — the parsed `properties.yaml` schema.
- `shaderRef:listMaterialsUsing()` — materials bound to this shader.
## Common pitfalls
- **A compile error shows up in one of three ways at the draw.** A shader that
never compiled has no pipeline, so the renderer binds the magenta placeholder.
A shader that compiled once and was then edited into brokenness KEEPS the
pipeline that build produced — the surface goes on drawing the last good
program, pixel for pixel, and looks entirely intact while the source is broken.
A geometry-pass-only shader has no magenta tell either, since it is not on a
forward mesh. `shaderRef:compileStatus()` gives the status + error text (as
does `asset.inspect("<name>")`), and `renderer.drawDiagnostics()` names which
renderables are in which of the three states — a row carries `substituted` for
the placeholder, `stale` for a program that no longer compiles, and the cause
either way.
- **A compile error's line numbers are lines of the composed module, not of your
file.** `renderer.compiledSource("<name>")` / `shaderRef:compiledWgsl()` is
that module; resolve the position against it rather than counting lines in
`shader.wgsl`. The `[N]` a message prints in place of a name is a naga handle
index — it moves with the size of the body and is the same value for two
unrelated faults in one file, so it is neither a line number nor a way to tell
two failures apart.
- **Don't declare group(0) or group(1) in a surface shader.** The engine owns
group(0) and generates group(1) from `properties.yaml`. Re-declaring them is the
fastest way to a layout mismatch.
- **`#include` does nothing by itself** — it only exposes functions; you must call
them.
- **Renaming a property** changes the generated uniform field; materials setting the
old name silently fall back to its default.
- **Compute shaders don't render** — verify output via a buffer readback or a
debug pass. Author them as a `.computeShader` (its own assetType), not a
`.shader` — see `man compute`.
## Related types
- `.material` — the required wrapper that applies a shader to entities.
- `.style` — UI cascade, not GPU shaders.
## In the Inspector
Selecting a shader opens its **Shader** section: its domain and shading model (and, for a post-process shader, the space its `fragment()` reads and returns), whether it compiled (and the compiler's error when it did not), a table of its declared properties (type, default, range), its post-process passes when it has any, the bindings it declares, and openers for its source. The **Materials** section (collapsed at first) has a Find materials action that lists, as links, every material drawing with the shader; it scans every material, so it runs only when asked.
# assetType (asset type)
The `assetType` is the **type of types** — the meta-type that every
`<typename>.assetType/` folder is an instance of, including itself. A
`<typename>.assetType/` folder declares a new asset type called
`<typename>`: its on-disk shape, its identity rule, and the structural
contract instances of the type must satisfy.
This type is self-hosting. `assetType.assetType/` conforms to its own
schema — a `type.yaml` plus a `README.md` — so the type system is
defined in terms of itself rather than a hidden engine special-case
(the same way a C compiler is written in C). Every asset in the engine,
including each `.assetType` definition, now resolves to a registered
assetType: a `.material` resolves to `material.assetType`, and
`material.assetType` resolves to `assetType.assetType`, which resolves
to itself.
## Why it exists
Assets used to be mapped to their type *implicitly*, by matching the
folder suffix against a name-keyed registry. That match carried no
stored link: nothing on a `Foo.material` recorded *which*
`material.assetType` it was written against, so two worlds shipping a
same-named type could silently disagree. Making `assetType` a real,
resolvable asset closes that gap — the link from an asset to its type is
now an explicit reference pinned in the asset's `.refs` sidecar
(`via: "asset_type"`), exactly like every other dependency.
## Where it lives
- Source: `/zero/source/.../<typename>.assetType/`
- Identity: `<typename>` (the `.assetType` suffix strips from the
identity; the folder retains the suffix on disk).
- Folder shape:
- `type.yaml` — the structural spec the validator reads. **Required.**
- `README.md` — type-level documentation. **Required.**
- `about.yaml` — three short plain-language texts saying what the type
is for (see "Say what your type is for" below). Every built-in type
ships one.
- `behavior.luau` — optional behavior/scaffolding module.
- `template/` — optional canonical placeholder body the templater
copies into a new asset of the type.
- `<name>.module/` — optional shared code the type ships to **every
instance** of it, conventionally `shared.module/` (see below).
## Shared code its instances reach (`asset.containing` + `.modules`)
A type ships code every instance of it uses by declaring the modules in
its own `behavior.luau`, as a map of tracked `require`s:
```luau
-- inside <typename>.assetType/behavior.luau
M.modules = { shared = require(".shared") } -- the sibling shared.module/
```
An instance reaches it with one location-independent line:
```luau
-- inside any foo.<typename>/init.luau
local api = asset.containing(__FILE__).modules.shared
```
`__FILE__` is the chunk's own VFS path; `asset.containing` resolves the
calling asset, and `.modules.<name>` follows the instance's pinned
`typeRef` (the type's **guid**, recorded in the instance's `.refs` as
`via = "asset_type"`) to the module its type declares. Because
resolution follows that link rather than a category name, the same line
in an instance of a different type resolves to that type's module, and
identically-named modules in two types never collide. `asset.typeRef(target)`
reads that guid for any target; `asset.resolve(asset.typeRef(target))`
gives the full `AssetRef<assetType>`. See `assetTypes/README.md`
§ "Shared code: type-owned modules" for the full mechanism.
## How to create one
Authoring a new asset type is just creating a `<typename>.assetType/`
folder under `/zero/source/`. The engine registers `<typename>` as a
category **the moment the folder is written** — no engine restart, no
Rust change, and it works for built-in (`@builtin/assetTypes/`) and
user-defined types identically. Once `<typename>` is registered,
`<name>.<typename>/` folders are recognised as assets of that type and
resolve their `asset_type` link back to this definition.
Creating a `<name>.<typename>/` folder *before* its
`<typename>.assetType/` exists fails fast: the suffix has no registered
type, so the folder can't be a valid asset. Author the type first.
## Say what your type is for (`about.yaml`)
Every type carries a small `about.yaml` beside its `type.yaml`, and the README
you write for the type documents how to author an asset of it. Both are
required, and both are meant to be written as you make the type, while you know
what it is for. `about.yaml` answers three questions in plain words, one key
each:
```yaml
intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering."
function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text."
usage: "You choose it by name for your UI or your text, and the text appears in that typeface."
```
- **`intent`** is what the type is for in someone's game. Name the whole range
of things it covers, in the words a game maker would use for them.
- **`function`** is how it works today: what an asset of the type is made of and
what the engine does with it.
- **`usage`** is what a person or an agent does with one: how they pick it, place
it, call it, or hand it to something else.
A few habits keep it useful. Write about the type as a whole, so the text holds
for every asset of it, and leave out any one asset's name. Say what the type
does right now. Stay with words a game maker would say, and mention a file name
or a call only where a game maker would know it. The limits are in bytes:
`intent` 800, `function` 1500, `usage` 1200. Each is generous, and a few
sentences usually say it.
Why bother: agents working in a world read these three texts to learn what your
type is for, so they reach for it when it fits and use it the way you meant. People
searching find the type by what they want to make, and the three texts let them
tell at a glance whether it is the one they need.
`asset.create("assetType", name)` scaffolds the file with all three keys, and a
README whose first paragraph is a `[[describe]]` note. Each value starts with
`[[describe]]` followed by a note on what to write; replace the whole value with
your own words. A value or a README line that still starts with `[[describe]]`
counts as not written yet, which the push's check of each asset it carries against
its type reports, naming the file. A type you leave as it was is not asked, so
older types stand.
Many types at once, or one you would rather not write by hand: `services
describe` lists the types that lack these texts and what filling them costs, and
`{ mode = "all" }` writes them into the same files, where you edit them like
anything else you wrote.
Where the texts show up: `asset.inspect("<typename>", "assetType")` returns them
as `detail.about`, `assetTypeRef:getAbout()` returns them as a table with the
keys `intent`, `function` and `usage`, the type's `types/<typename>` guide page
ends with an "About this type" section holding them, and the Inspector's Type
section lists them at the top. The guide page is this README plus that section,
so a README that explains the type well and an `about.yaml` that says what it is
for read well together.
## Ask your assets to say what they are
A type can ask each of its assets to carry a description: a file, written by the
author or generated, that says what that asset is and what it is for. The people
and agents who find an asset read it to decide whether it fits, and the author
knows what it is for at the moment of making it.
**1. Declare the file with a `described` check.** This is the whole requirement:
```yaml
files:
required:
- path: "README.md" # any file name works
kind: "file"
content:
- { check: "described", message: "Say what this widget is for and where it goes." }
```
With that in place:
- An asset whose file is missing, empty, or still has a line starting with
`[[describe]]` does not meet the type's requirements. `asset.validate` names it,
`zm status` and `world.publishBlockers()` list it, and a push that carries it is
refused with `message`.
- `services describe` finds it (`mode = "find"` lists it and the price) and can
write the description for it (`mode = "all"`). It writes only this file.
For a YAML file that holds several texts, name the keys and their limits in bytes,
the way this type does for `about.yaml`:
```yaml
content:
- check: "described"
keys:
- { key: "intent", max_bytes: 800 }
- { key: "usage", max_bytes: 1200 }
message: "Write intent and usage."
```
`headings` names sections a Markdown file must have. `assetTypes/README.md` has the
full check.
**2. Optionally, steer what gets generated with a `describe:` block:**
```yaml
describe:
guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI."
examples:
- "<identity of an asset of this type whose description reads well>"
```
`guidance` says what a description of your type covers, and `examples` names assets
whose descriptions show the shape you want. Without the block, generation still
works from the general describing guide and the check's `message`.
An example is an asset of your type in the library whose description is a true,
written one, never a scaffold's placeholder, and never the asset being described.
When the library has none, leave `examples` empty rather than name one that is not.
A type whose assets the model cannot perceive (a sound it cannot hear, a motion it
cannot see) says so in `guidance`: the description comes only from what the asset's
own files state, such as its name and the `.metadata` where a generation service
records the prompt that made it, and when they state nothing the model answers
`cannot` with that reason. `services describe` then fails that one asset with the
reason and leaves its file as it was.
**3. Start the file unwritten in your template.** Put a heading and one line that
starts with `[[describe]]` and a short note on what to write, in
`template/<file>`, so a new asset starts unwritten rather than with text that only
looks written. Do not put example content in it: every new asset carries the
template verbatim, and the same text on many assets makes them impossible to tell
apart in search.
Types whose assets say what they are through their own content (a mesh, a texture,
a sound) leave this out: declare nothing and nothing is asked.
## The `behavior.luau` contract
`behavior.luau` is the type's code. It returns ONE table, and the keys below
are the ones the framework reads off it for EVERY type — the surface you get
by declaring them. Anything else on the table is your own: reachable by name
through `require("@builtin::assetTypes.assetType.shared.ref").loadTypeModule("<typename>")` for a
system that knows your type (`computeShader` publishes `dispatchKey` that
way), and never called by the framework.
```luau
local M = {}
M.ref = { ... } -- methods on every AssetRef of this type
M.modules = { ... } -- shared code the instances reach
M.global = {} -- reserved key; ship the empty table
function M.onCreate(name, opts) ... end
return M
```
### The tables
| Key | Shape | What the engine does with it |
|-----|-------|------------------------------|
| `M.ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every `AssetRef` of this type: `ref:name(...)`, with `self` the ref. This is how a type gives its instances an API. Two names in here are contracted — see below. |
| `M.modules` | `{ [name] = require(".sibling") }` | Shared code the type's instances reach through `asset.containing(__FILE__).modules.<name>`, resolved by the instance's pinned `typeRef` guid. See the section above. |
| `M.refShapes` | `{ [method] = "TypeName" }` | Declares the result type of a `M.ref` method so the LSP can check what a call site does with it. See the `M.refShapes` section below. |
| `M.events` | an events schema | The events an ASSET of this type fires, declared the way a component declares its own. Readers subscribe through `ref.events.<name>:connect(...)`; firing authority stays with the type. Keyed by the asset's guid, so every resolver of the same asset shares the signals and a re-resolved ref re-attaches to subscriptions already there. |
| `M.namePattern` | a Lua pattern string | The name shape `asset.create` enforces for instances of this type, replacing the default `^[A-Za-z][A-Za-z0-9_]*$`. |
| `M.global` | `{}` | Reserved. Ship the empty table. |
### The lifecycle hooks
Each is optional; a type that omits one costs nothing. The engine calls them:
| Hook | Signature | When it fires |
|------|-----------|---------------|
| `M.onCreate` | `(name, opts) -> { [filename] = contents }` | On `asset.create("<type>", name, opts)`. Returns the files that scaffold the new instance, as a map of relative path to contents; the framework writes them. The `opts` type annotation is the schema `asset.create` validates the caller's arguments against, so annotate it. |
| `M.onReplace` | `(dest, files) -> { [filename] = contents }` | On an `asset.create` that writes over an asset already at `dest`, after `onCreate`. Receives the files `onCreate` produced and returns the files to write, so a type that re-derives its content (a rig re-imported from its source file) can carry what an author added to the asset it replaces. Optional. |
| `M.onRegister` | `(self)` | Once per instance, the first time it registers: on `engine.onWorldLoaded` for instances already in the world, immediately on a live `asset.create`, and when an instance arrives after that sweep (installed, pulled, or synced from a peer). Guarded by the instance's path, so a double trigger never double-registers. An instance that leaves the runtime releases the guard, so one arriving at the same path again registers. This is what makes "write an asset into the world and it takes effect live" work for content that registers into a runtime registry. The `@builtin` library is excluded from the sweep. |
| `M.onChange` | `(ref, change)` | On every VFS write to a file INSIDE one of this type's instances. `change` is `{ path, asset, type, kind, origin }`: `kind` is `"edited"` or `"seeded"`, `origin` is `"local"` or `"remote"` (an importer runs on the originator only). **Filter on `change.path`**: the hook fires for any file under the folder, so act on the one you care about. It runs as its own task and may wait on what it reads: a `vfs.read` of bytes only the blob store holds (a binary file on the web build) fetches them. The writes to one asset reach the hook in the order they were made, each once the hook before it has finished. A re-entrancy guard suppresses writes back into the same asset routed inline from the hook, and a write the hook makes is routed on a later frame like any other, so the hook must be convergent on its own: diff the meaningful state and short-circuit while your own regeneration is in flight. |
| `M.onDelete` | `(ref)` | When an instance of this type leaves the runtime: it is deleted, or the engine swaps away from the world binding that held it. Its files are gone from `/zero/source` by then. A removal routed while the instance's `onChange` is waiting reaches `onDelete` once that hook, and every write queued behind it, has finished. On a swap the instance still exists in the world it belongs to, and a VFS write the hook makes reaches the world now bound. |
| `M.validate` | `(assetRef) -> { { code, message, severity? } }` | On `asset.validate`, after the structural `type.yaml` check, for the type's own SEMANTIC validation. `severity` defaults to `"error"`; error-severity problems flip `ok` to false, warnings do not. A hook that raises or returns a non-table is itself reported as a `validate.hook_failed` error. `world.push` runs this per user asset, so declaring it enforces your type's rules at publish time with no further wiring. |
### The two contracted `M.ref` names
Most `M.ref` methods are your type's own surface: name them what you like,
return what you like. Two are read by the engine and mean the same thing for
every type, so their shape is fixed:
- **`instantiate(self, target?, opts?) -> (root, idMap)`** — makes an instance
part of the scene. Defining it is the whole opt-in: `ref:canInstantiate()`
is true exactly when it exists. Its **return is a contract** — see the next
section.
- **`inspect(self) -> detail`** — the type-specific half of `asset.inspect`.
See its section below.
### Names a type cannot shadow
Some keys resolve on every `AssetRef` before per-type dispatch, so an `M.ref`
entry of the same name is never reached: `canInstantiate`, `getSource` /
`getBytes` / `getText`, `exists`, `deps`, `meta`, `runtime`, `events`,
`modules`, `typeRef`, and the residency flags `has_backing_asset`,
`has_runtime_changes`, `cpu_resident`, `gpu_resident`. These are the
behaviours every asset must expose identically, which is why they win.
### Reloading
A `behavior.luau` edit ripples to existing refs with no restart: dispatch
reads `mod.ref` fresh each time and `require`'s cache is re-run in place. A
type whose folder appears at runtime is picked up on the next dispatch —
negative results are not cached either.
## The names your type's assets hold (`references:`)
An asset that names another asset by a string depends on it: the named asset
travels with it into a pack or a pull, and a name nothing answers to is an
unresolved dependency `worldValidation` reports and the push gate refuses. The
engine reads `require(...)` and the asset lookups on its own; a name your type's
format or API carries anywhere else is one you declare, in `type.yaml`:
```yaml
references:
# A top-level key of this type's own files that holds a name (or a table of them).
keys:
- { key: "shader", type: "shader" }
# A call's argument, counting from 1, wherever the call is written.
args:
- { call: "g:node", position: 2, type: "procNode" }
# A field of the options table a call takes.
fields:
- { call: "fx.beam", field: "material", type: "material" }
```
`type` is the category the name resolves in, one of `asset.categories()`. An
argument declared once per category, at the same `call` and `position`, takes
the name from whichever category answers. A key or a field holds one category:
declared again with another `type`, it takes the later one. The block is
declared as the type registers, when the library or the world holding it is
laid into the VFS, so every reference table reads it whatever script has or has
not run. `asset.declareReferenceKey`, `asset.declareReferenceArg` and
`asset.declareReferenceField` declare the same things from a script, for a
surface that is no type's.
## What search does with your type (`indexing:`)
A type declares what search embeds for its instances. **This is not optional
and there is no useful default**: ZeroMind runs your declaration and adds
nothing of its own, so anything you do not point at is absent from the index —
silently, and for every instance of the type forever. Twenty types once shipped
with no `indexing:` block and every instance of them was unfindable.
A type whose instances are never searchable (a run record, a log) says so with
`indexing: none`; every other type declares a recipe.
A type without an `about.yaml` beside its `type.yaml` refuses every push that
carries it, whether or not the push edited the type. Texts in it that are not
written yet follow the rule every `described` file follows: they refuse the
push that edits, stages or commits the type.
Two words carry the whole thing, and they are the same two the search tool
exposes:
- **`identity`** — what an instance IS. For anything you can look at, that is
the picture (`content:` + `modality: image`, matched directly by a text
query). For everything else it is the authored text that says what it is.
- **`capability`** — what it DOES and how it is made. Code, settings, the
model-written summary of them.
A type with no behaviour has no `capability` entry. A type with nothing to look
at has no image. Leaving a slot empty is a statement; filling it with whatever
happens to be lying around is not.
The one you have to decide when authoring a type is: *for an instance of this,
what is the thing a person would recognise it by, and what is the thing it
does?* A texture answers "the image" and "its compression settings". A module
answers "its README" and "its code". Write those two answers into `indexing:`
and the rest follows.
Three specifics worth knowing before you write one:
- **`derive` is instructed by this type's own `README.md`.** A model reads an
instance's source and writes a description; what it embeds is the
description, not the source. It follows your README to know what it is
looking at, so a type whose README says what its instances are gets good
derivations for free. There is no prompt to name.
- **`derive` loses detail.** It keeps the main technique and drops secondary
ones. If the source is code you want searchable by its own vocabulary,
declare the same files a second time as `capability` with
`extractor: verbatim`. Two entries, same role, different failure modes.
- **Never `source: { field: name }`.** A filename is one or two words with no
usable embedding, and a corpus indexed that way answers "language runtime"
with `say_runtime_2.soundClip`.
`facets:` is the second stage: a `file:` embedded whole (`.metadata`, so keys
nobody declared still get indexed) plus computed keys that state a value for
every instance including `false` — the raw file can imply "not rigged" and can
never say it.
The full schema, every extractor and the facet sources are in
[`assetTypes/README.md`](../README.md); the scaffolded block with inline
guidance is in [`template/type.yaml`](template/type.yaml).
## What your type looks like (`preview:`)
A type declares how its instances are pictured, and the engine makes the
picture when something needs it: staging an instance whose `preview.png` is
missing or pictures content it no longer holds queues a render, a view that
shows the instance asks for one, and `ref:preview()` renders one on demand. An
edit renders nothing on its own. Each `preview.png` records the content it
pictured, which is how a stale one is told from a current one. The preview studio owns the light, the
backdrop, the framing and the camera, and nothing in the world reaches it, so
an instance pictures the same in every world. Declare one of four recipes:
| `kind` | The picture is | Your type provides |
|---|---|---|
| `instantiate` | the asset stood in the studio through its own `instantiate` | `ref.instantiate` |
| `image` | a file the instance holds, fitted to the frame, nothing rendered | `source.files`, the candidate files in order |
| `surface` | the asset painted on a builtin mesh | `mesh`, and `ref.previewMaterial(self) -> { material }` |
| `custom` | whatever `ref.preview(self, opts)` returns | `ref.preview` |
```yaml
preview:
kind: surface
mesh: sphere
```
A scene-instantiable type that declares nothing still answers `ref:preview()`
through its `instantiate`, but persists no picture: the declaration is what
makes the engine keep one. List `preview.png` among the type's files so an
instance may hold it.
The picture is findable only when `indexing.content` names it. The two are
separate statements, and neither is derived from the other:
```yaml
indexing:
content:
- role: identity
modality: image
source: { file: "preview.png" }
```
`@builtin::assetTypes.assetType.shared.previewRecipe` reads the declaration;
the scaffolded block with inline guidance is in
[`template/type.yaml`](template/type.yaml).
## Typing a result from the instance (`M.refShapes`)
Every method on `M.ref` is checked against the type its `--!return` names,
and every asset of the type gets the same one. That is right for most
methods and wrong for the ones whose result is shaped by the ASSET: a
method answering one entry per child folder, per row of a config, per
binding an input map declares. The widest true annotation for those is
`{ [string]: Thing }`, and an indexer accepts every key — so a caller's
typo reads as valid and nothing reports.
`M.refShapes` lets the type state the result per instance. Each entry is
`function(self) -> (typeExpression, source?)`: a Luau type expression for
THIS asset, and the module whose type vocabulary the expression uses.
Read the asset; never run it — stating a type must not take effect.
```lua
-- inputMap.assetType/behavior.luau — the shipped example.
-- `activate()` hands back one handle per control the map declares.
M.refShapes = {
activate = function(self): (string, string)
local names = {}
for _, control in ipairs(M.ref.controls(self)) do
table.insert(names, control.name .. ": Handle")
end
if #names == 0 then return "", "" end
return "{ " .. table.concat(names, ", ") .. " }",
"@builtin::modules.zinput.scheme"
end,
}
```
With it, `map.jump:onPressed(fn)` resolves and `map.noexisting` is
reported with the map's real controls. Without it, both pass silently.
### What the call site has to say
A per-instance type is matched by the asset's IDENTITY, so it applies only
where the reference the method is called on says WHICH asset. Two spellings
do:
```lua
-- a component field, whose declared default names the asset
public = { map = Field.assetRef("inputMap", "@builtin::inputMaps.default", Sync) }
local controls = public.map:activate() -- typed for THAT map
-- an annotation, naming category and identity
local m: AssetRef<"inputMap", "@builtin::inputMaps.default">
```
`asset.resolve("<identity>", "<category>")` carries the CATEGORY, so the
methods the category defines are checked on the result — but not which
asset it found, so a per-instance result keeps the category's declared
return. A reference that names no asset (`asset.resolve(someVariable)`, a
value passed in as a parameter) carries neither, and calls on it are
unchecked. That is the same rule everywhere: the checker states what the
code states, and a name computed at runtime states nothing.
### The result is a value, not a binding
The type belongs to the expression, so it travels the way any inferred type
travels. Indexing the call's result is checked; stashing it in a module
local and indexing it from another function is not, because the local's
declared type is what carries across — and `any` (or no annotation) carries
nothing:
```lua
-- checked: `d.greting` is reported
function awake()
local d = public.dialogue:lines()
d.greeting:say()
end
-- NOT checked: `lines` is a module local typed `any`
local lines: any = nil
function awake() lines = public.dialogue:lines() end
function start() lines.greting:say() end
```
Bind what you need at the call site and the names stay checked in both
places — the asset-derived type at the boundary, ordinary scoping after it:
```lua
local lineGreeting = nil
function awake()
local d = public.dialogue:lines()
lineGreeting = d.greeting -- `d.greting` is reported here
end
function start() lineGreeting:say() end
```
### When nothing is reported and you expected something
From a call site, a type that is correct and a type that was never published
look the same: no diagnostic either way.
`require("@builtin::assetTypes.assetType.shared.refShapes").published()` answers which it
is. It returns two maps — the category surfaces, and the per-asset results
keyed by identity and then by method:
```lua
local shapes = require("@builtin::assetTypes.assetType.shared.refShapes").published()
shapes.categories.dialogue
--> "{ lines: () -> any, lineNames: () -> { string } }"
shapes.returns.Shopkeeper.lines
--> "{ browsing: Line, farewell: Line, greeting: Line, wares: Line }"
```
An identity absent from `returns` was never published for, which is a
different thing from published-and-correct — and the reason to look here
rather than at the call site.
The answers are recomputed when an instance is written, so a control added
to a map reaches the checker with no restart. Only types that declare
`refShapes` are read per instance, and at most 64 assets of one type are —
past that the type keeps its declared return and the engine log names what
was dropped.
## The instantiate hook (`M.ref.instantiate`) — a contracted return
A type opts into becoming part of the scene by defining `instantiate` on its
`ref` table. That is the whole opt-in: `ref:canInstantiate()` is true exactly
when the hook exists, so consumers offer a scene path — an `Asset.source`
field, a viewport drop, a tool argument — by CAPABILITY rather than by a list
of type names.
Unlike `inspect`, this hook's **return is a contract**. A caller writes one
piece of code against every instantiable type, so what comes back cannot vary
by type:
```lua
-- behavior.luau
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
local M = {}
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts) -- IN: the base opts
-- ... compose whatever this type is, under `root`, NOW ...
return Instantiable.result(self, root, idMap) -- OUT: the contract
end,
}
return M
```
**IN.** `target` is an owning entity ref: the instance lands under (or, for a
hierarchy type, onto) that owner. With no target the type spawns a fresh root.
`position`, `rotation`, `scale`, `name` and `temporary` mean the same for every
type — `Instantiable.root` applies them to a root you mint, `Instantiable.place`
to one you adopt, so you never re-read the spec. Honour more opts of your own if
your type needs them, and document them in the hook's `--!arg` docs.
**OUT.** Return `(root, idMap)` through `Instantiable.result`:
- **`root`** — the composed root, as an `EntityRef`. Composition is
**synchronous**: everything your type builds is live when you return, so the
caller can parent to it and read its components in the same statement. Do not
defer the work to a component's `awake` and return an empty shell — a root
that is not live is refused.
- **`idMap`** — the `originalId -> runtimeId` map naming what you spawned, or
nil for a type with no addressable children (`result` normalises it to `{}`).
**A caller never receives nil.** A component that re-composes your asset on
every load keeps this map and passes it back in, which is how a cross-entity
reference into the composition survives a reload.
`AssetRef` runs every `instantiate` through `result` on the way out whether or
not your type called it, so returning something else fails at your own call
rather than handing a caller a nil root. Calling it yourself is still how you
say what you return, and running it twice changes nothing.
`@builtin::assetTypes.assetType.shared.instantiable`'s README is the full reference for both halves.
## The inspect hook (`M.ref.inspect`)
`asset.inspect(ref)` resolves `ref`, builds a common envelope shared by
every asset (`identity`, `name`, `guid`, `source`, `typeName`,
`typeDefinitionPath`, `scope`, `origin`, `description`, `tags`), then
calls the resolved type's own inspect hook — `M.ref.inspect(self)` on
`behavior.luau` — for the type-specific `detail`. The hook returns
*only* `detail`; the framework fills in everything else:
```lua
-- behavior.luau
local M = {}
M.ref = {
inspect = function(self)
-- self.path is the asset's own folder. Parse the asset's OWN
-- files — source text, a native payload header, its `.metadata`
-- — never runtime state (a live component instance, a GPU
-- upload, a compiled schema): inspect must work on an asset that
-- hasn't been compiled, uploaded, or registered yet.
return {
-- type-specific fields, whatever this type wants to surface
}
end,
}
return M
```
A type that omits `M.ref.inspect` yields the generic record: the
envelope alone, `detail = nil`. That's a valid, working state — not an
error — but it means agents calling `asset.inspect` /
`tools.use("assets","describe", ...)` on an instance of the type see
only identity and scope, none of what makes an instance of it
meaningful. Declaring the hook is what makes a type's instances
inspectable for what they actually are.
A hook that raises leaves `detail = nil` and sets `record.warning` to
the error text — `asset.inspect` itself never raises for a resolved
ref.
## Discovery
- `asset.list("assetType")` — every registered asset type.
- `asset.inspect("<typename>")` — the type's identity, source path, and
this README, plus its `about.yaml` texts as `detail.about`.
- `asset.resolve("<typename>", "assetType")` — the `<typename>.assetType`
asset itself (used by the validator to find the type's `type.yaml`).
## Related
- `assetTypes/README.md` — the full `type.yaml` schema and validator
rules.
- `@builtin::assetTypes.assetType.shared.instantiable` — the instantiation contract's shared
implementation, both halves.
- Every other `*.assetType/` here — the concrete types built on this
meta-type.
## The Inspector a type ships
Every type names the file its Inspector sections come from with `inspector: { type: "inspector.luau" }` in its type.yaml. `asset.create("assetType", name)` scaffolds the block and an `inspector.luau` whose Contents section lists an asset's files, built from `ctx.parts`. `asset.validate` on a type that names none reports `assetType.inspector_required` (an error for a `@builtin` type the engine's library authors; a warning for a world's own, and for one the library carries by reference, which the world that published it answers for), and one whose file does not load `assetType.inspector_invalid`.
## In the Inspector
Type: what the type.yaml declares (suffix, container, primary files, the settings and inspector blocks), whether the type ships a behavior, how many instances it has, and **Open** for its files. Schema: the settings every instance carries, as read-only typed controls at their defaults (a type whose schema is per instance says where it is declared). Instances: a link to each of the first 20 assets of the type, and how many there are when there are more.