# 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.
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()`.
Globals leak across reloads. 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**.
# postReference_focusBars
Four rows of bar pairs, 8 pairs across the top row and doubling on each row below: the focus chart a depth-of-field reading is taken off.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
·computeshader · born here
❒asset # loops_cut
Finds where each ring and chain of linked edges starts and ends. Stage 0 marks
the first edge of every list (a chain's head, a ring's smallest edge); stage 1
makes the edge before each first edge the end of its list. The lists that result
are what `jump` ranks. See `loops` for the whole sequence.
Over a live count (`COUNT=device`, see the abi README) the edges are the first
`domain_count` slots of a capacity `n`, and the `n` param is not read. A slot past
the live edges is no head (`head` 0) and ends its own list (`cut` is the slot itself).
It binds 7 storage buffers (6 in the plain variant).
# postReference_skyRamp
A sky-blue ramp of light from 0.02 to 0.6 across: a clear sky's gradient.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
·computeshader · born here
❒asset # hash
The first step of a spatial hash over a run of points: the bucket of the cell
each point stands in. The sort kernel orders the points by bucket, and
`hash_starts` then states where each bucket's points start and end in that
order. The keys, the order and the bucket spans, with the cell size, are the
index `hash_count`, `hash_nearest` and `hash_gather` search. Exact: the same
points give the same keys.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` slots are live. A slot at or past the live count holds the key
`0x7fffffff`, which is past every bucket: the sort (over the same live count, or
over the capacity) places it after every live key, and `hash_starts` over the
capacity states every bucket's span over the live points only. It binds 3 storage
buffers (2 in the plain variant).
# volumetrics
Volumetric (3D-texture) rendering, end to end, in one package. Built
entirely on the engine's generic `compute.*` GPU primitives — no
Rust changes are needed to author new volumetric content.
## Layout
| Asset | Identity | Role |
|---|---|---|
| `Volume.component` | `@builtin::systems.volumetrics.Volume` | Attach a 3D voxel texture to an entity; raymarches it through the entity's transform AABB. |
| `VolumetricSky.component` | `@builtin::systems.volumetrics.VolumetricSky` | Singleton procedural cloud layer with TAA. |
| `ParticipatingMedium.component` | `@builtin::systems.volumetrics.ParticipatingMedium` | Mark an entity as fog/smoke/dust that attenuates the light passing through it. |
| `mediaTransmittance.module` | `@builtin::systems.volumetrics.mediaTransmittance` | Light-space optical-depth map: the registry, the settings, and the basis the map is built in. |
| `mediaShadow.renderFeature` | `@builtin::systems.volumetrics.mediaShadow` | Builds the optical-depth map and attenuates each surface by the density in front of it. |
| `volume.module` | `@builtin::systems.volumetrics.volume` | Builders (`noise`/`sphere`/`box`/`wrap`) + the `.zvol` header reader + occupancy + brick paging + the per-entity raymarch dispatch. |
| `VolumeSequence.component` | `@builtin::systems.volumetrics.VolumeSequence` | Play an open volume sequence through an entity's transform AABB. |
| `volumeSequence.module` | `@builtin::systems.volumetrics.volumeSequence` | A run of `.zvol` frames streamed through a fixed ring of resident volumes. |
| `volumeDemos.module` | `@builtin::systems.volumetrics.volumeDemos` | Shared pipeline for the showcase scenes (fill + emissive raymarch + composite). |
| `volumetricSky.module` | `@builtin::systems.volumetrics.volumetricSky` | Cloud volume + raymarch + TAA + composite orchestration. |
| `shaders/*.shader` | `@builtin::systems.volumetrics.shaders.*` | `volume_raymarch`, `volume_pages`, `volume_pack`, `cloud_noise[_v3/_v5]`, `cloud_raymarch[_v3/_v4/_v5]`, `cloud_taa`. |
| `importers/vdb_to_zvol.importer` | (auto-discovered) | `.vdb` → dense `.zvol` via the `openvdb` WASM plugin (procedural fallback when the plugin isn't loaded). |
| `presets/cumulus_default.preset` | `@builtin::systems.volumetrics.cumulus_default` | Canonical full `VolumetricSky` weather preset. |
| `demo/*.scene` | `@builtin::systems.volumetrics.demo.*` | `sdf_solids`, `smoke_plume`, `nebula`, `godrays`, `zvol_viewer`, `sky`. |
## Path convention — fully-qualified builtin identities
Every intra-package reference uses the asset's fully-qualified builtin
identity, the same convention every other builtin package follows:
```luau
local Volume = require("@builtin::systems.volumetrics.volume")
local Sky = require("@builtin::systems.volumetrics.volumetricSky")
local V = require("@builtin::systems.volumetrics.volumeDemos")
-- shader identities, e.g. asset.resolve("@builtin::systems.volumetrics.shaders.volume_raymarch")
```
Qualified identities are caller-independent: they resolve identically
from a module, a scene entrypoint, or a component. Caller-relative
(`.sibling`) requires are deliberately avoided here because the
component runtime caller identity is `@builtin::components.<Name>`, so a
`.sibling` require from a component resolves against the wrong root.
(An earlier revision of this package used a `~volumetrics` package-root
alias for relocatability; that alias is not resolvable on current main,
so the package uses qualified identities throughout.)
## Usage
```luau
-- Per-entity volume. The component resolves the name through `Volume.get`,
-- so a volume paged into a brick pool renders from the pool under the same
-- name:
local Volume = require("@builtin::systems.volumetrics.volume")
local cloud = Volume.noise({ name = "cloud", size = 64, scale = 4 })
cloud:buildSparse({ brickSize = 8 })
cloud:releaseDense()
entity(id).component.add("Volume", { volumeName = "cloud", density = 6.0 })
-- Procedural sky:
local sky = entity.spawn("sky")
sky.component.add("VolumetricSky", {})
preset.apply("cumulus_default", { entity = sky.id, component = "VolumetricSky" })
-- VDB import: drop a `.vdb` into the VFS; the importer writes a `.zvol`
-- alongside it. Load it with the zvol_viewer demo scene.
-- Animated run: one `.zvol` per frame, played through a bounded ring.
local Seq = require("@builtin::systems.volumetrics.volumeSequence")
Seq.open({ name = "plume", frames = framePaths, resident = 3, fps = 24 })
entity(id).component.add("VolumeSequence", { sequenceName = "plume", density = 6.0 })
```
## Plugin dependency
The VDB importer delegates real OpenVDB parsing to the `openvdb` plugin
in the builtin library, `@builtin::plugins.openvdb`. Without the plugin
the importer falls back to a deterministic procedural torus so the
pipeline stays functional.
·computeshader · born here
❒asset # search
Binary search of a run of queries in a sorted column: the pick of a value from
a cumulative distribution, the segment of an arc length.
| Specialize | Options | Meaning |
|------------|---------|---------|
| `T` | `f32`, `i32` | the scalar the column and the queries hold |
| `SIDE` | `lower`, `upper` | which boundary a query answers |
`lower` answers the first place whose value is not below the query, `upper` the
first place whose value is above it, and both answer the length of the column
when no place qualifies. The greatest place whose value is not above a query is
`upper - 1`; with the cumulative sums of a run of weights, `upper` of a draw in
`[0, total)` is the index of the weight it lands in.
The column bound as `sorted` is the sorted run, every element of it. One thread
per query; the dispatch size `n` is the number of queries.
Exact: a search reads the column and nothing else, so the same inputs give the
same answers on every dispatch.
·computeshader · born here
❒asset # gather
Builds a column from another column and a run of indices: element `i` of the
result is element `index[i]` of `src`. An index below 0 or past the end of
`src` gives zeros. The element type is the `T` specialization (`f32`, `i32`,
and two to four lanes of either); a three-lane column is read and written
tightly packed, twelve bytes an element.
Dispatch over `n`, the number of indices. Exact: each result element has one
writer.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` slots are live: a slot at or past it holds zeros. It binds 4
storage buffers (3 in the plain variant), and `dst` holds `n` elements.
# Mesh
Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
·computeshader · born here
❒asset # contour_cells
Whether each cell of a grid of samples straddles the surface: its eight corner
samples are not all on one side of zero. `flag[c]` is 1 for a straddling cell
and 0 otherwise, the keep mask `compact` turns into the list of cells that own a
vertex.
Dispatch over the cells. Exact: each flag has one writer.
# Chrome
A polished chrome surface built on the `pbr` shader — fully metallic (`metallic: 1.0`) with a bright near-white base colour (`0.95, 0.95, 0.97`) and very low roughness (`0.05`) for mirror-sharp reflections. Opaque, back-face culled, instanced, with the `_METALLICSPECGLOSSMAP` keyword enabled.
## Inputs
- `colors.base_color` (`0.95, 0.95, 0.97, 1.0`) — bright, faintly cool chrome tint.
- `floats.metallic` (`1.0`) — fully metallic.
- `floats.roughness` (`0.05`) — near-mirror sharpness.
- `textures.base_color_texture` (`default:white`): the white base texture the colour multiplies against, so the surface renders `base_color` alone.
# pbr_layered
A surface composed from two complete PBR layers: a base, and a top layer laid
over it wherever coverage says so.
Rust over painted metal, snow over rock, mud over a vehicle, wear over a finish.
Pre-blending those into one texture set bakes the coverage in — it can no longer
change at runtime, and every entity wearing the material wears it identically.
Here both layers keep their own shading inputs and coverage is evaluated per
fragment, so the same material can be pristine on one entity and ruined on the
next.
## Coverage
Coverage is the product of three terms, each neutral by default:
| term | property | what it is for |
|---|---|---|
| mask | `top_mask_texture`, `top_mask_channel`, `top_mask_contrast` | *where* the top layer gathers — creases, edges, upward faces |
| material | `top_coverage` | *how far* the look has progressed, for every entity sharing the material |
| instance | `top_instance_lane`, `top_instance_component` | how far for *this* entity |
`top_coverage` defaults to 0, so a material that sets nothing renders as its base
layer alone.
`top_mask_contrast` shapes the mask: 1 is a linear ramp, higher values pull the
top layer back into the mask's brightest areas, which is what makes rust and snow
gather in creases instead of washing evenly over everything.
## Driving it per instance
Point the material at an `instanceData` lane, then write that lane per entity:
```lua
-- material: top_instance_lane = 0, top_instance_component = 0
local clean, rusted = entity.find("barrel_a"), entity.find("barrel_b")
if clean and rusted then
renderer.instanceData.set(clean, 0, 0.1) -- nearly clean
renderer.instanceData.set(rusted, 0, 0.9) -- heavily rusted
end
```
Both entities share one material and one draw path; only the lane differs.
## Texture slot budget
WebGPU guarantees 16 sampled textures per fragment stage and the engine's
group(0) already holds several. This shader declares **9**, which leaves room for
those plus a margin. Two full five-map layers would not fit, so the top layer
carries the three maps that make it read as a different material — albedo,
roughness/metallic, normal — and takes occlusion and emissive from the base.
Layer count is **two**. The cost is fixed and predictable: both layers are always
sampled, and coverage selects between their inputs rather than branching.
## Why the inputs blend rather than the results
Lighting each layer separately and adding puts more energy back out than arrived,
so a half-covered surface would read brighter than either layer alone.
Interpolating the shading inputs and lighting once cannot do that.
# Snow Particle
A soft, cold-white flake surface for falling-snow particle effects — a near-white base colour (`0.95, 0.97, 1.0`) with a cool blue-grey emissive glow (`0.25, 0.3, 0.4`) so flakes stay faintly visible in shadow. Transparent, double-sided (`cull: none`), and drawn in the transparent queue (`3000`). Built on `@builtin::shaders.snow_material`.
## Inputs
- `colors.base_color` — the cold-white flake tint.
- `colors.emissive` (`0.25, 0.3, 0.4`) — cool self-illumination that keeps flakes readable in dark scenes.
- `floats.roughness` (`0.8`) — matte, non-glossy flakes.
- `floats.metallic` (`0.0`) — fully dielectric.
·computeshader · born here
❒asset # abi_scale
Multiplies every element of src by the scale param into dst, one element per invocation.
# `referenceChart` surface shader
A reference chart drawn on a surface, unlit: each point holds light its
properties and its UV state, so a picture of the surface is measured against
known input. The post-verification reference scenes
(`@builtin::scenes.postReference.*`) are built from its materials
(`@builtin::materials.postReference.*`).
| `pattern` | Draws |
|---|---|
| 0 | A grey wedge: one column per whole stop from `evMin` to `evMax`, each middle grey (0.18) at that stop. |
| 1 | The 24 ColorChecker Classic patches, 6 x 4, each its published sRGB value read as linear reflectance. |
| 2 | A ramp from `low` at u = 0 to `high` at u = 1. |
| 3 | A Siemens star of `frequency` spokes, `high` on `low`. |
| 4 | A checker `frequency` cells across, `low` and `high`. |
| 5 | Focus bars: four rows of bar pairs, `frequency` pairs across the top row, doubling on each row below. |
Every pattern's light is multiplied by `color` and `gain`. UV (0, 0) is the
surface's top-left, as the front face of `@builtin::meshes.cube` maps it.
·computeshader · born here
❒asset # compute_fft_scale
Inverse-FFT `1/N` scale pass: divides every complex sample by the per-line N.
Run after the inverse FFT stages. Used by `nx.gpu.fft*`.
Bindings (see bindings.yaml): `data` (read_write `array<vec2<f32>>`), `params`
(read `array<f32>` — `[total_elements, inv_scale]`).
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_fft_scale", ...)` —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
# Gold
Polished gold — a fully metallic PBR surface with a warm yellow base colour
(`1.0, 0.84, 0.0`) and low roughness (`0.25`) for bright, sharp reflections.
Built on `@builtin::shaders.pbr`.
## Inputs
- `colors.base_color` — the gold tint.
- `floats.metallic` (`1.0`) — fully metallic.
- `floats.roughness` (`0.25`) — sharpness of the reflection; raise for a
brushed look.
·computeshader · born here
❒asset # abi_inout
Writes src doubled into dst, or adds src to the dst it is bound when mode is 1.
# Checkerboard
A procedural checkerboard pattern rendered by `@builtin::shaders.checkerboard`, alternating a red base colour (`1.0, 0.2, 0.2`) with a blue emissive colour (`0.2, 0.2, 1.0`). Opaque and non-metallic (`metallic 0.0`) at mid roughness (`0.5`) — useful as a UV / scale test surface.
## Inputs
- `colors.base_color` — the red square colour.
- `colors.dark_color` — the blue square colour.
- `floats.roughness` (`0.5`) — diffuse spread on the lit squares.
- `floats.metallic` (`0.0`) — dielectric surface.
# Custom Textured
A textured opaque surface built on `@builtin::shaders.custom_material`, sampling the `array_texture` builtin over a warm peach base colour (`1.0, 0.8, 0.6`). Non-metallic (`metallic 0.0`) at mid roughness (`0.5`) — a worked example of pairing a custom shader with an array texture.
## Inputs
- `textures.base_color_texture` (`@builtin/textures/array_texture`) — the sampled array texture.
- `colors.base_color`: the warm peach colour the texture is multiplied by.
- `floats.roughness` (`0.5`) — diffuse spread.
- `floats.metallic` (`0.0`) — dielectric surface.
# Sky Procedural
A fully procedural atmospheric sky with a day/night cycle, built on `@builtin::shaders.procedural_sky`. Renders with no culling and no depth write behind all geometry (queue `1000`), computing gradient, sun, moon and stars analytically from its parameters — no texture required.
## Inputs
- `properties.zenith_color` / `horizon_color` / `ground_color` — the atmospheric gradient from overhead (`0.1, 0.3, 0.6`) through the horizon (`0.5, 0.7, 1.0`) to the ground (`0.3, 0.25, 0.2`).
- `properties.sun_intensity` (`20`) / `sun_size` (`0.02`) — brightness and disc size of the sun.
- `properties.turbidity` (`4`) — atmospheric haze / scattering density.
- `properties.stars_intensity` (`1`) / `moon_size` (`0.03`) — night-sky star brightness and moon disc size.
# `fog` post-process shader
Depth-keyed distance haze. `pp.add(name, "fog", { density = ..., color = { r, g, b } })`
registers it, and `asset.resolve("@builtin::shaders.post.fog", "shader"):getProperties()`
reads the knobs below before it is added.
The pass reads the scene depth already drawn at a pixel, turns it into a distance
in metres with `zero_linear_depth(d, near, far)`, and mixes the frame toward
`fogColor` by `1 - exp(-distance * density)` — an exponential falloff, so density
sets how many metres of air it takes to reach the fog colour.
`near` and `far` are the planes the frame was projected through. They are what a
stored depth is turned back into metres by, so they belong to the camera the
scene was drawn with rather than to the look: setting them to something the
camera does not use moves every surface's distance and with it the whole haze.
| Property | Meaning |
|---|---|
| `density` | Falloff rate. 0 leaves the frame untouched. |
| `fogColor` | The colour a fully fogged pixel reaches. |
| `near` | The scene camera's near plane, in metres. |
| `far` | The scene camera's far plane, in metres. |
# Sky Cubemap
A cubemap sky/environment background built on `@builtin::shaders.cubemap_sky`. Renders with no culling and no depth write behind all geometry (queue `1000`), sampling the built-in `Ryfjallet_cubemap` with adjustable rotation and exposure.
## Inputs
- `textures.sky_texture` — the cubemap sampled as the sky (`Ryfjallet_cubemap`).
- `floats.rotation` (`0.0`) — yaw rotation of the sky around the vertical axis.
- `floats.exposure` (`1.0`) — brightness multiplier applied to the sampled colour.
·computeshader · born here
❒asset # compute_add_vectors
Reference compute shader that adds two float arrays element-wise into a third —
the multi-buffer pattern with read-only inputs.
Bindings (see bindings.yaml): `a` (read), `b` (read), `result` (read_write) — all
`array<f32>`.
Usage: dispatch by identity — it resolves to the shader's stable guid and
auto-compiles on first use (no setup):
`compute.dispatch("@builtin::shaders.compute_add_vectors", { buffers = { "a", "b", "result" }, workgroups = { 1, 1, 1 } })`.
·computeshader · born here
❒asset # map
The per-element kernel: `dst[id] = TEMPLATE` over `n` elements. The template is
a WGSL expression over `p` (the element's position), `id`, the numbers `u_get(k)`
and the columns of the `cols` table; the preludes `rand`, `noise` and `color`
supply the functions a template calls. `fieldc.mapSpec` writes a chain of field
templates as one function, so a chain of any length is one dispatch.
Specialize `T` (f32, i32, vec2, vec3 or vec4 of f32), `TEMPLATE`, and optionally
`PRELUDE` and `POSITION`. Bind `cols` (a table from `compute_abi.table`) and `u`.
The output `dst` holds `n` elements of `T`, tightly packed.
```luau
local program = ref:program()
local variant = program:variant({ specialize = { T = "f32", TEMPLATE = "zero_rand(7u, id)",
PRELUDE = '#include "@builtin::systems.procgen.kernels.rand"' } })
local run = variant:run({ n = 64, inputs = { cols = emptyTable, u = numbers } })
```
`fieldc.evaluate(field, domain)` runs a Field through this kernel and answers the Column it wrote. Leaves of i32 runs are read through `cols_i32` and a read past a run's end reads its last element.
# lightCookies
Projects an authored image through a spot light's cone — a gobo, window blinds,
a headlight cutoff, a projector pattern.
## How it divides up
The renderer already projects a texture through a spot's frustum. At each shaded
point it reads `zero_feature_texture(uv, cookieLayer)`, with `uv` from that
point's position in the light's own clip space, and multiplies the cone by what
it finds. `SpotLight.cookieLayer = -1` means no cookie.
What the renderer does not decide is what goes in the layer. That is this
package: resample an authored image into one full layer of the shared
feature-texture array, and point a spot at that layer.
## Using it
```luau
local lightCookies = require("@builtin::systems/lightCookies.package/lightCookies")
-- Size the array once for every layer the scene will use.
lightCookies.configure({ resolution = 256, layers = 4 })
lightCookies.project(lampId, "/textures/cookies/window_blinds.png", { layer = 0 })
```
Or attach a `LightCookie` component next to the `SpotLight` and author
`texture` / `layer` / `gain` / `tint` on it.
`lightCookies.clear(lampId)` stops the projection; the layer keeps its contents.
## When a fill lands
`fill` and `project` queue the fill and return its layer at once. The module's
own loop writes it over the frames that follow: the rasterize is issued on the
next frame and the copy into the layer on the frame after, and the fill is
written once `renderer.featureTexture.state().fills` reports the copy landed in
its layer, one fill at a time in the order they were asked for. The loop belongs to the module, so a fill
lands even when the code that asked for it (a one-shot script, a task scope, a
component that is destroyed) has ended.
`lightCookies.status(layer)` reports where the last fill of a layer stands:
```luau
local s = lightCookies.status(0)
-- s.state: "queued" | "rasterizing" | "copying" | "written" | "refused"
-- s.reason: why a refused fill was refused, in the engine's words
-- s.filled: whether renderer.featureTexture.state().filled lists the layer
```
`status` reads a fill `"written"` from the first reading of the array that
reports its copy landed, so `s.state` and `s.filled` agree whichever of the
module's loop and the reader runs first in a frame.
A fill names a layer below the count `configure` sized the array to; one past
it is refused at the call, which returns nil and the reason. A fill that cannot
land once it is on its way (the GPU refuses its rasterize because its image was
given back first, a later `configure` left the array without its layer, or its
copy never reached the array) reads `"refused"` with the reason, and is also
logged as a warning.
A `LightCookie` component whose fill is refused at the call, such as one
authored before the scene's `configure` has sized the array, asks again each
time `configure` sizes it. `lightCookies.observe().configurations` counts
those calls for code of its own that does the same.
`lightCookies.observe()` reports how many fills are waiting, the one in
progress, and the loop's own counters.
## An empty layer puts the light out
The cone is multiplied by what it reads from its layer, so a spot pointed at a
layer nothing has filled renders black rather than plain. `project` fills before
it points the light, which is the order that keeps the cone lit; if you set
`SpotLight.cookieLayer` by hand, fill that layer first.
## The array is shared, and sizing it is explicit
The feature-texture array is one resource that every feature using
`zero_feature_texture` draws layers from, and it has no allocator: sizing it
zeroes every layer, including layers another feature owns. So this package never
sizes it as a side effect of setting a cookie, and `layer` is authored rather
than assigned. `lightCookies.configure` is the one call that resizes, made once
by whoever knows what else in the scene wants layers.
A scene that also bakes global illumination shares this array with the lightmap
atlas. Size it for both, and give cookies layers above the ones the bake fills.
## A cookie fills a whole layer
The cone's lookup runs over the layer's entire `uv` range, so an image is
resampled to the layer's extent rather than placed in a corner of it. One layer
carries one cookie.
## Alpha
The source's alpha is how much of the pattern applies. At alpha 0 the cone
passes through unmodulated, so a fully transparent image is a no-op rather than
a black cone.
·computeshader · born here
❒asset # compute_snow_terrain
GPU heightmap generation for a snowy mountain landscape. One thread per `(x, z)`
column, emitting a single `f32` height per cell. Uses multi-octave FBM for hills,
ridge noise for peaks, and a radial bowl to frame a mountain valley.
Bindings (see bindings.yaml): `params` (read `array<f32>` — `[gridSize,
worldExtent, seed, mountainScale, baseHeight, ridgeStrength, ...]`), `heights`
(read_write `array<f32>`, indexed `[z * gridSize + x]`).
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_snow_terrain", ...)` —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
# Default Unlit
A flat, unlit surface that renders its base colour directly with no lighting response, built on the `unlit` shader. Uses a white base colour (`1.0, 1.0, 1.0`) over the `default:white` texture with `emissive` (`1.0`) for full brightness — the go-to default for UI, gizmos, and debug geometry that must stay legible regardless of scene lighting.
## Inputs
- `colors.base_color` — the flat colour shown directly.
- `textures.base_color_texture` (`default:white`) — the white base texture the colour multiplies against.
- `floats.emissive` (`1.0`) — full, lighting-independent brightness.
·computeshader · born here
❒asset # concat
Joins one attribute of several geometries into one column. `sources` is a column
table with one column per geometry, in order; `desc` says where each geometry's
elements start in the result, how many it has, how far to shift each word of a
linkage column, and whether the geometry holds the attribute at all. Where it
does not, its elements take the default stated in the first four words of
`desc`.
Linkage is a shift: `vertex.pt` takes the number of points before the geometry,
`primitive.vstart` the number of vertices before it. Any other attribute shifts
by 0. A node joins a whole geometry by running the kernel once per attribute of
the union of the geometries' attributes.
Dispatch over `n`, the elements of the joined domain. Exact: each result
element has one writer.
# restirLighting
Direct light from many small sources at a cost that does not grow with how many
there are.
A shading pass that loops every light pays for every light at every pixel, which
is why the number of lights has to be capped. Resampled importance sampling
breaks that link: each pixel draws a few candidates, keeps ONE of them with a
probability proportional to what it would contribute, and carries a weight that
makes the survivor stand for the whole set. What it keeps is then reused — by its
neighbours this frame, and by itself on the next one — so the set a pixel
effectively samples keeps growing while the number of candidates it draws stays
where you put it.
A cave of glowing crystals, a street of practicals, a control room of indicator
lamps: hundreds of sources, and each pixel looks at about a dozen.
## Using it
Put an `EmissiveSource` on the geometry that glows:
```lua
local id = entity.spawn("crystal", { position = { 2, 1, 0 } }).id
entity(id).component.add("EmissiveSource", {
color = { 0.3, 0.8, 1.0 },
intensity = 8.0,
radius = 6.0,
size = 0.4,
})
```
Or register sources from a script, which is how a generated scene does it:
```lua
local restir = require("@builtin::systems.restirLighting.restirLighting")
for i = 1, 400 do
restir.set(`lamp{i}`, {
position = { math.random() * 60 - 30, 1.5, math.random() * 60 - 30 },
color = { math.random(), math.random(), math.random() },
intensity = 4.0,
radius = 5.0,
})
end
```
The pass starts with the first source and stops with the last. Settings are on
`restir.configure`, or on a `ResampledLighting` component for a scene to author:
```lua
restir.configure({ candidates = 16, spatialSamples = 6 })
```
## What a pixel pays
`candidates + spatialSamples + 1` evaluations, reported by
`restir.perPixelCost()`. None of those terms is the source count.
The estimate is formed on a grid of one cell per 2x2 pixels (`resolution =
"full"` gives every pixel its own cell), across four passes:
| Pass | Runs over | Does |
|---|---|---|
| `restir_sample` | grid cells | draws `candidates` sources at random, resamples to one, merges the cell's own history |
| `restir_spatial` | grid cells | borrows from `spatialSamples` neighbours, each evaluated against this cell's surface |
| `restir_resolve` | pixels | shades the chosen source with the pixel's own normal, roughness and albedo |
| `restir_denoise` | pixels | averages that light over the cells around the pixel and composites it |
Which source to look at is a low-frequency decision a cell of pixels can share.
What the surface does with it is not, and is computed per pixel.
One source per cell is correct on average and different from its neighbour,
which is the grain a single sample carries. `restir_denoise` averages across the
cells around a pixel, weighing each by how nearly its surface is this one, so the
estimate keeps its value and loses its variance.
`mode = "reference"` replaces the reservoir lookup with a loop over every
registered source at every pixel. That is the picture the resampled mode is
estimating and the cost it is measured against — the same shading, the same
filter and the same composite, so the two are comparable directly.
## Temporal reuse
A cell keeps its reservoir across frames and merges it with the fresh
candidates, so a good find keeps paying after the frame that made it. The stored
world position is what says the cell is still looking at the same surface; a
camera move or an occluder passing in front fails that test and the history is
dropped rather than smeared.
`historyCap` bounds how many candidates the history is allowed to stand for.
Without it a converged cell would outvote every new candidate forever and a
lighting change would never work its way out. At the default of 20 a change is
absorbed over roughly twenty frames.
Removing a source, or turning its `intensity` down to 0, releases it; the pass
stops with the last one.
## Where it sits
Sources registered here are additional to the lights the engine holds rows for.
The passes run in `afterLighting` at orders 80-84 and add to the scene as it was
drawn, reading position, normal, albedo and metallic-roughness back out of the
G-buffer.
A source lights every surface within `radius` that faces it, along the straight
line between them.
## One frame, several targets
A render feature's `render` runs once a frame, and the passes it enqueues run
once per render target — the window, an offscreen capture, a camera rendering to
a texture. Each pass therefore reads the frame size out of the textures it is
handed and works out its own cell grid, so every target resamples at its own
resolution. A reservoir carries the grid width it was written under, which is
what stops one target's history being read as another's.
The reservoir buffers are sized to the widest grid any target has asked for. A
target wider than they have yet been sized for reports the grid it needed, and
the frame after that covers it.
## Reading what it did
`restir.stats()` returns the counters the passes keep on the GPU for the most
recent frame a read-back has landed for, carrying that frame's number so a
repeated read is distinguishable from a fresh one. `meanWeight` is counted in
sixteenths with each cell capped at 16 so the total fits a 32-bit counter;
`peakWeight` alongside it is exact to a thousandth, and is where an estimator
that has come loose shows first.
·computeshader · born here
❒asset # grid
Reads and writes a field of cells in one kernel. The field is a Grid (one tile,
no apron, x fastest, `lanes` values per cell) or a Raster (tiles with aprons,
one batched dispatch) through the layout in `tile_layout`.
- sample (`MODE sample`): the field at positions, nearest or trilinear, held to the
edge cell past the field. Reads each cell from the tile that owns it.
- write (`MODE write`): a patch of values blended into the field (replace, add,
max, min, multiply, optionally weighted per cell). Every tile that holds a cell
as core or apron receives it, so apron copies agree. The patch window is stated
in field cells and may reach past the field (negative origin, or a size beyond
the cell counts): a stored cell a border tile holds past the field takes the
patch where the window covers it.
- stencil (`MODE stencil`): per stored cell, a neighbour at an offset, slope in
degrees, curvature (the laplacian over x and z) or the gradient, with neighbour
reads held to the tile's own stored edge. Slope and curvature are the terrain
mask's.
`MODE`, `SAMPLING` (nearest, trilinear), `STENCIL` (offset, slope, curvature, gradient) and `BLEND` (replace, add, max, min, multiply) are specializations.
`determinism: exact`: each output element has one writer. The bindings a mode
does not use take any buffer that is not bound elsewhere in the dispatch.
·computeshader · born here
❒asset # topology
Mesh edit operations over a geometry's linkage (`vertex.pt`, `primitive.vstart`,
`primitive.vcount`), selected by the `OP` specialization (`split_edge`, `collapse_edge`, `insert_face`, `delete_face`, `split_vertex`), each stage by `STAGE` (`count`, `write`): split an edge (insert a point),
collapse an edge (merge two points and drop the faces that degenerate), insert a
face, delete a face, split a vertex (give a group of corners a point of their own).
Each operation runs in two stages with an exclusive prefix sum between them. Stage 0 writes
`cnt`, how many output vertices each primitive contributes (each vertex, for split
vertex). The prefix sum of `cnt` is `off`. Stage 1 writes the output vertices'
points (`o_pt`) and where each came from (`o_src`). The output primitives are
`off` as run starts and `cnt` as run lengths; a primitive with an empty run is gone,
and the select node removes it. The shader's header states the records each
operation reads.
The operation's records come from the edge table: for split edge, the point
for each split edge gathered to the vertex slots through `edges`' side slots
(both faces of an edge name the same point); for collapse, the point each
point becomes, from an independent set of edges. The point an inserted
vertex or a split vertex stands for is carried by the output maps: `o_src` names the vertex
whose attributes an output vertex takes (negative when it is new, with ~v the
vertex a split inserted after), and the compaction of the records names each
new point's source. Integers are 32-bit words, exact.
# grass_material.shader
Grass, shaded root to tip with per-blade colour variation and a soft
half-lambert wrap.
The colouring reads `uv.y` as height along a blade — 0 at the root, 1 at the tip
— and darkens the roots while warming the tips. Per-blade variation comes from a
hash of the fragment's world xz on a 10 cm grid, so every fragment of one blade
shares a seed and neighbouring blades drift apart in hue and brightness. The
lighting is a diffuse half-lambert wrap kept below saturation, so this shader
returns its own final colour instead of a PBR surface.
`sway` is how far the vertex stage bends each vertex along its blade, and it is
what tells this shader that its mesh is a blade mesh: the bend scales with
`uv.y²`, so a vertex at the root holds still while the tip swings hardest. It
defaults to 0, at which every vertex arrives where the mesh put it — a material
that leaves it there shades a surface without moving it. `@builtin::materials.grass`
is that ground surface; `@builtin::materials.grass_blades` sets `sway` to 1 for a
blade mesh.
## Properties
- `base_color` — the grass green the root→tip gradient is built from.
- `sway` (`0`..`4`, default `0`) — how far each vertex bends along its blade.
·computeshader · born here
❒asset # contour_triangles
Each kept quad as two triangles: `pt` holds, per quad, the vertex numbers of
its corners (`a b c`, `a c d`), and `vstart` the position of each triangle's
first corner in `pt`. Slot `n` of the dispatch is the `n`-th quad `edges[n]`
names, so the quads are numbered in edge order.
Dispatch over the kept quads. Exact: each slot has one writer.
# Emissive White
A bright white light-emitting PBR surface built on the `pbr` shader with the `_EMISSION` keyword enabled. A white base colour (`1.0, 1.0, 1.0`) paired with a strong `emissive` (`20.0`) makes it glow and drive bloom — well suited to light fixtures, emitters, and glowing accents. Non-metallic (`metallic 0.0`) at mid roughness (`0.5`).
## Inputs
- `floats.emissive` (`20.0`) — high emission strength that produces the glow.
- `keywords: _EMISSION` — enables the emissive path in the PBR shader.
- `colors.base_color` — the white surface and emission colour.
- `floats.roughness` (`0.5`) — diffuse spread on the lit surface.
# gpuSort
A stable least-significant-digit radix sort, run entirely on the GPU, over a
caller-owned array of u32 keys.
The three passes here are the body of one radix digit. They read a key array and
a permutation and write a new permutation; they never touch whatever the keys
describe, so any subsystem with a key per item can drive them. The caller
supplies the keys, the identity seed, the per-pass constants and the dispatch
sequence.
## One pass
| Order | Shader | Dispatch |
|-------|--------|----------|
| 1 | `radix_hist` | one workgroup of 256 per 256 items |
| 2 | `radix_scan` | `{ 1, 1, 1 }` |
| 3 | `radix_scatter` | one workgroup of 256 per 256 items |
Each pass sorts on one 8-bit digit and keeps the relative order of items sharing
that digit, so `ceil(bits / 8)` passes over the low digits upward compose into a
total order on `(key, item index)`.
## Driving it
The caller owns six buffers: the keys, two permutation buffers the passes
ping-pong between, the digit histogram (`ceil(count / 256) * 256` entries) and
one constants buffer per pass. A pass reads its constants as
| Word | Meaning |
|------|---------|
| `[0]` | item count |
| `[1]` | block count, `ceil(count / 256)` |
| `[2]` | this pass's digit shift — `0`, `8`, `16`, `24` |
| `[3]` | `1` on the last pass, `0` otherwise |
| `[4]` | the key a dropped item carries |
Every value is fixed for the life of the sorted array, so the constants are
written once rather than re-uploaded per frame.
Each pass flips which buffer holds the permutation, so the parity of the pass
count decides where the caller seeds the identity for the last scatter to land
in the buffer the consumer reads.
An item the caller wants dropped takes a key at or past `[4]` — one past the
last real key — which parks it in the tail of the permutation; the last pass
resolves it to `0xffffffff`, and the consumer reads that as "this slot draws
nothing". A fixed dispatch size with a degenerate tail is what lets a consumer
issue a constant draw with no read-back and no indirect arguments.
·computeshader · born here
❒asset # rt_ao_apply
Multiplies the denoised occlusion into the scene colour.
## Bindings
| name | kind |
|------|------|
| `scene_color` | `texture2d` |
| `ao_clean` | `texture2d` |
| `applied` | `storage2d (rgba16f)` |
·computeshader · born here
❒asset # sort
A stable radix sort of a column's keys into a permutation: place `s` of `perm`
holds the index of the element that sorts `s`-th, so a gather by `perm` puts
any column in key order.
| Specialize | Options | Meaning |
|------------|---------|---------|
| `KEY` | `f32`, `i32` | the scalar a key holds |
Elements with equal keys keep their run order, in both directions
(`params.descending` 1 sorts from the greatest key down), and `-0` and `+0` are
one key. The sort works 4 bits of the key at a time from the least significant
up, and a pass whose digit is the same in every key is skipped, so a run of keys
inside a narrow range takes fewer passes. `work` is the sort's second
permutation; its contents after a dispatch are not an answer.
The dispatch size `n` is the number of keys. One workgroup of 128 works the whole
run; the other workgroups of a larger dispatch return.
Exact: the sort is a function of the keys and their order, so the same keys give
the same permutation on every dispatch.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` keys are live: they are sorted, and a slot at or past the live
count holds its own index in `perm`. A live count of 0 sorts nothing and `perm` is
the identity. It binds 4 storage buffers (3 in the plain variant).
·computeshader · born here
❒asset # compute_ocean
Ocean wave simulation. Displaces a mesh's vertex buffer in place by a sum of
Gerstner waves, recomputing each normal analytically from the wave derivatives.
`steepness` sets how far the surface travels along each wave's direction as well
as up. At `0` every vertex stays on its rest column and the result is a plain
sine height field; raising it sharpens crests and broadens troughs, which is the
shape that reads as a wave rather than a ripple. Values above roughly `1 /
(frequency * amplitude * wave_count)` make the surface self-intersect.
Bindings (see bindings.yaml): `vertices` (read_write `array<u32>` — the mesh
vertex buffer, 76 bytes/vertex, bitcast to f32), `params` (read `array<f32>` —
`[time, grid_size, amplitude, frequency, wind_x, wind_z, steepness, pad]`).
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_ocean", ...)` each frame —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
·computeshader · born here
❒asset # compute_fft_copy
Copies a `vec2<f32>` (re, im) buffer element-wise. Used by `nx.gpu.fft*` to seed
the ping-pong scratch buffer from the caller's input on stage 0 without an extra
ping-pong dispatch.
Bindings (see bindings.yaml): `src` (read), `dst` (read_write) — both
`array<vec2<f32>>`.
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_fft_copy", ...)` —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
# Water
An animated water surface with a deep blue base colour (`0.1, 0.3, 0.8`) and low roughness (`0.2`) for glossy, reflective highlights, driven by a scrolling normal map for wave detail. Opaque, back-face culled, instanced, in the opaque queue (`2000`). Built on `@builtin::shaders.water_material`, sampling `@builtin/textures/water_normals`.
## Inputs
- `colors.base_color` (`0.1, 0.3, 0.8`) — the water body colour.
- `floats.roughness` (`0.2`) — low roughness for sharp specular reflections.
- `floats.metallic` (`0.0`) — dielectric surface.
- `textures.normal_texture` — the wave normal map (`@builtin/textures/water_normals`).
# postReference_chrome
A polished metal: its highlight of a bright light is a sub-pixel specular, the firefly a bloom and a temporal resolve are read on in the post-verification reference scenes.
·computeshader · born here
❒asset # bvh_codes
A 30-bit Morton code for each primitive of a geometry: its bounds centre,
normalized inside the scene bounds and interleaved bit by bit. Sorting
primitives by this code puts primitives that are near in space near in the
order, which is what the `bvh` kernel builds its tree from. The scene bounds are
a min and a max reduce of the points. Exact.
·computeshader · born here
❒asset # make
Builds the elements and the primitives of a geometry from a count per owner and
a shape (`points`, `strip`, `fan`, `grid`, `ring`, the `SHAPE` specialization).
The result is the columns a Geometry holds: `P` over the points, `vertex_pt` over
the vertices (the point each reads), and `prim_vstart` / `prim_vcount` over the
primitives (each one's run of vertices). All indices are into the result, so
owners' pieces sit end to end with their links already offset.
It runs as two passes of one shader (`PASS`): `sizes` writes the points,
vertices and primitives each owner makes; after a prefix sum of each component
into `bases`, `fill` writes every element once, found by a binary search over the
bases. Exact: each output element has one writer. The shape's layout is stated
at the top of `bindings.yaml`.
# Grass blades
Swaying grass for a blade mesh, built on `@builtin::shaders.grass_material` with
the same green as `@builtin::materials.grass` (`0.22, 0.62, 0.16`) and `sway` at
`1.0`. The shader bends each vertex along its blade in proportion to `uv.y²`, so
this material belongs on a mesh whose `uv.y` runs 0 at a blade's root to 1 at its
tip — a merged field of blades, each a cross of two tapered quads. It inherits
the Rust-side render defaults (opaque, back-face culled, queue `2000`) so its
pipeline matches the library variant compiled at startup.
## Inputs
- `colors.base_color` (`0.22, 0.62, 0.16, 1.0`) — the grass green tint.
- `floats.sway` (`1.0`) — the full blade bend. `@builtin::materials.grass` leaves
it at the shader's default of `0` for a ground surface.
# Text Default
The default surface for Text3D — a white base colour (`1.0, 1.0, 1.0`) drawn with alpha blending and no depth write so glyphs composite cleanly over the scene. Transparent, double-sided (`cull: none`), `depth_write: false`, in the transparent queue (`3000`). Built on the `pbr` shader.
## Inputs
- `colors.base_color` (`1.0, 1.0, 1.0`) — the glyph colour.
- `render.depth_write` (`false`) — glyphs blend without occluding each other.
- `render.cull` (`none`) — text is visible from both sides.
- `floats.roughness` (`0.5`) / `floats.metallic` (`0.0`) — dielectric defaults.
# procedural_sky
The editable atmospheric sky: a day/night gradient with a sun disc and
glow, a procedural star field, and a moon opposite the sun, authored
entirely from material properties — no texture backs it.
Day, night and the dawn/dusk blend all derive from the directional
light's elevation, so the sky follows whatever drives the scene's sun;
there is no time-of-day uniform. The gradient's zenith, horizon and
ground colours, the sun's size and intensity, the stars, the moon,
turbidity and exposure come from `properties.yaml`.
Output is radiance scaled by `exposure` — the scene's own tone-mapping
does the range compression, the same contract as every sky-domain
shader.
The `ProceduralSky` component owns the runtime material over this shader
(`__procedural_sky`) and pushes its fields here; `sky.get()` reports the
resulting configuration.
# error_marker
The surface of the ERROR sign: the magenta and dark purple world-space checker
the engine's error pipeline draws, as an unlit surface shader. The
`error_marker` material draws the sign with it.
# Grid Background
A procedural background/reference-grid surface built on `@builtin::shaders.grid_bg`. It draws grid lines over a black base colour (`0.0, 0.0, 0.0`) with full roughness (`1.0`) and no metallic response, rendered opaque with culling disabled (`cull: none`) and instancing enabled so it can back many objects at once.
## Inputs
- `colors.base_color` (`0.0, 0.0, 0.0, 1.0`) — black backdrop behind the grid lines.
- `floats.roughness` (`1.0`) — fully diffuse, no highlights.
- `render.cull` (`none`) — visible from both faces.
- `render.instancing` (`true`) — supports instanced draws.
·computeshader · born here
❒asset # compute_tree_placement
GPU vegetation placement over a terrain heightmap. One thread per `(x, z)` cell:
reads the height, computes local slope, and uses noise-based density to pick what
grows (0 = nothing, 1 = tall pine, 2 = small pine, 3 = shrub, 4 = rock).
Bindings (see bindings.yaml): `params` (read `array<f32>` — `[gridSize,
worldExtent, seed, treeLine, slopeLimit, shrubLine, ...]`), `heights` (read
`array<f32>`), `placement` (read_write `array<f32>`, the per-cell type code).
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_tree_placement", ...)` —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
# Standard Default
The baseline PBR surface — a neutral white base colour (`1.0, 1.0, 1.0`), half roughness (`0.5`), non-metallic (`0.0`), wired with the full standard texture set (base colour, normal, roughness-metallic, emissive, occlusion) and the `_NORMALMAP` / `_OCCLUSIONMAP` keywords enabled. Opaque, back-face culled, instanced, in the opaque queue (`2000`). Built on `@builtin::shaders.pbr`. This is the starting point most materials copy and retint.
## Inputs
- `colors.base_color` (`1.0, 1.0, 1.0`) — the albedo tint over the base colour texture.
- `floats.roughness` (`0.5`) / `floats.metallic` (`0.0`) — dielectric, mid-gloss default.
- `floats.normal_strength` (`1.0`) / `floats.ao_strength` (`1.0`) — normal-map and occlusion intensity.
- `textures.normal_texture` / `textures.roughness_metallic_texture` / `textures.occlusion_texture` — the PBR map slots, seeded with neutral defaults.
·computeshader · born here
❒asset # intersect_pairs
The entries of two meshes that cut each other. One thread per triangle of mesh A walks the bounding volume
hierarchy of mesh B (the `bvh` family builds it, one primitive a triangle) and, for every triangle of B whose
bounds overlap, lists each part of the cut of the two triangles that `intersect_core` states (the ordinary
cut, the coplanar clips, the points on shared edges).
An entry is three words: `a`, `b` and the part. Two stages with an exclusive prefix sum (the `scan` kernel)
between them: `STAGE count` writes how many entries each triangle of A has, `STAGE write` writes the entries
at the offsets the sum gives, ordered by `a` and, within a triangle of A, in the order the tree is walked and
the parts of a pair in increasing order. Exact: the entries and their order are the same on every run.
Bind `apts`, `atri`, `bpts`, `btri`, `nodes` and `start` (any buffer in the count stage); params `nb`
(triangles of B) and `total` (the sum of the counts, which sizes `pairs`, three words an entry).
## The intersect family
`intersect` is a kernel family: `intersect_pairs`, `intersect_cuts`, `intersect_unify` and
`intersect_retri` (shared by `intersect_core`). Two triangulated meshes A and B go in; the pieces of
both, cut along their common curve and along the regions they share, come out. A node composes the family
with `bvh`, `scan`, `sort`, `compact` and `gather`:
1. Build the hierarchy of B (`bvh_codes`, `sort`, `bvh`, `bvh_pyramid` per level, `bvh_internal`), one
primitive a triangle (`vstart` 3 t, `vcount` 3).
2. `intersect_pairs` `STAGE count`, an exclusive `scan` of the counts, `STAGE write`: `pairs` (a, b, part),
ordered by a. `total` is the scan's total, the number of entries.
3. `intersect_cuts` over `total` entries: the endpoint records, slot `2 * entry + e`. Word 0 to 2 of a record
are the position as f32 bits.
4. `intersect_unify` (three stages) over `2 * total` slots: `rep`. `compact` of the slots with
`rep[s] == s` numbers the cut points; a cut endpoint's point is the number of `rep[s]`, and its
position is the record's position.
5. `intersect_retri` for A with `runs` from the counts and `start` and `order` the entry indices, `side` 0,
then for B with the entry indices stably sorted by b (`sort` on the b words) as `order`, `runs` the first
and count of each b and `side` 1. `STAGE count`, `scan`, `STAGE write`. Vertex references at or above
`npts` are cut endpoint slots, mapped through `rep`.
The pieces of each mesh share the cut points, so the two results agree along the curve and along the
boundary of every shared region. Each piece lies on one side of the other mesh, or on its surface.
## What a boolean reads
A boolean keeps pieces by what lies just outside and just inside each piece's centre, probed along the
piece's normal against the other mesh (`ray` winding at both probe points). Pieces on the other mesh's
surface read the same way:
- Same normal (the two surfaces coincide and face one way): the probe outside the piece is outside the other
mesh and the probe inside it is inside the other mesh.
- Opposite normals (the surfaces coincide and face each other): the probe outside the piece is inside the
other mesh and the probe inside it is outside.
| Operation | Pieces of A kept | Pieces of B kept |
|---|---|---|
| union | outside probe outside B | outside probe outside A and inside probe outside A |
| intersect | inside probe inside B | outside probe inside A and inside probe inside A |
| subtract (A minus B) | inside probe outside B | outside probe inside A and inside probe inside A, flipped |
A region shared with the same normal is kept once from A in a union and an intersection and dropped from
both in a subtract; a region shared with opposite normals is dropped from both in a union and an
intersection, and kept from A in a subtract.
# `retarget` module
`require("modules.retarget")` — skeletal animation retargeting in readable Luau.
Map a clip authored on one humanoid rig onto another, preserving the target's
shape. The behaviour lives here, in Luau, so an agent can follow and tweak it.
## How it works
Each rig maps onto the humanoid avatar type — a role → bone map derived from the
skeleton's structure, with the author's overrides laid over it (`rig:qualify()`,
see the `rig` asset type). Retarget is two steps:
1. **Bone map** — source bone → its role → the target bone filling that role.
Roles are the shared vocabulary, so any two rigs interoperate through their
mappings without a per-pair table.
2. **Shape-preserving transfer** — the target keeps its own bone lengths and rest
orientations; the animation contributes only delta-from-rest motion. Rotations
are bind-pose-corrected (the target reproduces the source's world-space motion
relative to its own rest). Only the pelvis and the root carry translation: the
pelvis's offset is taken through its animated source parent, stood on the axis
the source stands along, sized by the leg-length ratio (thigh plus shin, the
same in every pose) and re-expressed in the target pelvis's animated parent
frame, then applied relative to the target's bind. A source root's travel rides
the target root, or folds onto the target pelvis when the target has no root.
Every other bone keeps the target's own offset, so no limb or spine stretches.
Retarget is **cold**: `bake` once per (clip, target rig) and cache; the hot path
just samples the baked clip, exactly like a native one.
## Surface
- `parseRig(rig)` → enriched rig. Accepts a parsed `.rig` table, a `.rig` JSON
string, or an already-parsed rig (idempotent).
- `plan(srcRig, tgtRig)` → `{ mapped, unmappedSource, unmappedTarget, … }` —
which roles map across the rigs, and which don't (the diagnostic).
- `bake(clip, srcRig, tgtRig)` → a decoded clip table in the target's bone space.
`clip` is a decoded clip (`{ name, duration, channels, bone_names }`).
- `bakeBytes(clipBytes, srcRig, tgtRig, cacheKey?)` → retargeted clip `zanim`
bytes, with an in-memory cache keyed by `cacheKey`.
- `loadRig(ref)` → parsed rig from a `.rig` asset.
- `clearCache(cacheKey?)` → drop cached bakes (call after editing a rig profile).
## Example
```lua
local retarget = require("modules.retarget")
local src = retarget.loadRig(asset.ref("synty_character", "rig"))
local tgt = retarget.loadRig(asset.ref("hero", "rig"))
-- inspect the mapping
local plan = retarget.plan(src, tgt)
print(plan.mapped.leftarm.source, "->", plan.mapped.leftarm.target)
-- bake a walk clip onto the hero rig (cold, cached), then sample it like any clip
local walkBytes = vfs.read(asset.source("walk", "animation") .. "/data.zanim")
local walkOnHero = retarget.bakeBytes(walkBytes, src, tgt, "walk|hero")
local bind = skeleton.bindClip(walkOnHero, heroBoneOrder)
```
·computeshader · born here
❒asset # expand
Turns a count per element into runs. Element `j` takes `counts[j]` slots, in
element order; slot `s` of the result holds `owner[s]`, the element it belongs
to, and `local_index[s]`, its place within that element's run. `offsets` is the
exclusive prefix sum of `counts` (what the `scan` kernel makes of it), so every
slot finds its element by a binary search and has one writer.
`owner` is an appended output: its live count is the sum of the counts, up to
the capacity the dispatch was given. Slots at and past the live count hold -1.
An element with a count of zero has no slot; a column of all zeros gives a live
count of zero.
Dispatch over `n`, the capacity of the result. Exact.
Over a live count (`COUNT=device`, see the abi README) the elements are the first
`domain_count` of `counts` and `offsets`, so they can be held in runs larger than
their live count, and the counter of `owner` states the sum of their counts as it is,
above the capacity too: the first `n` slots are written and the sum minus `n` is how
many did not fit. A node that states `n` as a bound checks the count against it. The
plain variant clamps the count to `n`. It binds 6 storage buffers (5 in the plain
variant).
·computeshader · born here
❒asset # hash_count
For each query position, how many indexed points lie within a radius of it,
searched through the spatial hash the `hash` and `hash_starts` kernels build. An
exclusive scan of the counts gives the offsets `hash_gather` writes each query's
neighbour list at. Exact.
·computeshader · born here
❒asset # compute_particle_update
Reference compute shader for GPU particle simulation. Each particle is 8 floats
`[px, py, pz, life, vx, vy, vz, age]`; the shader applies velocity, gravity, and
aging every frame — thousands of particles updated entirely on the GPU.
Bindings (see bindings.yaml): `particles` (read_write `array<f32>`), `params`
(read_write `array<f32>` — `[dt, gravity_y, damping, pad]`).
`damping` is the fraction of velocity a particle keeps per 60th of a second, so
the same value produces the same motion whatever rate the shader is dispatched
at: `0.98` keeps 98% of the velocity every 1/60 s at 30 fps and at 144 fps
alike.
Usage: dispatch by identity — it resolves to the shader's stable guid and
auto-compiles on first use (no setup):
`compute.dispatch("@builtin::shaders.compute_particle_update", { buffers = { "particles", "params" }, workgroups = { math.ceil(count / 64), 1, 1 } })`.
·computeshader · born here
❒asset # splat_velocity_merge
Merges the Gaussian-splat velocity accumulation into the frame's velocity
buffer, so every consumer of that buffer — motion blur, temporal
antialiasing, temporal upsampling, a denoiser's history term — sees a moving
cloud move.
## What it reads
| binding | holds |
|---|---|
| `splat_velocity` | `xy` = each splat's NDC displacement summed premultiplied by its alpha, `w` = the coverage those splats add up to. The splat pass writes it as the second target of the Gaussian channel, composited "over" in the same sorted order as the colour. |
| `scene_motion` | The frame's velocity buffer as the geometry passes left it. |
| `merged_out` | Where the merged field lands. A copy lays it back over `@scene.motion`, because a pass cannot sample the attachment it renders into. |
## The weight
`w` is coverage, and coverage is the weight. A texel the cloud fully covers
reports the cloud's displacement; a texel it half covers reports halfway
between the cloud and the surface behind it; a texel it never reached keeps
what the geometry passes wrote, bit for bit. That is the same weight the
cloud's colour arrived at the texel with, so what a velocity consumer treats
as moving is what the image shows moving.
# eye.shader
An eye: an iris refracting behind a clear cornea.
The iris sample is displaced by refracting the view ray at the cornea and
walking it `iris_depth` inward, so the iris slides as the viewing angle changes.
The cornea itself is the engine's clearcoat lobe, which keeps one continuous
specular highlight across the iris and the sclera.
`iris_radius`, `pupil_radius` and `limbus_softness` shape the disc; `iris_texture`
is sampled in the refracted frame, `sclera_texture` in the surface's own UVs.
# postReference_grey18
A lit 18% grey (middle grey) surface, rough and dielectric: what a light of known intensity is read off in the post-verification reference scenes.
# loading_backdrop (screen shader)
A calm, slowly drifting full-screen backdrop for the world loading screen. A deep
near-black field carries two large, soft glows that move along slow independent
orbits, finished with a gentle vignette and a faint animated grain that keeps the
gradient from banding. Animation is driven entirely by `engine.time`, so it
advances on its own during boot with no per-frame uniform updates. It is quiet by
design, so it sits behind the world's cover image, title, and progress bar. Drawn
through the `backgroundShader` UI style after registration with
`ui.registerBackgroundShader`.
# shadowSystem
Cascaded shadow map (CSM) **policy** for crisp directional shadows across a
large view distance. The rendering *mechanism* lives in the engine; this
package is the per-frame policy that drives it.
## Layout
- `shadowSystem.module` — the policy: PSSM frustum splitting, per-cascade
bounding-sphere fit + texel-snap stabilization, and the matrix math. Pushes
per-cascade light-space matrices + split distances to the renderer via
`__rendering.setShadowCascades` each frame.
- `ShadowCascadeDriver.component` — attach ONE to a scene entity to drive the
module every frame from the active camera + sun.
- `depthBounds.renderFeature` — reduces the frame's depth target to the
nearest and farthest view depth any surface occupies, and hands the result to
the module.
## Flow
1. Add a `ShadowCascadeDriver` component to any entity in the scene.
2. Each frame it slices the camera frustum into N cascades (N from
`render.shadow_cascades`), fits a stable light-space ortho to each, and
pushes the matrices + split distances to the renderer.
3. The renderer renders one shadow depth pass per cascade; the fragment shaders
pick a cascade by the fragment's distance from the camera.
## Fitting splits to the depth that is there
Splits are placed over a range. Taken from the camera's near and far planes
that range is whatever the scene *could* occupy; taken from the depth buffer it
is what the scene *does* occupy. A courtyard that stops at 40 m under a 200 m
shadow distance spends most of its cascade texels on empty space.
```lua
entity.find("scene").component.add("ShadowCascadeDriver", {
fitToDepth = true, -- place splits over the measured depth
depthMargin = 0.1, -- room past the far end for a frame of movement
})
```
The **far** end is what moves. The near end stays where the camera puts it: the
renderer picks a cascade from a fragment's distance and cascade 0 is fitted to
the range's start, so raising that start would leave anything nearer sampling a
box it does not sit inside.
The measurement is one frame old, because a GPU read-back cannot land in the
frame that produced it. `depthMargin` is the room that gives something to move
away in before it falls outside the last cascade.
With `fitToDepth` off, no reduction is dispatched and splits are placed exactly
as before.
Purely additive: with no driver the renderer falls back to its legacy single
camera-fit directional shadow. Quality is controlled by the
`render.shadow_resolution` / `render.shadow_cascades` / `render.shadow_distance`
/ `render.shadow_split_lambda` world settings. `render.shadow_distance` is a cap
on the range the splits run over, and its default of 0 leaves that range to the
frame — the depth its own renderables reach.
## Documentation
See `shadowSystem.module/README.md` and `ShadowCascadeDriver.component/README.md`.
# Parallax Cube (Flat)
A brick surface built on `@builtin::shaders.pbr_parallax_occlusion` with `parallax_depth_scale = 0`, so the ray-march is bypassed and the shared brick textures render as plain textured PBR (rough `0.7`, non-metallic, white base colour). Opaque, back-face culled, queue `2000`. Pair it with `parallax_cube` to A/B the parallax effect from a fixed viewpoint.
## Inputs
- `floats.parallax_depth_scale` (`0.0`) — disables the occlusion ray-march, flattening the surface.
- `floats.roughness` (`0.7`) — matte brick finish.
- `floats.normal_scale` (`1.0`) — strength of the normal map.
- `textures.height_texture` — the brick height map (unused while depth scale is `0`).
# postReference_siemensStar
A Siemens star of 36 spokes, 0.9 on 0.02: the spokes narrow below a pixel toward the centre, where a temporal resolve aliases.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
# Skybox
An unlit cubemap skybox rendered from the inside of the mesh, built on `@builtin::shaders.cubemap_unlit`. Uses front-face culling and no depth write so it draws behind all scene geometry (queue `1000`), sampling the built-in `Ryfjallet_cubemap` environment.
## Inputs
- `textures.base_color_texture` — the cubemap sampled as the background (`Ryfjallet_cubemap`).
- `floats.reflect_mode` (`0.0`) — samples the cube directly as a background rather than as a reflection.
- `colors.base_color` (`1.0, 1.0, 1.0`) — tint applied to the sampled cubemap.
·computeshader · born here
❒asset # scan_mat4
The running product of a run of 4x4 matrices, whole or per segment: the frames
of a sweep, each placed relative to the one before it.
A matrix is 16 consecutive floats, column by column. The product runs in run
order, so `out[i] = m[0] * m[1] * ... * m[i]`. `params.exclusive` picks the
product of the matrices before each one (the identity for the first) or the
product up to and including it. `total` holds each group's product, the
identity for an empty group. A segmented scan (`params.segments` above 0, the
number of segments) restarts at each start in `starts`.
One workgroup scans one group at a time, a tile of 128 matrices at a time, with
the product of everything before a tile carried into the next. The dispatch size
`n` is the number of matrices; any workgroup count from 1 up scans every group.
Exact: the order of multiplication is fixed, so the same run gives the same bits
on every dispatch.
# `hdrChart` post-process shader
The synthetic HDR chart: a picture whose every pixel holds light its
properties and its position state, drawn in place of the scene. Registered
first in the chain (`postMetrics.chart.show`, priority -1000), it is the input
the display transform and every effect after it read, so they are measured
against known light with no lighting, geometry or material in between.
`@builtin::modules.postMetrics` computes the same light for any pixel on the
CPU (`chart.light`) and builds the picture a display curve should present for
it (`chart.reference`).
| Property | Meaning |
|---|---|
| `pattern` | 0 ramp, 1 grey wedge, 2 ColorChecker, 3 colour wedge over its grey. |
| `low`, `high` | The ramp's light at the left and right edges. |
| `evMin`, `evMax` | The wedges' leftmost and rightmost stops; each column is middle grey (0.18) at a whole stop. |
| `gain` | The ColorChecker's light, as a multiple of its reflectance. |
| `color` | The ramp's tint, and the colour wedge's saturated patch (scaled to its column's grey luminance). |
| `dither` | Triangular noise of that many code values either way, added in display-encoded sRGB. |
The effect declares `space: light`.
·computeshader · born here
❒asset # intersect_retri
The triangles of one mesh retriangulated along the segments that cut them. One thread per triangle: a
triangle no segment reaches is written as itself; a cut triangle is worked in its own plane, in world
lengths, where its corners and the cut endpoints are the points and its sides and the cut segments are the
constraints. The triangulation holds every constraint first (each cut out by the points that lie on it),
then holds the remaining candidate edges shortest first, a length class at a time (the exponent and top
three mantissa bits of the squared length), each when it crosses no held edge and has no point on it. The held edges are a planar graph: the
neighbours of each point are sorted by direction, the faces are walked with their inside on the left, a face
of three points is a triangle and a face of more is cut ear by ear (each ear a corner that turns left with no
other point of the face inside it or on its sides), and the face outside the triangle is left out. Every
triangle is wound the way the source triangle was, so the pieces of a triangle agree on the direction of every
side they share however thin the sliver between two cut points. A triangle whose three points stand on one
line in the world has no area and is left out. Every cut segment is a union of edges of the result, and the
pieces of a triangle tile it. Points and distances are compared within a few steps of the coordinates'
precision (`5e-7` of the largest coordinate of the triangle, and no less than `1e-7` of its longest side),
the same measure for a triangle of either mesh, so cut points a few millionths apart are told apart by the
triangles of both meshes alike.
Param `side` names the mesh the pass cuts, 0 for A and 1 for B; a segment cuts the mesh when its endpoint
records say so (`intersect_core`). A triangle takes every point of its entries, a segment of no length
giving a point on an edge and nothing more.
`STAGE count` writes how many triangles each triangle becomes; `STAGE write` writes them at the offsets of
the prefix sum, four words each (three vertex references, the source triangle) from word 4 of `out`. A
reference below `npts` is a point of the mesh; `npts + s` is the cut endpoint in slot `s`, which
`intersect_unify`'s `rep` names. `out[0]` is 1 when a triangle ran out of working space, which the sizing
below prevents.
## Working space
A triangle takes a slice of working memory sized by its entries, so the number of points a triangle can
carry follows the data: a run of `m` entries gives at most `3 + 2 m` points, `3 + m` segments and three
edges a point, and the slice is `64 + 40 m` words. The slices of consecutive triangles follow one another
and make the tail of `out`, after its 4 header words and the `4 * total` words of the triangles
(`total` is 0 in the count stage): the slice of triangle `t` starts `64 * t + 40 * first(t)` words into the
tail, `first(t)` the first entry of its run, so the runs' firsts are the exclusive prefix sum of their
counts (the `start` of `intersect_pairs` for mesh A, the offsets of the per-b counts for mesh B). `out`
is sized `4 + 4 * total + 64 * n + 40 * entries` words from the params `total` and `entries` (the number of
entries of `intersect_pairs`).
The triangles of mesh A are grouped by `a` already (`runs` is `start` and the counts of
`intersect_pairs`, `order` the identity); for mesh B the entries are stably sorted by `b` first and
`order` holds the sorted entry indices. Exact: each triangle is worked alone and in a fixed order.
·computeshader · born here
❒asset # jump
One round of pointer jumping over a run of links, three ways:
- `rank` (MODE rank): list ranking. Repeated rounds give each element its root and
its distance to it, for chains and trees. Both live in the double-buffered
`parent`/`parent_out` and `value`/`value_out` pairs; the caller swaps them
between rounds.
- `min` (MODE min): doubling of the smallest label within reach. After
ceil(log2 n) rounds, every element on a cycle holds the cycle's smallest label.
- `label` (MODE label): label propagation over pairs, in place. Iterated to
`changed` = 0 it labels each connected set of elements with its smallest label.
`changed` counts what the round altered; the caller zeroes it before a round and
reads it after, so iteration with a stop is one dispatch and one count per round.
Integers are 32-bit words and every mode is exact: the final labels do not depend
on the order invocations ran in.
Over a live count (`COUNT=device`, see the abi README) the elements (rank, min) or
the pairs (label) are the first `domain_count` slots of a capacity `n`, and the `n`
param is not read. In rank and min mode a slot at or past the live count links to
itself with the value 0. It binds 8 storage buffers (7 in the plain variant).
# fluidSurface
A GPU particle simulation, rendered as a continuous liquid.
Water made of particles has a problem: the particles are spheres, and a pile of
spheres looks like a pile of spheres. Turning them into a mesh every frame is
expensive and the mesh is thrown away immediately. This package skips the mesh —
it renders the particles into screen-space fields and shades those, so the
particle data never leaves the GPU and the cost scales with screen pixels rather
than with the surface's geometric complexity.
## What it does
```lua
local fluidSurface = require("@builtin::systems.fluidSurface.modules.fluidSurface")
local rts = fluidSurface.attach("lake", {
particles = { buffer = sim, stride = 16, posOffset = 0, count = 400000, velOffset = 4 },
radius = 0.35,
})
```
`particles` describes the record layout of the buffer the caller's simulation
writes: how wide a record is, where the position sits in it, and how many are
live. Pass the handle a compute shader's `createBuffer` answered. Everything
after that happens per frame until `detach`.
`update` moves the live knobs — the particle count as a sim grows, the sun
direction as the day turns, any composite property:
```lua
fluidSurface.update("lake", { count = active, sunDir = { 0.3, 0.8, 0.2 } })
```
## The chain
1. **Splat** (engine raster). Every particle draws as a velocity-stretched
billboard: nearest-surface depth, hardware z-tested; additive thickness and
thickness-weighted colour; and, when the records carry a foam weight, an
additive foam sprite layer.
2. **Narrow-range filter** (`fluid_narrow_x` → `fluid_narrow_y`, ping-ponged
`iterations` times). Neighbour depths are clamped into a band around the
centre before averaging, so particles fuse into a surface while silhouettes
stay crisp. The body is the `fluid_narrow_filter` shader module, included by
both axes.
3. **Resolve** (one of `fluid_resolve`, `fluid_resolve_col`,
`fluid_resolve_foam`, `fluid_resolve_col_foam`). Packs smoothed depth,
blurred thickness and the foam fraction into `data`, and the mean liquid
colour along each ray into `liq`. Which one runs is decided by whether the
records carry a colour and a foam weight, because that changes which textures
the pass binds.
4. **Composite** (`fluid_surface_composite`, a post-process shader). Refracts the
already-rendered scene through the surface normals, absorbs along the view
ray by Beer–Lambert, marches the reflected ray against scene depth so the
water mirrors what is above it, adds sun specular, and lays foam on the thin
edges. Depth-tested against the scene, so fluid behind geometry stays hidden.
Every stage runs at `resolutionScale` of the screen (half by default).
## Sharing
The passes are compiled once and shared by every surface. What a surface owns is
its render targets, its own filter-parameter buffer, and its own composite —
which is why two lakes at different particle radii filter at different widths
without interfering.
# areaLights system
Lights that emit from a surface rather than from a point.
Every screen, neon sign, glowing window, ceiling panel and lantern face is an
area emitter. Standing a point light in the middle of one gets the brightness
roughly right and the character completely wrong: a point puts a pinpoint
reflection on the floor and a radial falloff on the wall, where the real thing
puts the shape of the emitter and a falloff that follows its extent.
## Using it
An emitter that should follow an entity's face is a component:
```lua
local id = entity.spawn("tv").id
entity(id).component.add("SurfaceLight", {
width = 2.0,
height = 1.2,
face = "front", -- front | back | up | down | left | right
intensity = 6.0,
range = 12,
})
```
The rectangle turns with the entity, so a tilted screen lights the direction it
actually points. Every field is live, and an `intensity` of 0 removes the light.
For code placing emitters directly:
```lua
local surfaceLight = require("@builtin::systems.areaLights.surfaceLight")
surfaceLight.set("strip", {
position = { 0, 5, -12 },
right = { 1, 0, 0 }, up = { 0, 1, 0 },
width = 0.6, height = 7,
color = { 1, 0.72, 0.35 }, intensity = 5,
})
surfaceLight.remove("strip")
surfaceLight.configure({ diffuse = 1, specular = 0.5 })
surfaceLight.clear()
```
## What the knobs do
| field | effect |
|---|---|
| `width` / `height` | Size of the emitting rectangle, world units. The shape of the light is the shape of this. |
| `face` | Which way the entity emits. |
| `range` | How far the light carries, with a smooth cutoff at the end. |
| `intensity` | Brightness. 0 removes the light. |
| `colorR` / `colorG` / `colorB` | Emitter colour. |
| `offset` | Distance the rectangle sits proud of the entity's origin, along the face's normal. |
| `diffuse` / `specular` | Scales on the two terms — the wash across a surface, and the reflected shape of the emitter. |
Shape is the point. A wide panel puts a broad pool on the floor; a narrow strip
puts a narrow elongated one. That difference is not reachable with a point
light at any brightness.
At most 32 emitters are held at once, because the shader loops every light for
every pixel.
## How it renders
`areaLighting.renderFeature` runs one compute pass after lighting. Diffuse is
the exact irradiance of the quad — Lambert's formula over its four edges — which
matters where a point approximation fails hardest: a wide emitter close to a
wall. Specular uses the representative point on the rectangle nearest the
reflection ray, with the lobe widened to cover the emitter's solid angle and its
peak scaled down to match, so a large emitter reads broader rather than
brighter.
## Files
```
areaLights.package/
SurfaceLight.component/ -- an emitter on an entity's face
surfaceLight.module/ -- the emitter registry and scales
areaLighting.renderFeature/ -- the compute pass
```
·computeshader · born here
❒asset # hash_gather
Lists, for each query position, the indexed points within a radius of it, query
after query: query `q`'s points start at `qoff[q]`, the exclusive prefix sum of
the `hash_count` counts. The list is in the order the spatial hash walk visits
points, the same on every run. Exact.
Over a live count (`COUNT=device`, see the abi README) the queries are the first
`domain_count` of a capacity `n`, `total` is the capacity of `items` (the bound the
node states), and `items` is an appended output: its counter is the number of points
the live queries listed, above the capacity too when the lists do not fit (the first
`total` words are written and the counter minus `total` is how many did not). Words of
`items` past the lists are left as allocated, 0. A node that states `total` as a bound
checks the count against it. It binds 8 storage buffers (6 in the plain variant).
·computeshader · born here
❒asset # rt_ao_pass
Traces short hemisphere rays against the scene per pixel, so a surface darkens
by how much geometry actually stands around it rather than by what a depth
buffer happens to show.
## Bindings
| name | kind |
|------|------|
| `scene_color` | `texture2d` |
| `scene_depth` | `texture_depth` |
| `scene_normal` | `texture2d` |
| `scene_tlas` | `acceleration_structure` |
| `frame_cam` | `buffer` |
| `ao_params` | `buffer` |
| `ao_out` | `storage2d (rgba8)` |
## Params
| name | type | what it is |
|------|------|------------|
| `samples` | `float` | hemisphere rays per pixel |
| `radius` | `float` | world-space occlusion reach |
·computeshader · born here
❒asset # abi_live
Doubles src into dst for the elements a live count holds and writes -1 past it.
# postReference_greyWedge
The grey wedge: one column per whole stop from -10 to +10, each middle grey (0.18) at that exposure.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
·computeshader · born here
❒asset # compact
Turns a keep mask into the indices of the kept elements, and the map back from
every element to the place it holds among them.
`indices` lists the elements whose mask word is not 0 (a float mask of 0.0 and
1.0 reads the same way), in run order; its live count is the number kept.
`inverse` holds, for every element, its place among the kept ones, or -1 for an
element that is not kept, so a column carried to the kept elements (a gather by
`indices`) and a column of per-kept values carried back (a read through
`inverse`) agree on which element is which.
The dispatch size `n` is the number of elements. One workgroup of 256 works the
whole run, a tile of 256 elements at a time; the other workgroups of a larger
dispatch return.
Exact: the order is the run's own, so the same mask gives the same answer on
every dispatch.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` mask words are the elements: words past it are not read, a slot
of `inverse` at or past it holds -1, and the slots of `indices` past the kept ones
hold -1. `indices` has room for `n` and its counter is the live count the next kernel
takes as its domain. It binds 5 storage buffers (4 in the plain variant).
# Checkerboard White
A static white/grey checkerboard rendered by `@builtin::shaders.checkerboard`, alternating a white base colour (`1.0, 1.0, 1.0`) with a dark grey check colour (`0.3, 0.3, 0.3`). Animation is disabled (`animation_speed 0.0`), giving a fixed, neutral grid — ideal as a level-design blockout or scale-reference floor. Opaque, non-metallic (`metallic 0.0`) at mid roughness (`0.5`).
## Inputs
- `colors.base_color` — the white square colour.
- `colors.check_color` — the dark grey square colour.
- `floats.animation_speed` (`0.0`) — held at zero for a static pattern.
- `floats.roughness` (`0.5`) — diffuse spread on the squares.
# postReference_white
A flat unlit white of 0.8 light: the thin geometry of the temporal reference scene (wires, a fence, a fan's blades) drawn against the dark, so every pixel it touches stands out from its neighbours.
Drawn by `@builtin::shaders.referenceChart`. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
# test
Test framework — simple unit testing with the `describe` / `it` /
`expect` pattern. Used by the engine test suite and any user-authored
suites that want a single dependency. Pure Luau; flag-based failure
tracking instead of exceptions (works the same on native and WASM).
## Exports
Definition:
- `Test.describe(name: string, fn: () -> ()) -> Suite` — define a suite. The body declares the suite's cases, so only what it reached is in the run: a body that ends on a raise leaves a `<describe body did not finish>` case behind, naming the describe and what it raised, and the run ends on that case. A body that stands down leaves the same case marked skipped, carrying the reason.
- `Test.it(name: string, fn: (TestContext) -> ()) -> any?` — define a test.
- `Test.skip(name: string, fn: ((TestContext) -> ())?) -> any?` — skip a test. Inside a `describe` with a body it declares a skipped test; inside a running test (its body or one of its hooks) a reason alone stands that test down — the test ends there, is counted under `skipped`, and the reason reaches the console, the per-test record and the report. A reason alone anywhere a test is not running raises, naming the declaration form.
- `Test.beforeEach(fn: () -> ())` / `Test.afterEach(fn: () -> ())` — per-test hooks.
- `Test.expect(value: any) -> any` — expectation builder with `toBe`, `toBeTruthy`, `toBeFalsy`, `toBeNil`, `notToBeNil`, `toBeType`, `toBeGreaterThan`, `toBeLessThan`, `toBeCloseTo`, `toContain`, `toMatch`, `toHaveLength`, `toThrow`, `never()`.
- `Test.captureFailure(fn: () -> ()) -> string?` — run a body and return the failure it records instead of recording it, for tests that assert a matcher rejects something. A body that records several returns the headline for them.
- `Test.captureOutcome(fn: () -> ()) -> Outcome` — run a body the way the runner runs a test body and return `{ failed, error, failures, raised }`: its failures in the order they happened, with a raise that ended the body as the final entry.
- `Test.captureTestOutcome(spec: TestSpec) -> TestOutcome`: run a whole test the way the runner runs one (`beforeEach`, the body, `afterEach`, then the cleanups registered while it ran) and return `{ skipped, reason, failed, error, failures, raised }`. The runner reads its verdict from the same place, so what this reports for a captured test is what a sweep reports for a real one. A scene layer the captured test leaves loaded that was not loaded when it started is unloaded afterwards, as the runner unloads one after each test.
## What a failing test reports
A matcher records its failure and lets the body run on, so one body can produce
several. They are kept in the order they happened:
- `error` — the headline, and the one line the console, the engine log and the
report's result table carry. It is the failure that came first, plus
`(+N more)` counting the ones after it — `(+N more, ended by a raise)` when a
raise is what stopped the body.
- `failures` — the failures in order, on `Test.results[]`, in each per-test
JSON file under `Test.PER_TEST_RESULTS_DIR`, and in the JSON report. The
Markdown report lists them under the failing test's heading. A body that
records more of them than the list keeps ends it with a line counting the
rest and naming the last of them, so one test asserting inside a long loop
stays one bounded entry in the report.
The hooks that run around a body record onto the same list it does, so an
assertion a `beforeEach`, an `afterEach` or a registered cleanup fails — and an
error one of them raises — is a failure of the test it ran for and travels to
every consumer the body's failures reach. Each names the phase it came from
(`afterEach: Expected …`, `cleanup: Runtime error: …`); a body's own failures
stay unlabelled. A cleanup that raises still leaves the cleanups behind it to
run.
## Standing a test down
A test whose precondition this engine does not meet has nothing to verify and
has earned no pass. `Test.skip(reason)` from inside the running test says so:
```lua
Test.it("renders N copies from one transform buffer", function()
if engine.gpuCompute ~= true then
Test.skip("GPU compute reported unavailable (engine.gpuCompute)")
end
-- …the test, on an engine that can run it
end)
```
The test ends at that call. It is counted under `skipped`, printed as
`○ <name> (skipped: <reason>)`, and the reason travels as the `error` field of
its `Result` row, into its per-test JSON file, and into both reports. A
`beforeEach` may stand the test down the same way, and then the body never runs.
Whatever the test's hooks record around a stand-down is a failure of the test
they ran for and outranks it: a teardown that fails after a body stood down
reports the test as failed.
A reason on its own reaches a test that is running. Inside a `describe`, where
`Test.skip` declares, the call takes a body — a reason alone raises there,
naming the declaration form.
Run / inspect:
- `Test.run() -> boolean` — execute every registered suite; `true` when all pass.
Call from a yieldable context (the `tests` toolbox does) so multi-frame tests
yield. Discovering + running every suite is the `tests` toolbox's job
(`tests.run`), not this framework's.
- `Test.clear()` — reset suites + stats (re-run from clean state).
- `Test.getResults() -> { Result }`, `Test.getStats() -> Stats`.
Multi-frame / sandboxing:
- `Test.waitFrames(n: number?)` — yield until at least `n` engine frames elapse.
- `Test.tmpPath(relativePath: string?) -> string` — sandboxed path under `Test.TMP_ROOT`.
- `Test.prepareTmp()` / `Test.cleanupTmp()` — recreate / remove the tmp root.
Notices:
- `Test.noticeMark(template: string) -> NoticeMark` / `Test.noticesSince(mark) -> number`:
how many times a notice posted under `template` fired after the mark.
A drain seals the row it returns and the next emission starts a new row, so
this counts across every row of the template.
- `Test.latestNotice(template: string) -> any?`: the stored row of that template
the most recent emission landed in.
Scene layers:
- `Test.useScene(opts?) -> SceneProxy` — mint an isolated scene for the current
test from a `.scene` fixture and load it (root, or an additive overlay with
`{ additive = true }`). Unloaded and removed at teardown.
- `Test.useSceneEach(opts?)` — suite-level sugar: one freshly minted scene per test.
- `Test.ensureRootLayer() -> SceneProxy` — take a root scene layer for the
current test, so `layers.active` and the scene-scoped surfaces behind it
answer inside a test. Returns the loaded root, loading a stand-in scene from
`Test.BASELINE_SCENE` when none is; the layer is unloaded when the test ends.
- `Test.releaseRootLayer()` — unload the stand-in and remove its source folder.
The runner calls it when a run ends.
- `Test.beginWorldBaseline() -> WorldBaseline` / `Test.restoreWorldBaseline(baseline)` —
bracket a whole sweep: unload the layers the engine booted with (so no suite
depends on ambient content) and put them back afterwards.
Public state:
- `Test.suites`, `Test.currentSuite`, `Test.currentTest`, `Test.stats`, `Test.results`, `Test.TMP_ROOT` (`/zero/source/tmp/tests`).
Types:
- `Stats = { total, passed, failed, skipped: number }`
- `Result = { suite, test: string, passed, skipped: boolean, error: string? }` — on a skipped row `error` is the reason the test stood down
- `TestContext = { waitFrames, expect, fail, suiteName, testName }`
- `Suite = { name, tests, beforeEach?, afterEach? }`
- `Outcome = { failed, raised: boolean, error: string?, failures: { string } }`
- `TestOutcome = Outcome & { skipped: boolean, reason: string? }`
- `TestSpec = { body: (TestContext) -> (), beforeEach?, afterEach?: () -> (), name: string? }`
- `RunAllOpts = { path: string? }`
- `NoticeMark = { template: string, counts: { [string]: number } }`: each stored row's count at the mark, by row
## Usage
```luau
local Test = asset.containing(__FILE__).modules.shared
Test.describe("My Suite", function()
Test.it("does basic things", function()
Test.expect(1 + 1).toBe(2)
Test.expect("hello").toContain("ell")
end)
Test.it("cascade despawn cleans children across frames", function(t)
local parent = entity.spawn("parent")
local child = entity.spawn("child")
child.setParent(parent.id)
t.waitFrames(1) -- let setParent settle
entity.despawn(parent.id)
t.waitFrames(2) -- let cascade + ECS despawn run
Test.expect(entity.exists(parent.id)).toBe(false)
Test.expect(entity.exists(child.id)).toBe(false)
end)
end)
Test.run()
```
## Notes
- Failure is flag-based, not exception-based — every matcher records the
failure but allows the body to keep executing. Avoids WASM C++
exception handling cost.
- The runner records the loaded scene layers and the entity set before each
test. Afterwards it unloads every scene layer the test left loaded that was
not loaded before it, newest first, so the entities that layer's load built
leave with the layer and the scene's source is what its next load builds
from. It then despawns any other newly-spawned entity (mutations apply after
the `execute()` batch returns; `cleanedUpIds` makes the snapshot tolerate
deferred cleanup).
- After each test the runner defensively returns the scene to `edit`
mode if a body or its `afterEach` leaked `play`. This stops a single
mode-leaking test from cascading silently into every downstream
`vfs.write`-using suite.
- Multi-frame `t.waitFrames` needs a yieldable call chain. A non-yieldable
C-frame above `Test.run` (e.g. driving it from inside a `require`) makes
`waitFrames` raise a sentinel and the test is marked SKIPPED — the body had
nothing to verify, so what it recorded is dropped and what its setup recorded
stands. A hook that fails around such a body still fails the test. The `tests`
toolbox (`tests.run` → `AssetRef:run()`) runs the suite in a plain
coroutine, so the real wait path exercises.
- `toThrow` calls its subject under `pcall` and fails when the call
returns normally. `toThrow("substring")` additionally requires the
rendered raised value to contain that substring. `never().toThrow()`
asserts the call completes.
# parallax_cube
Brick wall material using `@builtin::shaders.pbr_parallax_occlusion`
with the parallax march enabled (`parallax_depth_scale = 0.08`, 48
ray-march layers). Pair with `parallax_cube_flat` for a same-textures,
no-POM A/B comparison.
## Shader
`@builtin::shaders.pbr_parallax_occlusion` — see that shader's README
for the full parameter list.
## Textures
All from `@builtin::textures.parallax_bricks` (height/normal derived
from three.js's MIT-licensed `brick_bump` + `brick_diffuse`):
- `base_color_texture` → `bricks_albedo`
- `normal_texture` → `bricks_normal`
- `roughness_metallic_texture` → `bricks_roughness`
- `occlusion_texture` → `bricks_ao`
- `height_texture` → `bricks_height`
## Usage
```luau
Material.Apply(entityId, "parallax_cube")
-- Override at runtime:
Material.SetProperty("parallax_cube", "parallax_depth_scale", 0.12)
```
Pair it with `parallax_cube_flat` (same textures, `parallax_depth_scale = 0`)
to compare the ray-marched surface against a flat-mapped baseline.
## Notes
- `Material.SetProperty` mutations are global — every entity using
`parallax_cube` sees the change. If you need per-entity variation,
derive a new material name and override the property there.
- Use under any standard camera (forward path). The deferred path is
not yet POM-aware; materials applied to a deferred camera will
render as plain textured PBR.
# `colorGrade` post-process shader
Brightness, saturation and contrast as multipliers around an identity of 1.0.
`pp.add(name, "colorGrade", { brightness = 1.1, saturation = 0.8 })` registers it, and
`asset.resolve("@builtin::shaders.post.colorGrade", "shader"):getProperties()`
reads the knobs below before it is added.
The three run in that order on the sampled frame: brightness scales the colour,
saturation mixes it against its own Rec. 709 luminance, and contrast pushes it
away from mid grey. Each is a multiplier, so 1.0 leaves the frame as it was and
all three at 1.0 pass it through unchanged.
`color_correction` grades the same three quantities as ADDITIVE offsets around
0.0 and adds a tint colour, so a look authored for one does not transfer to the
other by copying its numbers.
| Property | Meaning |
|---|---|
| `brightness` | Multiplies the colour. |
| `saturation` | 0 is luminance alone, 1 is the frame's own colour. |
| `contrast` | Scales distance from mid grey. |
·computeshader · born here
❒asset # compute_double
Reference compute shader that doubles every `f32` in a storage buffer — the
simplest possible compute pattern (one read-write buffer, no inputs).
Bindings (see bindings.yaml): `data` — read_write `array<f32>`.
Usage: dispatch by identity — it resolves to the shader's stable guid and
auto-compiles on first use (no setup):
`compute.dispatch("@builtin::shaders.compute_double", { buffers = { "data" }, workgroups = { 1, 1, 1 } })`.
# Neon
A glowing cyan neon surface built on `@builtin::shaders.pbr` with emission enabled. It pairs a bright cyan-blue base colour (`0.2, 0.8, 1.0`) with a matching emissive colour driven hard by `emissive: 5.0`, so it reads as a self-lit light source. Low roughness (`0.2`), non-metallic, opaque, instanced, with the `_EMISSION` keyword enabled.
## Inputs
- `colors.emissive` (`0.2, 0.8, 1.0, 1.0`) — cyan glow colour.
- `floats.emissive_intensity` (`5.0`) — strong emissive intensity (feeds bloom).
- `colors.base_color` (`0.2, 0.8, 1.0, 1.0`) — matching cyan base tint.
- `floats.roughness` (`0.2`) — glossy surface under direct light.
# oceans
A sea and the ground under it, as one package: the wave simulation, the surface
that renders it, the seabed it is seen through, and the answer to "how high is
the water here" that gameplay needs to float things on it.
```lua
local Ocean = require("@builtin::systems.oceans.modules.ocean")
Ocean.create({ preset = "gale" })
```
That is a whole ocean — waves out to the horizon, foam on the breaking crests, a
seabed below, and a surface that follows whoever is looking at it. To float
something on it:
```lua
local ocean = Ocean.forEntity(oceanEntityId)
boat.position = { x, ocean:sampleHeight(x, z), z }
```
It is a building block. The sun the water glitters under, the ambient its foam
sits in and the sky it reflects all come from the scene, through the same
directional light and reflection probes every other material in the engine
reads — so an ocean drops into a world that already has lighting instead of
bringing a second set, and changing the scene's light changes the water with it.
## What it does
The simulation is **spectral**: instead of animating individual waves, it builds
the sea's energy across every wavelength and direction from an oceanographic
spectrum, then inverse-transforms that into a height field. A real sea is what
comes out — wind speed alone decides wave height, and it rises with wind the way
a fully developed sea does, following the Pierson–Moskowitz law.
It runs in **cascades** — independent wave fields over different patch sizes,
each band-limited to its own range of wavelengths. A tile of roughly two
kilometres carries the long waves and one of a few hundred metres the short
ones; they sum into a surface with detail at every scale, and because the bands
are disjoint no wavelength is synthesised twice. Above them a **Gerstner bank**
adds the swell analytically, which no cascade can hold: a wave longer than its
own patch has nowhere to live, and swell arrives from a distant storm on its own
heading anyway.
**Foam** is not painted on. It comes from the Jacobian of the wave displacement:
where the surface folds over itself, the wave is breaking. Whitecaps appear
where and when the geometry actually breaks, accumulate into a persistent
world-space field, and streak behind the crest as they decay.
**Colour and transparency are the same mechanism.** Per-channel Beer–Lambert
extinction over the distance light travelled through water gives both — red dies
within a metre, blue survives tens. That is why shallow water over sand reads
turquoise and the open sea reads near-black blue without switching materials.
**The seabed** is one noise field read twice: scaled it is the terrain's relief,
unscaled it picks between sand and rock, so outcrops stand on the high ground
and sand fills the hollows. The sun's caustic web moves over both, bent by the
horizontal displacement of the water directly above it. Bodies land on it: the
pass that raises the ground writes the same field out as a height patch that
travels with the viewer, so what a body stands on is what the frame drew.
Nothing here ships an image. Every map the surface and the seabed sample — the
foam patterns, the sand, the rock, the caustics — is grown on the GPU at
startup.
## The pieces
| Asset | What it is |
|---|---|
| `components/Ocean` | Puts a sea on an entity. Its fields are the sea state; the simulation is rebuilt from them, so an ocean survives a scene reload. |
| `modules/ocean` | The substrate: `attach`, `create`, `forEntity`, `sampleHeight`, `sampleDisplacement`. |
| `components/Buoyancy` | Floats a rigid body on the sea. Its fields are the hull: how dense it is, how steady, and what box displaces water. |
| `modules/buoyancy` | The forces: `attach`, `forEntity`, `columns`, `submergedFraction`, `restingY`. |
| `modules/oceanPresets` | Nine named sea states, from `calmClear` through `gale`. |
| `modules/oceanQuality` | The four tiers — how finely a sea is resolved, as distinct from what sea it is. |
| `modules/oceanClipmap` | The camera-following ring geometry both the surface and the seabed are built on. |
| `modules/oceanFloor` | The seabed: terrain, ground materials, caustics and the ground physics collides with. |
| `modules/oceanScene` | The seam between the scene capture and the materials that sample it. |
| `shaders/oceanSurface` | The water: cascade normals, absorption, exact dielectric Fresnel, subsurface scattering, sun glitter, foam, and the view from below. |
| `shaders/oceanFloor` | The seabed: sand and rock blended by terrain noise, under a caustic web. |
| `materials/oceanWater`, `materials/oceanSeabed` | The default looks. |
| `renderFeatures/oceanScene` | Copies the frame's colour and depth so the surface can refract what is behind it and measure its own water column. |
| `computeShaders/ocean_*` | The ten-stage GPU pipeline. |
## Wind is the control
Significant wave height goes as the **square** of wind speed, so that one field
does most of the work:
| Wind | Sea | Wave height |
|---|---|---|
| 3 m/s | glassy, a mirror | ~0.2 m |
| 11 m/s | working sea, occasional whitecap | ~2.5 m |
| 24 m/s | gale, breaking and streaked | ~12 m |
Everything else shapes character rather than size: `choppiness` pinches crests
into peaks, `standingWaveRatio` runs waves both ways instead of only downwind,
`jonswapGamma` sharpens a fetch-limited sea, and the foam layers decide how
readily a breaking crest whitens and how long it streaks.
Read `documentation/oceans.guide` for the full walkthrough, including the
seabed, buoyancy, reflections and what each tier costs.
# subsurface
A metallic-roughness surface that also transports light beneath itself, for
skin, foliage, wax, marble and thin fabric.
Set `subsurface_color` to the tint of the light that scatters through; leaving
it black makes this a plain metallic-rough surface. `subsurface_radius` sets how
far light spreads beneath — larger values wrap the shading further past the
terminator, and reach further in whichever channels the colour is strongest in.
`thickness` (and `thickness_texture`) control how readily a backlit surface
glows. Thin geometry transmits; thick geometry stays solid.
Both effects are evaluated in the engine's light loop, so they are shadowed and
attenuated like every other lobe.
·computeshader · born here
❒asset # compute_terrain
GPU voxel-terrain generation: produces block data for a chunk. One thread per
`(x, z)` column, filling the full Y column with block types (air, grass, dirt,
stone, sand, water, wood, leaves, snow).
Bindings (see bindings.yaml): `params` (read `array<f32>` — `[chunkSizeX,
chunkHeight, chunkSizeZ, chunkWorldX, chunkWorldZ, seaLevel, seed, 0]`), `blocks`
(read_write `array<u32>`, indexed `[z * H * S + y * S + x]`).
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_terrain", ...)` —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
·computeshader · born here
❒asset # walk
One thread per walker running `steps` dependent steps: each walker's start state goes in, its end
state and the state after every step come out, with the number of steps it ran. A state is 1 to 8
floats (`width`).
The step is a Field, handed to the kernel the way `map` takes its template: the fields package
fuses the Field into WGSL expressions and the kernel is specialized with them. A node holds no
WGSL.
| Specialization | Type | Meaning |
|---|---|---|
| `WALK_STEP` | `vec4<f32>` expression | lanes 0 to 3 of the next state; default `zero_walk_advance(s)`, the constant step |
| `WALK_STEP_HI` | `vec4<f32>` expression | lanes 4 to 7 of the next state; default `s_hi` |
| `WALK_DONE` | `bool` expression | whether the walker stops before step `k`; default `false` |
| `WALK_PRELUDE` | module-scope WGSL | the functions the expressions call, and `#include` lines for the `rand`, `noise` and `color` preludes |
The expressions read the state leaves `s` (lanes 0 to 3) and `s_hi` (lanes 4 to 7), the step
number `k` (u32) and the walker number `id` (u32), the numbers of `u` (`u_get(n)`) and the columns
of the `cols` table (`cols_f32(slot, i, lane)`, `cols_vec3(slot, i)`), which is how a step reads a
raster, a field column or a per-walker attribute. The constant step needs no Field: its vector is
the params `dx`, `dy`, `dz` and `dw`.
Bind `cols` (a table from `compute_abi.table`), `u`, `start` (`width` floats a walker). Outputs:
`finish` (`n * width`), `path` (`n * steps * width`, row `k` of walker `i` at
`(i * steps + k) * width`) and `steps_run`.
```luau
local variant = ref:program():variant({ specialize = {
WALK_STEP = "vec4<f32>(s.x + 1.0, s.y * 0.5, 0.0, 0.0)",
WALK_DONE = "s.x > 8.0",
} })
local run = variant:run({ n = walkers, inputs = { cols = emptyTable, u = numbers, start = startBuffer },
params = { steps = 8, width = 2 } })
```
Exact: each walker writes its own path rows, so the result does not depend on thread order.
·computeshader · born here
❒asset # compute_voxelize
Voxelizes a triangle mesh on the GPU. For each grid cell it casts a ray along +X
and counts Möller–Trumbore triangle intersections — an odd count means the cell is
inside the mesh.
Bindings (see bindings.yaml): `triangles` (read `array<f32>`, 15 floats/triangle),
`params` (read `array<f32>` — `[minXYZ, maxXYZ, resXYZ, voxelSize, triCount, 0]`),
`output` (read_write `array<f32>`, one per cell: 1.0 = occupied, 0.0 = empty).
Usage: dispatch by identity with `compute.dispatch("@builtin::shaders.compute_voxelize", ...)` —
it resolves to the shader's stable guid and auto-compiles on first use (no setup).
# postReference_checker
A checker of 64 cells across, 0.8 on 0.03: the high-frequency background a fast object crosses.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
# postReference_colorChecker
The 24 patches of the ColorChecker Classic, each its published sRGB value read as linear reflectance.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
# Error Test
Intentionally broken material used to exercise the renderer's error-handling and fallback paths. It targets `@builtin::shaders.error_shader` and carries a bright magenta base colour (`1.0, 0.0, 1.0`) — the classic "missing/failed" flag colour — with mid roughness (`0.5`), opaque render type, and back-face culling.
## Inputs
- `colors.base_color` (`1.0, 0.0, 1.0, 1.0`) — magenta error flag tint.
- `floats.roughness` (`0.5`) — neutral surface roughness.
- `render.type` (`opaque`) / `render.queue` (`2000`) — drawn in the standard opaque pass.
·computeshader · born here
❒asset # hash_starts
Finishes a spatial hash: given each point's bucket and the permutation that
sorts the points by bucket, states for every bucket where its points start and
end in the sorted order. Each bucket finds its two places by binary search over
the sorted keys, so no bucket needs clearing and the answer is a function of the
keys alone. Exact.
# Animated Color
An opaque, back-culled surface whose colour animates over time, driven by `@builtin::shaders.animate_shader`. Starts from a white base colour (`1.0, 1.0, 1.0`) with an `emissive` of `1.0` so the shifting colour reads brightly, at mid roughness (`0.5`) and fully non-metallic (`metallic 0.0`).
## Inputs
- `colors.base_color` — the starting colour the animation modulates.
- `floats.emissive` (`1.0`) — self-illumination strength of the animated colour.
- `floats.roughness` (`0.5`) — matte diffuse spread.
- `floats.metallic` (`0.0`) — dielectric, non-metallic surface.
·computeshader · born here
❒asset ·computeshader · born here
❒asset # abi_spec
Doubles src into dst as the element type T the specialization names.
# billboard
Camera-facing billboard shader for textured quads — labels, sprites, and 3D
text. All four corners of the quad sit at the same anchor, so the vertex's world
position is the anchor under any entity or parent transform. Each corner carries
its in-plane offset in the vertex colour; the vertex stage offsets the corner in
world space facing whichever camera renders the pass, so the quad is visible and
correctly framed from the main viewport, an offscreen capture, and a
render-texture camera alike. Because the offset is applied in world space before
projection, the quad keeps real extent and stays drawn when the anchor leaves the
frustum. The horizontal axis stays world-level, so it tracks a pitching camera
without rolling.
The world size lives in the per-corner offset (resizing rebuilds the vertex
colours), so there are no size material properties, and the mesh declares its own
render bounds so frustum culling keeps it. The fragment mirrors `unlit`:
`base_color * base_color_texture` with masked-transparency cutoff.
# foliage.shader
Vegetation that sways with the scene's wind.
The motion comes from the engine's frame-global wind (`rendering.setWind`), so
every material reading it agrees on direction, speed and gust phase — a gust
crosses a whole field instead of each plant animating on its own clock.
`compliance` scales how far this material yields — 1 for a grass blade, 0.1 for
a trunk. The mesh's red vertex channel is how freely each vertex moves: 1 at a
blade's tip, 0 at its root, so a blade pivots from its base. A mesh with no
authored vertex colours reads white and sways as a whole.
The gust phase is a function of world position, so a gust travels across a field
rather than every instance of the same mesh swaying in unison.
With no wind set the sway is zero and the surface renders as a plain lit
material.
·computeshader · born here
❒asset # intersect_cuts
The segment each entry of `intersect_pairs` is cut along, one thread per entry. The thread reads the entry's
`a`, `b` and part and writes the part's two endpoints (`intersect_core` states the parts). An endpoint record
is 8 words: the position as f32 bits, the kind word (the kind in the low byte, which meshes the segment cuts
in bits 8 and 9), then `lo`, `hi`, `tri` and `extra`, which name the crossing; two endpoints, 16 words, an
entry. The endpoint slot `s = 2 * entry + e` names an endpoint to `intersect_unify` and `intersect_retri`.
The points on shared edges have both endpoints in one record. Exact.
·computeshader · born here
❒asset # intersect_unify
The first slot of every cut point. Endpoint slots whose records name the same crossing (the kind word, `lo`,
`hi`, `tri` and `extra`) are one point; `rep[s]` is the lowest slot among them, which is the point's
identity. A slot with `rep[s] == s` is a new point's first slot, so a compaction of those slots
numbers the cut points, and every endpoint reference maps through `rep`.
Three dispatches (`STAGE claim`, `fold`, `resolve`) over a hash table of `cells` words (a power of two,
at least twice the slot count) and a second table of the same size, both zero before the first stage.
Bind `rep` (one word a slot) to the same buffer in all three. Exact: the cell a key takes depends on thread timing, the answer does not.
·computeshader · born here
❒asset # ray
Casts rays and segments against the triangles of a geometry through the
hierarchy the `bvh` kernel builds (closest hit, or any hit for occlusion), and
computes the generalized winding number of the geometry about each origin, which
is the inside test a boolean or a distance field needs. A hit is the parametric
t, the primitive index and the barycentric weights. The shader's header states
the ray and hit layouts. Exact: the same rays give the same hits, ties going to
the lower index.
`ray` is a family of three kernels, since one dispatch binds at most 8 storage
buffers a stage:
| Kernel | Answers |
|---|---|
| `ray` | `hit` (t, u, v, fan) and `hit_prim` (the primitive, the shape index of a mesh hit) for the `closest`, `any` and `winding` stages |
| `ray_surface` | for the `closest` hits `ray` found: `hit_normal` (unit triangle normal facing the ray's origin side) and `hit_end` (the hit point pushed out along the normal by the `skin` param; a miss answers the ray's end) |
| `ray_shapes` | the analytic shape table, bound as a `columns` binding (`shapeKind, center, extent, rotation, bounce, friction, index`; a plane's extent is its unit normal, a sphere's extent.x its radius): `hit`, `hit_prim` (the row of the shape table), `hit_normal`, `hit_end` |
Chain for a mesh: dispatch `ray` with `STAGE = closest`, then `ray_surface` with
the same `rays`, geometry bindings and the `hit` and `hit_prim` that `ray`
wrote.
# `lut` post-process shader
Colour grading through a lookup table. `pp.add(name, "lut", { texture = ... })`
registers it; `@builtin::modules.lut` builds, imports and installs the tables it
reads.
`lut_texture` is a LUT **strip**: an N-entry colour cube laid out as one row of N
square tiles, so the image measures `N*N` wide by `N` tall. Tile `b` holds the
plane of constant blue index, red runs across a tile and green runs down it. N
comes from the texture's own height, so this one shader serves a 16-, 32- or
64-entry cube.
The eight lattice entries around a colour are fetched with `textureLoad` at exact
texel coordinates and interpolated in the shader. That makes the result
independent of the texture's filter and wrap mode, and each blue plane is read
from its own tile.
A texture whose shape is not a strip — including the 1×1 fallback bound when the
effect has no table — returns the frame untouched, so adding the effect before
its table exists changes nothing.
| Property | Meaning |
|---|---|
| `amount` | 0 = the ungraded frame, 1 = the table's answer. |
| `lut_texture` | The strip. |
·computeshader · born here
❒asset # abi_columns
Adds the first lane of the columns a and b of a table into dst.
# Error Text
A 3D "ERROR" text model used as the visible fallback when an asset fails to
load — spawned in place of missing geometry so a broken reference is obvious
in-scene instead of silently invisible. Decomposed from `ERRORText.fbx` into
this bundle (mesh + material + texture + entity template).
## Composition
- Root `error_text` → `Sketchfab_model` → the `ERRORText.fbx` node hierarchy.
- Carries the extruded "ERROR" letter mesh, its material, and texture as
private subassets.
## Usage
Spawned automatically by the engine as the placeholder for an unresolved
asset; can also be spawned directly to test the fallback path.
# Plastic White
A clean white plastic — a non-metallic PBR surface with a pure white base colour (`1.0, 1.0, 1.0`) and mid roughness (`0.5`) for a soft dielectric sheen. Built on `@builtin::shaders.pbr`. Opaque, back-face culled, queue `2000`.
## Inputs
- `colors.base_color` (`1.0, 1.0, 1.0`) — the white plastic tint.
- `floats.roughness` (`0.5`) — soft, semi-glossy highlight.
- `floats.metallic` (`0.0`) — dielectric (non-metal) response.
- `floats.emissive` (`0.0`) — no self-illumination.
·computeshader · born here
❒asset # edges
The sides of a mesh as point pairs: the first stage of the edge table. One
invocation per primitive writes, for every vertex slot of its run, the side
leaving that vertex as `lo`, `hi` (its lower and higher point), `face` (the owning
primitive) and `rev` (1 when the side runs from the higher point to the lower).
A slot with no side holds `ZERO_NONE` in `lo` and `hi`, so a sort puts it last.
Integers are 32-bit words, exact.
The edge table is this kernel, a stable sort of the slots by `hi` and then by
`lo`, and the `edges_runs` kernel (run heads, then the table). The sort and
the compaction between are the `sort` and `compact` kernels; `edges_runs` states the
whole sequence. `closed_all` is 1 for a mesh of faces, which wrap; with 0 the
`closed` column decides per primitive, for curves.
# postReference_darkRamp
A ramp of light from 0 at the left edge to 0.1 at the right: the dark gradient an undithered 8-bit display path bands on.
Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
# pbr
The engine's standard physically-based material — the full glTF metallic-roughness
workflow lit by the shared `@builtin::shaderModules.pbr_shading` model. This is the default surface shader a
model uses when its material doesn't specify another, and it is also registered
under the legacy alias **`standard`** (the name many materials reference).
It is a `surface()` shader: it fills a `PbrSurface` and the engine generates every
pipeline entry point and lights it. Every parameter defaults to a neutral value, so
a material that sets nothing renders as a clean dielectric; the advanced lobes only
cost anything when a material opts into them.
## Properties
| Property | Type | Default | Meaning |
|---|---|---|---|
| `base_color` | color | `[1,1,1,1]` | Albedo tint, multiplied by `base_color_texture` and vertex colour. |
| `emissive` | color | `[0,0,0,1]` | Emissive tint, multiplied by `emissive_texture` and `emissive_intensity`. |
| `emissive_intensity` | float | `1.0` | HDR multiplier on the emissive output. |
| `roughness` | range | `0.5` | Perceptual roughness, multiplied by the green channel of `roughness_metallic_texture`. |
| `metallic` | range | `0.0` | Metalness, multiplied by the blue channel of `roughness_metallic_texture`. |
| `reflectance` | range | `0.5` | Dielectric reflectance knob (neutral 0.5 → 4% F0). |
| `ior` | float | `1.5` | Index of refraction → dielectric F0 and the refraction direction. |
| `normal_scale` | float | `1.0` | Strength of the tangent-space `normal_texture`. |
| `occlusion_strength` | range | `1.0` | Blend of the `occlusion_texture` (R) into the ambient term. |
| `clearcoat` | range | `0.0` | Strength of a second dielectric clearcoat specular lobe. |
| `clearcoat_roughness` | range | `0.0` | Roughness of the clearcoat lobe. |
| `anisotropy` | float | `0.0` | Anisotropic highlight stretch along the tangent ([-1,1]). |
| `sheen_color` | color | `[0,0,0,1]` | Tint of the sheen lobe — the retroreflective rim of velvet, satin and brushed fabric. Black leaves the base untouched. |
| `sheen_roughness` | range | `0.3` | Width of the sheen lobe. |
| `iridescence` | range | `0.0` | Blend toward the thin-film response, the hue that shifts with view angle. |
| `iridescence_thickness` | float | `400.0` | Film thickness in nanometres — which wavelengths cancel and which reinforce. |
| `iridescence_ior` | float | `1.3` | Index of refraction of the film. |
| `subsurface_color` | color | `[0,0,0,1]` | Tint of the light that entered the surface, scattered beneath it and left again. Black leaves the base untouched. |
| `subsurface_radius` | float | `0.5` | How far the diffuse falloff wraps past the terminator, taken per channel against `subsurface_color`. |
| `fibre_color` | color | `[0,0,0,1]` | Tint of the second of the two highlights a hair or fur strand gives. Black leaves the base untouched. |
| `fibre_specular` | range | `0.35` | Strength of the first strand highlight, in the light's own colour. |
| `fibre_shift` | float | `0.06` | How far apart the two strand highlights sit along the fibre. |
| `fibre_roughness` | range | `0.1` | Width of the first strand highlight. |
| `transmission` | range | `0.0` | Specular transmission — refracts the environment through the surface. |
| `thickness` | float | `0.0` | Volume thickness for Beer–Lambert transmission absorption. |
| `attenuation_color` | color | `[1,1,1,1]` | Transmission absorption tint. |
| `attenuation_distance` | float | large | Beer–Lambert absorption distance. |
| `uv_scale` | float2 | `[1,1]` | UV tiling applied before every texture sample. |
| `uv_offset` | float2 | `[0,0]` | UV offset applied before every texture sample. |
| `alpha_cutoff` | range | `0.0` | Mask threshold — fragments with `alpha <` this are discarded (0 = no cutoff). |
| `double_sided` | bool | `false` | Flip the shading normal on back faces. |
| `receives_fog` | bool | `true` | Whether the screen-space fog passes (height fog, aerial perspective) reach this surface. `false` leaves an opaque deferred draw at the colour it shaded to, however deep in the medium it stands — see below. |
### Emissive authoring
The glow output is `emissive × emissive_intensity` (× the `emissive_texture`). The glow
**colour** is `emissive`, a vec; the **intensity** over it is `emissive_intensity`, a
scalar. So `{ emissive = {0.1, 0.9, 1, 1}, emissive_intensity = 5 }` is a cyan glow at 5×,
and it is these two names that `getProperties()` lists and `setProperty` writes.
A spelling another engine's convention uses for the same role — `emissive_color`,
`emission`, `emissive_tint` — is resolved onto `emissive` when the material is authored,
so content carried in from glTF, Unity or Godot reaches the property under the name this
shader declares. Where two such spellings meet on one of the two names, the shape of each
value says which of them it is: a vec is the colour and a number is the intensity, so
`{ emissive_color = {0.2, 0.8, 1, 1}, emissive = 5 }` is the same cyan glow at 5x. Two
values of one shape are one property's, and the one written under the name the shader
declares applies while the other is named in a warning.
A bare positive scalar `emissive` with no colour beside it is the "turn emission on"
shorthand and means a white glow at that intensity, so `emissive = 20` on a white material
lights up.
### The lobes over the base layer
Beyond metallic-roughness, the shading model carries six layers this material
declares. Each is gated on its own neutral value, so a material that sets none of
them shades as a plain dielectric and each one costs only where it is asked for.
| Layer | Turned on by | What it looks like |
|---|---|---|
| Clearcoat | `clearcoat > 0` | A second dielectric specular lobe on top — car paint, lacquer, a varnished surface. |
| Anisotropy | `anisotropy ~= 0` | The highlight stretches along the tangent — brushed metal, a vinyl record. |
| Sheen | `sheen_color` above black | A retroreflective rim that brightens toward grazing angles — velvet, satin, dusty cloth. |
| Iridescence | `iridescence > 0` | The specular hue shifts with view angle — an oil slick, a soap film, anodised metal, a beetle shell. Thickness picks the colours. |
| Subsurface | `subsurface_color` above black | Light wraps past the terminator and glows through thin geometry lit from behind — skin, wax, marble, a leaf. `thickness` gates how much reaches the far side. |
| Fibre | `fibre_color` above black | The two offset highlights a strand gives instead of the one a surface gives — hair, fur. Taken around the world tangent as the fibre axis. |
All six are evaluated inside the engine's own light loop, once for every light
that reaches the surface, so each one is shadowed, attenuated and cone-masked
with the base layer it sits over.
An oil-slicked wet surface is `iridescence = 1`, an `iridescence_thickness`
around 300-500 nm and a low `roughness` over a dark `base_color`. Skin is a warm
`subsurface_color` with a `subsurface_radius` near 0.5. Velvet is a `sheen_color`
at the fabric's own hue over a dark base.
### Standing outside the fog
`receives_fog = 0` declares that the screen-space fog passes — `heightFog` and
`aerialPerspective` in `@builtin::systems.atmosphere` — leave this surface at the
colour it shaded to.
The declaration travels to those passes as a per-pixel surface flag written into
the alpha of the G-buffer normal (`@builtin::shaderModules.surface_flags`). Only
the deferred G-buffer fragment entry writes that channel, so the declaration
reaches the fog from an **opaque** draw on the **deferred** path. A draw the
renderer sends through the forward fragment entry — every draw on the forward
path, and the transparent phase on either path — writes no G-buffer channel to
carry it, and its pixels take the fog like any other.
## Textures (glTF metallic-roughness set)
| Slot | Default | Channels |
|---|---|---|
| `base_color_texture` | white | RGBA albedo (sRGB). |
| `roughness_metallic_texture` | white | G = roughness, B = metallic (glTF packing). |
| `emissive_texture` | white | RGB emissive (sRGB). |
| `normal_texture` | flat-normal | Tangent-space normal map. |
| `occlusion_texture` | white | R = ambient occlusion. |
Because the engine holds the full `PbrSurface`, the capture tool's debug passes
(albedo / roughness / metallic / AO / emissive / world-normal / shadow / depth /
motion) all read real material data.
·computeshader · born here
❒asset # contour_crossings
Where the surface crosses each of the twelve edges of every straddling cell:
the point and whether it crosses. An edge that does not cross carries its cell's
centre, a point any shape can be read at. Slot `s` of the outputs is the `s`-th
straddling cell, `cells[s]`, and edge `e` of it is slot `s * 12 + e`.
Dispatch over the straddling cells. Exact: each slot has one writer.
# Lit Checkerboard
A static, lit checkerboard surface built on `@builtin::shaders.lit_checkerboard` — the default ground material for newly seeded worlds. It uses a neutral light-grey base colour (`0.85, 0.85, 0.85`) with a grey emissive tint (`0.35, 0.35, 0.35`) so the pattern stays readable in dim scenes, high roughness (`0.7`), no metallic, opaque, and instanced.
## Inputs
- `colors.base_color` (`0.85, 0.85, 0.85, 1.0`) — neutral grey checker palette.
- `colors.dark_color` (`0.35, 0.35, 0.35, 1.0`) — the dark square colour, close enough to the base that the pattern stays readable in low light.
- `floats.roughness` (`0.7`) — mostly diffuse surface.
- `render.instancing` (`true`) — supports instanced draws.
# Decal Default
The default material a `DecalProjector` stamps when none is assigned. A flat cyan
tint (`0.05, 0.95, 1.0`) on `@builtin::shaders.pbr`. Assign a material with a
`base_color_texture` to project a texture; the projector samples the material's
base colour at the box-local XY of every surface inside its projection box.
# hair.shader
A hair or fur strand.
Its specular is a pair of offset bands rather than one spot: a fibre reflects
into a cone around its own axis, so the highlights are taken around the world
tangent — which on strand geometry runs root to tip. `fibre_color` tints the
second, broader band and is what switches both on; `fibre_shift` sets how far
apart they sit and `fibre_roughness` how narrow the first one is.
Colour comes from `base_color` times the per-vertex colour, so a groom carries
its own root-to-tip gradient under one material. `transmission_color` and
`transmission` are the light that carries through a strand — the glow along a
backlit edge.
Both faces of a ribbon stand for the same round fibre, so back faces are lit
like front ones.
·computeshader · born here
❒asset # edges_runs
Turns the sorted sides of a mesh into the edge table. Two stages share one
dispatch shape, chosen by the `STAGE` specialization:
- `STAGE heads` flags, per sorted place, where a new edge starts;
- `STAGE table`, after the flags are compacted into `starts`, writes each edge's two
points (`a` < `b`) and the number of sides along it (`fcount`).
The whole sequence for a mesh with `nv` vertices: `edges` writes `lo`, `hi`,
`face`, `rev`; a stable sort by `hi` and then by `lo` gives `order`; `STAGE heads` flags
the heads; `compact` of the flags gives `starts` and the live edge count; `STAGE table`
writes the edges. An edge's faces are the primitives `face[order[starts[e] + j]]`
for j below `fcount[e]`, so `gather(face, order)` is the CSR `edgeFace` column with
`starts` as its starts and `fcount` its counts. An edge is open when `fcount` is 1
and manifold when it is at most 2. Integers are 32-bit words, exact.
Over a live count (`COUNT=device`, see the abi README) `domain_count` is the number
of live sorted places in both stages, and the `n` param is not read. Stage heads runs
over the capacity of places and holds 0 in `flag` past the live ones. Stage table
runs over the capacity of edges: an edge is live where `starts` holds a place below
the live places (the slots past the live edges hold -1 where `compact` over a live
count makes them), a run ends at the live places, and every other slot holds -1 and
-1 in `a` and `b` and 0 in `fcount`. The device variant binds the buffers of its own
stage only: 5 storage buffers in stage heads and 8 in stage table (8 in the plain
variant).
# `bloom` post-process shader
The light a bright surface spills into the pixels around it. A half-resolution
`bright` pass extracts what stands above `threshold`, a pyramid of `downsample`
passes carries it down to 1/64 of the view, and a chain of `upsample` passes
carries it back up, blending each octave into the one above it. `composite`
adds the result to the scene. `tools.use("pp", "add", "glow", "bloom")`
registers it — the shader declares `space: light`, so the effect takes the
scene layer: the rendered picture before the UI is drawn, over the scene's own
light in a float target, which is where a bloom belongs.
## Passes
| Pass | Scale | What it does |
|---|---|---|
| `bright` | 0.5 | Extracts what stands above `threshold` from a 2x2 block of the scene, soft-kneed by `softKnee`. |
| `down1`…`down5` | 0.25 … 0.015625 | Each halves the previous octave's resolution with a 13-tap filter; `down1` also Karis-averages its five taps to keep a single bright texel from dominating. |
| `up4`…`up0` | 0.03125 … 0.5 | Each carries the smaller octave up with a 3x3 tent and blends it into the next one by `scatter`. |
| `composite` | (view size) | Adds the bloomed image to the scene, scaled by `intensity`. |
## Properties
| Property | Default | Range | Meaning |
|---|---|---|---|
| `threshold` | 1.0 | 0–16 | The brightness the `bright` pass extracts above. |
| `softKnee` | 0.5 | 0–1 | How wide the roll-in is around `threshold`, so a surface crossing it brightens rather than pops. |
| `intensity` | 0.6 | 0–4 | How much of the bloomed image the `composite` pass adds back to the scene. |
| `scatter` | 0.7 | 0–1 | How much of each octave an `upsample` pass blends into the one above it, and so how far the halo carries. |
| `levels` | 6 | 1–8 | How many octaves of the pyramid draw. |
| `clampMax` | 16 | 0–64 | The per-texel cap the `bright` pass applies before extracting, so one blazing pixel cannot blow out its octave. |
`levels` and the 8-texel floor an octave's short side must clear are both read
per pass, not baked into the pass list: an octave past either one returns the
larger image it was handed unchanged, so a slider drag on `levels` changes what
the twelve passes DO and never how many there are.
Eleven scratch targets in the scene format, the largest at half the view —
about 11 MB at 1080p.