# Scene setup (asset type)
A scene setup configures a scene as a whole in one asset: its sun and ambient
light, its fog, its render features and post effects, or any other effect that
applies to a scene. It is an ordered list of **members**, each an asset whose
type implements `applicable`, with the values the setup states for them.
Placed in a scene, it applies every member; selecting the placement shows every
parameter of every member, and an edit made there is that placement's own.
## Where it lives
- Source: `<name>.sceneSetup/`
- Identity: `<name>` (the `.sceneSetup` suffix strips from the identity)
- Folder shape:
- `sceneSetup.yaml`: the definition. **Required.**
- `README.md`: what the setup puts on a scene. **Required.**
- `.metadata`: `description` and `tags`. **Required.**
- `preview.png`: its picture. Optional.
## The definition
```yaml
members:
- id: sun # required, ^[a-z][A-Za-z0-9_]*$, unique
source: "./sun.sceneLight" # any asset that implements applicable
- id: ambient
source: "./fill.sceneLight"
values: { intensity: 0.12 } # values for the member's parameters
- id: fog
source: "<a fog render feature>"
enabled: false # optional, default true
- id: grade
source: "./grade.postEffect"
values: { saturation: 0.82, contrast: 1.12 }
```
A member's `values` are the values this setup states for that member; the
member asset keeps its own, and another holder of it states its own.
A member's `source` is one of:
- an identity: `lighting.harbour_fill`, `@builtin::<library>.<name>`. It
resolves among the assets that can be members, so a name another kind of
asset also answers to reaches the member;
- a path with its type suffix: absolute (`/source/lighting/harbour_fill.sceneLight`),
from the folder holding this setup (`harbour_fill.sceneLight`,
`./harbour_fill.sceneLight`, `../shared/fill.sceneLight`), or from the
world's source folder (`lighting/harbour_fill.sceneLight`). A path starting
`./` or `../` is read from the setup's folder alone.
An identity drops the type suffix, so `harbour_dusk.sky` and
`harbour_dusk.sceneSetup` in one folder share `lighting.harbour_dusk`; a
member naming that identity is skipped as `sceneSetup.member.ambiguous`, which
names both assets, and its path names the one meant. A source that names
nothing is `sceneSetup.member.missing`, and its values and overrides are kept
until it resolves.
A member whose type does not implement `applicable` is refused by name
(`sceneSetup.member.unsupported`). A key the engine does not read is a warning.
## Parameters and paths
A setup's parameters are its members': `<member id>/<name>` (`fog/density`), a
nested member's under its path (`look/reflections/intensity`), and
`<member id>/@enabled` for every member. `@lit` (true by default) says whether
the scene renders lit; off, every surface shows its own colour with no light on
it, for a stylised game or a menu. `asset.schema(setupRef)` lists every path
with the member's own Field descriptor.
A setup that nests another names its parameters through the member id it
gives the nested setup: a setup whose member `base` is another setup has
`base/fog/density` for that setup's `fog/density`, and a placement sets
`base/fog/density`. A path that is no parameter is refused naming the paths
that end in it.
The value a member receives, for each parameter, first present wins: the
placement's override, the outermost setup's `values`, each inner setup's
`values`, the member asset's live value, then its saved value.
## Placing and tuning
```lua
-- A world's setup by its identity (`lighting/harbour_dusk.sceneSetup` is
-- `lighting.harbour_dusk`), or by its absolute path, `/source/lighting/harbour_dusk.sceneSetup`.
local root = asset.resolve("lighting.harbour_dusk", "sceneSetup"):instantiate(nil, { name = "lighting" })
local setup = root.component.get("SceneSetup")
setup:set("fog/density", 0.05) -- this placement's override
setup:set("fog/density", { scale = 3.75 }) -- relative: the setup's density times 3.75
setup:set("fog/heightFalloff", { offset = -0.06 }) -- relative: the setup's value plus -0.06
setup:set("ao/@enabled", true) -- turns a member on for this placement
setup:reset("fog/density") -- back to what the setup says
for path, m in pairs(setup:members()) do print(path, m.state.status) end
```
The placed root holds the `Asset` component (its `source` is the setup) and the
`SceneSetup` component (this placement's `overrides`); the scene stores nothing
of any member. Removing the `Asset` removes the `SceneSetup`, and every member's
application goes with it.
A relative override (`{ scale = n }` or `{ offset = n }`, numeric parameters
only) lands at the value the setup supplies times `scale` or plus `offset`,
checked against the parameter's descriptor, and follows that value: edit the
setup's fog density and every placement scaling it moves with it. It is saved
and synced like any override, and the Inspector shows it as relative.
**Where each value comes from.** `setup:get(path)` and each member's `values`
in `setup:members()` say it: `origin` is `override` (this placement's, with
`relative` and `supplied` for a relative one), `definition` (with `definedBy`,
the setup stating it, and `definedAt`, the path it states it at there, so a
value inherited through a nested setup names that setup), `live` (the member
asset's live value) or `saved`. One line proves what a placement shares:
```lua
for name, v in pairs(setup:members()["fog"].values) do print(name, v.value, v.origin, v.definedBy) end
```
**A light that follows the sky lands at what the sky makes of it.** A sun, a
fill or a rim that follows the sky (`followSky`) states its intensity as its
noon peak: the sky gives it that intensity with the sun 30° up or higher and
dims it toward the horizon, to about a third at 7° and 0 below it. So a dusk
sun stated at 3.2 at 17:51 lands near 0.4. `setup:get(path).landed` (and
`setup:set(path, value)`, which returns the same read) is what it lands at
now, beside `value`, what it states; the card shows `3.2 → lands at 0.4 at
17:51` on the row. The member's `state.notice` in `setup:members()` names a
light the sky dims to under a third of what it states, a distant fill that
lands brighter than the sun it is meant to support, and an ambient term at
half the sun or more. Raise
the stated intensity, move the hour, or, for a fill or a rim, set
`followSkyIntensity` to `false` so it keeps what it states.
**`set` in edit mode is a scene edit.** In edit mode on a world scene, a `set`
is an authored edit of the scene, recorded and saved: it holds over what
`build.luau` states until it is reset or released (`sceneAuthoring`
`releaseAuthored`). A `reset` that leaves the placement with no override
records nothing and releases the edit an earlier `set` recorded. Overrides
stated in `build.luau` are the build's own.
## Auditioning another setup
Two placements, or a placement and an application from code, each apply their
own sun, ambient term and fog; the effect decides which is in force (the
light-tie rule for lights), so an application beside a placed setup reports the
members another application holds as `held`, with `heldBy`, and its
`ApplyState.notice` names each held member, its asset and its holder. To see a
setup in place of the placed one:
- audition it on the placement, a preview for the session:
`setup:audition(asset.resolve("lighting.harbour_night", "sceneSetup"))`
applies it in the placed setup's place and records nothing;
`setup:endAudition()` (or the card's End audition, a flip, a reload) puts
the placement's own setup back. `set` and `reset` are refused while it lasts;
- apply it from code (below): it holds over the placement across flips until
it is dropped;
- read its preview: `preview.png` lights the reference subject
`@builtin::preview.subjects.lookdev` with the setup alone, its exposure fit
so a night setup reads (below);
- point the placement's `Asset` source at it (a scene edit that stays;
`releaseAuthored` returns the placement to `build.luau`'s setup);
- or apply it in a scene with no setup placed, such as a scratch scene.
## Applying it from code
A setup implements `applicable` itself, so it can be applied for an owner
like any member: `setupRef:as("applicable"):apply(owner, values)` starts an
application and `setupRef:as("applicable"):drop(owner)` ends it. Each member is
applied with the owner `"<owner>/<member id>"`.
- **It takes the effects that hold one at a time.** The scene's sun, its
ambient term, its sky and each render feature's settings are held by one
application at a time: of the applications standing, the newest to state
something holds it, so an application made over a placed setup holds them
while it stands, and the placement's members report `held` by it.
- **It stays in force until it is dropped,** across edit/play flips and device
rebuilds.
- **Its drop hands every effect back** to the application before it: the
placement's own, or the scene's own lights.
Which of two suns or two fogs is in force is the effect's own to decide; the
setup decides nothing about its members. An audition (above) is a preview for
the session that a flip ends; an application from code stands until it is dropped.
```lua
local night = asset.resolve("lighting.harbour_night", "sceneSetup")
night:as("applicable"):apply("myGame:time", {}) -- night holds over the placement
-- … flips, rebuilds …
night:as("applicable"):drop("myGame:time") -- the placement's lighting is back
```
## Checking one
`asset.validate(setupRef)` (an engine API function) reads the definition and
every value and returns `{ ok, problems }`: each diagnostic (`sceneSetup.member.missing` and the rest) with its
code, severity, path and message. A problem of severity `error` refuses a push.
## Its picture
A setup's `preview.png` shows its own lighting on a fixed reference subject,
`@builtin::preview.subjects.lookdev` (a grey ground, a white diffuse sphere, a
chrome sphere and a grey card). The preview studio stands the subject and
applies the setup to the world with the owner `preview` for the shot, so its
sun, sky and effects are the ones in force, then drops it, which hands every
effect back to the scene's own holder. A frame that reads darker than mid
grey (a night setup) is shot with its exposure opened up for the picture
alone, by up to eight stops, so the night look reads without the setup
changing. For those frames the world shows the
setup's lighting, so the picture renders only on an explicit request
(`preview.writePreview`, `assets.generatePreviews`, staging) and never from
the preview queue or a live preview; the last picture stands otherwise.
## Make one
```lua
asset.create("sceneSetup", "dusk", { members = {
{ id = "sun", source = "./sun.sceneLight" },
{ id = "ambient", source = "./fill.sceneLight", values = { intensity = 0.1 } },
} })
```
·renderfeature · born here
❒asset # ambientOcclusion
The render pass behind the `AmbientOcclusion` component and the `ao` module. It
stands in the `lighting` post stage and runs at `afterDepthPrepass`, where this
frame's opaque depth is complete and nothing has shaded yet:
1. An estimator writes, per texel of a grid at the quality level's `scale` of the
frame, the occlusion of the hemisphere above the surface and its bent normal
(the mean open direction): `ao_pass`, the screen-space horizon integral over
a visibility bitmask, or `ao_trace`, rays traced against the scene
acceleration structure while `traced` is set and the scene's ray tracing is on.
2. `ao_temporal` carries the estimate across the renders of each view,
reprojecting the view's previous accumulation through its previous
view-projection and taking it only where the depth says the surface is the
same one. The accumulation is a history target (`history = true`), so the
viewport, every render-to-texture camera and every capture read and write
their own, and its state says when a view's previous image is there to
read.
3. `ao_filter` lifts the grid to the frame's resolution, weighing each tap by
depth, and writes the scene's occlusion channel (`@scene.ao`): occlusion in
r, the bent normal laid flat on the octahedron in g and b, and in a whether
a bent normal was written.
4. With the `ao` module's `indirect` on, the estimate is `ao_pass_indirect`:
the same walk (`ao_walk`), which also gathers, over each run of sectors a
tap closes first, the light that occluder sent toward the camera in the
view's previous render (`@scene.colorHistory`), where that render drew the
same surface there and its face turns toward the surface. `ao_light_temporal`
carries the gathered light across the view's renders like step 2, and
`ao_light_filter` lifts it into the scene's indirect channel
(`@scene.indirect`): the light in rgb and the share of the closed hemisphere
it answers for in a. A traced estimate runs that walk beside it for the
light. The light passes stay out of a reflection probe's cube faces, which
continue no render of their own.
Every lit material reads the channel at its own pixel the same frame, on its
indirect light alone: `FragmentData.ambient_visibility` carries the open share,
and PBR shading (`zero_pbr_shade`) takes it on the diffuse lobe with the light
the surface's colour bounces back into a crease, and on the reflection lobe as
the share of that lobe the open cone around the bent normal holds
(`zero_scene_bent_normal`, `zero_pbr_indirect_visibility`). The gathered
light reaches the diffuse lobe in place of the surroundings' light the
occlusion took from the closed part (`zero_scene_indirect_here`), and the
crease-return estimate stands only for the share the gather did not answer.
Direct light, emissive surfaces and transparents keep the light they carry.
Both estimators reconstruct the surface normal from this frame's depth. Depth
and camera come from the render target being drawn, so the pass is correct in
offscreen captures and render-to-texture cameras at their own resolutions. Sky
pixels have no surface to occlude and write none.
The `ambientOcclusion` capture view is drawn into a target the pass makes when
a capture of the view asks for it and releases once captures stop asking; its
passes run on that capture's channel alone.
Settings arrive through the `ao_params` buffer, packed by the `ao` module, which
also reports what the pass built through `ao.stats()`.
·renderfeature · born here
❒asset # probeGI
Indirect diffuse light from a field of probes traced against the scene.
The field is up to four nested grids of probes (cascades), each centred on the
camera and each with `cascadeSpacingRatio` times the spacing of the one before,
so the finest holds the nearest surfaces in detail and the coarsest reaches far.
Every frame each probe shoots `raysPerProbe` rays through the scene's
acceleration structure and records what comes back: the sky where a ray leaves
the scene, and at a surface the sun's light (with a shadow ray toward the sun),
the light of the scene's point, spot, area and distant lights (with a shadow ray
toward each), the surface's emission, and the light that surface takes from the
field as the previous frame left it. That last term carries light from surface
to surface, one bounce per frame.
The scene those rays walk holds every entity's model and every drawn copy of
each population `renderer.mesh.drawInstanced` registers as `traced` (which
follows `castsShadows` unless the registration says otherwise), so plants and
props block the sky and the sun from the probes under and around them and send
their own colour back. A population whose matrices only a compute pass writes
cannot be placed and reports `traced = "noCpuTransforms"` from
`renderer.mesh.instanceInfo`.
Each probe keeps two small octahedral maps of the sphere around it, blended over
frames by a hysteresis: the irradiance arriving from each direction (and, in the
alpha, the share of the sky it sees that way), and the mean and mean-squared
distance its rays travel in each direction, each ray counted at most a cell
diagonal of its cascade far (and, in the blue, the share of rays that left the
scene). A surface reads the eight probes around it, weighted by trilinear share,
by how squarely it faces each probe, and by the Chebyshev bound on how much of
the way to the surface each probe sees clear, so a probe on the far side of a
wall carries no weight. What a surface reads is stable under camera motion
because the maps live in probe space and each grid is anchored to the world.
## Holding still, and following a change
A probe's rays leave in new directions every update, so each update of one
direction's texel differs from the last by the sampling noise of its rays: a few
rays that find a small emitter, a random point across an area light, the light
the surfaces they hit pass on. Whether the probe's light changed is read over
the whole probe: where the mean of its tile moved by no more than
`changeSigmas` standard errors of the mean of its rays (the noise its recent
updates carried), its recent updates do not lean to one side of what it holds,
and the share of the sky it sees did not move past its own noise, the update is
noise and every texel keeps `stillHysteresis`, so a still scene settles to a
still field. Past that, the light changed and the texels keep
`irradianceHysteresis`; past `changeThreshold` of the smaller of the new and
held means as well, up or down, they take `hysteresisFloor`, so a sun that
steps or a lamp that switches on shows within a few frames. The distance
moments read their probe's mean distance the same way, between
`stillHysteresis` and `visibilityHysteresis`, and follow the irradiance where it
found a change. Each blend rounds to half precision at random in proportion, so
a blend that keeps most of the past still moves the stored value by what it
should on average.
A probe whose cell enters its grid, or whose field has just started, is young
for a dozen updates: it updates every frame, whatever its cascade's turn, and
takes the mean of the updates it has had, so a new field reaches its light
in a few frames. A probe whose cell entered takes the plain mean of its first
dozen updates. A probe that started with its field (the field started, or its
cascade's grid moved by its whole extent at once) reads a field that climbs
bounce by bounce as every probe in it starts, so its earlier updates hold less
of the light than its later ones: its irradiance takes a mean of its first two
dozen updates in which the k-th, counted from 0, weighs (k + 1)(k + 2). Until
four dozen updates it blends by the hysteresis, never the still one, while the light the field passes on climbs bounce by bounce. A
young probe outside geometry may move away from a nearby
surface; after that it keeps its place, so where it stands does not wander with
each update's rays. A probe inside geometry moves out on any update that finds
it inside. A probe the store holds inside stays inside until fewer than half of
`insideShare` of its rays hit the back of a surface.
## Where each probe stands
Each probe also keeps an offset from its lattice position and whether it stands
inside geometry, which a pass of its own works out from the probe's rays every
frame. A probe more than `insideShare` of whose rays hit the back of a surface
stands inside geometry and carries no weight wherever the field is read. One on
a solid's boundary (some of its rays left the solid: it stands on a surface, or
in a wall where a corner opens) moves toward the side its rays open onto,
`probeClearance` of a spacing a frame; one buried in a solid stays put, inside.
A probe outside geometry nearer than `probeClearance` to a surface facing it
moves away from it. A probe moves at most 0.45 of a spacing from its lattice
position along any axis, and one whose cell enters its grid starts on its
lattice position.
A pass of its own reads the field at every surface in view, multiplies by the
surface's diffuse colour and the field's gain and tint, and adds the result to
the frame. It reads the G-buffer, so it runs on the deferred path, and it turns
scene ray tracing on when it starts. A closed room of walls 0.3 m thick holds the
field's light out at a finest spacing of 1 m or 2 m.
The reads are taken on a grid of one read per `applyScale` x `applyScale`
pixels, and go through the denoiser `denoiser` names (`denoise`): an asset
implementing the `denoiser` interface, `@builtin::systems.denoising.svgf` by
default. It filters the light arriving at each surface, before the surface's
colour: each read is carried from frame to frame through the frame's motion
(the camera's, each moving entity's and each animated pose's), let go where the
surface under it changed, held to a fast estimate so a change of light shows
within a few frames, and smoothed across reads of matching surfaces, most where
its history is short. Another pass lifts the reads to every pixel, weighing each
by how well the surface it was read at matches the pixel's. Naming another
denoiser in `denoiser` swaps the filter; `denoise` off takes the field as each
frame reads it.
Within `edgeFade` cells of a cascade's edge a point is read partly from the next
coarser cascade, whose probes stand farther apart. A coarser probe and the finer
probe that weighs in most at the point must see each other, so a coarser probe
past a wall the finer probes resolve carries no weight there, and the coarser cascade
takes its share only as far as its probes see the point as clear as the finer
cascade's do; the rest stays with the finer cascade. A room of walls 0.3 m
thick in a field only eight probes tall, most of it inside the fade band of its
finest cascade, holds the coarser cascades' light out too.
The field's sky is the captured sky of a sky light member: `skySource` names it
and its captured environment is what a ray that leaves the scene returns. The
field is where the sky's diffuse light is occluded, so a scene that places it
gives the sky light a `diffuse` of 0.
## The scene's lights
A ray's surface takes the light of the lights the light grid lists where it
stands, with the falloff, spot cone and rect integral the surfaces are shaded
with (`@builtin::shaderModules.scene_lights`), so the bounce a lamp sends is in
the units of its direct light: the lamp that lights a red floor directly lights,
through the field, the wall that floor faces. The surface counts as one on the
default light channel. Of the lights that reach it, it takes the
`maxLocalLights` that put the most light on it unshadowed and traces one shadow
ray toward each, as long as the way to the light, so a lamp behind a wall adds
nothing on the far side of it. A rect light's ray goes to a point drawn across
its face for each ray and frame, so the field, which blends its rays over frames,
reads the share of the rect a surface sees.
Each light a ray's surface takes costs one shadow ray, so the trace costs at
most `raysPerProbe` x probes x `maxLocalLights` shadow rays a frame for the
scene's lights, on top of its own rays and the sun's. A light out of reach of a
surface (past its radius, outside a spot's cone, behind a single-sided rect)
costs a few compares there and no ray. A surface reached by more lights than
`maxLocalLights` takes is stated: the field reads its stats store back every 60
drawn frames, and while a ray hit since the read before was reached by more, the
sentence naming how many reached it stands in the feature's log, in
`live.droppedLights` and in the member's notice.
## What it publishes
`modules.state("@builtin::systems.probeGI.probeGI.live")` holds the field's
parameter buffer (`params`), the two atlas pairs (`irradiance`, `visibility`),
the ray store (`rays`), which of each pair the last frame wrote (`current`),
`droppedLights` (the sentence stating that ray hits are reached by more of the
scene's lights than `maxLocalLights` takes, nil while none are), and
`skyVisibility`: a screen-sized picture with, per surface in view, the share of
the sky it sees over its hemisphere in red and along its mirror direction in
green (widened toward the hemisphere's by roughness). A sky light member whose
`occlusionSource` names this member scales its diffuse and reflection terms by
that picture.
## Parameters
| name | default | what it is |
|---|---|---|
| `probesPerAxis` | (16, 8, 16) | Probes each cascade holds along x, y and z, each 2 to 64; every cascade holds that many, and the whole field holds at most 65536 probes. A setting past that limit is stated in the feature's log, in `live.clamped` and in the notice of the member's application, with what the field holds. |
| `cascades` | 3 | Nested grids, 1 to 4. |
| `baseSpacing` | 1.5 | Distance between neighbouring probes of the finest cascade, in world units. |
| `cascadeSpacingRatio` | 2 | How many times a cascade's spacing the next coarser has. |
| `followCamera` | true | Whether the field is centred on the camera. |
| `anchor` | (0, 0, 0) | The field's centre when `followCamera` is off. |
| `belowShare` | 0.6 | The share of each cascade's height that lies below the camera. |
| `edgeFade` | 3 | How many cells inside a cascade's edge its light fades over into the next coarser cascade. A point no cascade holds reads the coarsest cascade at its nearest cell. |
| `gridOffset` | (0.5, 0.5, 0.5) | Where the lattice sits relative to the world's whole multiples of the spacing, in spacings. |
| `raysPerProbe` | 48 | Rays each probe shoots every frame, 8 to 256. |
| `irradianceHysteresis` | 0.97 | Share of a probe's irradiance carried over per sixtieth of a second: a slower frame carries over proportionally less. |
| `hysteresisFloor` | 0.8 | The share carried over where a probe's light changed (`changeThreshold`, `changeSigmas`). |
| `changeThreshold` | 1 | How far a probe's mean luminance must move, up or down, as a share of the smaller of its new and held values, before the probe takes `hysteresisFloor`. |
| `stillHysteresis` | 0.995 | Share of a probe's irradiance and distances carried over per sixtieth of a second while what its rays find stays within `changeSigmas` of their noise. |
| `changeSigmas` | 4 | How many standard errors of the mean of the probe's rays a move must pass to count as a change: within it, the move is the noise of one update's rays. |
| `maxCatchUp` | 2 | The most sixtieths of a second one drawn frame advances the field, 1 to 12. A frame after a longer gap (an editor that idles and wakes, a slow frame) blends as if only this many had passed, so one frame keeps at least `irradianceHysteresis^maxCatchUp` of the history (0.94 at the defaults, `hysteresisFloor^maxCatchUp` = 0.64 where a texel changed past `changeThreshold`) and the field follows a lasting change within a few dozen drawn frames. At 12, a frame after a long gap keeps 0.69 of the history. |
| `visibilityHysteresis` | 0.97 | Share of a probe's distance moments carried over per sixtieth of a second. |
| `visibilitySharpness` | 50 | Cosine power a ray weighs in by when it joins the distance moments. |
| `irradiancePower` | 1 | Cosine power a ray weighs in by when it joins the irradiance. |
| `bounceGain` | 1 | How much of the light a surface takes from the field is sent on again. |
| `maxBounceLuminance` | 16 | The most luminance a ray carries back; 0 sets no limit. |
| `skySource` | empty | The sky light member whose capture rays that leave the scene return; empty, black. |
| `skyIntensity` | 1 | Gain on the sky's light. |
| `skyBelowHorizon` | 0 | Share of the sky's light kept by a ray that leaves the scene below the horizon. |
| `sunIntensity` | 1 | Gain on the sun's light at a ray's surface. |
| `localLightIntensity` | 1 | Gain on the light of the scene's point, spot, area and distant lights at a ray's surface. |
| `maxLocalLights` | 8 | The most of the scene's lights one ray's surface takes, 0 to 16, each with a shadow ray: the ones that put the most light on it. 0 takes none. A surface reached by more is stated (above). |
| `emissiveGain` | 1 | Gain on emitted light. |
| `maxRayDistance` | 200 | How far a ray looks, in world units. |
| `normalBias` | 0.25 | How far, in spacings, a read point moves along its normal. |
| `viewBias` | 0.1 | How far, in spacings, a read point moves toward the viewer. |
| `weightCrush` | 0.2 | Probe weights under this fall off by their cube. |
| `intensity` | 1 | How much of the field's light reaches the frame; 0 draws nothing. |
| `tint` | (1, 1, 1) | A colour the field's light is multiplied by. |
| `minimumIrradiance` | 0 | A floor under the irradiance over pi any surface receives. |
| `probeClearance` | 0.1 | How far, in spacings, a probe keeps from the surfaces around it: a probe on a solid's boundary moves out by this much a frame, and one outside geometry nearer a surface than this moves away from it to this far. |
| `insideShare` | 0.25 | The share of a probe's rays that hit the back of a surface past which the probe stands inside geometry, where no surface reads it. |
| `update` | true | Whether the probes trace and blend every frame. Off, the field keeps the light, distances and probe places it holds, its grids stay where they stand, and every surface reads it as it stands, so two frames drawn apart read the same field: what changes between them is what else changed. On again, the field goes on from what it holds. |
| `denoise` | true | Whether the reads at the surfaces in view go through `denoiser`. |
| `denoiser` | `@builtin::systems.denoising.svgf` | The denoiser the reads go through: any asset implementing the `denoiser` interface. |
```yaml
# a setup member
- id: probeGI
source: "@builtin::systems.probeGI.probeGI"
values:
skySource: "@builtin::systems.sky.skyLight"
raysPerProbe: 48
```
## At lower quality levels
The settings that carry its cost scale with the device's quality level (`Field.scaled`): the values a setup authors are the high look, and `renderer.feature.resolved(handle)` states what each level draws. The `graphics-quality` guide lists the rules.
·renderfeature · born here
❒asset # heightFog
The render pass behind the `HeightFog` component and the `fog` module. Fog over
a scene comes from adding that component to an entity; this feature runs while
its density is above 0.
Two compute passes in the `medium` stage:
1. `height_fog_light` reads the light of the surroundings at the camera of the
view being drawn (the scene's ambient term, the captured sky and reflection
probes, the light-probe volumes, averaged over every direction) into one
texel.
2. `height_fog` reconstructs each pixel's world position from `@scene.depth`
and the drawn camera's inverse view-projection (`@frame.camera`), integrates
the height-falloff density along the view ray analytically from `start` to
the surface, and composes `surface * exp(-tau) + light * (1 - exp(-tau))`.
`light` is the fog's colour times the scene's sun (`@frame.light`, through a
Henyey-Greenstein lobe) plus the surroundings' light from the first pass, so
with every light dark the fog only dims what is behind it.
Working in world space is what lets density vary with altitude and what lets the
medium respond to view direction — neither is expressible from screen depth
alone.
Parameters arrive through the `heightfog_params` buffer, which the feature packs
from its settings. The fog is drawn over everything in view, the sky included: a sky
pixel takes the fog of its whole view ray, the lit medium where the fog never
thins and the column the ray climbs through where it does.
Because the camera rides `@frame.camera`, the fog is correct in offscreen
captures and render-to-texture cameras at their own resolutions, not only in the
live viewport.
The passes declare `environmentCapture = false`: the sky fallback and the
reflection probes the fog is lit by are captured without it, so each capture
holds the light of the scene as it stands, and a reflecting surface is seen
through the fog in front of it.
# dynamicMoon
The moon of `dynamicLighting.sceneSetup`: a shadow-casting distant light, a
cool blue-white (0.62, 0.74, 1.0), that follows the sky and keeps the intensity
it states (`followSkyIntensity: false`). After dark it stands at the moon the
sky draws, opposite the sun, and lights the scene at 0.05, an eightieth of the
sun. While the sun is up it stands with the sun and adds its 0.05 to the sun's
light.
·renderfeature · born here
❒asset # ssr
The render feature behind `ScreenSpaceReflections` and
`@builtin::systems.reflections.ssr`. Two compute passes run at the
`afterDepthPrepass` seam, once the visibility raster has laid the frame's depth
and before anything shades:
| order | pass | output |
|---|---|---|
| 60 | `ssr_trace` | one ray per pixel, drawn from the pixel's GGX lobe: where it hit and how confident the hit is, or the direction it travelled when it found nothing, into the feature's `ssr_rays` target |
| 61 | `ssr_resolve` | each pixel's lobe gathered over its own ray and its neighbours' rays, accumulated over frames in the feature's history target, into `@scene.reflection` |
That channel is what a material's environment term reads the same frame, at
its own pixel: the traced light, mixed over the probes and the sky by the share
of the surface's lobe the screen answered, with the material's own Fresnel,
roughness and tint weighing it into the pixel the way they weigh any
environment. Nothing here touches the lit picture.
The trace marches against this frame's depth, which the visibility raster
has just written, so the reflection stands where the camera is now. What it reads
about the surfaces (the reflecting surface's normal and roughness, the hit's
normal) comes from the previous frame: the G-buffer as that frame left it
(`readsPrevious`), reprojected through the previous view-projection
`@frame.camera` carries in its rows `[5..9)`. The resolve reads the light at each
hit from `@scene.colorHistory`, the light the previous frame ended with, at
the pixel the hit stood at then. A point the previous frame did not show
reflects its environment alone.
## The rays
Every pixel draws one ray from the lobe its roughness describes. A mirror (below
perceptual roughness 0.1) takes the reflection vector. A rougher pixel samples a
half vector from the distribution of normals visible from the camera (Heitz
2018) at `alpha = roughness²`, and reflects the view ray about it, from noise
that depends on the pixel and the frame. Each ray carries the density it was
drawn with, as `log2(pdf)`, so the resolve can weigh it against another pixel's
lobe.
The ray texel is `rgba16f`: for a hit, `xy` is the hit pixel minus this pixel (in
whole pixels), `z` is `log2(pdf)` and `w` the confidence in (0, 1]; for a ray
that found nothing, `xy` is the octahedral encoding of the direction, `z` the
same `log2(pdf)` and `w` is -1; a pixel that traced no ray holds zero. A
mirror ray carries 15 in `z` in place of a density.
## The march
`ssr_trace` walks the ray through the depth buffer.
Steps are uniform in **screen** space, not world space. A ray heading toward
the horizon covers enormous world distance across a few pixels, so stepping in
world units there means either missing every thin occluder near the camera or
spending the whole budget on distance nothing can be seen at. The world
parameter is recovered from the screen parameter through `1/w`, which is what
interpolates linearly under perspective.
At each step the ray's world position is compared against the world position
reconstructed from the depth sample under it. Comparing in world space is what
lets `thickness` mean a distance in world units rather than a depth-buffer
epsilon whose meaning changes with range.
The march looks only for the **crossing**, where the ray first passes behind
the depth buffer. Thickness is tested after bisecting that crossing, not
during the march: one march step covers roughly as much depth as a surface is
thick, so a ray tested during the march can jump from in front of a surface to
well behind it without ever landing inside it.
Bisection runs for whichever is larger, the quality tier's budget or however
many halvings bring one march step under `thickness`. A coarse march that
stopped bisecting early would leave the crossing bracketed more loosely than a
surface is thick, and every hit would then fail the thickness test, so
long-range reflections would vanish outright instead of thinning.
A rough pixel's ray marches fewer steps and refinements (down to 0.35 of the
tier's, reached 0.65 of roughness above a mirror), because the resolve blurs
what the rays find.
A hit on a surface that faces along the ray (what is on screen there is that
surface's far side) is trusted at half the confidence.
## The resolve
For each pixel the resolve gathers its own ray and up to `taps` neighbours (4 at
`low` and `medium`, 8 at `high`, 12 at `ultra`) on a disk of up to 6 px that
turns with the pixel and the frame and grows with roughness. A neighbour counts
only where its normal is within 0.9 of the pixel's and its depth within 5
percent. Each ray is weighed by the pixel's own lobe: `D · Vis · cos / pdf`.
A pixel's result is the light of the rays that hit and the share of the lobe
they cover. A ray that found nothing counts toward the lobe and carries no
light. The history accumulates that result, premultiplied, at up to 0.9 of the
previous frame for a rough surface and none for a mirror, with the history's
light and coverage both held to the mean plus or minus 1.25 standard deviations
of the rays gathered: a reflection whose rays now find nothing keeps nothing.
## What the channel holds
`@scene.reflection` holds linear radiance in `.rgb` and in `.a` the share of
the lobe the screen answered, multiplied by `intensity` and by the hand-over
above `roughnessCutoff`. A surface at or below the cutoff keeps the full share,
one 0.1 above it holds zero, and between the two the share fades. A miss is a
zero the material reads as "the environment alone". The channel is cleared at
the top of every scene render this feature does not run for, so such a frame
reflects the environment alone too. The passes read the light the previous
frame ended with, so they run on the lit channel alone (`debugChannel = 0`); a
camera drawing a diagnostic pass is drawn lit first, unpresented, so the passes
run for where that camera stands, and the diagnostic reads the channel gathered
for it.
## Memory
Each view that draws the feature holds three screen-sized `rgba16f` images: the
rays and the history pair. At 1080p that is about 16.6 MB each, about 50 MB for
the viewport.
·renderfeature · born here
❒asset # skyLight
The light the scene takes from what is drawn behind it. It captures that
picture into a cube of six textures it owns, gathers the cube into a diffuse
term and a set of reflection bands, and adds both to every lit surface in a
pass of its own, at the strengths its parameters state. Whatever draws the
backdrop (a gradient, a material, a photograph, clouds) is what it captures:
the capture is a render of the `captureLayers`, with no knowledge of what draws
them.
Every step is a call in its `init.luau`:
1. **Capture.** Six cameras, one per cube face, each 90 degrees across, stand at
`capturePosition` drawing only `captureLayers` and running only the
render-feature passes `captureFeatures` names: by default the ones an
environment capture runs, so a fog or a volumetric medium filling the air
stays out of the light that lights it. Each is held disabled and
rendered once into a `faceSize` x `faceSize` texture.
2. **Gather.** `skyLight_faces` folds the six faces into one equirectangular
map, which `ibl_irradiance` convolves into the diffuse term and
`ibl_specular` into five reflection bands of rising roughness. These run on
the frames after a capture.
3. **Light.** Every frame `skyLight_apply` adds both terms to the lit G-buffer, the
diffuse term scaled by `diffuse` and the reflection by `reflection`.
4. **Publish.** With `publishReflection` on, `environment.captureSky` puts the
sky, drawn from `capturePosition`, into the environment's sky slot: the
reflection every surface the reflection probes leave uncovered shows,
water and transparent surfaces among them, which the G-buffer pass never
reaches. Turned off, or with the feature torn down, the slot is switched off.
A capture is taken when the feature is set up, when what it draws changes
(`captureLayers`, `captureFeatures`, `capturePosition`, `faceSize`, or
`recapture`, a count an author changes to ask for one), and, with `followSky`
on, when the scene's sky row or the direction of its sun changes, at most once per `recaptureInterval`
seconds. The diffuse term and the reflection bands are gathered from every
capture whatever the strengths, so a strength changed relights from them.
What a render feature draws into the capture (an atmosphere's sky, a layer
over the sky) is part of the picture. A capture, and the sky slot the sky light
publishes, is taken once every live render feature has drawn with the settings
it holds, so a setup applied in one step is captured as it stands once all its
members are in force; the wait ends after 120 drawn frames at most. With
`followSky` on, a change of value in the settings of a render feature that runs
in environment captures (its `contentRevision` in `renderer.feature.list`)
takes a capture and, with `publishReflection` on, publishes the sky into the
slot again, at most once per `recaptureInterval` seconds. The sky light's own
settings do not count.
A render drawn while the renderer still held builds for the scene (pipelines,
shader compiles; the `pipelinesPending` of the face camera's `lastRender` in
`camera.observe()`) holds the scene as it looked before they landed. The six
faces are rendered again, at growing intervals of drawn frames, until one is
drawn with nothing pending; `redraws` counts those repeats.
## Parameters
| name | default | what it is |
|---|---|---|
| `diffuse` | 0.15 | The strength of the captured surroundings' diffuse light on surfaces, 0 to 4. |
| `reflection` | 0.25 | The strength of the captured surroundings in surfaces' reflections, 0 to 4. |
| `captureLayers` | `sky` | The render layers the capture draws. |
| `captureFeatures` | `environment` | Which render-feature passes the capture runs: `environment`, the ones an environment capture runs (the sky and what is drawn into it; the air and overlays stay out), or `all`. |
| `capturePosition` | (0, 0, 0) | Where the six capture views are taken from. |
| `faceSize` | 64 | The width and height of each capture view, in texels. |
| `followSky` | true | Whether a change to the sky row, the sun's direction or the settings of a render feature that runs in environment captures takes a capture. |
| `recaptureInterval` | 0.5 | The fewest seconds between two captures `followSky` takes. |
| `recapture` | 0 | A count; any change takes a capture. |
| `publishReflection` | false | Whether the sky also fills the environment's sky slot, the reflection a surface no reflection probe covers shows. |
| `occlusionSource` | empty | The member whose picture of how much of the sky each surface sees (`live.skyVisibility`) scales the diffuse and reflection terms, as its identity; empty, the terms are not scaled. |
With both strengths at 0 it enqueues no lighting pass and still gathers the
captured environment, which other members read. The textures it captured
into and gathered (`faces`, `environment`, `irradiance`, `reflection`), the
number of captures taken (`captures`), of repeated renders (`redraws`) and of
gathers that have written the irradiance and reflection maps (`gatherCount`)
are readable at
`modules.state("@builtin::systems.sky.skyLight.live")`.
```yaml
# a setup member
- id: skyLight
source: "@builtin::systems.sky.skyLight"
values:
diffuse: 0.15
reflection: 0.25
```
·renderfeature · born here
❒asset # taa.renderFeature
One compute pass in the `temporal` stage and the depth it restates for the
passes after it, its sharpening in the `display`
stage after the debanding and the edge antialiasing, and a per-frame offset to where the projection
samples.
## What it does
A pixel is one sample of a continuous image. Which point inside the pixel that
sample is taken at is normally fixed forever, and that is what makes an edge
resolve to the same staircase in every frame — the frames agree because they all
ask the same question.
This pass moves the sample. Each render the projection is offset by a sub-pixel
amount (`renderer.setProjectionJitter`), so consecutive renders are different
estimates of the same image, and the pass keeps a running result across them.
After a handful of frames that result holds detail no single frame contains: a
silhouette becomes a gradient, a specular highlight stops flashing on and off as
it crosses the sample point, fine texture stops crawling.
Where the samples go matters. The offsets come from a Halton sequence in bases 2
and 3 — successive points of a low-discrepancy sequence avoid each other, so a
short run of frames covers the pixel evenly, where independent random points
clump and leave gaps and a regular grid repeats as a visible texture. The two
bases are coprime, so the axes do not fall into step. Eight offsets is enough to
resolve an edge and short enough that the result refreshes before anything
drifts.
## Carrying the result forward
The accumulated result is only usable at a pixel where it describes the same
surface. These tests decide that, in order.
**Where to look.** `@scene.motion` gives the screen-space velocity of the surface
under each pixel — where it was in the previous frame. The velocity is read from
the closest-depth pixel of the 3x3 neighbourhood rather than from the pixel
itself: along a moving silhouette the pixel's own velocity belongs to whichever
of the two surfaces won the depth test, and the nearer surface is the one whose
edge is sweeping across the pixel. The history is read there through a
Catmull-Rom spline rather than bilinearly: a bilinear read averages the four
texels around the point, so a history reprojected a fraction of a pixel every
frame softens a little more each frame, and a slow pan blurs thin lines away.
**Whether to look at all.** A reprojection landing outside the frame has nothing
recorded there. That pixel starts its own accumulation from the current frame
rather than inventing one.
**Whether something used to stand in front.** Each render also records how far
from the camera every pixel's surface stood (a second history target). Where the
previous render held a surface well in front of the one here now, what
reprojects onto the pixel is whatever used to cover it, and the pixel starts
over from the current frame. The farthest of the four recorded texels around
the reprojected point is the one compared, so a thin object whose edge falls on
a different side of a texel each render does not read as having moved away.
**Whether the answer is still about this surface.** Something newly uncovered
reprojects to wherever the thing that was covering it went, and reads as a
perfectly valid sample of the wrong surface. That is the smear temporal
antialiasing is known for. The neighbourhood's own colour statistics bound it:
the 3x3 block around the pixel describes what colours belong there now, so the
carried sample is clipped into the range the mean and standard deviation of that
block describe before it is trusted.
Mean and spread rather than min and max, because a single bright texel stretches
the extremes far enough to admit a sample that is nothing like the pixel, while
the standard deviation stays honest about how much the block actually varies.
The clip runs in YCoCg and along the line from the neighbourhood mean. Luminance
is one axis there, so the box tracks a neighbourhood that varies mostly in
brightness far more tightly than an RGB box, whose corners admit colours the
neighbourhood never contained. Moving the sample along a line rather than
clamping three channels independently keeps its hue, so the result is a colour
between two the frame actually holds.
## How much of each frame goes in
Every colour is weighed in a reversible tonemapped space (each divided by one
plus its luminance, and the result expanded again after), so a highlight many
times brighter than its surroundings counts in proportion to how it looks
rather than to how much light it carries, and the pixel holds steady as the
jitter crosses one bright sample.
The frame's sample is not the pixel's own raster sample alone. Each render's
projection moves every sample by the same sub-pixel offset, so the pass knows
where each of the 3x3 samples around the pixel landed, and weights each by its
distance from the pixel's centre (`temporal_reconstruct`). The pixel's own
sample flips between the two sides of every edge the jitter crosses; the
weighted estimate moves little as the offset changes.
Every pixel's history records how many renders it holds (a third history
target, which also carries the spread below). This render's estimate takes its
share as one sample among them, so a history a few renders long settles in as
many renders as it holds, from a cut, from a disocclusion and from a camera
stop alike. How many a history may hold depends on whether its surface moves:
- **Still** (its surface moved under a quarter of a pixel since the previous
render): `stillSamples` of them, several whole passes through the jitter
sequence, so the accumulation settles on the average of the renders the
sequence draws instead of rippling as the samples visit the pixel.
- **Moving**: as many as `historyWeight` keeps, fewer as `motionRejection`
shortens the memory for fast motion; twice that where the history passes the
clip untouched (it then differs from the estimate only by where the jitter
put it), and the weight's own count where the clip moved it, so real change
is followed.
A still pixel also carries how far the jitter moves its estimates: their
variance about the history, kept over about one pass through the jitter
sequence. An edge thinner than the 3x3 samples, a blade of grass or a frond
seen from a distance, drops out of some renders' neighbourhood altogether, so
the box those samples span says nothing of it and the clip would pull the
history to whichever side the jitter landed on. An estimate within two standard
deviations of that spread is the jitter, and the history stands unclipped; one
past three is a change, and the clip follows it. The spread is trusted once it
has seen two passes through the sequence, and a pixel that moves or is
disoccluded starts it over.
## Sharpening the shown picture
`sharpness` runs `rcas`, a contrast-adaptive sharpening of the picture after the
display transform, in the display stage. It reads what the accumulation
produced and writes only what is shown, so it is applied once per frame and
never compounds through the history. Its lobe is limited per pixel and its
result held inside the range the pixel and its four neighbours span, so an edge
gets steeper without a bright halo along a dark line or a dark one along a
bright line.
## Velocity and the offset
The offset is folded into the projection, so it would otherwise show up in
velocity as a sub-pixel wobble on a scene that is not moving. The engine
publishes the offset alongside the matrix and the vertex stage subtracts it back
out, so `@scene.motion` describes the surfaces and a still scene reports no
motion however the samples are placed.
## What the passes after it read
The resolved picture samples every pixel at its centre; the raster under it
sampled this render's offset. An effect after the resolve that draws from the
scene's depth (an outline found where the depth steps, a pattern laid on the
surfaces through the world position the depth reconstructs) would draw from the
raster and move by up to half a pixel on every frame of a still view, over a
picture that holds still.
So the resolve is followed by two passes in the same stage. `stable_depth`
keeps, for every pixel, the depth sample taken nearest the pixel centre for as
long as no surface around the pixel moves and the sample still lies among the
depths its neighbourhood holds; over one pass through the offsets a still pixel
settles on one sample and keeps it. A fragment pass whose output is
`@scene.depth` (`restates = true`) then restates the frame's depth from it:
every pass after it reads that depth through `@scene.depth`, the post
framework's `scene_depth` and `zero::scene_depth`, and reads the camera with no
sub-pixel offset through `@frame.camera` and `engine.view_proj` /
`engine.inv_view_proj`. Those two passes name `@scene.depth` and the kept
depth in `whenRead`: on a frame where nothing after them reads the depth (a
pass binding `@scene.depth` or drawing with a shader that samples it, or an
effect of the post-process chain that samples it) they are left out, and the
first render that has such a reader again starts the kept depth over from its
own. A third pass, whose output is `@frame.camera` (`restates = true`),
restates the camera on every frame, so a pass after the resolve that reads
the camera and no depth reads it with no sub-pixel offset as well. A pass
ahead of them reads the raster's own depth, which every render lays again
before its first phase, and keeps neither. On the deferred path
`stable_surface` keeps the G-buffer normal and material of the same sample,
and two more passes restate
`@scene.normal` and `@scene.material` from them, so the passes after the resolve
that read the G-buffer (the rest of the `afterLighting` phase) see the surface
the restated depth describes. Those three passes name the two channels in
`whenRead`: on a frame where no pass reads what they leave in `@scene.normal`
or `@scene.material` (a pass after them, or one ahead of the shading reading
the G-buffer the previous frame left, such as screen-space reflections) they
are left out, and the first render that has such a
reader again starts the kept surface over from its own. Lines and patterns an
effect draws there hold still on a still view and move with the surfaces on a
moving one. A pass ahead
of the resolve (occlusion, reflections, fog, depth of field) reads the
raster's own depth and surface, which describe the same scene, and
`__renderpass.schedule()` reports no such read.
## Every view keeps its own result
A frame draws several views: the viewport, every render-to-texture camera, every
capture. Each runs this pass against its own picture, at its own size, so each
keeps its own running result. The result lives in a history target
(`renderer.texture.create { history = true }`), which holds one pair of images
per view: for the length of a view's render the pass resolves into the target's
`guid` and reads `previous`, the image that view's previous render resolved. A
minimap or a capture drawn beside the viewport neither reads the viewport's
result nor disturbs it.
Each view also walks the sample sequence on its own count of renders. Its first
render, and its first after a cut, samples the pixel centre and starts the
result from that render alone, which is all a one-shot capture ever draws.
The colour images are `rgba16f`, so an accumulated highlight brighter than white
keeps its value instead of clipping on the way through. The distance images are
`r32f`, the temporal images `rgba16f` (how many renders each pixel's history
holds and the spread of its estimates), and the stable depth images `rgba32f`
(the kept depth and how far from the pixel centre it was sampled).
## Parameters
`taa_params` carries the tuning and `rcas_params` the sharpness, both written by
`@builtin::systems.antiAliasing.temporalAntiAliasing`. `taa_state` is the history
target's state, written by the engine before each render of a view: whether
`previous` holds that view's previous result, how many renders in a row have
carried it, and the render's sub-pixel offset. A render with no result to carry
begins from its own sample.
·renderfeature · born here
❒asset # contactShadows
The render passes behind the `ContactShadows` component and the module. Its
settings (`strength`, `length`, `steps`, `bias`, `thickness`, `followSun`,
`lightDirection`, `localLights`, `maxTracedLights`) are its fields, so it can
stand as a placed member with every value stated.
The sun, at the depth seam before anything shades: a jittered depth-buffer
march from each surface toward the sun, its normal read off the depth, writes
the share of the sun's light it finds taken; a depth-aware blur smooths it; a
fragment pass composes it into the scene's sun occlusion channel
(`@scene.sunOcclusion`) with the `union` blend. The sun's term alone takes it,
so the sky, the probes, the emissive surfaces and the other lights keep their
light, and it stands with a participating medium's share as `a + b - ab`.
With `localLights`, after lighting: a march toward each of the
`maxTracedLights` point, spot and distant lights putting the most light on the
pixel, each result weighted by the share of the pixel's light that light
supplied, then a depth-aware blur that composites the result scaled by how lit
the pixel already is, so contact shadows and shadow-map shadows do not stack.
Those lights arrive through `contact_lights`, packed by the module once a
frame, so the traces follow lights that move.
The forward view-projection is the frame's own, so captures and RTT cameras
project through their own matrix.
·renderfeature · born here
❒asset # exposure
The render feature behind `AutoExposure` and
`@builtin::systems.exposure.exposure`. Two compute passes run in the `meter`
stage, on the picture the temporal resolve reconstructed:
| local order | pass | output |
|---|---|---|
| 0 | `exposure_meter` | 32x32 grid of tile log-luminances, weighted by the metering mask |
| 2 | `exposure_adapt` | the live exposure, moved toward the scene's reading |
## Metering
`exposure_meter` gives each tile a slice of the frame and averages the
log-luminance across it, sampling every fourth pixel in each axis — a tile
covers hundreds of pixels and the result is an average, so sampling all of them
buys precision the eye cannot see at sixteen times the cost.
Averaging happens in **log** space. The eye's response is logarithmic and so is
the quantity being averaged, which is why a few very dark pixels do not drag the
whole frame's exposure up the way a linear average would.
The metering mask weights that average. Full metering reads everything;
centre-weighted tapers to a floor at the frame edge; spot reads only the middle.
## Adaptation
`exposure_adapt` runs as a single invocation, so there is one writer to the
state buffer and no ordering to arrange between workgroups. It reduces the tile
grid, works out the exposure that would land the average on `targetGrey`, and
moves the live value toward it.
The approach is exponential in `dt`, so the rate is independent of frame rate.
Rising and falling use different speeds on purpose: the eye adjusts to
brightness far faster than it adjusts to darkness.
The live exposure lives in the `exposure_state` buffer, written by the GPU and
read back the next frame — that persistence across frames is the whole
mechanism behind an image that settles rather than snaps. The buffer starts
zeroed, and a zero in its "initialised" slot tells the first frame to settle on
its reading immediately instead of adapting up from an exposure the scene never
had.
`exposure_state[0]` is `(currentEV, initialised, targetEV, compensation)`, and
`exposure_adapt` also writes the live and target stops to its single-texel
output.
## Reaching the picture
`exposure.module` reads `exposure_state` back to the CPU each `tick`, adds
`compensation` (already held there) to the adapted stop, and writes
`exp2(adapted + compensation)` to the chain's display pass as `__display__`'s
`exposure` property — the one place in the frame a stop turns into a change on
screen.
Parameters arrive through the `exposure_params` buffer, packed by
`@builtin::systems.exposure.exposure`, which also supplies the frame's `dt`.
# dynamicSun
The sun of `dynamicLighting.sceneSetup`: the scene's directional light, a warm
white (1, 0.88, 0.74). It follows the sky (`followSky`), so the sky's hour aims
it, and lands at its stated intensity of 4 with the sun 30° up or higher,
dimmer and warmer toward the horizon and out below it. It casts the scene's sun
shadow.
# dynamicSky
The sky of `dynamicLighting.sceneSetup`: the procedural backdrop
(`@builtin::systems.sky.backdrops.procedural`) at 16:00, a clear blue day over
a grey-green ground, with blue-black night colours, stars and a moon.
Its hour (`backdrop/timeOfDay`) is the one value that moves the scene between
day and night: the sun and the moon that follow the sky take their direction
from it, the backdrop leans to its dawn colours as the sun nears the horizon
and draws its night colours, its stars and its moon once the sun is below it,
and the sky light captures what it draws.
# assetType (asset type)
An asset type says what a kind of asset is: the files an asset of the kind is
made of, the code that gives it behaviour, the interface a person uses to work
with it, and how it is found, pictured and checked. A `<typename>.assetType/`
folder declares a type called `<typename>`, and every `<name>.<typename>/`
folder is an asset of it. `assetType` is itself a type, so a type is an asset
like any other: it is created, versioned, installed and contributed the same way.
## Making a type
`asset.create("assetType", "<typename>")` scaffolds a type. The type registers
the moment its folder is written, anywhere under `/zero/source/`, and from then
on `<name>.<typename>/` folders are its assets. An asset of a type that is not
registered yet is not an asset, so make the type first.
A type folder is a root: `~.x` in any file inside it names the type's own `x`,
wherever the type is installed. Keep the type's whole implementation inside its
folder and reach it that way.
What a type folder must hold is set by this type's own `type.yaml`, the same way
every type's `type.yaml` sets what its assets hold. `asset.validate` on a type
reports anything missing, and the scaffold produces a folder that passes.
## What sets your type's schema (`type.yaml`)
`type.yaml` is the structural contract every asset of the type is checked
against. The keys below are the ones the engine reads; a key not listed here is
ignored.
| Key | What it controls |
|---|---|
| `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. |
| `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. |
| `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. |
| `is_container` | Whether the suffix stays in the identities of what the asset holds. |
| `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. |
| `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. |
| `is_text_default` | Whether the asset's files are text unless stated otherwise. |
| `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. |
| `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. |
| `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. |
| `files: { required, optional }` | The files an asset holds (below). |
| `allow_unlisted` | `false` reports every file the type does not declare. |
| `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. |
| `settings:` | Typed per-asset settings (below). |
| `inspector:` | The interface people use for the type and its assets (below). |
| `preview:` | How an asset is pictured (below). |
| `references:` | Names of other assets the type's files carry (below). |
| `indexing:` | What search reads for each asset (below). |
| `describe:` | How a missing description is generated (below). |
### The files an asset holds
Each entry under `files.required` or `files.optional` is
`{ path, kind: file | folder, one_of_group?, content? }`. `*` in a path matches
within one segment. Entries that share a `one_of_group` are satisfied by any one
of them. `content` lists checks on the file's bytes:
| Check | Passes when |
|---|---|
| `non_empty` | the file has content |
| `json_field { key, type?, non_empty?, accept? }` | the JSON holds the key (a dotted path) with that shape |
| `yaml_field { key, type?, non_empty?, accept? }` | the same for YAML |
| `described { keys?, headings?, message? }` | the file says what the asset is (see "Ask your assets to say what they are") |
Each check takes a `message`, which is what the author is told when it fails.
### Settings
`settings: { values, schema: { type | instance, export? } }` gives every asset
typed settings. `values` names the file an asset's values live in; `schema.type`
declares one schema for the whole type, and `schema.instance` names a file each
asset declares its own in. `asset.create` writes the resolved values, and a write
to the values file reaches `onChange` with what changed.
## The human side (`inspector.luau`)
A type is used by people through its Inspector, and without one the type is
usable only from code. The Inspector is the type's interface for a person: for a
procedural graph it is the graph editor, for a kit it is the tracking view of
what the kit holds and what is still missing. Writing it is part of writing the
type.
`inspector: { type, instance? }` in `type.yaml` names the files. `type` is the
interface for the type itself and for its assets; `instance` names a file an
asset may ship to add its own. Each returns:
```luau
return {
sections = { { id = "graph", title = "Graph", build = function(ctx) ... end } },
replace = { contents = { ... } }, -- replace a default section by id
order = { "graph", "contents" }, -- section order
}
```
`build(ctx)` receives the asset and builds the section. A section's `title`, and
the text its rows carry, is a string or an `i18n.text` value read from a catalog
(`i18n.text("inspectors.mesh.title")`), which follows the editor's language. `asset.create("assetType",
...)` scaffolds a working `inspector.luau` to start from. `asset.validate` on a
type that names no inspector, or names one that does not load, reports it.
## Say what your type is for (`about.yaml`)
Every type carries an `about.yaml` that says what the type is for, in three
plain-language texts:
```yaml
intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering."
function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text."
usage: "You choose it by name for your UI or your text, and the text appears in that typeface."
```
- **`intent`** is what the type is for in someone's game, in the words a game maker uses. Up to 800 bytes.
- **`function`** is how it works today: what an asset of it is made of and what the engine does with it. Up to 1500 bytes.
- **`usage`** is what a person or an agent does with one. Up to 1200 bytes.
Write about the type as a whole, not one asset of it, and say what it does now.
Agents read these texts to learn when to reach for the type and how; people
searching find the type by them. The scaffold starts each text with
`[[describe]]` and a note on what to write; a text that still starts that way
counts as not written. `services describe` can write them.
They show up in `asset.inspect` as `detail.about`, in
`assetTypeRef:getAbout()`, at the end of the type's `types/<typename>` guide,
and at the top of the type's Inspector.
## Ask your assets to say what they are
A type can require each asset to carry a description: a file, written by the
author or generated, saying what the asset is and what it is for. Declare it with
a `described` check:
```yaml
files:
required:
- path: "README.md"
kind: "file"
content:
- { check: "described", message: "Say what this widget is for and where it goes." }
```
A file that is missing, empty or still has a line starting with `[[describe]]`
fails the check, and so does a YAML file whose named `keys` are missing or over
their `max_bytes`, or a Markdown file missing a named heading. `asset.validate`
names the asset, and a push that carries it is refused with `message`.
`services describe` finds such assets and writes their descriptions.
`describe:` steers what is generated:
```yaml
describe:
guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI."
examples:
- "<identity of an asset of this type whose description reads well>"
```
An example is an asset of your type whose description is a true, written one,
never a placeholder and never the asset being described; with none, leave
`examples` empty. A type whose assets the model cannot perceive (a sound, a
motion) says so in `guidance`, and the description is drawn only from what the
asset's own files state.
Start the file unwritten in your `template/`: a heading and one line starting
with `[[describe]]`, never example content, which every new asset would carry
verbatim. A type whose assets say what they are through their own content (a
mesh, a texture) declares no check.
## The type's code (`behavior.luau`)
`behavior.luau` returns one table. These are the keys the engine reads from it;
anything else on the table is the type's own.
### What the type's assets can do
| Key | Shape | What the engine does with it |
|---|---|---|
| `ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every asset of the type: `ref:name(...)`. |
| `modules` | `{ [name] = require(".x") }` | Code the type's assets reach with `asset.containing(__FILE__).modules.<name>`. |
| `events` | an events schema | Events an asset fires. Readers subscribe through `ref.events.<name>:connect(...)`; the type fires them. |
| `refShapes` | `{ [method] = function(self) -> (typeExpr, source?) }` | The result type of a `ref` method for one particular asset (below). |
| `namePattern` | a Lua pattern | The names `asset.create` accepts for the type's assets. Default `^[A-Za-z][A-Za-z0-9_]*$`. |
| `derive` | `{ output, module, compute, fingerprint, matches?, required?, timeout? }` | A file computed from the asset when it is committed; a `required` one holds the commit until it lands. |
Some `ref` names mean the same for every type, and the engine calls them:
- **`instantiate(self, target?, opts?) -> (root, idMap)`**: puts the asset in a scene. Defining it is what makes the type scene-instantiable. Its return is a contract (below).
- **`inspect(self) -> detail`**: what `asset.inspect` reports for the asset beyond the common record (below).
- **`preview(self, opts)`**: renders the asset's picture; it wins over the type's `preview:` recipe.
- **`previewMaterial(self) -> { material }`**: the material a `surface` preview paints.
- **`saveDefinition(self)`**: writes the asset's in-memory edits back to its files in edit mode.
Some names are answered for every asset before the type is asked, so a `ref`
entry of the same name is never reached: `getSource`, `getBytes`, `getText`,
`exists`, `deps`, `canInstantiate`, `canPreview`, `preview` (which calls yours
when you define one), `meta`, `runtime`, `events`, `typeRef`, `modules`, and the
residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`,
`gpu_resident`.
### When the engine calls the type
| Hook | Signature | When it runs |
|---|---|---|
| `onCreate` | `(name, opts) -> { [path] = contents }` | On `asset.create`. Returns the files of the new asset, laid over the type's `template/`. Annotate `opts`: its type is the schema `asset.create` checks the caller's arguments against. A `""` key writes a single loose file. |
| `onReplace` | `(dest, files) -> files` | On an `asset.create` over an asset already at `dest`, after `onCreate`, so what the author added can be carried into the replacement. |
| `onRegister` | `(self)` | Once per asset, when it first registers: when the world loads, on a live `asset.create`, and when an asset arrives later (installed, pulled, synced). This is what makes an asset take effect the moment it is written. |
| `onChange` | `(ref, change)` | On every write to a file inside an asset of the type. `change` is `{ path, asset, type, kind, origin }`, plus `settings` and `settingsChanged` for a write to the settings values file; `kind` is `edited` or `seeded`, `origin` is `local` or `remote`. Filter on `change.path`. Writes to one asset arrive in order, each after the hook for the one before has finished, and the hook may wait on what it reads. A write the hook makes inside its own asset arrives later like any other, so keep the hook convergent. |
| `onDependencyChange` | `(ref, change)` | When a module the asset's code requires is re-run, or a name the asset carries starts resolving. `change.kind` is `dependency`. |
| `onDelete` | `(ref)` | When an asset of the type leaves the world: deleted, or the world it is in is swapped away. |
| `validate` | `(ref) -> { { code, message, severity?, path? } }` | On `asset.validate`, after the `type.yaml` checks, for the type's own rules. `severity` defaults to `error`. Runs on every push, so a type's rules hold at publish. A hook that fails reports `validate.hook_failed`. |
### Settings hooks
| Hook | When it runs |
|---|---|
| `settingsDefaults(name, opts, asked) -> table` | Once per `asset.create`, for values the schema's defaults do not give. |
| `settingsCorrections(values, name, opts) -> (corrections?, reasons?)` | On every settings write. A correction to a field the writer named refuses the write, giving the reason. |
| `settingsDerivedDefaults(values, explicit, changed)` | On a settings write, for fields derived from others. |
| `normalizeSettings(values, stored?)` | On every read and write, to map an earlier spelling of a field to the current one. |
| `settingsHealed(values, stored)` | On a read, to repair stored values. |
| `settingsSchemaProblem(schema, ref) -> string?` | When an asset's own schema is read; a returned string refuses the schema. |
`creationInputs` (`{ [opt] = true | selectorOpt }`) names `asset.create` options
that are inputs to the type rather than settings.
### Reloading
An edit to `behavior.luau` reaches existing assets with no restart.
## How an asset is pictured (`preview:`)
| `kind` | The picture is | The type provides |
|---|---|---|
| `instantiate` | the asset placed in the preview studio through its `instantiate` | `ref.instantiate` |
| `image` | a file the asset holds, fitted to the frame | `source: { files }`, the candidate files in order |
| `surface` | the asset painted on a mesh | `mesh`, and `ref.previewMaterial` |
| `custom` | whatever `ref.preview` returns | `ref.preview` |
```yaml
preview:
kind: surface
mesh: sphere
```
`angle: [yaw, pitch]` turns the camera. The studio owns the light, the backdrop
and the framing, so an asset pictures the same in every world. A type with no
`preview:` that defines `instantiate` still answers `ref:preview()`.
A picture is rendered when something asks to view it (the editor showing the
asset, `ref:preview()`), when previews are generated on request
(`assets.generatePreviews`), and when the asset is staged. An edit alone
renders nothing. The picture records what it was made
from, so a stale one is told from a current one.
## The names your type's assets hold (`references:`)
Where your type's own format or API carries the name of another asset, declare
it here:
```yaml
references:
keys: # a top-level key of the type's files that holds a name, or a table of them
- { key: "shader", type: "shader" }
args: # an argument of a call, counting from 1
- { call: "g:node", position: 2, type: "procNode" }
fields: # a field of the options table a call takes
- { call: "fx.beam", field: "material", type: "material" }
```
`type` is the category the name resolves in. `asset.declareReferenceKey`,
`asset.declareReferenceArg` and `asset.declareReferenceField` declare the same
from a script.
## What search reads (`indexing:`)
`indexing:` is how assets are found. Search reaches an asset only through what
its type's `indexing:` names, and adds nothing of its own. That includes you: an
asset indexed badly is one you cannot find later, when you are making something
else and need it. A type whose assets are never looked for says `indexing: none`.
```yaml
indexing:
data: # text, read from the asset's files
- role: identity
extractor: verbatim
source: { file: "README.md" }
- role: interface
extractor: symbols
source: { files: ["init.luau"] }
- role: implementation
extractor: verbatim
source: { files: ["init.luau"] }
content: # the picture
- role: identity
modality: image
source: { file: "preview.png" }
facets: # what a query filters and re-ranks by
file: ".metadata"
rigged: { type: bool, from: { components: { contains: SkinnedModel } } }
roughness: { type: number, filter: range, from: { file: "mat.yaml", field: "floats.roughness" } }
```
**Roles.** Each `data` and `content` entry has a `role`, and a query matches in
two slots:
- **`identity`**: what an asset is. For anything you look at, the picture; for anything else, the text that says what it is.
- **`capability`**: what it does and how it is made. `interface` (the signatures or shape a caller uses) and `implementation` (the body) both count as capability, and a type with code usually declares both.
Ask what a person would recognise an asset of the type by, and what it does, and
point each role at the file that says it. For text, that is the asset's
description: the file your template starts with a `[[describe]]` block, which the
author writes or `services describe` fills in (see "Ask your assets to say what
they are").
**`data`.** `extractor: verbatim` embeds a file's text as it is; `symbols` embeds
the declared signatures of code. `source` is `{ file }` or `{ files: [...] }`.
Never index a file name (`source: { field: name }`): one
or two words carry nothing to match.
**`content`.** `modality: image` embeds the picture itself, so a text query
matches what the asset looks like. A type whose assets are looked at makes the
picture its identity.
**`facets`.** What a query narrows and re-ranks the matches by. `file` is embedded
whole, so keys nobody declared in it are still found. Each further key is
computed for every asset and states a value for every one, including `false`: a
file can imply "not rigged" but never say it, and a query separates rigged from
unrigged only because the unrigged ones say `rigged: false`. A key is
`{ type: bool | number | enum, filter?: range, from }`, where `from` is
`{ file, field }` (a field of one of the asset's files, dotted for nesting),
`{ metadata: key }`, or `{ components: { contains | any_outside } }` (what the
asset's entities carry).
## What blocks a push
A push checks every asset it carries against its type. These refuse it:
- a required file that is missing, a `content` check that fails, a `described` file not written yet;
- an error from the type's `validate`.
Unlisted files and warnings do not. A `described` file blocks only a push that
changes the asset. When a push is refused, the message names each asset and what
it lacks. `world.publishBlockers()` and `zm status` read the same list without
pushing.
## Typing a result from the asset (`refShapes`)
A `ref` method whose result depends on the asset (one entry per child folder, per
row of a config, per control a map declares) can only be annotated as
`{ [string]: Thing }`, which accepts any key. `refShapes` states the result for
each asset instead: a function returning a Luau type expression for that asset,
and the module whose types the expression uses. Read the asset; never run it.
```lua
-- inputMap.assetType/behavior.luau
M.refShapes = {
activate = function(self): (string, string)
local names = {}
for _, control in ipairs(M.ref.controls(self)) do
table.insert(names, control.name .. ": Handle")
end
if #names == 0 then return "", "" end
return "{ " .. table.concat(names, ", ") .. " }", "@builtin::modules.zinput.scheme"
end,
}
```
With it, `map.jump:onPressed(fn)` is checked and `map.noexisting` is reported.
A per-asset type applies where the call site names which asset: a component
field whose default names it, or an annotation `AssetRef<"inputMap", "<identity>">`.
`asset.resolve(name, category)` carries only the category, and a name computed
at runtime carries nothing, so calls on those keep the declared return. The type
belongs to the call's result: index it there, or bind what you need from it
there, and the names stay checked.
`require("@builtin::assetTypes.assetType.shared.refShapes").published()` shows
what was published: `categories` (each type's method surface) and `returns`
(per-asset results by identity, then method). An identity missing from
`returns` was never published. Results are recomputed when an asset is written;
at most 64 assets of one type are read.
## Putting an asset in a scene (`ref.instantiate`)
A caller writes one piece of code against every instantiable type, so what
`instantiate` returns is fixed:
```lua
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts)
-- compose the asset under `root`, now
return Instantiable.result(self, root, idMap)
end,
}
```
**In.** `target` is the entity the asset lands under, or onto for a hierarchy
type; with none, the type spawns a new root. `position`, `rotation` (three
numbers in degrees, or a quaternion), `scale`, `name` and `temporary` mean the
same for every type: `Instantiable.root` applies them to a root you make,
`Instantiable.place` to one you adopt. Document any options of your own in the
hook's `--!arg` docs.
**Out.** `(root, idMap)`. `root` is the composed root, live when you return:
build synchronously, never defer to a component's `awake`. `idMap` maps each
original id to the spawned one, so a component that composes the asset again on
every load can pass it back in and keep references into the composition. Every
call goes through `Instantiable.result`, which refuses a root that is not live
and turns a missing `idMap` into `{}`.
## Inspecting an asset (`ref.inspect`)
`asset.inspect(ref)` builds a record every asset shares (`identity`, `name`,
`guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`,
`description`, `tags`), then calls `ref.inspect(self)` for the type's own
`detail`:
```lua
M.ref = {
inspect = function(self)
-- read the asset's own files, never runtime state: inspect works on an asset
-- that has not been compiled, uploaded or registered
return { --[[ what makes this asset what it is ]] }
end,
}
```
Without it, the record is the shared part alone, and an agent inspecting the
asset learns nothing of what it is. A hook that raises leaves `detail` empty and
sets `record.warning`.
## Discovery
- `asset.list("assetType")`: every registered type.
- `asset.inspect("<typename>")`: the type, its README and its `about.yaml` texts.
- `asset.resolve("<typename>", "assetType")`: the type itself.
# renderFeature
A **render feature** inserts custom GPU passes into the frame pipeline. The engine
provides one generic capability — a per-frame render-pass queue and a set of
pipeline-phase insertion points — and a feature is the authored Luau that decides
what passes to enqueue, and where, every frame.
## Authoring contract
A `.renderFeature` folder holds an `init.luau` that returns a feature module:
```luau
return {
setup = function(ctx) -- optional; runs once when the feature goes live
-- A "fragment" pass's `shader` names a POST EFFECT, not a `.shader`
-- guid directly — postprocess.add compiles the shader asset under
-- that name once, here. Enqueueing a name never passed to
-- postprocess.add runs the pass as a no-op every frame (the log
-- reads "effect '<name>' not compiled — pass skipped").
postprocess.add("my_effect", asset.resolve("my.shader.guid", "shader"), { enabled = false })
end,
render = function(ctx) -- required; runs every frame
-- enqueue one or more passes. The spec shape depends on `kind` (see
-- "Pass kinds" below): this is a "fragment" pass (full-screen shader over
-- input textures); a mesh effect (outline, x-ray) is a "geometry" pass
-- with `material` + `select` (see "Geometry passes").
ctx.enqueue {
phase = "afterTransparent",
shader = "my_effect",
inputs = { src = "@scene.color" },
output = myRenderTargetGuid,
}
end,
teardown = function(ctx) end, -- optional; runs once when the feature is destroyed
}
```
Optional `materials/` and `shaders/` subfolders hold shader source the feature
constructs GPU programs from. A feature constructs its GPU programs (it does not
reference `.material` surface assets).
## `ctx`
Built fresh each frame and passed to `setup` / `render` / `teardown`:
| Field | Meaning |
|-------|---------|
| `ctx.enqueue(spec)` | Queue one render pass for the current frame. |
| `ctx.viewport` | `{ w, h }`: the size the **main viewport's** scene rasterized at, in pixels (`renderer.rasterSize()`: the viewport taken down by the render scale). |
| `ctx.time` | The instant this frame's per-frame fields are drawn at, in seconds: the running clock, or the instant a `renderer.temporal.hold` pins. |
| `ctx.frame` | The frame index beside that instant: it counts every frame of the loop, drawn or not, and reads 0 while a hold stands. |
| `ctx.renderPath` | `"forward"` / `"deferred"` / … — branch passes on the active path. |
| `ctx.settings` | The feature's knobs as they stand this frame — see "Settings". |
| `ctx.authored` | The same knobs as authored: a setting declared with `Field.scaled` reads its authored value here and the value of the quality level in force in `ctx.settings`; every other setting reads the same in both. |
### Per-frame values and a still picture
A buffer a feature's passes read is part of the picture: written with new words
between two frames, it is a change of the picture, and a renderer draws for as
long as such changes arrive. A field that animates with time (film grain, a
moving noise) seeds from `ctx.time` and draws while the clock runs. The jitter
an accumulation averages over (a ray offset, a rotated sample pattern) turns
with the renders of the view instead, so the feature's parameters hold the same
words on every frame of a still scene and the renderer stops drawing once the
accumulation settles: a history target's `state` buffer
(`renderer.texture.create { history = true }`) carries in `y` how many renders
in a row the view being drawn has carried, written as each render of the view
begins, and a pass that binds it reads its jitter frame there. While
`renderer.temporal.held()`, the feature writes a frame taken from `ctx.time`
into its parameters and the passes read that one, so two renders under one hold
agree. `@builtin::systems.reflections.ssr` works this way.
## Settings
A feature declares the knobs it takes as `settings`, each a Field descriptor
with a default, the way a component declares its public fields. A feature that
declares no `settings` has nothing to tune: its schema is empty, and applying it
turns it on or off.
```luau
local Fields = require("@builtin::modules.field")
local Field, NoSync = Fields.Field, Fields.NoSync
return {
settings = {
intensity = Field.number(1.0, NoSync, "How much of the effect reaches the image."),
quality = Field.enum({ "low", "high" }, "high", NoSync, "How many samples the pass spends."),
},
render = function(ctx)
local s = ctx.settings -- { intensity = 1.0, quality = "high" }, or what a caller set
...
end,
}
```
The engine holds one settings table per live feature — every declared default,
overridden by what it was handed — and passes it as `ctx.settings` on every
`setup` / `render` / `teardown`. A feature reads its knobs there and nowhere
else, so any caller tunes any feature by name:
```luau
local h = renderer.feature.create(ref, { settings = { intensity = 0.5 } })
renderer.feature.configure(h, { quality = "low" }) -- lays over the rest
renderer.feature.settings(h) -- { intensity = 0.5, quality = "low" }
renderer.feature.find(ref) -- the live handle, or nil
renderer.feature.schema(ref) -- the declared knobs, unrun
```
A knob the feature does not declare, or a value of the wrong shape, is refused
by name. A scene authors its features on one `RenderFeatures` entity — a list
of features, each with its settings — which adopts a feature already live
rather than stacking a second, and takes every one down on disable and destroy.
Each entry is an application of its asset (`applicable`): the asset holds its
one live feature, every application joins it, the settings in force are those
of the application that last stated something new, and the last to leave stops
it. A feature already running when the first application comes is adopted, and
runs on with its own settings once the last leaves. A feature stopped from
outside the asset (`renderer.feature.destroy`, a
`render` that raised) stays stopped until an application is stated again.
`render` runs **once per frame**; the passes it enqueues run **once per render
target** drawn that frame — the live viewport, every offscreen capture, every
RTT camera — each at its own resolution. So `ctx.viewport` is the main
viewport's size, not the size of the target a pass ends up drawing into. Size a
full-screen scratch RT with `screen = true` and let the engine track the drawn
target (see "Screen-sized targets") rather than deriving it from `ctx.viewport`.
## Screen-sized targets
`renderer.texture.create { screen = true }` marks a feature RT as full-screen:
before each render target's feature passes, the engine resizes it to that
target's resolution. Create it once — the engine owns its size from then on:
```luau
myRt = renderer.texture.create {
width = ctx.viewport.w, height = ctx.viewport.h, -- initial size only
screen = true, format = "rgba16f", name = "my_effect",
}
```
A target that holds a picture of the scene is `rgba16f`, which is what the scene
target itself carries: linear light with headroom above the display's white and
no 256-step floor under a dark gradient. Omitting `format` on a screen-sized
target asks for the same thing. `format = "rgba8"` is for a mask, a weight or an
occlusion term, where 0..1 is the whole range — hand one of those back over
`@scene.color` and the frame loses every highlight and bands every gradient, and
the engine says so in the log.
`screenScale` (default `1.0`) takes a fraction of the drawn target's resolution,
for a scratch that runs below composite resolution (a half-res blur passes `0.5`).
A screen-sized RT is what makes a full-screen effect composite correctly at any
resolution. Deriving the size from `ctx.viewport` instead pins the RT to the main
viewport, and every differently-sized render target then composites a mismatched
scratch — the scene scaled into a corner with the rest black.
`screenSpace` names WHICH image a screen-sized RT follows:
| value | what it tracks |
|---|---|
| `"scene"` (default) | the scene render target, at whatever resolution the render scale asked for. Resized before EVERY render target's feature phases — the main frame and each offscreen one — and cleared to transparent before an offscreen render, so one sink never reads what another left behind |
| `"composite"` | the image the post-scene phases draw into. The presented frame's allocation is resized and drawn by the presented frame alone; an offscreen render that runs a post-scene phase (a capture, a render-to-texture camera whose picture goes through the `display` stage) draws in an allocation of its own at its own size, cleared to transparent before it draws |
The two carry the same size until the render scale drops below 1. From there,
while the renderer presents the viewport itself, the scene reaches the display's
resolution through an upscale that runs before `afterScenePost` — so a
composite-space RT is the display's size while a scene-space one is the smaller
rasterized frame. Under a UI viewport panel the panel draws the scene target at
its own rect, nothing upscales beforehand, and both spaces carry the scene's
size.
A scene-space target is scratch: whatever a pass does not rewrite this render is
transparent black. The presented frame's allocation of a composite-space target
survives every offscreen render untouched.
## History targets
An accumulation across frames (temporal antialiasing, a temporal denoiser, any
pass that reads what it wrote last time) lives in a history target:
```luau
history = renderer.texture.create {
width = ctx.viewport.w, height = ctx.viewport.h, -- initial size only
history = true, format = "rgba16f", name = "my_accum",
}
-- in render(ctx):
ctx.enqueue {
kind = "compute", program = myResolve,
inputs = { scene_color = "@scene.color", accum_previous = history.previous.guid },
buffers = { accum_state = history.state },
storage = { accum_out = history.guid },
phase = "afterLighting",
}
```
The passes a feature enqueues run once for every view the frame draws (the
viewport, each render-to-texture camera, each capture), so an accumulation has
to be one per view. A history target keeps one pair of images per view, sized to
that view: for the length of a view's render `history.guid` names the image the
render writes and `history.previous.guid` the image the same view's previous
render wrote. Another view never resizes, clears or overwrites them, and a
view's images are freed when it stops drawing. It follows `screenSpace` and
`screenScale` like any screen-sized target; a composite-space one is kept for
every view that runs the post-scene phases: the viewport, a capture, and a
render-to-texture camera whose picture goes through the `display` stage.
Before each render of a view the engine writes `history.state`, one
`vec4<f32>` a pass binds through `buffers`:
| field | holds |
|---|---|
| `x` | 1 when `previous` holds this view's previous image; 0 on the view's first render, its first after a camera cut or a change of size, or after a render of the view that ran without the target, and `previous` then reads transparent black |
| `y` | how many renders in a row have carried the history |
| `zw` | this render's sub-pixel projection offset, in pixels (`renderer.setProjectionJitter`) |
`renderer.setProjectionJitter` is the matching per-view sample sequence: every
view walks it by its own count of renders, so the sequence a temporal pass
expects is the one each view's renders sampled.
## Post stages
A post effect belongs to one of the frame's named **post stages**, in frame
order, each stating what the picture holds there: the space an effect there
reads and writes (`light`, the scene's own light ahead of the display
transform's exposure and tone curve, `display`, code values, or `encoded`, the
presented surface's own values) and the size
the picture is held at (`raster`, the size the scene rasterized; `output`, the
size the frame is composed and shown at):
| Stage | Space | Resolution | Runs |
|-------|-------|------------|------|
| `lighting` | light | raster | screen-space lighting terms and what draws into the lit scene: occlusion, reflections, indirect light, contact shadows, decals, splats, outlines, diagnostic views. It spans every phase up to `afterLighting`, so a pass of a feature declaring it may name one of those phases |
| `medium` | light | raster | participating media: aerial perspective, fog, volumetric light |
| `preTemporal` | light | raster | effects reading the jittered raster before reconstruction: depth of field |
| `temporal` | light | raster | the one temporal reconstruction of the raster (TAA); the stage holds one feature at a time |
| `postTemporal` | light | raster | effects reading the reconstructed picture: motion blur |
| `meter` | light | reduced | measuring the picture: the exposure histogram, a fraction of the raster |
| `optics` | light | raster, then output | lens light: bloom, flare, streaks. Its render features run on the raster; the frame then carries the picture to the output size, and the post-process chain's `scene` layer runs there |
| `display` | display | output | the display transform, then on code values the temporal upscale, debanding, edge antialiasing and sharpening; the chain's `display` layer, the film grain last |
| `ui` | display | output | the UI, drawn over the finished picture, then what grades the picture with the UI on it: `afterUI` passes, the chain's `all` layer, then `afterPost` passes |
| `output` | encoded | output | the renderer's output stage alone: the one write of the presented surface, in the surface's encoding, rounded to its bit depth with a blue-noise dither (`renderer.output`). It takes no render feature and no chain effect |
A feature declares the stage it belongs to, and each pass it enqueues with no
`phase` runs in that stage, at the stage's phase and its band of orders plus the
pass's own local `order` (a whole number from 0 to 99):
```luau
return {
stage = "postTemporal",
render = function(ctx)
ctx.enqueue { kind = "fragment", shader = "my_effect", inputs = { src = "@scene.color" }, order = 0 }
end,
}
```
Passes sharing an order run in the order they were enqueued, so a chain of
passes over shared targets can run at one order, in sequence.
The `meter` and `optics` stages are the camera's film. A pass placed in one of
them, stating neither `postProcessing` nor `presented`, is part of the camera's
post-process chain (`postProcessing = true`): a camera running no
post-processing, such as a capture asking for the scene ungraded or an
environment cube face, skips it. A pass stating `postProcessing = false` runs on
every camera.
`render` runs once a frame, but each view the frame draws (the viewport, a
capture, a render-to-texture camera, an environment cube face) looks at the
world from its own camera, so an order that depends on where the camera stands
is stated per pass rather than chosen in `render`. A pass that composites
something standing in the world states the world point it stands at as
`sortPoint`: `{ x = .., y = .., z = .. }`, `{ x, y, z }` or a `vector`, so an
entity's `position` is one. Among the passes of one phase sharing one `order`
that run together (its fragment, compute and raster passes; its geometry
passes, which run ahead of those), the ones stating a point trade the places
they were enqueued in so that every view runs the one farthest from its own
camera first and the nearest last: composites laid over the frame by each of
them leave the nearest in front from wherever the view looks. Depth is
taken along the view (the distance in front of a perspective camera, the depth
into an orthographic one's box). Passes at the same depth keep the order they
were enqueued in, so the passes of one effect stating one point (a march into a
target and the composite reading it) stay together, and a pass stating no
point keeps its place:
```luau
for _, item in ipairs(items) do
ctx.enqueue { kind = "compute", program = march, storage = { out = scratch.guid }, order = 2, sortPoint = item.center }
ctx.enqueue { kind = "fragment", shader = composite, inputs = { src = scratch.guid }, blend = true, order = 2, sortPoint = item.center }
end
```
A draw or splat pass takes no `sortPoint`, and a value that is not three finite
numbers is refused by `ctx.enqueue`.
A pass may name a
`stage` of its own in place of the feature's, placed the same way: a feature
whose work spans two stages declares one and names the other on those passes,
the way temporal antialiasing declares `temporal` for its resolve and names
`display` on its sharpening passes. A pass naming both a `stage` and a `phase` is refused. A stage the
frame does not have is refused by `renderer.feature.create`, naming the stages
there are, and a second feature declaring the `temporal` stage while one stands
in it is refused naming both; the `temporal` stage takes the passes of the
feature declaring it alone. A pass that names a `phase` runs at that phase and
`order`, as below. `renderer.post.stages()` reports every stage and what stands
in it: a feature by the stage its passes' position falls in, marked `declared`
where that is the stage the feature declares or a pass names. Every built-in
render feature declares its stage; `postStages`'s README lists where each
built-in effect runs.
## Pass phases
`enqueue` runs a pass at a named pipeline boundary — a real seam between the
scene's discrete passes — ordered within a phase by `order`. Each phase is the
point where the scene colour holds a specific, nameable state:
| Phase | Scene colour there |
|-------|--------------------|
| `afterDepthPrepass` | the visibility raster written: `@scene.depth` holds this frame's complete opaque depth, and `@scene.motion` its opaque motion, before anything shades. Scene colour is not yet drawn; `@scene.colorHistory` holds the previous frame's lit colour, and the deferred g-buffer the previous frame's surfaces (`readsPrevious`) |
| `afterShadows` | shadow maps populated; scene colour not yet drawn. `@scene.depth` and `@scene.motion` hold what the visibility raster laid at `afterDepthPrepass` |
| `afterSky` | sky only. `@scene.depth` holds the frame's opaque depth, so a pass here tells the pixels the geometry pass draws over (depth above 0) from the ones that stay sky (depth 0) |
| `afterOpaque` | opaque drawn, before transparents. `@scene.depth` (and the deferred G-buffer) are populated. Forward: lit opaque. Deferred: lit opaque too, which the geometry pass shades straight into the scene colour, on a render no pass reads or writes `@scene.shaded` in; on one that does, the opaque surfaces are in the G-buffer's shaded channel, so the colour is still sky only until the composite (use `afterOpaqueLit`). Radiance stamped into `@scene.emissive` reaches the colour at the composite |
| `afterOpaqueLit` | the lit opaque scene, still before transparents, on **both** paths — the forward opaque draw, or the deferred geometry pass and composite. The background a refractive or transmissive surface samples: the one phase whose colour holds what is behind such a surface without holding the surface itself |
| `afterTransparent` | transparents drawn, before the OIT composite |
| `afterLighting` | deferred-lighting + OIT composite done — fully lit, final geometry on **both** paths |
| `afterScenePost` | the chain's `scene` layer and the display transform done: display code values, before the chain's `display` layer and the UI |
| `afterUI` | scene + UI composited |
| `afterPost` | the chain's `all` layer done — the finished picture in display code values, before the output stage writes it to the surface. A pass here reads that picture as `@scene.color` and draws over a copy of it |
The last three are the post-scene phases, and they work on the COMPOSITED image:
`@scene.color` there is the target the UI lands on, not the scene render target.
`@scene.depth` and `@scene.motion` still bind — they are the scene's own buffers
for the frame just drawn, which is what lets a pass at these phases reproject the
composite it is handed — and on the deferred path so do the G-buffer channels
(`@scene.normal`, `@scene.material`, `@scene.shaded`, `@scene.emissive`), the
surfaces of that same frame, so a look drawn over the finished picture reads
what each pixel's surface is without copying the G-buffer at an earlier phase.
All of them keep the SCENE's resolution. Whenever the
render scale is below 1 on the presented frame, that is smaller than
`@scene.color`, so a pass here maps between the two by uv rather than by texel
index, and takes its own output size from the target it writes.
**A texture is a texture.** A pass's sampled input names any texture the engine
holds by the handle that made it: a render target or a texture
`renderer.texture.create` returned (its guid), or a storage texture a compute
shader created (`ref:createStorageTexture2D`, its `key`). Which one it is decides
nothing about whether the pass accepts it. A pass sees the contents a texture
holds when the pass runs: a compute shader that wrote the texture in an earlier
pass of the same frame, or in a `dispatchEx` recorded at the start of the frame,
is read by a pass at any later point of the frame, and a pass that reads a
target an earlier phase of the frame draws sees that draw once the phase has run.
The `@scene.*` inputs (`@scene.color`, `@scene.depth`, …) bind the live frame
buffers; the deferred g-buffer channels (`@scene.normal`, `@scene.shaded`, …)
resolve only on the deferred path. Before the pass that shades has drawn — at
`afterDepthPrepass` — a g-buffer channel holds the previous frame's surfaces,
and a pass reading it there names the slot in `readsPrevious`
(`readsPrevious = { "scene_normal" }`); one that does not is held back rather
than handed a stale normal. `@scene.colorHistory` is the lit colour the target's
previous render ended with, kept by the engine per render target and never
cleared by a frame: what a pass tracing at `afterDepthPrepass`, against this
frame's depth, takes its light from — reprojected through the previous
view-projection `@frame.camera` carries. A capture drawn once, or a camera drawn
again after a pause, is drawn lit first when a pass reads the history, so its
first frame holds one.
Every `@scene.*` channel, what it holds, its format, the phase it is first
valid from, and the other names it answers to:
| Name | Holds | Format | Valid from | Also named |
|---|---|---|---|---|
| `@scene.color` | the scene's lit colour; the display composite at a post-scene phase | the scene target's format at a scene phase, the display composite's at a post one | every phase | — |
| `@scene.depth` | opaque depth, reversed (1.0 near, 0.0 far/empty sky) | `Depth32Float` — binds through a `texture_depth` compute slot, not `texture2d` | `afterDepthPrepass` on | — |
| `@scene.motion` | screen-space NDC velocity since the previous frame | `Rg16Float` | `afterOpaque` on | — |
| `@scene.normal` | world-space normal + the per-pixel surface-flag field | `Rgb10a2Unorm` | deferred path, `afterOpaque` through `afterPost` (previous frame's before — declare `readsPrevious`) | — |
| `@scene.shaded` | what a surface SENT — its shaded colour, linear and scene-referred | `Rgba16Float` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | `@scene.albedo` |
| `@scene.material` | what a surface IS — base colour (RGB565) + metallic + perceptual roughness | `Rgba8Uint` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | `@scene.mr` |
| `@scene.emissive` | radiance a pass stamped on the surface, added at the composite | `Rgba16Float` | deferred path, `afterOpaque` through `afterPost` (previous frame's before) | — |
| `@scene.ao` | scene occlusion a feature wrote, read back by shading: occlusion in r, the bent normal laid flat on the octahedron in g and b, and in a whether a bent normal was written | `Rgba8Unorm` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.sunOcclusion` | the share of the sun's direct light a feature found taken on the way to each pixel's surface (`.rgb`, 0 none to 1 all), read back by the sun's term alone | `Rgba8Unorm` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.reflection` | traced reflection radiance (`.rgb`) + confidence (`.a`) | `Rgba16Float` | every scene phase (cleared at the top of the scene render) | — |
| `@scene.indirect` | the indirect diffuse light the surfaces closing each pixel's hemisphere send it (`.rgb`, in the ambient term's units) + the share of the closed hemisphere it answers for (`.a`), read back by the diffuse term through `zero_scene_indirect_here`; the second layer of the texture `@scene.reflection` is the first of | `Rgba16Float` | every scene phase (cleared at the top of every scene render) | — |
| `@scene.decal` | the base colour stamped over each pixel's opaque surface, premultiplied by its coverage (`.rgb`), with that coverage (`.a`); written at `afterDepthPrepass` (blend `premultiplied`), and every opaque surface takes it into its own base colour before it is lit (`zero_take_scene_decal`, which `zero_pbr_shade` calls), so the stamp is lit, shadowed and written to `@scene.material` with the surface; the third layer of the texture `@scene.reflection` is the first of | `Rgba16Float` | `afterDepthPrepass` through `afterSky` (cleared at the top of every scene render and again once the opaque surfaces have shaded, so a surface drawn after them takes none) | — |
| `@scene.colorHistory` | the lit colour the target's previous render ended with | `Rgba16Float` | every phase | — |
| `@scene.lights` | the punctual-light storage buffer: 1024 light entries of eleven vec4s each (the light, then its projection, which names the shadow record it casts through), the light grid, then the virtual shadow map's region: a shadow record per casting light and their page tables. A loop runs over the first `@frame.camera[4].w` entries, the lights in use; the buffer's length counts the regions after the lights too, so `arrayLength` does not size a light loop | storage buffer | every phase | — |
| `@scene.shadowPool` | the depth pool every shadow-casting light renders its shadow pages into, read beside `@scene.lights` through `@builtin::shaderModules.light_shadows` (`zero_light_shadow`): the shadow a point, spot or area light casts at any world point, the one the surfaces take. A frame with a pass reading it keeps the coarsest page of every map of each casting light whose reach meets the view | `Depth24Plus` — binds through a `texture_depth` compute slot | scene phases only | — |
| `@scene.sunShadow` | the sun's virtual shadow map as the view being drawn reads it: its basis, depth range, clipmap levels and window origins and where its page table starts in `@scene.lights`, read beside `@scene.lights` and `@scene.shadowPool` through `zero::sun_shadow` (`zero_sun_visibility`): how much of the sun reaches any world point, past the occluders that shadow the surfaces. A frame with a pass reading it keeps the sun's pages under the air the view looks through | storage buffer (`ZeroVsmUniform`, a `kind: buffer` slot with `array: false`) | scene phases only | — |
| `@scene.environment` | the reflection-probe cube array | texture cube array | scene phases only | — |
| `@scene.environmentSampler` | the filtering sampler for `@scene.environment` | sampler | scene phases only | — |
| `@scene.reflectionProbes` | the environment buffer: the probe blend data naming which probe reaches a point, then the irradiance light-probe volumes | storage buffer | scene phases only | — |
The rendering and ray-tracing guides (`guides { path = "topics/rendering" }`,
`guides { path = "topics/raytracing" }`) point here rather than repeating this
table.
**What a full-frame pass reads, at each stage, on each path.** A full-frame
pass is a fragment or compute pass of a render feature, or an effect of the
post-process chain (`postprocess.add`). The G-buffer channels above are what the
deferred path knows about each pixel's surface, and they are the four the paths
differ on:
| Channel | Deferred path | Forward path |
|---|---|---|
| `@scene.color`, `@scene.depth`, `@scene.motion` | every stage (depth and motion from `afterDepthPrepass` and `afterOpaque` on, as the table states) | the same |
| `@scene.normal`, `@scene.material`, `@scene.shaded`, `@scene.emissive` | `afterOpaque` through `afterPost`: the `lighting`, `medium`, `preTemporal`, `temporal`, `postTemporal`, `meter`, `optics`, `display` and `ui` stages, and every layer of the chain. Before `afterOpaque` a pass naming one in `inputs` reads the previous frame's surfaces (`readsPrevious`), and the surface helpers read their stated substitute with `zero_scene_surfaces_drawn()` false | none: the forward path draws no G-buffer. A pass naming one as an input is skipped, and the log names the channel and the reason. A shader reading one through the surface helpers reads its stated substitute (zero) and `zero_scene_surfaces_drawn()` reads false, so it draws a picture of its own there |
Two readers reach them. A pass names a channel in `inputs` (or a compute
binding), as above. A fragment pass's shader, or a chain effect's, reads them
by screen uv through the post framework's surface helpers (`zero_scene_normal`,
`zero_scene_material`, `zero_scene_shaded`, `zero_scene_emissive`; the shader
type README's post-process section has the table), which spend none of the
pass's input slots. Either way a render keeps a channel only when
something reads it: a queued pass naming it, a queued fragment pass whose
shader calls its helper, or a running chain effect that does. The channels
are at the scene's resolution, so a pass after an upscale reads them by uv.
A pass before the `temporal` stage reads each channel as the raster drew it,
with this render's sub-pixel offset. With temporal antialiasing running
(`@builtin::systems.antiAliasing.temporalAntiAliasing`), a reader after the
`temporal` stage reads `@scene.depth`, `@scene.normal` and `@scene.material`
restated at each pixel's centre, with no sub-pixel offset, so under a still
camera they hold still the way the resolved picture does: the restatements
run on a frame where a pass after them names the channel or a shader reads it
through its helper, and a chain effect reading the helpers is such a reader.
`@scene.shaded` and `@scene.emissive` keep the raster's sub-pixel offset at
every stage. `ctx.renderPath` names the path a feature's
`render(ctx)` runs on, and `postprocess.status()` lists, for each effect, the
channels it `reads` and, after a frame it drew with their substitute, the
`substituteReason`.
**Two g-buffer channels describe the surface, and they answer different
questions.** `@scene.shaded` is what a surface SENT — the colour the geometry
pass shaded it to, linear and scene-referred, so a surface lit above the
display's peak reads above 1 there. `@scene.material` is what the surface IS:
the base colour it reflects, its metallic and its perceptual roughness, each in
[0, 1] and each independent of how brightly the surface happens to be lit. A
pass that multiplies incoming light by a reflectance — a bounce multiplier, a
Fresnel tint, an ambient floor — reads `@scene.material`; a pass that filters
the picture reads `@scene.shaded`.
`@scene.material` is an `Rgba8Uint` channel packing all three into 32 bits, so
its slot declares `sample: uint` and the module unpacks it:
```yaml
# bindings.yaml
- { name: scene_material, kind: texture2d, sample: uint }
```
```wgsl
#include "@builtin::shaderModules.gbuffer_material"
let m = zero_gbuffer_material(scene_material, coord);
let bounce = incoming * m.base_color;
```
`@scene.albedo` is another name for `@scene.shaded` (the SHADED lit colour) and
`@scene.mr` for `@scene.material` (the material channel). The engine logs the
substitution once per name, naming the canonical one to write.
`@scene.motion` carries screen-space velocity: the NDC displacement each pixel's
surface underwent since the previous frame, so a still surface under a still
camera reads `(0, 0)`. Opaque geometry contributes it on both render paths:
the visibility raster writes it for every surface it records, and an opaque
surface whose depth state the raster cannot express writes its own where it
draws. A moving entity, a moving camera and an animated pose all reach it in
the viewport; transparents, particles and sky carry none. A surface a
material's `vertex()` hook displaces carries the displacement's own velocity. A render target's own camera and a
capture keep no view history, so velocity there is the entity's motion with no
camera term.
`@frame.camera` is a reserved **buffer** input carrying the camera CURRENTLY
being drawn: 14×`vec4<f32>` = the inverse view-projection (columns `[0..4)`,
column-major) + camera world position (`[4].xyz`, with the number of lights
`@scene.lights` holds in `[4].w`) + the previous render's view-projection
(columns `[5..9)`), which projects a point into the picture that render left +
the view-projection itself (columns `[9..13)`), which projects a world point
onto the view being drawn and is the matrix the scene rasterized with + the
sub-pixel offset that matrix carries (`[13].xy`, in NDC; zero without a
temporal upscale). 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 scene's light
`@frame.light` is a reserved **buffer** input carrying the scene's sun and
ambient term as the camera being drawn is shaded by them, the values the lit
passes read in the same frame: 3×`vec4<f32>` = the direction the sun's light
travels (unit, world space) with its intensity in `w`, the sun's colour with
`w` 1 while it casts shadows, and the ambient colour with its intensity in `w`.
A pass that lights a participating medium (clouds, haze, fog) reads its sun
here rather than carrying one of its own, so a day cycle, a scripted sun and a
sun switched off reach the medium in the frame they reach the surfaces, and a
scene with the sun and every light at zero leaves it black. `#include
"@builtin::shaderModules.frame_light"` reads it, and states the sun's light
either in the units the scene's lights are stated in
(`zero_frame_light_sun_irradiance`), for a medium that scatters those lights
too, or as the share of a medium's authored brightness the sun lights (its
intensity up to a unit sun, `zero_frame_light_sun_tint`):
```yaml
# bindings.yaml
- { name: scene_light, kind: buffer, access: read, element: vec4<f32> }
```
```wgsl
#include "@builtin::shaderModules.frame_light"
let light = zero_frame_light(scene_light[0], scene_light[1], scene_light[2]);
let toward_sun = zero_frame_light_toward_sun(light);
let sun = zero_frame_light_sun_tint(light) * authored_brightness;
```
```luau
inputs = { scene_light = "@frame.light" }
```
### The environment
A compute pass reads the scene's captured surroundings — the reflection-probe
cube array, its sampler and the environment buffer (the probe blend data, then
the irradiance light-probe volumes) — through three reserved inputs, bound to
bindings of the shapes group(0) binds them in:
```yaml
bindings:
- { name: environment_map, kind: textureCubeArray }
- { name: environment_sampler, kind: sampler }
- { name: zero_environment, kind: buffer, access: read, element: ZeroEnvironment, array: false }
```
```luau
inputs = {
environment_map = "@scene.environment",
environment_sampler = "@scene.environmentSampler",
zero_environment = "@scene.reflectionProbes",
}
```
Named like that, `#include "zero::environment"` in the shader resolves the
environment at a world point along a direction — `zpbr_sample_environment(world_pos,
dir, lod)`, the probes whose radius reaches the point blended by rank and
proximity, each through its proxy volume, and the sky under them — exactly as a
material's environment term does, so a reflection a pass draws and one a
material draws agree about the room they are in. A pass that reads several
directions at one point selects the probes once, `let probes =
zpbr_select_probes(world_pos);`, and gathers each direction with
`zpbr_gather_environment_with_probes(probes, world_pos, dir, lod)`, which answers
the radiance in `rgb` and the share of it the probes and sky claimed in `a`.
The three bind at the scene phases; a post or UI phase carries none. A `textureCubeArray` binding takes
`@scene.environment` alone, and a fragment pass has no slot of that shape.
## Pass kinds
`enqueue` runs one of six kinds (the `kind` field; default `"fragment"`):
- **`"fragment"`** — a full-screen shader over input textures. The program is a
GPU **material** (or `shader`) the feature constructed; `inputs` bind live
textures (`@scene.*` or RT guids), `output` is the target RT (omit = the
phase's default scene target). Post-process, blur, edge effects.
**Writing named G-buffer channels (`outputs`).** Instead of the single `output`
RT, a fragment pass may declare an `outputs` array — one or more targets, each a
named engine channel (`@scene.shaded` / `@scene.normal` / `@scene.emissive` /
`@scene.color`) or an RT guid — each with its own blend mode:
```luau
ctx.enqueue {
kind = "fragment",
shader = myShaderKey,
outputs = {
{ target = "@scene.shaded", blend = "under" }, -- premultiplied dst-over-src
{ target = "@scene.emissive", blend = "additive" }, -- one fullscreen pass, two targets (MRT)
},
phase = "afterOpaque", -- deferred: G-buffer filled, before the composite
}
```
Blend modes — the keywords every pass's `blend` takes, `src` being what the
pass returns and `dst` what the target holds:
| Keyword | Result |
|---|---|
| `"replace"` | `src` — overwrites |
| `"alpha"` | `src.rgb * src.a + dst.rgb * (1 - src.a)` — straight-alpha source-over |
| `"premultiplied"` | `src + dst * (1 - src.a)` — source-over for a colour already multiplied by its alpha |
| `"additive"` | `src + dst` — sums |
| `"under"` | `src * (1 - dst.a) + dst` — premultiplied destination-over-source: what the target holds stays in front, which accumulates coverage-weighted contributions |
A keyword outside the table raises from `ctx.enqueue`, naming the field. A
`@scene.*` channel resolves only where it exists (the deferred
G-buffer at a pre-composite phase); a pass whose targets are all unavailable at
its phase is skipped (logged). `output` + `blend = true` remains the shorthand
for a single alpha-blended target. The shader's returned colour is written to
every target in the set.
A fragment shader returns `vec4<f32>`, so the channels it can target are the
float ones. `@scene.material` (also named `@scene.mr`) is
`Rgba8Uint`, which binds as `uint` — naming it as an output is refused by
name, with the channel's format and class in the log, and the rest of the
frame draws. A fragment pass's `inputs` reads through the same fixed float
slot, so naming `@scene.material` there is refused the same way; a compute
pass reads that channel through a `sample: uint` slot instead.
**What a pass with no `inputs` samples.** A fragment pass that declares no
`inputs` reads `@scene.color` — the shape of an effect that filters the scene
image. A pass that names `@scene.color` among its own `outputs` samples a 1x1
transparent texel instead, because the scene colour is that pass's render
target and one texture is a colour attachment or a sampled resource in a render
pass, never both. Declare `inputs = { src = "@scene.color" }` and write an RT
to read the scene image and write somewhere else in one pass.
- **`"compute"`** — a workgroup dispatch (`shader`, `storage`, `buffers`, `dispatch`;
see "Compute passes").
- **`"geometry"`** — draw scene geometry with a constructed pipeline. The program
is a **material** the feature built (`renderer.material.create`); the engine
draws the scene's render-objects with that material's pipeline + uniforms.
- **`"draw"`** — rasterize the feature's OWN geometry: `geometry` names a buffer
created with `usage = { "vertex" }`, `storage.index` one created with
`usage = { "index" }`, and `select` the one entity whose transform and
material the draw lands through. `params[0]` is how many indices to submit —
or name a buffer under `storage.indirect` (created with
`usage = { "indirect" }`, holding a `DrawIndexedIndirectArgs` block: index
count, instance count, first index, base vertex, first instance) and the count
comes from the GPU instead, so a compute pass that compacts geometry pays only
for what it kept and nothing waits on a read-back. `first_instance` must be 0;
the engine resolves the entity's per-instance data another way, because a
non-zero one needs a device feature WebGPU does not guarantee.
- **`"splat"`** — rasterize a compute buffer of particle records as instanced
camera-facing billboards into feature RTs (see "Splat passes").
- **`"raster"`** — draw geometry the feature makes itself with a `.rasterShader`
of its own: `vertexCount` vertices for each of `instanceCount` instances,
pulled from the buffers the pass binds, into the scene or the feature's
targets, depth-tested against the scene (see "Raster passes").
### Geometry passes
A geometry pass re-draws the scene's meshes with a material you supply — the
generic primitive for mesh-space effects (the engine names none of them):
```luau
ctx.enqueue {
kind = "geometry",
material = myMaterial, -- the HANDLE renderer.material.create
-- returned (or its registry-key string)
geometry = "@geometry.opaque", -- which drawables: "@geometry.opaque" |
-- "@geometry.transparent" | "@geometry.all"
select = { entityA, entityC }, -- OPTIONAL: restrict to these entities
-- (entity refs); omit = every matching mesh
phase = "afterLighting", -- afterLighting = lit scene + valid depth
}
```
`select` restricts the draw to the given entities — the per-instance signal that
turns a whole-scene pass into a chosen-meshes effect. A pass with no `select`
also draws the instanced populations (`renderer.mesh.drawInstanced`) its
`geometry` set takes, every copy at its own slot, so a whole-scene pass sees an
instanced forest as it sees the entities around it. The **material** decides how
those meshes are drawn; you control three things:
- **Pipeline render-state.** `renderer.material.create` takes a `render` block —
`cull` (`back`/`front`/`none`), `depthWrite` (bool), `blend`
(`opaque`/`alpha`/`additive`) — so the pass can rasterize differently from the
surface pass:
```luau
local myMaterial = renderer.material.create({
shader = myShaderKey, -- a .shader you authored (identity, not guid)
render = { cull = "none", depthWrite = false },
properties = { outline_color = { 1, 0.4, 0, 1 } }, -- seed the shader's uniforms
}, "my_pass_mat") -- pass `myMaterial` (or "my_pass_mat") as the pass `material`
```
- **The shader.** A geometry `.shader` is a surface shader: author `fn vertex(v:
VertexData) -> VertexData` to move vertices (object-local `v.position` /
`v.normal`) and `fn fragment(input: FragmentData) -> vec4<f32>` for the colour.
- **Its properties.** A shader reads ONLY the uniforms IT declares in
`properties.yaml`, via `material.<yourProp>`. Referencing a field it didn't
declare (e.g. a StandardMaterial `material.base_color`) fails to compile and the
mesh renders **magenta** — declare the property or use a constant.
What effect those three produce (outline, x-ray, wireframe, highlight, …) is
yours to design — the engine just draws the selected geometry with your pipeline.
#### What a pass starts its target from (`load`)
A geometry or draw pass with no `output` draws over the phase's own scene target,
which holds the frame as it stands. A pass naming an `output` render target begins
by setting that target's colour and depth to a starting state, and `load` says
which:
| `load` | the target starts as |
|---|---|
| `"clear"` (default) | empty: transparent colour and the far depth, so the target holds only what this pass draws |
| `"keep"` | what it holds: colour and depth as the last pass to draw into it left them, so this pass draws over that, depth-tested against it |
Two geometry passes naming one `output` therefore leave only the second one's draw
by default, since the second pass starts from an empty target. State `keep` on the
second to draw both, the way one camera draws many entities into one target:
```luau
ctx.enqueue { kind = "geometry", material = tagMat, output = mask.guid,
select = groupA, phase = "afterLighting", order = 0 } -- starts from empty
ctx.enqueue { kind = "geometry", material = tagMat, output = mask.guid,
select = groupB, phase = "afterLighting", order = 1,
load = "keep" } -- draws over groupA's
```
`keep` loads what the target holds when the pass begins: the draws of the passes
before it this frame, and the previous frame's picture where none drew it first
(and where a screen-sized target is made again, an empty one). The first pass to
draw a target each frame says `"clear"` so the target starts the frame empty; an
accumulation across frames is the one that says `"keep"` there too. `load` is
refused, naming the field, on a pass that is not a geometry or draw pass or that
has no `output`. A splat pass loads its targets with `blend = true`, and a raster
pass clears them with `clear = true`.
**How much of each mesh it draws.** A pass drawing into a small map (a
top-down cover or height map, a coarse occlusion mask) holds none of the
detail finer than a texel, and two fields keep it from paying for that detail:
- `detail = 1.0` states the world-space size of the finest detail its target
holds. Each static mesh then draws at the coarsest cut of its cluster
hierarchy whose error, placed at the object's scale, stays within that size,
the cut the scene's own draw takes for a distant object: a building keeps its
walls and roof and a tree its crown, in far fewer triangles than their full
detail. A mesh drawing from its own vertex streams (a skinned or morphing
mesh, one with no cluster set yet) and an instanced population draw in full.
- `rigid = true` leaves out every mesh a skeleton poses or morph targets blend,
so a crowd of characters costs the pass nothing.
`renderer.feature.drawn()` reads what each geometry pass drew on the last drawn
frame, as `{ objects, triangles }` keyed by its material, so the difference
either makes is a number.
### Compute passes
A compute pass dispatches a `.computeShader` program over a workgroup grid:
```luau
ctx.enqueue {
kind = "compute",
program = myComputeShader,
storage = { outTex = myStorageRtGuid }, -- slot -> storage-texture RT guid
buffers = { particles = "my_particle_buf" },-- slot -> named compute buffer
inputs = { camera = "@frame.camera" }, -- slot -> @frame.*/@scene.* buffer
dispatch = { x = 64, y = 1, z = 1 },
}
```
**`dispatch` is optional.** Omit it and the pass is dispatched over what it
WRITES: a grid covering its first `storage` texture, at the `@workgroup_size` the
shader's entry point declares. With a screen-sized storage target that grid
tracks the render target being drawn, so a screen-space effect covers the live
viewport, an offscreen capture and an RTT camera without the feature knowing any
of their resolutions:
```luau
ctx.enqueue {
kind = "compute",
program = myComputeShader,
inputs = { scene_color = "@scene.color", cam = "@frame.camera" },
storage = { outTex = myScreenSizedRt.guid }, -- screen = true
phase = "afterLighting",
}
```
State an explicit `dispatch` for a grid that is not one thread per output texel
(a reduction, a particle sim), or when the shader's `@workgroup_size` is an
override/const expression the engine cannot read.
Each WGSL storage-buffer binding in the shader resolves its bound slot in this
order: an explicit `buffers` mapping (the handle a buffer's owner holds, or a
name), then `inputs` (`@frame.camera` / `@frame.light` / `@scene.lights` /
`@scene.reflectionProbes`), then — when a slot has neither — a buffer whose
engine-side name equals the slot's own name. `buffers`
is the seam a pass binds through: the buffers a shader works over are the ones
handed to it, whatever each is called. `storage` binds storage TEXTURES (RT
guids) the same way, one map per resource kind.
**A table built from a few settings.** A compute pass whose targets follow
from inputs that rarely change (a lookup table, a baked noise volume) states
the version of those inputs as `version`, a string or a number. The pass runs
in a view only while some render target it writes holds no picture this
program recorded at this version, so the table is built in the first view
after the version moves and skipped in every later view and frame:
```luau
ctx.enqueue {
kind = "compute", program = bakeLut,
buffers = { settings = settingsBuf },
storage = { lut_out = lutRt.guid },
phase = "afterSky",
version = string.format("%.17g,%.17g", density, falloff),
}
```
A pass reading the table later in the frame reads the picture it holds. The
table is built again when the version changes, when the pass's own
`params`, `dispatch`, `buffers` or `storage` change, when the program's
pipeline is rebuilt (an edit to its source), when a render target it reads
through its `inputs` holds a new picture (so a table built from another table
is built again whenever that one is, and one built from a camera's target or a
video target whenever that target draws), when another texture it reads there
holds new texels, when a pass of any other version or none writes the target,
when the target is reallocated or cleared, and when the device reports an error
after the build was recorded. What the build reads from a buffer's contents or
from a value its program holds (`ref:setParam`) belongs in the version. A pass reading a
texture a GPU producer outside the texture cache writes, a 3D texture, or the
scene's acceleration structure and hit tables is built in every view.
**A table built from the view being drawn.** A table that follows the camera
too (a sky seen from the camera's altitude) binds `@frame.camera`, and names
what its program reads of the view in `viewReads`: `"@frame.camera.position"`
(the camera's world position, `@frame.camera[4].xyz`) and `"@frame.light"`
(the whole light buffer). The engine names the build by those values as each
view holds them, so the table is built in a view drawn from where it was not
built and stands in every view and frame drawn from where it was. `render`
runs once a frame and states what follows from the frame alone in `version`;
the engine adds what each view holds:
```luau
ctx.enqueue {
kind = "compute", program = skyTable,
inputs = { cam = "@frame.camera", lut = transmittanceRt.guid },
buffers = { settings = settingsBuf },
storage = { sky_out = skyRt.guid },
phase = "afterSky",
version = string.format("%.17g,%.17g,%.17g", sun.x, sun.y, sun.z),
viewReads = { "@frame.camera.position" }, -- built again when the camera moves
}
```
Every view of a frame shares the target, so a capture or a render-to-texture
camera standing elsewhere builds the table for its own camera, and the next
view drawn from the viewport builds it again for the viewport's. The program
reads nothing else of the camera buffer: its orientation, its projection and a
temporal upscale's sub-pixel offset move from frame to frame and name no build.
A geometry pass drawing a map of the scene into a render target of its own
(`output`) takes a `version` too. Its build is its material (the shader's
install, the row it draws with: its property values, textures, render state
and the buffers it binds, and the picture each render target it samples
holds), its version, its `geometry`, `select`, `detail` and `rigid`, the render
layers of the camera drawing it, and the meshes its selection takes as they
stand: each one's mesh, geometry, world transform and node pose (or the place
a substrate binding gives it on the device), the cluster sets the meshes draw,
and each instanced population's transforms. So a map of a
scene where nothing moved is drawn once, a mesh that moved, arrived, left or
changed draws it again in the next view, and an edit to some other material
leaves it standing. A selection taking a mesh a skeleton poses or morph targets
blend draws in every view (`rigid = true` leaves those out), and so does a
material whose properties follow each object's named values.
The material makes the same picture from every view the build stands for: it
places what it draws without the camera's view (a map seen from above, placed
by a `vertex_clip` hook), and reads the camera being drawn only through
`viewStep`: its position rounded to whole steps of that size
(`floor(position / step + 0.5)`), and the build stands for every view whose
camera stands in the same step. What else it reads that changes (the frame
clock, the sun, a texture's texels) belongs in the version. A power of two
rounds alike in Luau, the engine and WGSL (multiply by its reciprocal there):
```luau
ctx.enqueue {
kind = "geometry", material = coverMaterial, geometry = "@geometry.opaque",
output = coverMap.guid, phase = "afterLighting",
rigid = true, detail = 1, -- the meshes nothing deforms, at 1-unit detail
version = 1, viewStep = 32, -- drawn again when a mesh moves or the camera steps
}
```
A pass of any other kind stating a `version` is refused when it is enqueued, and
so is a geometry pass drawing into the frame, a `viewStep` without a `version`
or on another kind, `viewReads` without a `version`, on another kind or naming
a buffer no input binds, and a versioned compute pass binding what each view
draws for itself: an `@scene.*` input, an `@scene.*` storage target, or a
`@frame.*` input its `viewReads` names nothing of.
### Raster passes
A raster pass draws geometry the feature makes itself: a `.rasterShader`'s
`vs_main` runs `vertexCount` times for each of `instanceCount` instances, and
pulls whatever it places from the buffers the pass binds. No mesh and no vertex
buffer stand behind it — the shape of an instanced field of grass, kelp,
leaves or debris, one record per instance. This one draws a field of leaves
from a storage buffer, hidden behind the scene's opaque geometry:
```luau
local leafShader = asset.resolve("leaves", "rasterShader")
local leaves -- a buffer of vec4 records, one per leaf: xyz position, w size
return {
setup = function(ctx)
leaves = substrate.createBuffer({ name = "leaf_field", type = "vec4", len = 256, kind = "gpu" })
local records = {}
for i = 0, 255 do
local x, z = (i % 16) - 7.5, (i // 16) - 7.5
table.insert(records, x); table.insert(records, 0); table.insert(records, z); table.insert(records, 0.6)
end
leaves:write(records)
end,
render = function(ctx)
ctx.enqueue {
kind = "raster",
shader = leafShader,
phase = "afterLighting",
vertexCount = 4, -- one quad per leaf
instanceCount = 256, -- one leaf per record
topology = "triangle-strip",
cull = "none",
buffers = { quads = leaves }, -- slot -> buffer, as a compute pass binds them
inputs = { cam = "@frame.camera" }, -- the drawn camera, for vs_main
depth = { target = "@scene.depth", test = true, write = true, compare = "less" },
}
end,
}
```
The fields a raster pass reads:
| Field | Default | Holds |
|---|---|---|
| `shader` | — (required) | the `.rasterShader` (its reference or guid) whose `vs_main` and `fs_main` the pass draws with |
| `vertexCount` | — (required without `indirect`) | vertices per instance, `@builtin(vertex_index)` 0 .. n-1 |
| `instanceCount` | `1` | instances, `@builtin(instance_index)` 0 .. n-1 |
| `indirect` | none | a buffer created with `usage = { "indirect" }` holding vertex count, instance count, first vertex and first instance as four `u32`; the counts then come from the GPU, so a compute pass that culls or spawns instances draws exactly what it kept |
| `topology` | `"triangle-list"` | `"triangle-list"` or `"triangle-strip"` |
| `cull` | `"none"` | `"none"`, `"back"` or `"front"`; a triangle wound counter-clockwise on screen faces the camera, as in WebGPU |
| `depth` | none | `{ target, test, write, compare }`, `true` for `{ target = "@scene.depth", test = true, write = true, compare = "less" }`, or `false` for no depth buffer |
| `outputs` / `output` / `blend` | `@scene.color`, replaced | where `fs_main`'s colours land and how they blend: `@scene.color`, `@scene.motion` or render targets the feature created, each `"replace"`, `"alpha"`, `"premultiplied"`, `"additive"` or `"under"` (the blend table under "Pass kinds") |
| `generateMips` | none | render targets (made with `mips`) whose mip chain the pass fills once it has drawn |
| `params` | the shader's own | values for the shader's `params:` fields, by name, for this pass |
| `phase` | — (required) | any pass phase (see "When it runs") |
| `clear` | `false` | clear the render targets the pass draws into (colour and depth) before it draws; the scene's own targets are never cleared |
| `buffers` / `inputs` / `storage` | — | the shader's bindings, resolved exactly as a compute pass resolves its own |
**Depth.** `depth.target` is `"@scene.depth"` (the opaque depth the frame laid
down) or a render target the feature created, whose own depth buffer the pass
draws and tests against. `compare` states the visible order a fragment is kept
in — `"less"` keeps the fragment nearer to the camera than what the target
holds, `"greater"` the farther one, and `"lessEqual"`, `"greaterEqual"`,
`"equal"`, `"always"`, `"never"` likewise — the keywords a material's depth test
takes. Every depth buffer a raster pass draws into is reversed, the scene's and
a render target's alike: 1.0 is the near plane and 0.0 the far plane, and the
engine maps each keyword onto the comparison that order takes, so `"less"` is
the hardware's `greater`. `clear = true` clears a render target's depth to 0.0,
the far plane, so the first fragment `"less"` meets is always kept. The matrix
in `@frame.camera` already writes reversed depth. A pass placing vertices with a
projection of its own that maps the near plane to 0 and the far plane to 1 (a
light's orthographic shadow matrix built the conventional way) writes
`clip.z = clip.w - clip.z` in `vs_main` to store the reversed value, and states
its compare keywords in visible order as above. `test = false` keeps every
fragment; `write = false` leaves the depth as it stood, and lets the same pass
sample `@scene.depth` through its `inputs`.
**A render target's depth as a texture.** `inputs = { shadow = "@depth.<guid>" }`
binds the depth buffer of the render target `<guid>` (built with the target
the first time a pass draws into it or reads its depth) to a `kind: texture_depth` binding, so a later raster or
compute pass reads what a raster pass drew there: a shadow map,
a depth pre-pass of the feature's own. Sample it with `textureLoad`, or with
`textureSampleCompare` through a comparison sampler (below).
**Winding.** A triangle whose vertices run counter-clockwise on screen faces
the camera, as in WebGPU: `cull = "back"` drops the clockwise ones and
`cull = "front"` the counter-clockwise ones. A projection that mirrors the
picture (a negative determinant, such as one whose x or y axis is flipped)
mirrors every triangle's winding with it; depth does not enter into it.
**Colour targets.** `outputs` (or `output`) names `@scene.color`,
`@scene.motion` or render targets the feature created, each with its blend:
`"replace"`, `"alpha"`, `"premultiplied"`, `"additive"` or `"under"`, as the
blend table under "Pass kinds" defines them. `blend` beside a single
`output` takes the same keywords (`true` is `"alpha"`), so
`output = rt, blend = "additive"` sums into `rt`. A keyword the pass does not
know raises from `ctx.enqueue`, naming `blend`.
**Motion vectors.** A pass whose geometry moves writes its velocity into
`@scene.motion` as a second target, `outputs = { { target = "@scene.color" },
{ target = "@scene.motion" } }`, with `fs_main` returning it at
`@location(1)` as a `vec2` NDC displacement since the previous frame: the
current clip position divided by its `w`, less the sub-pixel offset this
render's matrix carries (`cam[13].xy`), less the previous clip position divided
by its `w`. `vs_main` projects the previous position through the previous
render's view-projection, `cam[5..9)`. `@scene.motion` is drawn from
`afterDepthPrepass` to `afterLighting`; temporal reconstruction and motion blur
read what the pass wrote there.
**Samplers.** A `sampler` binding takes how it samples from `bindings.yaml`:
`filter` (`linear` | `nearest`), `mipmap` (`linear` | `nearest`), `address` for
every axis or `addressU` / `addressV` / `addressW` (`clamp` | `repeat` |
`mirror`), and `anisotropy` (1 to 16, with `filter` and `mipmap` linear). A
binding that also states `compare` (`never`, `less`, `less-equal`, `equal`,
`greater`, `greater-equal`, `not-equal`, `always`, compared as WebGPU states
them, reference against stored texel) is a `sampler_comparison`, for
`textureSampleCompare` on a `texture_depth` binding. A binding stating none of
these is the engine's linear, clamped sampler. A compute shader declares its
samplers the same way.
```yaml
bindings:
- { name: albedo, kind: texture2d }
- { name: smp, kind: sampler, filter: linear, mipmap: linear, address: repeat, anisotropy: 8 }
- { name: shadow, kind: texture_depth }
- { name: shadow_smp, kind: sampler, compare: greater-equal }
```
**Textures the feature made.** A texture `renderer.texture.create` made from
pixels (`rgba = ...`) binds by its handle (or its guid) in `inputs`, the way a
render target does. It holds its whole mip chain, each level made from the
pixels it was given, so a sampler declaring `mipmap` reads it at any level.
**Mip chains.** `renderer.texture.create({ width, height, mips = true })`
makes a render target holding its whole mip chain (`mips = <n>` holds `n`
levels). A pass draws into the first level; naming the target in
`generateMips = { target }` fills every level below it, each the 2x2 average
of the level above, once that pass has drawn — a raster, fragment or compute
pass alike. Bound in `inputs`, the target binds its whole chain, so a sampler
declaring `mipmap: linear` (and `anisotropy`) reads it the way it reads a
texture asset's. A `screen` or `history` target is resized to each view it
follows and holds one level.
```luau
local water = renderer.texture.create({ width = 512, height = 512, format = "rgba16f", mips = true })
ctx.enqueue({ kind = "raster", shader = waterShader, phase = "afterOpaque", vertexCount = 3,
output = water, clear = true, generateMips = { water } })
ctx.enqueue({ kind = "raster", shader = seabedShader, phase = "afterOpaque", vertexCount = 6,
inputs = { water = water }, depth = true })
```
**Per-pass values.** `params = { exposure = 1.5, layer = 2 }` gives the
shader's `params:` fields values for this one pass, laid over the values the
shader holds; a field the shader does not declare skips the pass, with the
field named in the log. A compute pass takes the same table, and so does a
compu
# ambientOcclusion system
Ambient occlusion: the contact darkening of indirect light in corners, creases
and where objects meet.
Without it, every concave region takes as much ambient and environment light as
a flat one: a box resting on a floor has no seam, a corner is as bright as the
wall, and an untextured scene reads as plastic.
One effect answers one question: what fraction of the hemisphere above this
pixel is open. Its answer goes into the scene's occlusion channel before
anything shades, and PBR shading (`zero_pbr_shade`, which the `pbr` shader and
the materials built on it run) multiplies it into the indirect term alone
(ambient, irradiance, environment reflection). Direct light, emissive surfaces
and transparents keep the light they carry.
## Using it
The scene's occlusion is a component; author it once and it persists with the
scene:
```lua
local id = entity.spawn("ambient_occlusion").id
entity(id).component.add("AmbientOcclusion", {
intensity = 0.9, -- how far the darkening goes, 0..1
radius = 1.5, -- world-space reach
quality = "high", -- low | medium | high | ultra
})
```
Every field is live: edit one in the inspector and the shading follows. Setting
`intensity` to 0 turns it off without losing the rest.
For code that adjusts occlusion at runtime (a quality slider, a cutscene), reach
for the module directly, with the same options:
```lua
local ao = require("@builtin::systems.ambientOcclusion.ao")
ao.set({ intensity = 0.9 }) -- any subset; the rest is kept
ao.get() -- the settings in force
ao.qualityLevels() -- the cost each level pays
ao.active() -- is the pass running
ao.stats() -- what the pass built and ran this frame
ao.clear() -- off, settings kept
```
## What the knobs do
| field | effect |
|---|---|
| `intensity` | How far the darkening goes, in [0, 1]. 0 turns it off and releases the pass. |
| `radius` | World-space reach, roughly "how big is a crease worth darkening". Constant in world space, so it does not swell as the camera approaches. |
| `power` | Contrast curve on the visibility term. Above 1 deepens the dark end. |
| `thickness` | World-space thickness assumed for an occluder, so a thin foreground object stops occluding everything behind it out to the full radius. |
| `bias` | How far a neighbour must rise above the tangent plane before it raises a horizon, in [0, 1]. Raise it if a flat surface shades itself in patches; lower it if fine creases disappear. |
| `quality` | The cost of the estimate. See the table below. |
| `traced` | Trace the hemisphere against the scene acceleration structure while the scene's ray tracing is on (`renderer.setRaytrace(true)`). A frame drawn without ray tracing takes the screen-space estimate. |
| quality | screen-space slices x steps | depth taps per texel | traced rays per texel | resolution |
|---|---|---|---|---|
| `low` | 2 x 3 | 12 | 3 | half |
| `medium` | 3 x 4 | 24 | 6 | half |
| `high` | 4 x 6 | 48 | 6 | full |
| `ultra` | 6 x 8 | 96 | 12 | full |
The lower two levels compute occlusion on a half-resolution grid: a quarter of
the texels, each still costing its level's work. Occlusion is low-frequency
almost everywhere, and the filter that removes the sampling noise lifts the
coarse grid back to the frame in the same pass, weighting each texel by the
depth where it sits so silhouettes survive the upsample. What a half-resolution
grid loses is the innermost pixel of a sharp crease.
## How it renders
The pass runs at `afterDepthPrepass`, where this frame's opaque depth is
complete and nothing has shaded yet, in the `lighting` post stage:
1. The estimate. Screen-space, it is ground-truth ambient occlusion: a few
slices are walked through the texel, the steepest horizon is found in both
directions along each, and the visible arc between the two is integrated
against the cosine lobe around the normal in closed form. Traced, it is a
cosine-weighted hemisphere of short rays, and the fraction that reaches
nothing within `radius` is the visible fraction. Both reconstruct the
surface's normal from this frame's depth and store through one function.
2. The filter. Each tap is weighted by how close its depth is to the centre
pixel's, so the sampling noise goes without bleeding occlusion across a
silhouette. It writes the occlusion into the scene's occlusion channel
(`@scene.ao`).
PBR shading reads the channel at its own pixel the same frame, on the forward and
deferred paths alike. Depth and camera come from the render target
being drawn (`@scene.depth`, `@frame.camera`), so the result is correct in
offscreen captures and render-to-texture cameras at their own resolutions. Sky
pixels have no surface to occlude.
## Seeing the occlusion on its own
While occlusion is running, `ambientOcclusion` is a capture view: the filtered
visibility with no scene colour, white where the hemisphere is open and dark
where it is closed.
```
capture { pass = "ambientOcclusion" }
```
It is the fastest way to tell a shading problem from an occlusion one, and to
compare two `radius` values or quality levels without the lighting in the way.
## Files
```
ambientOcclusion.package/
AmbientOcclusion.component/ -- the scene's occlusion, authored and persisted
ao.module/ -- ao.set / .get / .qualityLevels / .active / .stats / .clear
ambientOcclusion.renderFeature/ -- the pass: estimate, filter, occlusion channel, capture view
ao_common.shaderModule/ -- the prelude both estimators are written against
ao_pass.computeShader/ -- the screen-space estimate
ao_trace.computeShader/ -- the traced estimate
ao_filter.computeShader/ -- the depth-aware filter that writes the channel
```
# probeGI
Indirect diffuse light from a field of probes traced against the scene. The
`probeGI` render feature places probes on a grid that follows the camera, traces
rays from each every frame through the scene's acceleration structure, keeps each
probe's irradiance and distances as small octahedral maps blended over frames,
and adds the light those maps hold to every surface in view in a pass of its own.
- `probeGI.renderFeature` is the member a scene places.
- `probegi_trace`, `probegi_classify`, `probegi_irradiance`, `probegi_visibility`
and `probegi_apply` are the passes it runs.
- `probe_gi_common` and `probe_gi` are the shader modules the passes share.
The light the field adds takes the scene's occlusion channel (`@scene.ao`, which
an ambient occlusion member writes): each surface's light is scaled by the share
of its hemisphere the channel leaves open, raised by the multi-bounce fit for the
surface's colour. `contactOcclusion` states how much of that the field takes, 0
to 1; where no member writes the channel the light stands as the field states it.
The field resolves occluders at about its finest spacing and above, and the
occlusion channel those inside its radius, so a radius under half of
`baseSpacing` keeps the two from occluding the same geometry twice.
# Scene light (asset type)
A scene light is one light that reaches the whole scene alike, as an asset. It
is one position-independent `Light` (`directional`, `ambient` or `distant`,
the kinds `lighting.isPositionIndependent` answers for) described in
`sceneLight.yaml`, and it implements `applicable`: applying it puts that light
in force for the applier.
## Where it lives
- Source: `<name>.sceneLight/`
- Identity: `<name>` (the `.sceneLight` suffix strips from the identity)
- Folder shape:
- `sceneLight.yaml`: the light. **Required.**
- `README.md`: what light it puts on a scene. **Required.**
- `.metadata`: `description` and `tags`. **Required.**
```yaml
# moonFill.sceneLight / sceneLight.yaml
kind: distant
direction: [0.3, -0.5, 0.4]
color: [0.6, 0.7, 1.0]
intensity: 0.3
```
## Parameters
Its parameters are the `Light` component's own fields for the light, with their
descriptors (`intensity`, `colorR`/`colorG`/`colorB`, `directionX`/`Y`/`Z`,
`castsShadows`, `lightChannels`, `mobility`), defaulting to what
`sceneLight.yaml` states, and three of its own:
- `followSky`: whether the sky orients this light (a `directional` or `distant`
one). A sky that drives the sun (a procedural backdrop) then writes the
light's direction from its hour, and its colour and intensity as the stated
ones multiplied by the curve of the sun's elevation: the stated `intensity`
is the noon peak, reached from 30° up; toward the horizon the light dims and
warms (about 0.3 of the peak at 7°), and below it the intensity is 0. A sun
that should follow the sky states `followSky: true` and no direction.
- `skyOffset`: where a following light stands from the sun, `[yaw, pitch]` in
degrees. Yaw turns it about the vertical, so `[180, 0]` is a fill from the
side opposite the sun at the sun's elevation; pitch raises it above the sun.
The curve is the sun's, so a fill dims with the sun and is out at night.
- `followSkyIntensity` (default `true`): whether a following light takes its
intensity from the sky as well as its direction and colour. `true` puts the
sun's curve on the stated intensity, as above. `false` keeps the stated
intensity while the light stands above the horizon (its own elevation,
after `skyOffset`) and 0 below it; the direction and the colour still come
from the sky. A sun follows with it `true`; a fill or a rim that should hold
its strength through dusk states it `false`. After dark a following light
stands at the moon the sky draws, opposite the sun: with `true` it is out,
with `false` it is moonlight at the intensity it states.
A cool fill for a dusk scene: it stands opposite the sun, a little higher,
takes the sky's direction and its warm-to-cool colour, and lands at the 0.9 it
states at 17:42, where with `followSkyIntensity` true it would land near 0.18.
```yaml
# harbourFill.sceneLight / sceneLight.yaml
kind: distant
color: [0.5, 0.6, 1.0]
intensity: 0.9
castsShadows: false
followSky: true
followSkyIntensity: false
skyOffset: [180, 12]
```
What a following light lands at is not what it states. A placed setup's
`SceneSetup:members()` reports, for such a member, `landed` (its intensity,
colour and direction now) beside `stated`, and `SceneSetup:get(path)` carries
`landed` beside `value` for each of those parameters; `SceneSetup:set(path,
value)` returns that read, so setting `fill/intensity` answers what it lands at
straight away, and the setup's card shows it on the row (`0.9 → lands at 0.18
at 17:42`). `ref:landed(owner)` is the same answer for one application.
## Applying it
Each application spawns a temporary entity of its own (`ref:entityOf(owner)`)
and puts a `Light` of the asset's kind on it; it publishes itself as the sun or
the ambient term the way every `Light` does, and the last to publish holds it.
Dropping the application removes the `Light` and the entity. The `ApplyState`
reports `held` while another light holds its kind (`heldBy` names that
application's owner, or the holding entity), and a notice when an ambient term
is as bright as half the sun or more, which flattens the scene's shading. A
write the lighting API makes to the light (`lighting.setSun`,
`lighting.setAmbient`, `sky.setSunDirection`) lands on the application,
through its owner's writer when it handed one.
A kind that lights from where its entity stands (`point`, `spot`) is refused by
name (`sceneLight.kind`).
# sceneLighting
Scene setups that light a whole scene with the engine's real-time lighting in
one placement, and a scene that shows them.
- `dynamicLighting.sceneSetup`: a sky whose hour drives a sun and a moon, the
sky light, ray-traced probe global illumination, ambient occlusion, contact
shadows, height fog, exposure that adapts from day to night, temporal
anti-aliasing and screen-space reflections. Its sky, sun and moon are the
assets beside it: `dynamicSky.sky`, `dynamicSun.sceneLight` and
`dynamicMoon.sceneLight`.
- `dynamicLightingShowcase.scene`: a cottage in a garden lit by
`dynamicLighting`, with a room lit through its windows, lamps inside and
out, trees and bushes, a glossy terrace and a mirror ball.
Place the setup in any scene:
```lua
asset.resolve("@builtin::systems.sceneLighting.dynamicLighting", "sceneSetup")
:instantiate(nil, { name = "lighting" })
```
and set `sky/backdrop/timeOfDay` on the placement to move the scene between day
and night.
# reflections system
Screen-space reflections — a polished floor reflects what stands on it, wet
ground reflects what is above it, and metal picks up its surroundings, all from
geometry the camera can already see.
Environment reflections describe a surface's surroundings in general. They
cannot show the character walking across the floor, because that character is
not in the environment — it arrived this frame. Screen-space reflections read
the frame the engine has just drawn, so anything visible can appear in anything
reflective, with nothing authored per surface.
What that buys and what it costs are the same thing: only what is **on screen**
can be reflected. A reflection of something behind the camera, or off the edge
of the frame, is not there to find. So reflections fade out toward the screen
edge rather than cutting off, and where a ray finds nothing the surface keeps
the shading it already had.
## Using it
Reflections are a render feature. List it on the scene's `RenderFeatures`
entity with the settings it should run under, and it persists with the scene:
```lua
local id = entity.spawn("render features").id
entity(id).component.add("RenderFeatures", {
features = {
{ feature = "@builtin::systems.reflections.ssr", settings = {
intensity = 1.0, -- how much of the reflection reaches the image
maxDistance = 40, -- how far a reflection ray travels, world units
quality = "auto", -- low | medium | high | ultra, or auto (the device's tier)
} },
},
})
```
Every setting is live: edit one in the inspector and the reflections follow.
`renderer.feature.schema("@builtin::systems.reflections.ssr")` lists every knob
with its default.
For code that adjusts reflections at runtime — a quality slider, a cutscene,
weather turning pavement wet — the module is the hand on the same knobs:
```lua
local ssr = require("@builtin::systems.reflections.ssr")
ssr.set({ intensity = 0.6, quality = "medium" }) -- any subset; the rest is kept
ssr.get() -- the settings in force
ssr.active() -- are the passes running
ssr.clear() -- the passes down
```
`set` brings the feature up when none is live, and an `intensity` of 0 takes
it down; the same feature is found rather than stacked when `RenderFeatures`
already runs it.
## What the knobs do
| field | effect |
|---|---|
| `intensity` | How much of the reflection reaches the image, in [0, 1]. 0 turns reflections off and releases the passes. |
| `maxDistance` | How far a reflection ray travels, in world units. |
| `thickness` | How thick a surface is assumed to be, in world units. A ray passing behind one by more than this went past it rather than onto it. |
| `roughnessCutoff` | Perceptual roughness up to which a surface takes the full screen-space reflection. Above it the reflection hands over to the probes and the sky, and is gone 0.1 higher. |
| `quality` | `low` / `medium` / `high` / `ultra` — how many steps the march spends and how many neighbouring rays a pixel gathers — or `auto` (the default), which follows the device's quality tier (`renderer.qualityTier()`): `high` on a desktop, `medium` on a handheld and at the medium tier, `low` at the low tier. `ssr.drawn()` reports the level in force and the sampling it spends. |
| `edgeFade` | How far from the edge of the screen reflections fade out, in UV. |
`roughnessCutoff` is the one to understand first. Every pixel traces one ray
drawn from the lobe its roughness describes, and gathers the rays of its
neighbours that stand on the same surface, so a rough floor shows a bright
sign as the soft, stretched streak its lobe spreads the sign into, and a
mirror shows it sharp. Up to the cutoff a surface takes the full screen-space
reflection. Above it the reflection hands over to the probes and the sky, and
it is gone 0.1 higher, so the hand-over has a soft edge in place of a line. The
default, 0.75, covers wet asphalt and polished stone. A scene that states a
lower cutoff (0.4 was the old default) leaves those surfaces to the probes.
Where the screen holds only part of a surface's lobe (the lobe reaches off the
edge of the frame, or behind the camera) the reflection covers the part it
found and the probe or sky fills the rest.
`maxDistance` and `quality` trade against each other: quality sets the step
count, so a long distance at a low quality samples coarsely and reflections
thin out at range. They thin rather than disappear because the hit refinement
adapts to the step size on its own.
How much of a reflection shows through is the surface's own Fresnel term, taken
from the G-buffer's metallic. Metal takes nearly all of it; a dielectric floor
takes a few percent head-on and much more at a grazing angle — which is why a
wet road reads dry underfoot and mirror-like down the street.
## How it renders
`ssr.renderFeature` runs two compute passes at the `afterDepthPrepass` seam,
before anything shades. `ssr_trace` draws one ray per pixel from the pixel's
GGX lobe (a visible-normal sample; a mirror, below roughness 0.1, keeps its
one reflection ray) and marches it against this frame's depth. The surface's
normal and roughness come from the G-buffer as the previous frame left them,
reprojected through the previous view-projection. The pass writes where each
ray hit and how confident the hit is, or the direction it travelled when it
found nothing. A rough pixel's ray marches fewer steps, because the next pass
blurs what the rays find.
`ssr_resolve` gathers each pixel's lobe over its own ray and the rays of up to
twelve neighbours (4 at `low` and `medium`, 8 at `high`, 12 at `ultra`),
weighing every ray against the pixel's own lobe and counting a neighbour only
where it shows the same surface. The light at a hit is read from the colour
the previous frame ended with, where the hit stood then. The resolve
accumulates the result over frames in a history target (one image pair per
view), holds that history to the spread of the rays it gathered, and writes the
scene's reflection channel, `@scene.reflection`: the light of the rays that
found something on screen, and the share of the lobe those rays cover.
A material reads that channel the same frame, at its own pixel, inside its
environment term: it mixes the traced light over the probe and the sky by the
share of the lobe the screen answered, so what the screen did not find comes
from the environment, and the material's Fresnel, roughness and tint weigh the
result into the pixel as they weigh any environment. The reflection stands
where the camera is now; only the light in it is a frame old. The `reflection`
capture pass shows it. Where the trace found nothing the channel holds zero and
the material reflects its environment alone.
A blended material (a `blend` other than `opaque` or `cutout`) reads none of
the channel. It draws over the depth the trace ran against, so the channel at
its pixel holds the reflection traced for the opaque surface behind it. A
blended pane of glass reflects its environment, or the reflection its shader
traces for itself through `@builtin::shaderModules.screenReflection`.
A camera drawing a diagnostic pass holds readings in its colour target rather
than light, so the passes have no light to read from that frame: such a frame
is drawn lit first, unpresented, the passes run for that, and the diagnostic
reads the channel gathered for where the camera stands now. A capture drawn
once, or a camera drawn again from a new station, is drawn lit first for the
same reason, so its first frame holds a reflection (without accumulated
history, so it shows more grain than a continuously drawn view). The march
steps uniformly in screen space and compares in world space; the full account,
including why thickness is tested after refinement rather than during the
march, is in the render feature's own readme.
Each view that draws the feature holds three screen-sized images of its own: the
rays and the history pair, about 50 MB at 1080p for the viewport.
The pass takes its camera from `@frame.camera`, so reflections are correct in
offscreen captures and render-to-texture cameras, not only the live viewport.
## The demo scene
The scene `@builtin::systems.reflections.demo.polished_floor`, loaded with the `scene.load` tool, is a polished
stone floor with three coloured pillars standing on it, under an afternoon
sky, with the feature listed on the scene's `render_features` entity. The
floor reflects the pillars and a player walking across it; delete the entity
and it mirrors the sky alone. `demo/polished_floor.scene/build.luau` is the
whole scene as code, materials included.
## Files
```
reflections.package/
ssr.renderFeature/ -- the trace and resolve passes, and the settings they take
ssr_trace.computeShader/ -- draws and marches one lobe-sampled ray per pixel
ssr_resolve.computeShader/ -- gathers each pixel's lobe, accumulates, writes the reflection channel
ssr.module/ -- ssr.set / .get / .clear / .active, the runtime hand on them
ScreenSpaceReflections.component/ -- the older one-feature component; RenderFeatures is the list
demo/polished_floor.scene/ -- the showcase: a polished floor, three pillars, the feature on one entity
```
# antiAliasing system
Geometry is rasterised at one sample per pixel, so a silhouette crossing a pixel
either covers its sample or does not. A shallow-angle edge therefore comes out as
a staircase of hard steps rather than as a line, and that staircase is the most
recognisable artifact of an unfiltered render. In motion it gets worse: the step
pattern shifts as the edge moves, a specular highlight flashes on and off as it
crosses the sample point, and fine texture crawls.
Two corrections live here, and they work from different information.
**Edge antialiasing** (`EdgeAntiAliasing`, FXAA) works from the finished frame
alone. It finds each edge and shifts that pixel's sample across it. Fixed cost,
no dependencies, corrects the staircase in a still image — and knows nothing
about time, so what only appears in motion stays.
**Temporal antialiasing** (`TemporalAntiAliasing`) samples a different point
inside each pixel every frame and accumulates the frames, following the scene's
own motion to know where each pixel's surface was. That recovers detail no single
frame holds and settles exactly what edge antialiasing cannot see — the crawling
and flickering that exist only between frames. It needs the scene's velocity, and
costs a small amount of softening, which its `sharpness` puts back on the shown
picture.
A world created from the default template runs temporal antialiasing from its
first frame: the template's `.world_settings` names `antialiasing = "taa"` under
`[render]`, and the world entrypoint applies it as the world loads, tuned by
`[render.taa]`. A world whose settings name `"off"`, or name no mode, runs none.
They compose: edge antialiasing cleans up within a frame, the temporal pass
handles what happens between them.
## Using them
```lua
local id = entity.spawn("antialiasing").id
entity(id).component.add("TemporalAntiAliasing", { historyWeight = 0.9 })
entity(id).component.add("EdgeAntiAliasing", { edgeThreshold = 0.125 })
```
Every field is live. For runtime control (a quality slider, or turning one off)
drive the modules:
```lua
local antiAliasing = require("@builtin::systems.antiAliasing.antiAliasing")
local temporalAntiAliasing = require("@builtin::systems.antiAliasing.temporalAntiAliasing")
temporalAntiAliasing.enable({ historyWeight = 0.9, sharpness = 0.2 })
antiAliasing.enable({ edgeThreshold = 0.125 })
```
Each module has `.enable` / `.get` / `.active` / `.disable`, acting on its
render feature asset (`fxaa`, `taa`): `enable` lands each value where it takes
effect (a component's or a placed setup's own value when it states it, else the
asset's live value) and applies the pass when nothing else does, `disable` drops
the module's own application, and a component's stays. A component applies the
asset with its fields, owned by its entity; of two, the one edited last is in
force.
Temporal antialiasing draws at a quality level: its `quality` (on the
component and in `enable`) is `low`, `medium`, `high`, or `auto` (the
default), which follows the device's quality tier (`renderer.qualityTier()`).
`high` sharpens the shown picture by `sharpness`; `medium` and `low` show the
accumulation unsharpened, and the sharpening pass and the copy of its result
into the picture leave the frame. The accumulation is the same at every level.
`temporalAntiAliasing.drawn()` reports the level in force and the sharpening it
draws.
To see temporal antialiasing as a player sees it, read the frame the screen
showed: `capture { source = "presented" }` (`frames = n` for a run of
consecutive frames, which is how convergence and flicker read), or
`renderer.presentedFrames()` for the pixels with each frame's jitter and
history reset. Every view keeps its own accumulation: a render-to-texture
camera accumulates over its own renders, and an offscreen capture draws a fresh
view whose single render has no history behind it, so it shows none of the
accumulation and leaves the viewport's untouched.
## What the edge knobs do
| field | effect |
|---|---|
| `edgeThreshold` | How much a pixel's luminance must differ from its neighbours', as a fraction of the brightest of them, before it counts as an edge. Lower catches fainter edges and costs more. |
| `edgeThresholdMin` | The absolute floor under that test. It keeps the pass off dark areas, where a small relative step is still visually flat. |
| `subpixel` | How strongly features finer than one pixel are corrected. |
| `searchSteps` | How far the pass walks along an edge looking for its end. Longer reach resolves shallower edges, at linear cost. |
## What the temporal knobs do
| field | effect |
|---|---|
| `historyWeight` | How much of the accumulated result to keep each frame. Higher resolves more detail and settles smoother, at the cost of taking longer to let go of what a surface used to look like. |
| `neighbourhoodClamp` | How far outside the neighbourhood's own colour spread an accumulated sample may sit before it is pulled back in. Lower rejects more, trading some of the settling for a result that follows change faster. |
| `sharpness` | How strongly the shown picture is sharpened, in [0, 1]: a contrast-adaptive pass (`rcas`) after the display transform, which steepens edges without lifting either side past its plateau and is never written back into the accumulation. 0 shows the accumulation as it is. |
| `motionRejection` | How much fast motion shortens the memory, which is what stops a moving object trailing behind itself. |
| `stillSamples` | How many renders a pixel whose surface holds still accumulates, in [1, 256]. Each render samples a different point inside the pixel, so a still pixel holding several whole passes through the sample sequence settles on their average instead of rippling as the samples visit it; fewer let a still picture follow a slow change of its lighting sooner. |
## How they render
`fxaa.renderFeature` runs one compute pass in the `display` stage, on display
code values, so its edge thresholds read luma the way a viewer sees it. A
picture of the edge antialiasing is read from the presented frame
(`renderer.presentedFrames`, a `capture` with `source = "presented"`): the
`display` stage's render-feature passes draw there. The result is **not a
blur**. A blur softens everything; this moves each edge pixel's sample
perpendicular to the edge by a sub-pixel amount, so the step between two flat
regions becomes a gradient while both regions are left as they were. That is why
the pass has to find the edge's direction and extent rather than filtering a
neighbourhood — the offset depends on where along the edge the pixel falls, so a
pixel near the middle of a long edge barely moves and one near an end moves
nearly a full half-texel.
Luminance drives every decision there. The eye resolves luminance detail far more
finely than chroma, so a step that reads as a jagged edge is a step in luminance,
and an edge that is pure chroma needs no correction. A pixel whose neighbourhood
varies less than the threshold is passed through untouched, which is what keeps
flat regions and gentle gradients out of the filter entirely. Features finer than
a pixel produce no long edge to walk, so the 3x3 luminance average carries their
correction instead.
`taa.renderFeature` offsets where the projection samples each frame and
accumulates the frames that produces, reprojecting through `@scene.motion` and
bounding what it carries by the neighbourhood's own colour statistics. Its README
covers the sample sequence, the tests that decide whether an accumulated sample
is still about the same surface, and why the bound is computed in YCoCg. The
accumulation itself is `temporal_resolve`, the one resolve the temporal upscale
(`@builtin::systems.temporalUpscale`) folds its frames through as well. Both
then restate the frame's depth from `stable_depth`, the depth sample nearest
each pixel's centre while nothing there moves, so an effect after them draws
lines and patterns that hold still with the picture.
## Files
```
antiAliasing.package/
EdgeAntiAliasing.component/ -- the scene's edge antialiasing, authored and persisted
antiAliasing.module/ -- .enable / .get / .disable / .active
fxaa.renderFeature/ -- the edge pass
TemporalAntiAliasing.component/ -- the scene's temporal antialiasing, authored and persisted
temporalAntiAliasing.module/ -- .enable / .get / .disable / .active
taa.renderFeature/ -- the accumulation pass + the per-frame sample offset
taa_resolve.computeShader/ -- the accumulation at render scale 1
temporal_resolve.shaderModule/ -- the temporal resolve every reconstruction accumulates through
stable_depth.computeShader/ -- the depth a reconstruction restates for the passes after it
stable_surface.computeShader/ -- the G-buffer normal and material restated beside it
rcas.computeShader/ -- the sharpening of the shown picture after the temporal stage
```
# contactShadows system
Short screen-space shadow traces that supply the small-scale contact a shadow
map cannot resolve.
A shadow map has a texel size. Contact finer than that texel — a chair leg on a
floor, a prop on a table, fingers on a desk — falls between texels and is simply
not there, which is why small objects read as hovering slightly above the
surface they are resting on. No amount of shadow resolution fixes it, because
the missing detail is below the sampling scale.
This traces a short ray through the depth buffer from each shaded pixel toward
the light and darkens the pixel when the ray passes behind visible geometry. It
adds the contact term; the shadow map keeps doing everything else.
## Using it
```lua
local id = entity.spawn("contact_shadows").id
entity(id).component.add("ContactShadows", {
strength = 0.9, -- how dark a fully occluded contact goes, 0..1
length = 0.35, -- trace length in WORLD units
steps = 16, -- samples along the trace
})
```
Every field is live. Setting `strength` to 0 turns it off without losing the
rest. For runtime control (a quality slider, a cutscene) drive the module:
```lua
local contactShadows = require("@builtin::systems.contactShadows.contactShadows")
contactShadows.set({ strength = 0.9, length = 0.35 })
contactShadows.get()
contactShadows.active()
contactShadows.lights() -- the lights this frame's traces aim at
contactShadows.drawn() -- the newest frame the passes drew, and the lights they traced
contactShadows.clear()
```
## What the knobs do
| field | effect |
|---|---|
| `strength` | How dark a fully occluded contact goes, in [0, 1]. 0 turns it off and releases the pass. |
| `length` | Trace length in **world** units. This is the scale of contact supplied, so it scales with the scene rather than the screen. |
| `steps` | Samples along the trace. More resolves finer occluders, at linear cost. |
| `bias` | Normal offset before the march starts, so a surface does not read as its own occluder. |
| `thickness` | World-space thickness assumed for an occluder. Past it the ray has emerged out the far side and stops counting. |
| `localLights` | Whether the scene's point, spot and distant lights supply contact of their own alongside the sun. |
| `maxTracedLights` | How many of them a single pixel may trace toward — the heaviest contributors at that pixel. Each one costs that pixel another march, so this is the per-pixel ceiling. |
`lightDirection` tracks the scene's sun on its own, re-read every frame. Pin it
through `contactShadows.set` when a scene wants the sun's trace aimed
elsewhere; a later `set` that names no direction goes back to tracking the sun.
## Lights
A lamp on a desk grounds the props under it the same way the sun does, and the
same shadow-map texel that loses the sun's contact loses its. So with
`localLights` the point, spot and distant lights supply contact too, each
traced toward and each weighted by the share of the pixel's light it put there
— its intensity and colour luminance against the same distance attenuation and
cone the renderer shades it with. A pixel darkens by the share of its light the
traces found blocked, which is what keeps a lamp's contact out of the regions
that lamp does not reach.
A local light's ray also stops at the light itself rather than running the full
`length`: geometry past a lamp stands between nothing.
The pool holds point, spot and distant lights. An area light shades from a
surface rather than a point, and the trace takes a single direction per light,
so contact under one comes from the sun and whatever punctual lights share the
scene with it.
The module selects the pool once a frame — every distant light, then the local
lights whose sphere of influence touches the view, ranked by what each is worth
at the camera — and that rank is what a scene holding more lights than the pool
has rows spends them on. `contactShadows.lights()` reads back exactly what it
selected. The view it selects against is the main camera's, so an offscreen
camera looking somewhere else traces toward the lights the main view holds.
At each pixel the pass then weighs the whole pool — intensity and colour
luminance against that pixel's own N·L, distance attenuation and cone — and
marches toward the `maxTracedLights` heaviest. So a lamp across the room that
ranked into the pool does not spend the budget of a pixel the lamp beside it is
lighting.
## How it renders
`contactShadows.renderFeature` runs the sun's trace at the depth seam, before
anything shades, and the local lights' traces after lighting.
The sun's march (`contact_shadows_sun`) starts at each surface, its normal read
off this frame's depth, and steps toward the sun. Each sample along the ray is
projected back to the screen and compared, in world space, against what the
depth buffer holds there: the ray is blocked while it is behind visible
geometry and still within `thickness` of it. The march is jittered per pixel
so the step pattern lands as noise rather than visible stair-stepping, and a
surface facing away from the sun takes nothing: it is already unlit by it. The
pass writes `strength` times how blocked the ray is, `contact_sun_blur` smooths
it along the depth, and a fragment pass composes it into the scene's sun
occlusion channel (`@scene.sunOcclusion`) with the `union` blend
(`src + dst - src * dst`). The sun's term is the only one that reads that
channel, so the sun's contact darkens the sun's light and nothing else: the
sky, the probes, an emissive surface and the other lights keep theirs, and a
participating medium's shadow written into the same channel composes with it.
With `localLights`, the local march (`contact_shadows`) reads the deferred
G-buffer's normal, so it needs the deferred path (the default). Its blur
composites the result over the shaded colour scaled by how lit the pixel
already is (`@scene.material` against the shaded colour), so a region the
shadow map has already darkened takes little further darkening and the two
shadow sources do not stack.
The forward view-projection needed to project a sample back to the screen is
the one the frame provides, rather than one passed in from script, so an
offscreen capture or an RTT camera projects through its own matrix.
## Files
```
contactShadows.package/
ContactShadows.component/ -- the scene's contact shadows, authored and persisted
contactShadows.module/ -- .set / .get / .clear / .active / .lights / .drawn / .refresh
contactShadows.renderFeature/ -- the passes, and the settings they read
contact_shadows_sun.computeShader/ -- the sun's trace, at the depth seam
contact_sun_blur.computeShader/ -- the sun's share, smoothed
contact_shadows.computeShader/ -- the local lights' trace
contact_shadows_blur.computeShader/ -- the local lights' composite
```
## At lower quality levels
The settings that carry its cost scale with the device's quality level (`Field.scaled`): the values a setup authors are the high look, and `renderer.feature.resolved(handle)` states what each level draws. The `graphics-quality` guide lists the rules.
# Sky (asset type)
A sky is the sky of a scene in one asset: a composition of **members**, each an
asset whose type implements `applicable`, with the values the sky states
for them. One of them is a **backdrop**, a render feature that writes the
scene's `Sky` row (`@builtin::systems.sky.backdrops.procedural`,
`@builtin::systems.sky.backdrops.material`, or a creator's own); the others are
whatever else belongs to the sky, such as clouds. A sky has no parameter of its
own: its parameters are its members', by path (`backdrop/timeOfDay`,
`clouds/coverage`, `clouds/@enabled`). A member whose parameters follow from
content its values name has those too: a material backdrop's parameters are
its own (`material`, `exposure`, `rotation`) and the shader properties of the
material it names (`backdrop/zenith`, `backdrop/glow_size`), each with the
material's value as its default.
## Where it lives
- Source: `<name>.sky/`
- Identity: `<name>` (the `.sky` suffix strips from the identity)
- Folder shape:
- `sky.yaml`: the definition. **Required.**
- `README.md`: what the sky draws. **Required.**
- `.metadata`: `description` and `tags`. **Required.**
- `preview.png`: its picture. Optional.
## The definition
```yaml
members:
- id: backdrop
source: "@builtin::systems.sky.backdrops.procedural"
values: { timeOfDay: 18.5, zenithColor: [0.2, 0.1, 0.3], horizonColor: [0.9, 0.4, 0.2], horizonHeight: 2 }
- id: clouds
source: "@builtin::systems.volumetrics.volumetricSky"
# Omitted values use the package's complete default weather preset.
```
It is read the way a scene setup's is: the same member grammar, the same
diagnostics, nested compositions under their member id. A member's `source`
is an identity (`skies.parts.haze`, `@builtin::systems.sky.backdrops.procedural`)
or a path with its type suffix: absolute (`/source/skies/parts/haze.renderFeature`),
from the folder holding this sky (`haze.renderFeature`, `./haze.renderFeature`,
`../parts/haze.renderFeature`) or from the world's source folder
(`skies/parts/haze.renderFeature`). An identity drops the type suffix, so a
sky and a scene setup of one name in one folder share it; their paths name
each apart. The scene setup type's README has the whole grammar.
A volumetric cloud member's weather is its `preset` table, and a value for it states the whole table.
## Using one
A sky implements `applicable`: applied, it applies every member for the
owner:
```lua
local dusk = asset.resolve("my-dusk", "sky")
dusk:as("applicable"):apply("myEntity:sky", { ["backdrop/timeOfDay"] = 19 })
local drawn = sky.drawn() -- { entity, source = dusk, description }
dusk:as("applicable"):drop("myEntity:sky")
```
`sky.drawn().description` (the sky's own `describeSky`) is `{ material, timeOfDay,
sunDirection, members, notice? }`, built from what is drawn; `notice` is what a
member states about the settings it runs, by member path. A procedural
backdrop draws its base colours (`zenithColor`, `horizonColor`, `groundColor`)
in the shape `horizonHeight` gives them: the elevation in degrees where the sky
is halfway from the horizon colour to the zenith colour (default 7.933). A
palette whose horizon colour is a band, such as a sunset's orange under a
violet sky, lowers it (to 2, say) so the zenith
colour shows at eye level. The backdrop draws them while the sun is high and its night and dawn tint sets as the sun sinks, as far
as `nightStrength` and `dawnStrength` say; a sky that holds one hour states its
look in the base colours with both strengths at 0, and the notice names a set
that masks the base colours at the hour drawn. The backdrop's README has the
table of which set shows at which hour. A light that follows the sky
(`lighting.followSky`) is oriented by a procedural backdrop's hour.
**Moon and moonlight.** A procedural backdrop draws its moon opposite its sun,
at the hour it draws. After dark a light that follows the sky stands at that
moon: a sun that takes its intensity from the sky is out, and a light that
keeps its own (`followSkyIntensity: false`) is moonlight at the intensity it
states, from where the moon is drawn. A night setup keeps the two together by
giving its moonlight `followSky: true`, `followSkyIntensity: false` and a
moonlight intensity and colour (a setup nesting a day setup sets its sun's
`followSkyIntensity` to `false` and its intensity to the moon's), so the
light stands where the moon is drawn.
## A material sky's shader values
A sky drawn by a material takes that material's shader properties as
parameters, so a sky, a setup nesting it, or a placement states them by path
like any other value, and a setup's card lists them:
```yaml
# night_variant.sceneSetup/sceneSetup.yaml: the base setup, its sky's glow raised
members:
- id: base
source: "./base.sceneSetup"
values:
"sky/backdrop/glow_intensity": 2.5
"sky/backdrop/zenith": [0.02, 0.01, 0.08, 1]
```
The backdrop draws the material itself while every value stated for it is the
material's own, and a runtime copy of the material with the stated values laid
over its own once one differs; the material asset is not written. Two
applications of one backdrop are arbitrated the way every render feature's
are: the newest that states something new is in force, and dropping it brings
back the values of the one before it.
## Making one
```lua
asset.create("sky", "aurora", { members = {
{ id = "backdrop", source = "@builtin::systems.sky.backdrops.material",
values = { material = "my-aurora-material", exposure = 1.2 } },
} })
```
# scene_instantiable (module)
The instantiation contract's shared implementation. An asset type opts into
scene instantiation by defining `instantiate(self, target?, opts?)` on its
behaviour `ref` table; this module carries the parts that mean the same thing
for every type, so a caller writes ONE piece of code against all of them.
```lua
local root, idMap = ref:instantiate(target?, opts?)
```
## The contract
**IN — the base opts.** `target` is an owning entity ref: the instance lands
under (or, for a hierarchy type like a bundle, onto) that owner. With no
target the type spawns a fresh root. `position`, `rotation`, `scale`, `name`
and `temporary` place that root and mean the same for every type. `rotation`
takes three numbers as pitch/yaw/roll in DEGREES, or four as a quaternion. A
type may honour more opts of its own — `params` for a type built from declared
inputs, `idMap` / `diff` / `sourceTag` for the bundle override contract — and
says so in its own `instantiate` docs.
**OUT — the two returned values.** Every type returns the same pair:
- **`root`** — the composed root, as an `EntityRef`. Composition is
**synchronous**: the root and everything the type built under it are live
the moment the call returns, so a caller can parent to it, read its
components and hand it on in the same statement. There is no frame to wait
for and no callback.
- **`idMap`** — the `originalId -> runtimeId` map naming what the composition
spawned, `{}` for a type with no addressable children. **Never nil.** A
component that re-composes the asset on every load (`Asset`) keeps this map
and passes it back in, which is how a cross-entity reference into the
composition — `SkinnedModel.skeletonRoot` pointing at a bone — survives a
reload.
The return is enforced, not merely described: `AssetRef` dispatches every
`ref:instantiate(...)` through `result` on the way out, whether or not the
type called it. A type that returns something else fails at its own call
rather than handing its caller a nil root or a map that is sometimes absent.
## Exports
- `M.root(self, target?, opts?) -> root` — stand the root entity for a type
that spawns one: parented to `target`, born temporary when
`opts.temporary`, named `opts.name` else the asset's own name, placed.
- `M.place(root, opts?) -> root` — apply the placement opts to a root the type
already has (the adopt path: a bundle exploding onto its target, a
sceneModule reconciling under one).
- `M.result(self, root, idMap?) -> (root, idMap)` — return through the
contract. Checks `root` is a live entity ref, normalises a missing map to
`{}`, and errors naming the asset type when either is something else.
- `M.isOwned(opts?) -> boolean` — whether a component drives this call. The
`Asset` / `SceneModule` components tag their own calls with `sourceTag`;
they hold the reference and re-compose on every load. An untagged call came
straight from `ref:instantiate(...)` and has no such owner.
- `M.own(root, self, idMap?) -> root` — hand an already-composed root to an
`Asset` component pointing at `self`, so the reference and its map persist
and the composition is rebuilt on the next load. The component adopts the
live composition rather than building a second one.
- `M.check(value, constraint) -> ok, reason?` — the `sceneInstantiable`
field-constraint validator, also registered under that kind on load.
## The field constraint
`Field.instantiableRef` emits `constraint = { kind = "sceneInstantiable" }`,
and this module registers the validator for it on load. Given a written value:
1. `nil` passes — the field is optional (no asset assigned).
2. Reads the value's identity — a bare string, or a table's `__ref` / `guid` /
`identity` / `name`.
3. Resolves it (`asset.resolve(identity)` — any category) and asks the
resolved ref `ref:canInstantiate()`: true iff the asset's type defines an
`instantiate` method.
This is what lets `Field.instantiableRef` accept by CAPABILITY rather than a
hardcoded type list — a new scene-instantiable asset type is accepted the
moment it defines the hook, with no edit to the field or its consumers.
# SceneSetup
The per-instance state of a placed scene setup. A setup's `instantiate` adds it
to the placed root beside the `Asset` component whose `source` is the setup. It
holds this placement's `overrides`, by parameter path, and applies the setup with
them; the setup's members are applications of their assets, so the scene records
the root, its `Asset` and these overrides alone.
```luau
local setup = entity(root).component.get("SceneSetup")
setup:members() -- { [path]: { source, state } }, every depth
setup:get("fog/density") -- { value, origin, definedBy?, desc }
setup:set("fog/density", 0.05) -- this placement's override
setup:set("ao/@enabled", false) -- turns a member off here
setup:reset("fog/density") -- back to what the setup says
setup:orphans() -- overrides that address nothing
```
It applies the setup when it wakes and when it is enabled, applies a change of
`overrides`, turns the setup off when it is disabled and drops it when it is
removed; removing the `Asset` removes it. While it is disabled, a change of its
overrides applies the setup off. Across an edit/play flip the setup
stays applied: the instance that ends hands its application to the one that
wakes on the same root, so no frame is drawn without its sky, sun or fog. It
runs nothing per frame. A system
API's write of a parameter this placement states (`fog.set`) becomes this
placement's override.
Its application is one of the scene's applications: the effects that hold one
at a time (the sun, the ambient term, the sky, each render feature's settings)
go to the newest application standing. Another setup applied from code
(`setupRef:as("applicable"):apply(owner)`) holds them over this placement
until it is dropped, across flips, and its drop hands them back to this
placement. `audition(setup)` shows another setup in this placement's place as a
preview for the session; `endAudition()`, a flip or a reload ends it.
# contract
The shared half of `applicable`. Every call of `apply`, `setEnabled` and
`drop` on an asset whose type implements the interface passes through `gate`,
which checks the owner, the values against `asset.schema`, and `opts.enabled`;
keeps one record per application (the values the owner stated and whether it
is on); calls the type with the asset's own values and what the owner stated
laid over them; and checks the returned `ApplyState` (`status`, `heldBy`,
`notice`).
```lua
local Apply = require("@builtin::interfaces.applicable.contract")
Apply.values(self, owner) -- the values the application receives
Apply.stated(self, owner) -- what the owner stated, sparse
Apply.restate(guid?) -- apply the records again
```
After an edit/play flip, a render-device rebuild and an edit of an applied
asset, the contract applies every record of the asset again, and each type puts
back what of its effect is gone.
# editorSelection
Named selection scopes for the editor. A scope is an independently
tracked, ordered set of typed refs plus a primary (the last ref added
or clicked). Distinct scopes never clobber each other, so viewport,
outliner, inspector and asset browser share one answer to "what is
selected" per kind.
A ref is `{ kind: string, id: string }` — a stable id, never a display
string, so rename/move never invalidates a selection.
## Exports
- `M.scope(name) -> Scope` — get/create a named scope handle.
- `M.set(scope, refs)` — replace refs in order; primary becomes the last.
- `M.get(scope) -> { Ref }` — refs in click order (fresh array).
- `M.primary(scope) -> Ref?` — last-clicked ref, or nil.
- `M.clear(scope)` — empty a scope.
- `M.toggle(scope, ref)` — add if absent, remove if present.
- `M.add(scope, refs)` — add each ref not already present; primary becomes the last added.
- `M.remove(scope, refs)` — remove each of `refs`; primary becomes the last remaining or nil.
- `M.contains(scope, ref) -> boolean` — membership by `(kind, id)`.
- `M.count(scope) -> number` — the scope's selection size.
- `M.subscribe(scope, fn) -> handle` / `M.unsubscribe(scope, handle) -> boolean`.
- `M.context() -> { scope, refs, primary }` — last-focused scope, for command ctx.
## Usage
```luau
local Selection = require("@builtin::modules.api.editor.selection")
local scope = Selection.scope("entity")
Selection.set(scope, { { kind = "entity", id = "player_1" } })
Selection.subscribe(scope, function() refreshInspector() end)
```
## Notes
- State lives in a fixed `_G` slot, seeded pre-seal by the boot chain
(`prelude.luau`); it survives hot-reload and edit↔play flips. Mutations
after boot write into nested tables only.
- `set` / `toggle` / `clear` mark their scope as last-focused, which drives
`context()` and therefore which scope commands act on.
- The service holds the editor's selection state in Luau. Refs handed back by
`get` / `primary` / `context` are copies, so a caller can hold or mutate them
without touching internal state.
# 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**.
# lookdev (bundle)
The reference subject a lighting preview is photographed on: a grey ground,
a white diffuse sphere, a chrome sphere and an 18% grey card standing behind
them. The diffuse sphere shows the light's direction, colour and softness, the
chrome sphere reflects the sky and the light sources, and the grey card reads
the exposure. Five entities under one root, built from builtin meshes and
materials.
A type whose pictures show what an asset does to a scene names it as its
preview `subject` (a scene setup's preview, for one); the asset is applied to
the world while the subject is photographed.
```lua
asset.resolve("@builtin::preview.subjects.lookdev", "bundle"):instantiate(nil, { position = { 0, 0, 0 } })
```
# applicable
Can be applied for an owner, with values for its declared parameters. A type
that lists `applicable` under `interfaces:` in its `type.yaml` guarantees that
any of its assets can be put in effect for an **owner**, with values for the
parameters the asset declares (`asset.schema`), and that the owner can change
those values, turn the application off and on, and drop it, which leaves
nothing behind, and that the owner can read the application's state as it
stands. A caller applies any implementer with the same calls; here `ref` is
any asset whose type lists `applicable`:
```lua
local view = ref:as("applicable")
local state = view:apply("owner-key", {})
view:setEnabled("owner-key", false)
view:state("owner-key")
view:drop("owner-key")
```
## The members
| Member | What it does |
|---|---|
| `apply(self, owner, values, opts?) -> ApplyState` | Puts the asset in effect for `owner` with `values`. Called again for the same owner, it changes the values. |
| `setEnabled(self, owner, enabled) -> ApplyState` | Turns that application on or off while it stays applied; its values are kept. |
| `drop(self, owner)` | Removes that application entirely. Dropping an owner with nothing applied does nothing. |
| `state(self, owner) -> ApplyState?` | The application's state now, the answer `apply` would give, read without applying. `nil` when nothing is applied for `owner`. |
`owner` is a key the caller forms from something only it holds, so two callers
never share an application. With the asset, it identifies the application
across the calls.
`ApplyState` is `{ status = "inForce" | "off" | "held", heldBy?, notice? }`:
`held` when another application is in force instead (`heldBy` names it), and
`notice` the words a person should see about the application. A type may return
more fields beside these and documents them itself. An application's state can
change with no call for it, when another application of the same kind comes or
goes; `state` answers it as it stands on the frame it is asked.
## The values an application receives
Every call of a member passes through the interface's contract
(`@builtin::interfaces.applicable.contract`), which keeps one record per
application: the values the owner stated and whether it is on. The type's
`apply` receives the asset's own values (`asset.settings`, else its schema's
defaults) with what the owner stated laid over them. A name `values` gives that
the schema does not declare, or a value its descriptor refuses, raises at the
call, naming the asset and the parameter. `Apply.values(self, owner)` and
`Apply.stated(self, owner)` read an application's record.
After an edit/play flip, a render-device rebuild, and an edit of an applied
asset, the contract applies every record again; no owner acts. A type's `apply`
puts back what of its effect is gone and leaves what still stands as it is.
## Implementing it
```yaml
# <type>.assetType/type.yaml
interfaces: [applicable]
settings: { values: "<type>.yaml", schema: { type: "settings.luau" } }
```
```lua
-- <type>.assetType/behavior.luau
local Apply = require("@builtin::interfaces.applicable.contract")
local M = {}
M.ref = {
apply = function(self, owner, values, opts)
-- make the application `owner` be `values`, on when `opts.enabled`
return { status = if opts.enabled then "inForce" else "off" }
end,
setEnabled = function(self, owner, enabled)
return { status = if enabled then "inForce" else "off" }
end,
drop = function(self, owner)
-- remove everything made for `owner`
end,
state = function(self, owner)
-- the answer `apply` would give now, without applying
local on = Apply.enabled(self, owner)
return { status = if on then "inForce" else "off" }
end,
}
return M
```
A type states `settings:` in its `type.yaml` so its parameters are readable
with `asset.schema`; an empty schema is valid, and such an asset is applied
with no values. A type whose own `apply` means something else meets the member
under `M.interfaces.applicable.apply`.
## Required behaviour
1. **In effect on return.** When `apply` returns `inForce`, the asset's effect
is in effect with those values.
2. **A change is a write.** After `apply(owner, changes)`, the effect is what a
first `apply` with the complete changed values would have given.
3. **Edit and play.** In effect in edit mode and in play mode.
4. **Off keeps values.** `setEnabled(false)` takes the effect away;
`setEnabled(true)` brings it back with the same values.
5. **Drop leaves nothing.** After `drop`, what the application made is gone:
the engine's entities, render features, post-process entries and claims are
as before the first `apply`.
6. **Nothing saved.** Nothing an application holds reaches a saved scene.
7. **Independent.** Two owners' applications of one asset are two: one
changing, turning off or dropping never changes the other, except through
the asset's own rule for which application is in force.
8. **One in force is the asset's rule.** An asset whose effect holds one
application at a time decides among its applications and reports the others
`held`.
9. **Kept in force.** What an application holds is put back after the events
that remove it, by the contract's restatement.
The conformance suite (`conformance`) checks these against every asset of every
implementing type it can reach.
# sceneInstantiable
Can be placed in a scene. A type that lists `sceneInstantiable` under
`interfaces:` in its `type.yaml` guarantees that `instantiate` composes any of
its assets under or onto an owning entity, synchronously, and returns the live
root and the map naming what it spawned. A consumer places any such asset with
one call, `source:as("sceneInstantiable"):instantiate(target, opts)`, and it
works for types the consumer has never heard of: the `Asset` component, a
viewport drop, a procedural generator and a tool argument all place assets this
way.
## Implementing it
```yaml
# marker.assetType/type.yaml
interfaces: [sceneInstantiable]
```
```lua
-- marker.assetType/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)
root.component.add("Text3D", { text = self.name })
return Instantiable.result(self, root, {})
end,
}
return M
```
A type whose own `instantiate` means something else meets the member under
`M.interfaces.sceneInstantiable.instantiate`.
## The base inputs
`target` is the owning entity; with none, the type spawns a fresh root.
`opts.position`, `opts.rotation`, `opts.scale`, `opts.name` and
`opts.temporary` mean the same for every type, and `Instantiable.root` applies
them to a root the type makes (`Instantiable.place` to one it adopts).
`opts.idMap`, `opts.diff` and `opts.sourceTag` are what the `Asset` component
passes to every type: a type that spawns no addressable children ignores them.
`opts.detached` composes a permanent copy that nothing composes again. A type's
own extras (`raw`, `deferred`, `params`) travel in `opts` beside these, are
always optional, and never change a base input's meaning.
## Required behaviour
1. `root` exists on return, with everything composed under it.
2. `idMap` maps each original id to the spawned id; `{}` for none.
3. Passing the returned `idMap` back reproduces the same ids.
4. `temporary = true` keeps the root and everything under it out of the saved
scene.
5. Despawning `root`, or the composition the `Asset` component despawns, removes
everything the call put in effect.
The conformance suite, `sceneInstantiableConformance` beside this file, holds
one asset of every implementing type (or of the types a run names) to the base
options' meanings, the returned map reproducing its ids when passed back, and
a detached composition's live root. `asset.validate` of a world's own type runs
it over that type.
## Legacy types
A type that defines `M.ref.instantiate` and lists nothing (one written
before `interfaces:` existed, or defined by its `behavior.luau` alone)
implements `sceneInstantiable` with a warning (`interfaces.implied`) naming the
line to add.
# assetType runtime
The machinery that reads a `<typename>.assetType/behavior.luau` and turns its
declarations into live behaviour.
A `behavior.luau` is a table of declarations — `ref` methods, `modules` shared
code, an `events` schema, a `namePattern`, `refShapes`, and the `onCreate` /
`onRegister` / `onChange` / `onDelete` / `validate` / `settingsDefaults` /
`settingsCorrections` hooks. None of it runs itself. This is the code that
runs it, and it lives here because reading a type's declarations is the
**assetType type's own behaviour** — the same way `material.assetType` owns
what a `.material` does.
## Sub-modules
| Module | Reads | Responsibility |
|---|---|---|
| `ref.module` | `ref`, `modules` | Builds every `AssetRef` envelope, attaches the shared metatable, and dispatches per-type methods and shared modules onto it. Also owns edit-mode write-behind persistence. |
| `create.module` | `onCreate`, `namePattern`, `validate` | Backs `asset.create`: resolves the type, checks the name against its pattern, runs `onCreate` (or clones `template/`), and writes the instance. `validate.module` beside it checks a creation `opts` table against the type's `createSchema`. Before running `onCreate`, resolves the type's settings chain (below) and hands the result to the hook as `opts.settings`. |
| `settings.module` | `settings`, `settingsDefaults`, `settingsCorrections` | A type's declared settings schema and where its values live (`type.yaml`'s `settings:` block). `Settings.resolveForCreate` layers the schema's own defaults, the type's own `settingsDefaults(name, opts, asked)` hook (a DEFAULT the schema can't express — a name-derived convention, a fact read off a payload the caller handed it, a value following a field `asked` shows a higher layer naming; any later layer overrides it), the Preset Manager, an importer's settings, the caller's `settings` table, then the type's own `settingsCorrections(values, name, opts)` hook (a CROSS-FIELD CONSTRAINT the schema can't express, applied last over the fully merged values). A correction over a default/preset/importer value lands silently; a correction that would override what the caller's own `settings` table explicitly asked for refuses the creation instead, naming the field and why. Neither hook is ever handed a table to mutate; each returns what it wants changed (`settingsCorrections` may also return a `{ [field]: reason }` table for that refusal message). `Settings.cloneValues` deep-copies a values table — `create.module` hands `onCreate` a copy, never the table it stamps. `Settings.valuesOf` / `writeValues` read and write an asset's own values file. |
| `typeYaml.module` | `type.yaml` | The folder a type lives in and its parsed `type.yaml`, decoded once per content version of the file. `settings.module` and `inspector.module` read their blocks through it. `about` / `aboutAt` read a type's `about.yaml` (`intent`, `function`, `usage`), leaving out any key that is empty or still starts with `[[describe]]`; `aboutRows` and `aboutMarkdown` lay the texts out for the Inspector and the `types/<name>` guide. |
| `inspector.module` | `type.yaml`'s `inspector:` block | Which inspector a type declares for its assets (`inspector: { type: ... }` or `{ instance: ... }`), and the declaration that file returns — the sections it adds, the generic ones it replaces, and their order — or the problem that kept it from loading. |
| `onRegister.module` | `onRegister` | Fires an instance's once-only registration hook — on arrival, on world load, and for `@builtin` library instances. |
| `changeDispatch.module` | `onChange`, `onDelete`, `refShapes` | Routes a VFS source write or a folder delete to the enclosing typed asset's type hooks. |
| `refShapes.module` | `refShapes`, `ref` | Publishes what every `AssetRef<category>` answers to, so a member read on an asset-typed value is checked against that category's real surface. |
| `events.module` | `events` | The per-asset event runtime behind `ref.events`. |
| `instantiable.module` | `ref.instantiate` | The instantiation contract an asset type opts into: `root` stands the root entity, `place` applies the base placement opts to one the type adopted, and `result` shapes the `(root, idMap)` every `instantiate` returns. Also registers the `sceneInstantiable` field-constraint validator. |
| `declaration.module` | `type.yaml` | The type's decoded declaration, read once and held until a write inside an `.assetType` folder; what every question about a type as a whole reads. |
| `previewRecipe.module` | `type.yaml` `preview:` | How an instance's `preview.png` is produced: which of the four recipes (`instantiate`, `image`, `surface`, `custom`) the type declares, and what that recipe needs. |
## Reaching it
```luau
local rt = require("@builtin::assetTypes.assetType.shared")
rt.ref.loadTypeBehavior("material")
```
Fields resolve lazily. The prelude requires the sub-modules directly, in
dependency order (`ref`, then `changeDispatch`, `onRegister.install()`,
`refShapes.install()`) — a table that required all six on load would take that
ordering away from it.