# Effect
Plays one entry of an effect on its entity. Every graph the entry holds runs on
a Generator under this entity, from the same moment, each given the inputs it
declares; the entity's transform is where the effect stands, and it moves with
the entity. `effectRef:play` hands these out from gameplay; one placed in a
scene, or dropped into the viewport, plays the same way.
## Fields
| Field | What it does |
|-------|--------------|
| `effect` | The effect this plays. |
| `entry` | The entry it plays, as the effect's `effect.yaml` lists it under `plays`; empty plays the effect's default. |
| `inputs` | Values for the entry's inputs, by input name; an input left out takes its default. A name no graph of the entry declares is refused, naming the inputs it does take. |
| `playOn` | What starts it in play mode: `load` plays as soon as it binds, `manual` waits for `play()`. In edit mode an Effect is not set to play, whatever `playOn` says: it shows the frame it is on until it is played. |
| `ending` | At the end of its timeline: `graph` does what the timeline declares, `loop` plays it round again, `hold` stays on the last frame. |
| `speed` | How fast it plays: 1 its own rate, 0 still, negative backwards through a timeline with an end. |
## Methods and events
`play()` plays the entry from its start; `pause()`, `resume()`, `seek(seconds)`
and `stop()` drive it, and `stop()` also takes what it shows away.
`set(input, value)` changes one input. `getTime()` and `isFinished()` read where
it stands, `isPrepared()` whether its graphs have done the work its first frame
needs (every frame of a timeline with an end cooked, one with no end on the
device), `cookError()` why a graph's latest cook failed while one does (the
check to make each frame while waiting for `isPrepared()`), and `playback()`
what it costs: the entry's combined numbers, and each graph's own `playback()`
under `graphs`. `onFinished` fires when every graph of the entry has reached
the end of its timeline.
## From gameplay
A shot, a hit or an explosion is a play of an effect's entry, from the effect
itself; it is kept ready and goes back to be played again when it finishes:
```lua
local beacons = asset.resolve("beacons", "effect")
beacons:play("flare", { root = mast, offset = { 0, 0.9, 0 }, inputs = { size = 0.4 } })
```
# effect shared
What the effect type and its Effect component share: which of an entry's graphs
takes each input, and the plays `effectRef:play` hands out and keeps to play
again.
# assetType (asset type)
An asset type says what a kind of asset is: the files an asset of the kind is
made of, the code that gives it behaviour, the interface a person uses to work
with it, and how it is found, pictured and checked. A `<typename>.assetType/`
folder declares a type called `<typename>`, and every `<name>.<typename>/`
folder is an asset of it. `assetType` is itself a type, so a type is an asset
like any other: it is created, versioned, installed and contributed the same way.
## Making a type
`asset.create("assetType", "<typename>")` scaffolds a type. The type registers
the moment its folder is written, anywhere under `/zero/source/`, and from then
on `<name>.<typename>/` folders are its assets. An asset of a type that is not
registered yet is not an asset, so make the type first.
A type folder is a root: `~.x` in any file inside it names the type's own `x`,
wherever the type is installed. Keep the type's whole implementation inside its
folder and reach it that way.
What a type folder must hold is set by this type's own `type.yaml`, the same way
every type's `type.yaml` sets what its assets hold. `asset.validate` on a type
reports anything missing, and the scaffold produces a folder that passes.
## What sets your type's schema (`type.yaml`)
`type.yaml` is the structural contract every asset of the type is checked
against. The keys below are the ones the engine reads; a key not listed here is
ignored.
| Key | What it controls |
|---|---|
| `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. |
| `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. |
| `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. |
| `is_container` | Whether the suffix stays in the identities of what the asset holds. |
| `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. |
| `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. |
| `is_text_default` | Whether the asset's files are text unless stated otherwise. |
| `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. |
| `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. |
| `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. |
| `files: { required, optional }` | The files an asset holds (below). |
| `allow_unlisted` | `false` reports every file the type does not declare. |
| `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. |
| `settings:` | Typed per-asset settings (below). |
| `inspector:` | The interface people use for the type and its assets (below). |
| `preview:` | How an asset is pictured (below). |
| `references:` | Names of other assets the type's files carry (below). |
| `interfaces:` | The interfaces every asset of the type implements (below). |
| `indexing:` | What search reads for each asset (below). |
| `describe:` | How a missing description is generated (below). |
| `contexts:` | The environment the engine loads a file of the asset into, and what it holds (below). |
### The files an asset holds
Each entry under `files.required` or `files.optional` is
`{ path, kind: file | folder, one_of_group?, content? }`. `*` in a path matches
within one segment. Entries that share a `one_of_group` are satisfied by any one
of them. `content` lists checks on the file's bytes:
| Check | Passes when |
|---|---|
| `non_empty` | the file has content |
| `json_field { key, type?, non_empty?, accept? }` | the JSON holds the key (a dotted path) with that shape |
| `yaml_field { key, type?, non_empty?, accept? }` | the same for YAML |
| `described { keys?, headings?, message? }` | the file says what the asset is (see "Ask your assets to say what they are") |
Each check takes a `message`, which is what the author is told when it fails.
### Settings
`settings: { values, schema: { type | instance, export?, export_optional? } }` gives every asset
typed settings. `values` names the file an asset's values live in; `schema.type`
declares one schema for the whole type, and `schema.instance` names a file each
asset declares its own in. `asset.create` writes the resolved values, and a write
to the values file reaches `onChange` with what changed.
## The human side (`inspector.luau`)
A type is used by people through its Inspector, and without one the type is
usable only from code. The Inspector is the type's interface for a person: for a
procedural graph it is the graph editor, for a kit it is the tracking view of
what the kit holds and what is still missing. Writing it is part of writing the
type.
`inspector: { type, instance? }` in `type.yaml` names the files. `type` is the
interface for the type itself and for its assets; `instance` names a file an
asset may ship to add its own. Each returns:
```luau
return {
sections = { { id = "graph", title = "Graph", build = function(ctx) ... end } },
replace = { contents = { ... } }, -- replace a default section by id
order = { "graph", "contents" }, -- section order
}
```
`build(ctx)` receives the asset and builds the section. A section's `title`, and
the text its rows carry, is a string or an `i18n.text` value read from a catalog
(`i18n.text("inspectors.mesh.title")`), which follows the editor's language. `asset.create("assetType",
...)` scaffolds a working `inspector.luau` to start from. `asset.validate` on a
type that names no inspector, or names one that does not load, reports it.
## Say what your type is for (`about.yaml`)
Every type carries an `about.yaml` that says what the type is for, in three
plain-language texts:
```yaml
intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering."
function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text."
usage: "You choose it by name for your UI or your text, and the text appears in that typeface."
```
- **`intent`** is what the type is for in someone's game, in the words a game maker uses. Up to 800 bytes.
- **`function`** is how it works today: what an asset of it is made of and what the engine does with it. Up to 1500 bytes.
- **`usage`** is what a person or an agent does with one. Up to 1200 bytes.
Write about the type as a whole, not one asset of it, and say what it does now.
Agents read these texts to learn when to reach for the type and how; people
searching find the type by them. The scaffold starts each text with
`[[describe]]` and a note on what to write; a text that still starts that way
counts as not written. `services describe` can write them.
They show up in `asset.inspect` as `detail.about`, in
`assetTypeRef:getAbout()`, at the end of the type's `types/<typename>` guide,
and at the top of the type's Inspector.
## Ask your assets to say what they are
A type can require each asset to carry a description: a file, written by the
author or generated, saying what the asset is and what it is for. Declare it with
a `described` check:
```yaml
files:
required:
- path: "README.md"
kind: "file"
content:
- { check: "described", message: "Say what this widget is for and where it goes." }
```
A file that is missing, empty or still has a line starting with `[[describe]]`
fails the check, and so does a YAML file whose named `keys` are missing or over
their `max_bytes`, or a Markdown file missing a named heading. `asset.validate`
names the asset, and a push that carries it is refused with `message`.
`services describe` finds such assets and writes their descriptions.
`describe:` steers what is generated:
```yaml
describe:
guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI."
examples:
- "<identity of an asset of this type whose description reads well>"
```
An example is an asset of your type whose description is a true, written one,
never a placeholder and never the asset being described; with none, leave
`examples` empty. A type whose assets the model cannot perceive (a sound, a
motion) says so in `guidance`, and the description is drawn only from what the
asset's own files state.
Start the file unwritten in your `template/`: a heading and one line starting
with `[[describe]]`, never example content, which every new asset would carry
verbatim. A type whose assets say what they are through their own content (a
mesh, a texture) declares no check.
## Computed output files
A type can declare files produced by its compiler. Each rule names an exact
asset-relative output path, an activation marker, and guidance for editing the
inputs:
```yaml
computed_files:
- path: "cache.json"
when_exists: "authoring/state.json"
edit: "Edit the recipe and run the asset compiler."
```
Once the marker exists, ordinary writes, removal and individual-file moves are
refused for that output. The marker and output paths stay within the asset.
Declare their folders in `files.required` or `files.optional` as usual.
Compilers commit their outputs with the input revisions through
`modules.sourceOperations.materialize`. A complete asset copy to a new
destination carries its inputs and computed files together. Copying individual
files into protected outputs and merging a tree over protected outputs are
refused before destination leaves change.
## The type's code (`behavior.luau`)
`behavior.luau` returns one table. These are the keys the engine reads from it;
anything else on the table is the type's own.
### What the type's assets can do
| Key | Shape | What the engine does with it |
|---|---|---|
| `ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every asset of the type: `ref:name(...)`. |
| `modules` | `{ [name] = require(".x") }` | Code the type's assets reach with `asset.containing(__FILE__).modules.<name>`. |
| `events` | an events schema | Events an asset fires. Readers subscribe through `ref.events.<name>:connect(...)`; the type fires them. |
| `refShapes` | `{ [method] = function(self) -> (typeExpr, source?) }` | The result type of a `ref` method for one particular asset (below). |
| `namePattern` | a Lua pattern | The names `asset.create` accepts for the type's assets. Default `^[A-Za-z][A-Za-z0-9_]*$`. |
| `derive` | `{ output, module, compute, fingerprint, matches?, required?, timeout? }` | A file computed from the asset when it is committed; a `required` one holds the commit until it lands. |
Some `ref` names mean the same for every type, and the engine calls them:
- **`instantiate(self, target?, opts?) -> (root, idMap)`**: puts the asset in a scene. A type that lists `sceneInstantiable` under `interfaces:` guarantees it, and its return is a contract (below).
- **`inspect(self) -> detail`**: what `asset.inspect` reports for the asset beyond the common record (below).
- **`preview(self, opts)`**: renders the asset's picture; it wins over the type's `preview:` recipe.
- **`previewMaterial(self) -> { material }`**: the material a `surface` preview paints.
- **`saveDefinition(self)`**: writes the asset's in-memory edits back to its files in edit mode.
Some names are answered for every asset before the type is asked, so a `ref`
entry of the same name is never reached: `getSource`, `getBytes`, `getText`,
`exists`, `deps`, `implements`, `as`, `canInstantiate`, `canPreview`, `preview` (which calls yours
when you define one), `meta`, `runtime`, `events`, `typeRef`, `modules`, and the
residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`,
`gpu_resident`.
### When the engine calls the type
| Hook | Signature | When it runs |
|---|---|---|
| `onCreate` | `(name, opts) -> { [path] = contents }` | On `asset.create`. Returns the files of the new asset, laid over the type's `template/`. Annotate `opts`: its type is the schema `asset.create` checks the caller's arguments against. A `""` key writes a single loose file. |
| `onReplace` | `(dest, files) -> files` | On an `asset.create` over an asset already at `dest`, after `onCreate`, so what the author added can be carried into the replacement. |
| `onRegister` | `(self)` | Once per asset, when it first registers: when the world loads, on a live `asset.create`, and when an asset arrives later (installed, pulled, synced). This is what makes an asset take effect the moment it is written. |
| `onChange` | `(ref, change)` | On every write to a file inside an asset of the type. `change` is `{ path, asset, type, kind, origin }`, plus `settings` and `settingsChanged` for a write to the settings values file; `kind` is `edited` or `seeded`, `origin` is `local` or `remote`. Filter on `change.path`. Writes to one asset arrive in order, each after the hook for the one before has finished, and the hook may wait on what it reads. A write the hook makes inside its own asset arrives later like any other, so keep the hook convergent. |
| `onDependencyChange` | `(ref, change)` | When a module the asset's code requires is re-run, or a name the asset carries starts resolving. `change.kind` is `dependency`. |
| `onDelete` | `(ref)` | When an asset of the type leaves the world: deleted, or the world it is in is swapped away. |
| `validate` | `(ref) -> { { code, message, severity?, path? } }` | On `asset.validate`, after the `type.yaml` checks, for the type's own rules. `severity` defaults to `error`. Runs on every push, so a type's rules hold at publish. A hook that fails reports `validate.hook_failed`. |
| `validateCommitted` | `(folder, read) -> { { code, message, severity?, remedy? } }` | On every push, for each asset the push changes, over the asset as the commit the push publishes holds it. `read(file)` answers a file's committed text, relative to the asset's folder, or nil for a file the commit holds no text of. A problem of `error` severity (the default) refuses the push, whatever the working tree holds. |
### Settings hooks
| Hook | When it runs |
|---|---|
| `settingsDefaults(name, opts, asked) -> table` | Once per `asset.create`, for values the schema's defaults do not give. |
| `settingsCorrections(values, name, opts) -> (corrections?, reasons?)` | On every settings write. A correction to a field the writer named refuses the write, giving the reason. |
| `settingsDerivedDefaults(values, explicit, changed)` | On a settings write, for fields derived from others. |
| `settingsSchemaProblem(schema, ref) -> string?` | When an asset's own schema is read; a returned string refuses the schema. |
`creationInputs` (`{ [opt] = true | selectorOpt }`) names `asset.create` options
that are inputs to the type rather than settings.
### Reloading
An edit to `behavior.luau` reaches existing assets with no restart.
## How an asset is pictured (`preview:`)
| `kind` | The picture is | The type provides |
|---|---|---|
| `instantiate` | the asset placed in the preview studio through its `instantiate` | `ref.instantiate` |
| `image` | a file the asset holds, fitted to the frame | `source: { files }`, the candidate files in order |
| `surface` | the asset painted on a mesh | `mesh`, and `ref.previewMaterial` |
| `custom` | whatever `ref.preview` returns | `ref.preview` |
```yaml
preview:
kind: surface
mesh: sphere
```
`angle: [yaw, pitch]` turns the camera. The studio owns the light, the backdrop
and the framing, so an asset pictures the same in every world. A type with no
`preview:` that defines `instantiate` still answers `ref:preview()`.
An asset whose picture is what it does to a scene rather than what it looks
like (a lighting setup) names a `subject` on an `instantiate` recipe: a
scene-instantiable asset stood in the studio in its place, while the asset
itself is applied to the world (`applicable`, owner `preview`) for the
shot and dropped after it. `studio_light: false` photographs the subject under
the world's lighting, which the applied asset states, instead of the studio's;
such a picture renders only on an explicit request (`preview.writePreview`,
`assets.generatePreviews`, staging), never from the preview queue or a live
preview.
```yaml
preview:
kind: instantiate
subject: "@builtin::preview.subjects.lookdev"
studio_light: false
```
A picture is rendered when something asks to view it (the editor showing the
asset, `ref:preview()`), when previews are generated on request
(`assets.generatePreviews`), and when the asset is staged. An edit alone
renders nothing. The picture records what it was made
from, so a stale one is told from a current one.
## The names your type's assets hold (`references:`)
Where your type's own format or API carries the name of another asset, declare
it here:
```yaml
references:
keys: # a top-level key of the type's files that holds a name, or a table of them
- { key: "shader", type: "shader" }
args: # an argument of a call, counting from 1
- { call: "g:node", position: 2, type: "procNode" }
fields: # a field of the options table a call takes
- { call: "fx.beam", field: "material", type: "material" }
```
`type` is the category the name resolves in, or a list of categories: a name
there is recorded as the one asset of those categories it answers to, a name
two of them answer to is recorded as neither, and a name written as a path
ending in one of their suffixes is the asset at that path.
A key whose names are assets of any type implementing an interface is stated
under `interfaceKeys`, and is declared typed to the types that implement the
interface, again whenever a type or an interface changes:
```yaml
references:
interfaceKeys:
- { key: "members", implements: applicable, field: "source" }
```
`asset.declareReferenceKey`,
`asset.declareReferenceArg` and `asset.declareReferenceField` declare the same
from a script.
A JSON or YAML data file of your type is read whole for the references it holds:
every `{ __ref }` envelope, `@` identity and `components` entry in it. When a file
also keeps values that are data rather than links (an edit history holding the
asset a field used to name, say), `documents` names the fields that carry its
links, and the rest of the file is read as data:
```yaml
references:
documents:
- path: authoring/entities/ # every file under this folder of the asset
fields:
- [records, "*", references] # keys from the root; "*" is every entry of a list or mapping
- references
- path: authoring/settings.json # this one file
fields: [references]
```
`path` is inside the asset's folder; the longest `path` covering a file decides
it. Each value a field reaches is read whole. A file that holds none of the
fields is read whole, as is every file no `path` covers. An entry with no valid
`path` or `fields` is refused with a warning naming it.
## What your type guarantees (`interfaces:`)
An interface is an asset (`<name>.interface/`, see the `interface` type) that
states a guarantee: members with signatures, and properties. A type lists the
interfaces its assets implement in its `type.yaml`:
```yaml
interfaces: [sceneInstantiable]
```
Every asset of the type implements every interface the type lists; an asset of
a type that lists nothing never does. The key is a reference to `interface`
assets, so each name resolves like any asset name and is recorded by guid in the
type's reference table, which is where the engine reads the type's marks from.
The `indexing:` role named `interface` is a different thing: it names the file
that states the signatures a caller of an asset uses.
The type meets each member in its `behavior.luau`, implicitly with its own
`M.ref.<member>` of the member's name and signature, or explicitly when its own
method of that name means something else:
```lua
M.ref = { apply = function(self, into) ... end } -- the type's own meaning
M.interfaces = {
applicable = { apply = function(self, owner, values, opts) ... end },
}
```
`M.interfaces` is keyed by the interface's name as the type lists it. A property
the interface states is met by a value or a getter `(self) -> value` in the same
two places, else by the interface's default. A type whose own `<member>` is
shared by two interfaces with different signatures meets at least one of them
explicitly.
| Question | Call |
|---|---|
| Does this asset implement X? | `ref:implements("X")` (a name, identity or guid, or a list meaning any of) |
| Call a member through the interface | `ref:as("X"):member(...)`; `ref:as("X").property` reads a property |
`ref:as("X")` raises, naming the asset and `X`, when the type does not implement
it. A direct `ref:member(...)` reaches the type's own method of that name; when
the type meets the member implicitly, that method is the member and the call goes
through the interface's gate, which checks its inputs and its result. A generic
caller (one that knows only the interface) calls through `:as`.
A declaration that breaks a check is refused: it carries no marks, `asset.validate`
reports each problem as an error that refuses a push, and the engine log states
each once. The codes are `interfaces.shape`, `unknown`, `ambiguous`, `duplicate`,
`missing`, `arity`, `typeKey`, `explicitUnclaimed`, `explicitUnknown`,
`propertyMissing`, `propertyType`, `conflict` and `unloadable`; each message names
the type, the file, the fault and what to write instead. A type that defines
`instantiate` and lists no `interfaces:` (one written before the key existed, or
defined by its `behavior.luau` alone) implements `sceneInstantiable` with the
warning `interfaces.implied`, which names the line to add. `asset.inspect` of an asset lists the interfaces its type
implements, and of a type definition lists them under `detail.interfaces` with
`detail.interfaceProblems` when the declaration was refused. The type's
Inspector shows the same under **Interfaces**: one row per interface (its name,
the first line of its description, and whether the type declares it or it is
implied), then every problem the declaration raised. An interface's own
Inspector shows its guarantee, its contract module and conformance suite, every
member with its signature, inputs and output, and the types that implement it.
The asset browser's **Implements** filter narrows the list to the assets whose
type implements the interface chosen, each interface's description as its
tooltip.
## The environment a file runs in (`contexts:`)
A type whose assets hold a script the engine loads itself states the environment that script runs in, so the engine binds it and the language server checks the script against the same names:
```yaml
contexts:
- name: sceneBuild
file: "build.luau"
surface: "scene's `build.luau`"
globals:
build: "the build surface is bound in a scene's `build.luau`'s own environment, where `build.asset` authors ..."
hooks: [content, editorOnly]
modules: true
```
- `name` is the context's name.
- `file` is the file of the asset folder that runs in the context.
- `surface` names that file in a diagnostic, without an article.
- `globals` are the names the type's loader binds into each run of the file. Each carries the note an unknown-global message gives when the name is used in a file that lacks it.
- `hooks` are the functions the engine calls by name from the file, which the language server does not report as unused.
- `modules: true` says the loader binds the exports of the modules that join the context.
A module joins with `--!context <name>` in its leading comment block. The type's loader builds the environment with `ScriptContext.bind(env, path, values)` (the `script_context` module), which refuses a value the context does not declare. `asset.context(path)` reads the context a file runs in.
## What search reads (`indexing:`)
`indexing:` is how assets are found. Search reaches an asset only through what
its type's `indexing:` names, and adds nothing of its own. That includes you: an
asset indexed badly is one you cannot find later, when you are making something
else and need it. A type whose assets are never looked for says `indexing: none`.
```yaml
indexing:
data: # text, read from the asset's files
- role: identity
extractor: verbatim
source: { file: "README.md" }
- role: interface
extractor: symbols
source: { files: ["init.luau"] }
- role: implementation
extractor: verbatim
source: { files: ["init.luau"] }
content: # the picture
- role: identity
modality: image
source: { file: "preview.png" }
facets: # what a query filters and re-ranks by
file: ".metadata"
rigged: { type: bool, from: { components: { contains: SkinnedModel } } }
roughness: { type: number, filter: range, from: { file: "mat.yaml", field: "floats.roughness" } }
```
**Roles.** Each `data` and `content` entry has a `role`, and a query matches in
two slots:
- **`identity`**: what an asset is. For anything you look at, the picture; for anything else, the text that says what it is.
- **`capability`**: what it does and how it is made. `interface` (the signatures or shape a caller uses) and `implementation` (the body) both count as capability, and a type with code usually declares both.
Ask what a person would recognise an asset of the type by, and what it does, and
point each role at the file that says it. For text, that is the asset's
description: the file your template starts with a `[[describe]]` block, which the
author writes or `services describe` fills in (see "Ask your assets to say what
they are").
**`data`.** `extractor: verbatim` embeds a file's text as it is; `symbols` embeds
the declared signatures of code. `source` is `{ file }` or `{ files: [...] }`.
Never index a file name (`source: { field: name }`): one
or two words carry nothing to match.
**`content`.** `modality: image` embeds the picture itself, so a text query
matches what the asset looks like. A type whose assets are looked at makes the
picture its identity.
**`facets`.** What a query narrows and re-ranks the matches by. `file` is embedded
whole, so keys nobody declared in it are still found. Each further key is
computed for every asset and states a value for every one, including `false`: a
file can imply "not rigged" but never say it, and a query separates rigged from
unrigged only because the unrigged ones say `rigged: false`. A key is
`{ type: bool | number | enum, filter?: range, from }`, where `from` is
`{ file, field }` (a field of one of the asset's files, dotted for nesting),
`{ metadata: key }`, or `{ components: { contains | any_outside } }` (what the
asset's entities carry).
## What blocks a push
A push checks every asset it carries against its type. These refuse it:
- a required file that is missing, a `content` check that fails, a `described` file not written yet;
- an error from the type's `validate`.
Unlisted files and warnings do not. A `described` file blocks only a push that
changes the asset. When a push is refused, the message names each asset and what
it lacks. `world.publishBlockers()` and `zm status` read the same list without
pushing.
## Typing a result from the asset (`refShapes`)
A `ref` method whose result depends on the asset (one entry per child folder, per
row of a config, per control a map declares) can only be annotated as
`{ [string]: Thing }`, which accepts any key. `refShapes` states the result for
each asset instead: a function returning a Luau type expression for that asset,
and the module whose types the expression uses. Read the asset; never run it.
```lua
-- inputMap.assetType/behavior.luau
M.refShapes = {
activate = function(self): (string, string)
local names = {}
for _, control in ipairs(M.ref.controls(self)) do
table.insert(names, control.name .. ": Handle")
end
if #names == 0 then return "", "" end
return "{ " .. table.concat(names, ", ") .. " }", "@builtin::modules.zinput.scheme"
end,
}
```
With it, `map.jump:onPressed(fn)` is checked and `map.noexisting` is reported.
A per-asset type applies where the call site names which asset: a component
field whose default names it, or an annotation `AssetRef<"inputMap", "<identity>">`.
`asset.resolve(name, category)` carries only the category, and a name computed
at runtime carries nothing, so calls on those keep the declared return. The type
belongs to the call's result: index it there, or bind what you need from it
there, and the names stay checked.
`require("@builtin::assetTypes.assetType.shared.refShapes").published()` shows
what was published: `categories` (each type's method surface) and `returns`
(per-asset results by identity, then method). An identity missing from
`returns` was never published. Results are recomputed when an asset is written;
at most 64 assets of one type are read.
## Putting an asset in a scene (`ref.instantiate`)
A caller writes one piece of code against every instantiable type, so what
`instantiate` returns is fixed:
```lua
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts)
-- compose the asset under `root`, now
return Instantiable.result(self, root, idMap)
end,
}
```
**In.** `target` is the entity the asset lands under, or onto for a hierarchy
type; with none, the type spawns a new root. `position`, `rotation` (three
numbers in degrees, or a quaternion), `scale`, `name` and `temporary` mean the
same for every type: `Instantiable.root` applies them to a root you make,
`Instantiable.place` to one you adopt. Document any options of your own in the
hook's `--!arg` docs.
**Out.** `(root, idMap)`. `root` is the composed root, live when you return:
build synchronously, never defer to a component's `awake`. `idMap` maps each
original id to the spawned one, so a component that composes the asset again on
every load can pass it back in and keep references into the composition. Every
call goes through `Instantiable.result`, which refuses a root that is not live
and turns a missing `idMap` into `{}`.
## Inspecting an asset (`ref.inspect`)
`asset.inspect(ref)` builds a record every asset shares (`identity`, `name`,
`guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`,
`description`, `tags`), then calls `ref.inspect(self)` for the type's own
`detail`:
```lua
M.ref = {
inspect = function(self)
-- read the asset's own files, never runtime state: inspect works on an asset
-- that has not been compiled, uploaded or registered
return { --[[ what makes this asset what it is ]] }
end,
}
```
Without it, the record is the shared part alone, and an agent inspecting the
asset learns nothing of what it is. A hook that raises leaves `detail` empty and
sets `record.warning`.
## Discovery
- `asset.list("assetType")`: every registered type.
- `asset.inspect("<typename>")`: the type, its README and its `about.yaml` texts.
- `asset.resolve("<typename>", "assetType")`: the type itself.
# Component (asset type)
A component is code that runs on an entity. The component file
declares public fields, methods, and lifecycle hooks and callbacks; the
engine creates one per entity it is attached to and drives those hooks
(`start`, `update` every frame, `onDestroy`) and callbacks. Components
are the unit of per-entity gameplay code: movement, AI, animations, UI
panels, network sync, and per-entity state all live here.
## When to use one
- You need per-entity state that survives across frames.
- You need per-entity behavior driven by engine lifecycle hooks
(`start`, `update`, `onDestroy`).
- You want to expose configurable fields to designers / `entity.spawn`
callers / scenes without code changes.
If the code does not run on an entity and needs no hooks or callbacks,
use a `.module`. If you
need to generate content declaratively, use a `.service`; compute work
belongs in a `.computeShader`.
## Where it lives
- Source: `/zero/source/.../<Name>.component/`
- Identity: `<Name>` (the `.component` suffix strips from the
identity, but the folder retains the suffix on disk).
- Folder shape:
- `init.luau` (or `init.lua`) — declares the component. **Required.**
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
The structural contract is enforced by `asset.validate` against this
type's `type.yaml`.
## How to create one
Always start with the scaffold — it guarantees the folder shape
matches `type.yaml` from the moment it's on disk:
```luau
asset.create("component", "<Name>")
-- Creates: /zero/source/<Name>.component/
-- init.luau (canonical declare + public block + hooks stubbed)
-- README.md (instance README template)
```
After scaffolding, edit `init.luau` to fill in the actual fields and
behaviour. The component registers as soon as the file is written —
hot-reload is automatic; no engine restart required.
## How it operates
1. **Registration.** Writing `init.luau` into a `.component/` folder
indexes the asset, mints a guid (in the `.meta` sidecar), and
surfaces the type to the engine's component registry. Same-frame
visible to `entity.component.add`.
2. **Attachment.** `entity(id).component.add(name, data)` (or the
batch form `tools.use("entityOps", "addComponents", targets,
{ [name] = data })`) attaches an instance.
The `data` table's fields override the component's declared
defaults; omitted fields take the declared default. The `data`
values are copied into `public.*` BEFORE `awake()` runs.
3. **Lifecycle.** The hooks run in this order:
- `awake()` — same frame as attach, immediately after the data
copy. Initialise state, set up native bridges, register with
other systems. Other components on the same entity may not have
awoken yet.
- `start()` — the next frame. Every component on the entity has
completed `awake()` by then, so cross-component setup is safe
here.
- `update(dt)` — same frame as `start()`, then every frame after,
for as long as the gameplay clock is running. `fixedUpdate(dt)`
runs once per physics step, straight after it, with the step's
`dt`, so a frame can run it several times or not at all;
`editorUpdate(dt)` runs
while the clock is held. Which of them ticks is decided by
`engine.mode` AND `engine.paused` together — see **Per-frame
hooks and the two axes** below, and `man modes`.
- `onDestroy()` — when the component is removed via
`component.remove` or when the owning entity is despawned.
Release resources, drop native ECS components.
For the full list (`onEnable`, `onDisable`, `fixedUpdate`,
`editorUpdate`, `onPropertyChanged`, `onAssetReload`,
`onModuleReload`,
`onBeforeSave`, …) and the timing details, **read `man components`
— that is the canonical lifecycle reference. Generic component
patterns (declare blocks, public fields, sync, ECS bindings,
typed methods) all live there.**
4. **Public surface.** Fields declared in `public` are inspectable,
editable in the inspector, and persist with the entity. Methods are
declared on that same table with a colon —
`typed function public:method(args)` — and every one of them takes
the component ref as `self`, so a caller invokes it with a colon
too: `entity(id).component.get(name):method(args)`. That is the one
calling convention a component ref answers to: the reflection
methods `ref:fields()` / `ref:getField(name)` /
`ref:setField(name, value)` take the same spelling. A function the
chunk declares at file scope (`function helper()`) is the
component's own, reachable from its hooks under its bare name;
`public` is what the ref carries.
5. **Settings and the Inspector card.** `type.yaml` names the component's
settings schema as `settings: { schema: { instance: "init.luau",
export: "public" } }`: the `public` table IS the schema, and its values
live on each entity the component is on, so `asset.schema(componentRef)`
answers the Field descriptors and no values file exists. On an entity
the Inspector shows the component as a card whose generic `settings`
section edits those fields as typed controls, each edit checked against
the schema and written to the live component as one undoable operation.
`type.yaml` also names `inspector: { instance: "inspector.luau" }`: a
component that ships an `inspector.luau` beside its `init.luau` shapes
its card — the file returns `{ sections, replace, order }` (see
`assetTypes/README.md`, "`inspector:`"), each section's `build(ctx)`
reading `ctx.component` (the live component) and `ctx.selection.id` (the
entity). `SceneModule.component/inspector.luau` replaces `settings` with
the bound module's declared inputs.
6. **Events.** An `events` block declares typed moments the component
fires from inside — `events = { onHit = Event({ dmg =
Field.number(0, NoSync) }) }`. The owner fires with
`events.onHit:fire({ dmg = 10 })`; outside code subscribes through
the proxy's subscribe-only facade,
`entity(id).component.get(name).events.onHit:connect(fn)`
(`:once` / `:wait` too). Pass `Sync` as the event's second argument
to replicate a fire to other peers. Events let one component react
to another's moments without polling. Full reference: **`man
components`**, Events section.
7. **Hot reload.** Editing `init.luau` reloads the component
definition; live instances are reconciled with the new declaration
in-place, and each crosses one lifecycle boundary: `onDestroy()`
ends the running life, then `awake()` and `start()` construct the
one that replaces it, and `update()` resumes on the next frame.
`public` and `private` values carry across; module-level `local`s
belong to the chunk, so the new life starts with them at their
initial values and its `awake`/`start` are what fill them in.
Whatever the old life handed elsewhere — a subscription, a shared
registration, a spawned entity — is released in `onDestroy`, the
call that pairs with the construction about to run. An edit that
leaves the source byte-identical crosses no boundary at all.
A field carries its value across when something stated it: a key of
the `data` table the instance was attached with (a scene record's
data is that table), or a write made since. Every other field takes
the edited source's declared default, so changing a default reaches
every instance that left the field to it. An instance that states
its own value for a field whose default the edit changed keeps that
value, and the reload logs a `[HotReload]` warning naming the field,
the entity, the value kept and both defaults.
## Discovery
- `asset.list("component")` — every registered component (engine +
world + libraries).
- `asset.inspect("<name>")` — identity, scope, public fields,
lifecycle methods, source path, and this type README. `detail`
carries the component's declared `fields`, `methods`, and `events`,
parsed from its source — `tools.use("assets","describe", "<name>")`
renders it as markdown, so a component's events are visible without
opening its source.
- `ls /zero/source/<Name>.component` lists the files the folder holds.
- `entity(id).component.list()` — components attached to an entity.
## Per-frame hooks and the two axes
`engine.mode` (`"edit"` / `"play"`) and `engine.paused` (the gameplay
clock) are independent, and the per-frame hooks read them separately:
- `update(dt)` / `fixedUpdate(dt)` tick while **the gameplay clock is
running** — whichever mode the engine is in.
- `editorUpdate(dt)` ticks while **the clock is held** — because the
mode is `edit`, or because play is paused — and also alongside
`update` whenever edit is running.
Which gives four states, and this table is the contract:
| `engine.mode` | `engine.paused` | hooks that tick |
|---|---|---|
| `edit` | `true` | `editorUpdate` |
| `edit` | `false` | `update`, `fixedUpdate`, `editorUpdate` |
| `play` | `false` | `update`, `fixedUpdate` |
| `play` | `true` | `editorUpdate` |
Entering edit sets `paused = true` and entering play sets it back to
`false`, so a session that never writes `engine.paused` only ever sees
rows 1 and 3 — which is where the shorthand "`update` is the play tick,
`editorUpdate` is the edit tick" comes from. It is the two default rows
of a four-row table, not the rule.
**Row 2 is the one that surprises.** With `engine.paused = false` in
edit — set by hand, or by a tool that advances the gameplay clock to
sample it, such as a `capture.collage` given a `duration` — `update` and `editorUpdate`
both fire, once each, every frame. A component that declares both and
routes them to one body therefore runs that body **twice per frame**:
```luau
local function drive(dt) ... end
function update(dt) drive(dt) end
function editorUpdate(dt) drive(dt) end -- twice per frame in row 2
```
Nothing reports the doubling; it reads as an animation running at twice
its intended speed. To get exactly one tick per frame in every row, ask
which axis you meant and answer it in the body:
```luau
function update(dt) drive(dt) end
function editorUpdate(dt) if engine.paused then drive(dt) end end
```
A scene `entrypoint.luau` declaring the same two hook names is dispatched
by the scene loader, not by this table: there `update` needs play AND
running, `editorUpdate` needs edit, and play-paused ticks neither. Read
`man scenes` before carrying a component's rule to an entrypoint.
## Authoring conventions
- Annotate public fields with `--!desc` so the inspector + LSP show
documentation alongside the field name.
- Declare lifecycle hooks (`start`, `update`, `onDestroy`) explicitly
rather than relying on engine defaults — readers can see at a glance
what runs when.
- Keep `update(dt)` cheap — it runs every frame per instance. Move
heavy work to `start`, to a `.computeShader`, or behind a job (`man jobs`).
- For multi-entity batching, prefer
`tools.use("entityOps", "addComponents", targets, components)` over
a loop of `entity(id).component.add` — it takes many targets and
many components in one call.
## Common pitfalls
- **Naming.** The component identity is the folder stem with
`.component` stripped (e.g. `<Spinner>.component/` → identity
`Spinner`). Don't repeat the suffix in the identity passed to
`component.add`.
- **`init.lua` vs `init.luau`.** Either is accepted (it's a
`one_of_group: "entrypoint"`), but `.luau` is canonical. Mixing both
in one folder is invalid.
- **`update` in edit mode.** It runs whenever the gameplay clock is
running, and entering edit stops that clock — so `update` is idle in
a freshly-entered edit session and ticks again the moment anything
sets `engine.paused = false`. Use `tools.use("wld", "play")` to test
update logic under the mode it ships in; `tools.use("wld", "edit")`
to return. See **Per-frame hooks and the two axes** above.
- **Renaming.** Renaming the folder changes the identity. References
to the component are recorded against the component itself, so
renaming or moving it does not break them.
## Related types
- `.module` — pure-function library, no per-entity state.
- `.service`: a declarative content generator, no per-entity state.
- `.preset` — a captured component configuration, replayable into
`component.add` without re-typing fields.
- `.bundle` — entity hierarchies that may carry component attachments
as part of the bundle.
## In the Inspector
Fields: its execution order, hooks, and how many methods and events it declares, then the fields its `public` table declares as read-only typed controls holding their defaults, with **Check** and **Open** for its entry file. Instances: a link to every entity carrying it. What its card shows on an entity comes from the component's own `inspector.luau`.
# `bloom` post-process shader
The light a bright surface spills into the pixels around it. A half-resolution
`bright` pass extracts what the picture shows above `threshold`, a pyramid of `downsample`
passes carries it down to 1/256 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.
What blooms is judged in exposed light: the scene's light times the exposure in
force (`zero_display_exposure()`, the gain `__display__` applies before its
curve). The same scene shown brighter or darker blooms the same highlights, and
a scene lit four times brighter and exposed four times lower is one picture
with one glow. Below the threshold nothing blooms, so a diffuse surface the
picture shows under its highlights lifts no shadow. Above it the glow is carried
in the scene's own light and grows in proportion to the light a source stands
above the threshold with, so the brightest things in a frame keep their order
through their glow.
## One look at every resolution
The halo is measured in the frame's own units: it covers the same share of the
picture at 360 lines, 1080 and 4K, on a landscape, a square and a portrait
frame, so a screenshot, a phone held either way and a monitor show one glow.
Every pass of the pyramid below the bright pass declares `lines: 1080`, so it
is drawn at the size it has in a 1080-line view of the frame's shape: its
finest level, `up0`, is 540 texels tall and each level below it half the one
above, at every output size. Octave
`n` is a texel 2^n lines of a 1080-line frame, the same share of the height of
a frame of any size and shape (`zero_view_size()` names the frame's size to
every pass), and every frame holds the same images of the same octaves. A
frame under 540 lines draws the levels that would outgrow it at its own size,
and those levels pass the image they read through unchanged, so its pyramid
starts at the finest octave its own texels resolve.
The bright pass declares `maxLines: 1080`. On a frame of 1080 lines or fewer
it is drawn at half the frame's own size, so each of its texels is the 2x2
block of the frame's pixels it covers and every pixel's light is taken once at
the cost of four reads; on a taller frame it is 540 texels tall, each texel
the block of the frame's pixels it covers (four on a side at 2160 lines). The
image `down1` reads is therefore never more than twice `down1`'s size, so its
taps reach every texel of it and a small source glows alike wherever it stands
on the frame. `down1` spaces its taps in halves of its own texel, the spacing a
1080-line frame's first level has on any frame, and `up0` reads the bright
image at its own texel. A frame under 1080 lines therefore spends less on the
bright pass than a 1080-line frame, and keeps every octave of the pyramid.
The weights follow one curve over that size: falling by `scatter` per octave
from octave 0.5 out to `levels` - 0.5, with the last octave, out to
`levels` + 0.5, carrying what the fall leaves. The light the curve holds
between two octaves is shared between them by how near it lies to each, the
way a filter between two mip levels blends them, the finest octave taking
every share finer than itself; the shares sum to the whole of the curve, so
the bloomed image holds exactly the light the bright pass took, at every size.
The deepest octave a frame keeps is the last whose image is 8 texels tall,
octave 7 (8 of a 1080-line view's rows, an eighth of the frame's height): the
floor is met on the frame's height, the axis the octaves are measured on, so a
portrait frame keeps every octave a landscape frame of its height keeps.
Measured on one disc a 36th of the frame's height across, under
`threshold = 1` and `intensity = 4` with every other property at its default
(the mean light of the ring 0.02 of the height wide):
| capture | ring at 0.05 h | ring at 0.10 h | ring at 0.18 h | ring at 0.25 h |
|---|---|---|---|---|
| 640x360 | 0.3003 | 0.0575 | 0.00734 | 0.00101 |
| 1280x720 | 0.3046 | 0.0585 | 0.00749 | 0.00103 |
| 1600x900 | 0.3054 | 0.0586 | 0.00750 | 0.00103 |
| 1920x1080 | 0.3057 | 0.0587 | 0.00751 | 0.00103 |
| 3840x2160 | 0.3073 | 0.0589 | 0.00755 | 0.00104 |
| 1280x1280 | 0.3043 | 0.0587 | 0.00745 | 0.00102 |
| 720x1280 | 0.3070 | 0.0596 | 0.00785 | 0.00111 |
Every frame of one shape reads within 3% of the 1080-line frame at every ring,
and so do `levels = 3`, `levels = 8` and `scatter = 1`. A portrait frame reads
its inner halo as a landscape frame of its height does; its outer rings come
within a few octave texels of its sides, where the light an octave carries
past the frame's edge is held at the edge rather than lost, and read up to 9%
brighter at 720x1280.
## Passes
| Pass | Size (rows) | What it does |
|---|---|---|
| `bright` | half the frame's, at most 540 | Extracts what each texel of the block of the scene it covers (2x2 up to 1080 lines, a third texel in part on a frame of an odd size, 4x4 at 2160) shows above `threshold`, soft-kneed by `softKnee`, and averages them weighed by the share of each the block covers. A texel holding more light than the half-float targets carry (an infinity a shader overflowed to) is taken at the largest light they hold, and one holding no number is taken as none, so one texel spreads glow and never a value that blacks out the octaves it reaches. |
| `down1`…`down7` | 270 … 4 | Each halves the previous octave's resolution with a 13-tap filter, its taps spaced in halves of its own texel; the first of them that reads the bright image also Karis-averages its five groups, each weighed against the plain average of the five, so a group standing far above its neighbours (a firefly) weighs little while groups alike average plainly at every brightness. |
| `up6`…`up0` | 8 … 540 | Each carries the smaller octave up with a 3x3 tent and blends it into the next one, by the share of the halo the octaves below carry against the share this one adds to them. `up0` blends into the bright image. |
| `composite` | (view size) | Adds the bloomed image to the scene, scaled by `intensity`. |
## Properties
| Property | Default | Range | Meaning |
|---|---|---|---|
| `threshold` | 4.0 | 0–16 | The exposed brightness (light times the exposure in force) the `bright` pass extracts above. 1 is what a linear display shows as white; the default 4 sits two stops over it, where the display's curve is in its shoulder, so diffuse surfaces stay out of the glow and emitters, sun glints and the sky by the sun bloom. |
| `softKnee` | 0.5 | 0–1 | How wide the roll-in is around `threshold`, as a share of it, so a surface crossing it brightens rather than pops: at the defaults the roll-in runs from 2 to 6. |
| `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 the glow each octave carries out to the next one: each octave out carries `scatter` times the light of the one inside it, so a higher `scatter` carries the halo further. |
| `levels` | 6 | 1–8 | How far the halo reaches: its widest octave is a texel 2^`levels` lines of a 1080-line frame tall (64 lines at 6, about a seventeenth of the height), the same share of a frame of any size and shape. A fraction reaches part of the way into the next octave; past 7 the deepest octave, an eighth of the height, carries what reaches further. At 1 the glow stays within a line or two of a 1080-line frame around its source. |
The weights and the 8-texel floor an octave's height 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 or a resize changes
what the sixteen passes DO and never how many there are.
Fifteen scratch targets in the scene format, the largest 540 texels tall and
as wide as the frame's shape makes it: about 11 MB on a 16:9 frame 1080 lines
tall or taller, and less on a smaller one.
# vfs Module
Public Luau surface over the `__vfs` Internal FFI namespace — the
engine's virtual filesystem.
## Purpose
Wrap the raw `__vfs.*` FFI namespace in a typed Luau table that gets
auto-injected as `_G.vfs` via the prelude. The standard read / write /
move / remove / mkdir / list / exists / readAsync / reload / evict
surface, plus trusted-only `watch` / `unwatch` for the bootstrap VM.
`vfs.read` yields on a byte-cache miss: the module's last step installs
the `vfs_async_read` fallback over the synchronous read, so every VM that
holds this namespace, the trusted VM included, reads a path through the
same two steps and gets the same bytes for it.
## Usage
```luau
-- Read / write
local src = vfs.read("/zero/source/libs/@builtin/components/Camera.component/init.luau")
vfs.write("/zero/source/notes.md", body)
-- What a write landed: where the bytes went, and what the static passes
-- read in the Luau among them
local ok, report = vfs.write("/zero/source/game/Vent.component/init.luau", code)
if report.diagnostics then
for _, d in report.diagnostics do
print(d.severity, d.path, d.line, d.message)
end
end
if not report.durable then
log.warn(report.warning)
end
-- Listing
for _, e in ipairs(vfs.list("/zero/source")) do
print(e.isDirectory and "[d] " or " ", e.name)
end
-- Async fetch
local png = task.await(vfs.readAsync("/zero/runtime/screenshots/last.png"))
-- Reclaim RAM after processing a big binary
vfs.evict("/zero/source/textures/imported_huge.png")
-- Reload a module after editing its source on disk
if vfs.reload("@builtin::modules.json") then
local m = require("@builtin::modules.json") -- sees the new source
end
```
`vfs.reload(identity)` answers whether a module was cached under that name
and has now been dropped. A `false` says the name matched nothing — either a
misspelled identity or a module this VM never required — so the next
`require()` returns whatever it would have returned anyway.
A module that caches state derived from OTHER files keeps serving the old
value when those files are rewritten, since only its own source is watched.
Reload it by identity to make the next `require()` recompute.
## How a write reaches disk
A native engine's `vfs.write` returns once the engine holds the bytes and the
session's journal holds the record of the write, its bytes with it. The record
is in the operating system's hands before the call returns, so an engine
process that ends right after a write, however it ends, leaves the write for
the next session on the same machine to owe and make again. The blob a binary
write stores by content is written and flushed by a worker thread (`vfs-io`) in
the order the writes were made, so a script that writes a thousand files pays
for handing them over and for their journal records, not for the flush of
each. A read of a blob still waiting for its file answers from memory, so a
write reads back the moment it returns. A queue holding more than its byte
budget (256 MiB) makes the next write wait for it and write inline, which
bounds the memory the queue pins. The queue is flushed when the engine exits
normally. `world.syncStatus()` reports nothing owed once the writes have also
reached the world.
## Exports
- `vfs.read(path, opts?) -> string?`
- `vfs.write(path, content, opts?) -> (boolean, WriteReport | string)`
- `vfs.move(src, dst, opts?) -> (boolean, WriteReport | string)`
- `vfs.copy(src, dst) -> (boolean, WriteReport | string)`
- `vfs.remove(path, opts?) -> (boolean, string?)`
- `vfs.mkdir(path, opts?) -> boolean`
- `vfs.list(path?) -> { VfsListEntry }`
- `vfs.exists(path, opts?) -> boolean`
- `vfs.readAsync(path, opts?) -> promiseId`
- `vfs.reload(modulePath?) -> boolean`
- `vfs.evict(path, opts?) -> boolean`
- `vfs.mutationSeq() -> number`
- `vfs.contentClock() -> number`
- Trusted-only: `vfs.watch(path, callback) -> number` /
`vfs.unwatch(watcherId) -> boolean`.
# entity
The `entity` global: spawning, despawning, finding, and the reference you get
back when you call it.
`entity` is a table you can also call. `entity.spawn(...)` and its siblings act
on the scene; `entity(id)` hands back an **entityRef** — the per-entity surface
carrying `.position`, `.component`, `:despawn()` and the rest.
```luau
local id = entity.spawn("Crate")
local e = entity(id)
e.position = { 0, 1, 0 }
e.component.add("Model", { mesh = "@builtin::meshes.cube" })
```
## What lives here
| File | What it is |
|------|-----------|
| `init.luau` | The `entity` global — typed wrappers over the Internal `__entity` namespace, plus the coercions and `entity.hierarchy`. |
| `members.module/` | The entityRef's member set: every member's kind, type and description, in one table. |
| `ref.module/` | The entityRef metatable — what `entity(id)` returns and how a member access dispatches. |
## Where the entityRef's surface is defined
`members.module` is the single description of it. The runtime's accepted-member
set derives from that table, the LSP's `entityRef` type is generated from it,
and each member's documentation is published from it. Nothing describes the
entityRef anywhere else — a second description could only drift from this one.
To add a member: declare it in `members.module` with its `kind`, `type` and
`doc`, and implement it in `ref.module`. A member missing from the table is
refused by the runtime; a member in the table with no implementation answers
nil.
## Related
- `entity.hierarchy` — swap a blockout entity for a generated asset.
- `ecs.*` — the ECS storage surface. **ECS components are not script
components**; `entity(id).component` is the script-component surface and the
two are separate systems.
# yaml.module
YAML decode + encode for authored engine content. Pure Luau, no engine
dependencies — a general parsing library, not data-system plumbing.
```luau
local Yaml = require("@builtin::modules.yaml")
local doc = Yaml.decode(vfs.read(path))
vfs.write(path, Yaml.encode(doc))
```
## Supported subset
- Block mappings (`key: value`) and block sequences (`- item`), nested
to any depth.
- Compact sequence-of-mapping entries (`- path: x` / ` kind: y`).
- Flow collections — `{ a: 1, b: 2 }` and `[1, 2, 3]` — single line.
- Plain scalars with type inference: `~` / `null` → nil, `true` /
`false` → boolean, numeric literals → number, everything else →
string.
- Single- and double-quoted strings (`''` escapes a literal quote
inside a single-quoted string; `\n` `\t` `\r` `\\` `\"` inside a
double-quoted one). A quote opens a quoted scalar where a scalar
begins — after `key:`, after a `- ` entry marker, or inside a flow
collection — so a plain scalar carries an apostrophe as data
(`note: the world's rules`). Quoted keys are read in flow mappings.
- `#` comments — honored outside quotes, so a `#` inside a quoted
string is kept as data.
- Literal (`|`) and folded (`>`) block scalars, with a chomping
indicator (`-` strips the final newline, `+` keeps every trailing
blank line, none keeps one newline) and an indentation indicator
(`1`-`9`: the content's indent past the parent's), in either order
(`|-`, `>+`, `|2`, `>1-`). A block scalar's content is literal text:
quotes (balanced or not), `#`, `key: value` and `---` inside it are
data.
- An optional leading `---` document marker.
## Loud-error contract
Constructs outside the subset above raise instead of misparsing:
anchors/aliases (`&`, `*`), tags (`!`), directives (`%`),
multi-document streams (a second `---`), a block-scalar header
it cannot read (`|x`, `|-+`, `|0`), tab indentation, and inconsistent indentation (both block structure and
block-scalar bodies). Every error carries the offending line number
(`yaml: line N: ...`), so a bad config points straight at the line to
fix.
Tab indentation is rejected everywhere — including block-scalar body
lines whose leading whitespace contains a tab. A tab after the first
non-space character of a line is content and passes through.
## API
- `Yaml.decode(text: string): any` — decode a YAML document into a
Luau value (table, scalar, or nil for an empty document). Raises on
malformed input or an unsupported construct.
- `Yaml.decodeWithComments(text: string): (any, boolean)` — decode as
`decode` does, and report whether the text carries a comment by the
decoder's own rule: a `#` at a line's start or after whitespace, outside
a quoted scalar and outside a block scalar. Re-encoding the value drops
such comments, so an editor that writes a document back reads this first.
- `Yaml.stripComment(line: string): string` — one line of YAML text less
its comment and the spaces before it, by the same rule. A reader that
takes a document apart line by line reads each line through it, so
`roughness: 0.5 # polished` reads as `roughness: 0.5`.
- `Yaml.encode(value: table): string` — encode a Luau table as YAML
(block style, two-space indent, alphabetically sorted keys). Raises
on values YAML can't represent (functions, userdata, non-string
mapping keys).
A top-level empty table encodes to an empty document, which decodes
back to `nil` (the YAML empty-document ambiguity).
# renderer
GPU-resource factory plus CPU codec/store wrappers — the GPU/CPU half of the asset↔resource split. Moves a resource Disk → CPU → GPU in explicit steps and returns inert handles describing each live resource. assetType behaviours, components, and every other module call `renderer.*`.
A resource moves through three states, each an explicit call:
- `ref:load()` → `renderer.<res>.loadCpu(ref)` decodes the asset's primary content into the guid-keyed CPU store and returns a CPU handle (holds only a guid plus dims/counts and the read/encode/unload ops).
- `renderer.<res>.create(cpuHandle | rawData, guid?)` uploads CPU → GPU, keyed by guid, and returns a GPU handle. `create` never takes an `AssetRef` — load the CPU first.
- `renderer.destroy(handle)` frees the GPU resource; a CPU handle's `:unload()` frees the CPU copy.
A `MeshHandle` / `TextureHandle` / `MaterialHandle` is an inert data record (`{ kind, category, guid, name, ... }`) describing one live GPU resource. Every GPU op lives on `renderer.*` and takes the handle.
Anywhere a call names a resource it takes any of the forms you already hold — the handle `create` returned, the CPU handle `loadCpu` returned, the guid, or the `AssetRef` `asset.resolve` returned. Handles compose: what one call hands back, the next call accepts.
## Types
- `Aabb` — `{ min = {x,y,z}, max = {x,y,z} }`.
- `MeshHandle` / `MeshCpuHandle` / `MeshGeometry` / `MeshBuffers`.
- `TextureHandle` / `TextureCpuHandle` / `TexturePixels`.
- `MaterialHandle` / `MaterialContent`.
## renderer.mesh
- `encode(geom) -> string?` / `decode(zmsh) -> (geom?, errmsg?)` — the ZMSH CPU codec.
- `loadCpu(ref) -> MeshCpuHandle` — Disk → CPU load (called by `meshRef:load()`).
- `create(src, guid?) -> MeshHandle` — create or fetch a GPU mesh from a `MeshCpuHandle`, raw geometry `{positions, indices, normals?, uvs?, colors?}`, compute buffers `{vertexBuffer, indexBuffer, vertexCount, indexCount, aabbMin?, aabbMax?}`, or a `MeshHandle`.
- `geometry(mesh) -> MeshGeometry` — the mesh's vertex data, the read that pairs with `create`.
- `update(handle, src) -> MeshHandle` — overwrite the GPU resource in place under the same guid.
- `readback(mesh, into?) -> MeshCpuHandle`: GPU → CPU recovery of a runtime mesh's geometry. `into` lands the copy under a CPU-store key of the caller's own, which stays resident until the caller unloads it, whatever re-registers or unloads the mesh itself.
- `isResident(mesh) -> boolean` / `isCpuResident(mesh) -> boolean`.
- `clusters(mesh)` / `scheduleClusters(mesh, opts?)` / `clusterBakes()` — the mesh's level of detail. Every static mesh draws through clusters, and a baked hierarchy of them (`kind = "dag"`) is cut by the GPU per view and per instanced copy, so detail falls off continuously with distance with no authored LOD meshes; `kind = "lod0"` draws full detail at every distance until a bake lands. `guides { path = "topics/world-detail" }` covers which meshes bake on their own.
Geometry moves in four directions, two per axis — DATA the caller holds, and the geometry of a mesh the ENGINE holds:
| From | → bytes | → geometry |
|---|---|---|
| geometry (data the caller holds) | `encode(geom)` | — |
| ZMSH bytes (data the caller holds) | — | `decode(zmsh)` |
| a mesh the engine holds | `encodeCpu(mesh)` | `geometry(mesh)` |
`geometry(mesh)` reads the resident CPU copy when there is one and reads the geometry back off the GPU when there isn't (yielding a frame or two), so a mesh straight out of `create` answers it:
```luau
local h = renderer.mesh.create({ positions = P, indices = I, tangents = T })
local geom = renderer.mesh.geometry(h) -- { positions, indices, tangents, ... }
```
An optional stream is present only when the mesh carries one. The GPU vertex layout has no "unset" — it holds a zeroed tangent, a zeroed skin binding, and a second UV set copied from the texture UVs for every mesh — so a stream saying only what its absence already says is reported absent. `geom.tangents == nil` is therefore the answer to whether a mesh has a tangent basis, and `geom.uvs1 == nil` to whether it has a second UV set.
## renderer.texture
- `encode(rgba, width, height, opts) -> (string?, errmsg?)` / `encodeFromImage(bytes, opts) -> (string?, errmsg?)` / `decode(ztex) -> (rgba?, width?, height?)` — the ZTEX CPU codec.
- `withSampler(ztex, { filter?, wrapU?, wrapV?, anisotropy? }) -> (string?, errmsg?)` — the same payload with only its recorded sampler state changed; every level is byte-identical.
- `loadCpu(ref, encodeOpts?) -> TextureCpuHandle` — Disk → CPU load with per-pixel access.
- `create(src, guid?) -> TextureHandle` — from a `TextureCpuHandle`, raw pixels `{rgba, width, height, srgb?}`, a `TextureHandle`, or render-target dimensions `{width, height, name?}` (an empty GPU texture a render pass writes into).
- `update(handle, src) -> TextureHandle`, `destroy(handle)`, `capture(handle) -> string` (CPU readback result key), `readback(texture) -> TextureCpuHandle`, `isResident(texture) -> boolean`.
## renderer.material
- `create(content, key) -> MaterialHandle` — register or update a material's GPU record (`content = { shader, properties, textures, aliases?, name? }`) under its canonical registry key.
- `animatedTexture(texture, opts?) -> MaterialHandle` — a material that PLAYS a layered texture: its layers bound as the frames, its timing beside them, the built-in `animatedTexture` shader turning the clock into the layer showing now. One call from an imported GIF / APNG / animated WebP to a material an entity can wear. `guides { path: "topics/animated-images" }` is the whole surface.
- `setProperty(key, name, value)` — push one changed uniform.
- `setTexture(key, slot, ref)` — push one changed texture slot (the texture must already be GPU-resident).
- `destroy(key) -> boolean` — drop the definition filed under `key`, so `describe` and `list` stop answering for it. A surface already wearing the handle goes on drawing it.
A `MaterialHandle` and its `guid` are two different currencies. What a surface wears is the HANDLE — `Model:applySessionMaterial(handle)`, or a Model's `material` field. The handle's `guid` is the material's registry key, which is what `setProperty`, `setTexture`, `describe` and `destroy` take. A component field resolves an asset, so a bare registry key in one leaves the component waiting for an asset to register under that name.
## renderer.instanceData
Four `vec4` lanes of generic shader data per entity — the channel that lets ONE material serve many entities that differ in a value, instead of one material per entity. A surface shader reads lane `i` back as `input.shader_data[i]`, and the engine attaches no meaning to what a lane holds.
- `laneCount() -> number` — lanes per entity, so a lane index runs `0 .. laneCount() - 1`.
- `set(target, lane, x, y?, z?, w?)` — write one lane of an entity's block. `target` is an entity proxy or an entity-id string naming a live entity; `y` / `z` / `w` default to 0. The lane reaches the block where the call is made, and the draw on the next frame.
- `clear(target)` — drop the entity's whole block, so its draws read zero again. Takes an entity that has already gone, and does nothing for one holding no block.
A lane index outside the block, or a target no live entity answers to, is an error at the call rather than a write that lands nowhere. A feature picks the lane indices it owns and names them where it writes them: `@builtin::systems.globalIllumination.lightmap` holds lane 0 for a receiver's atlas rect and lane 1 for its layer and enable flag, which is the shape to copy.
The same lanes reach a GPU-driven population through `renderer.mesh.drawInstanced`'s `instanceDataBuffer`, on slots no entity owns.
## renderer.featureTexture
The texture analogue: a shared `rgba16f` 2D array every surface shader can sample as `zero_feature_texture(uv, layer)`, and the array a `SpotLight` projects a layer of through its cone via `cookieLayer`.
- `configure(width, height, layers)` — size the array. A call for the size it already has is left alone; one that changes the size reallocates, and the replacement is zeroed, so it empties every layer in the array — the layers other features and other cookies own along with your own.
- `setLayer(layer, textureKey, x, y)` — copy a GPU-resident `rgba16f` texture into one layer at that offset, GPU to GPU with no readback. Several small images pack into one layer at different offsets.
- `state() -> { width, height, layers, filled, fills }`: the extent the array carries and `filled`, the ascending 0-based indices of the layers a fill has landed in since it was last sized. One array is shared by every feature and every light cookie, and it has no allocator, so this is what a feature asks to tell whether the array it sized and filled is still the array it is writing into. A layer some other `configure` emptied leaves `filled` without it, which is what separates that from a fill that never landed. What it describes is the array a shader samples: the source texture a `setLayer` copied from is a GPU resource of its own and keeps the bytes it was written with, so `filled` is the reading that answers whether the layer behind a `cookieLayer` is live right now. `fills` counts the fills that have landed in each layer since the array was last sized, `fills[layer + 1]` for a 0-based layer: a fill of a layer already holding content leaves `filled` as it was and moves this count, so a feature re-filling its own layer reads its fill arriving here. Measured at the end of the last rendered frame, like every reader below.
```luau
renderer.featureTexture.configure(256, 256, 4)
renderer.featureTexture.setLayer(0, "my_gobo", 0, 0)
-- ... elsewhere in the scene, another feature sizes the array ...
local ft = renderer.featureTexture.state()
if ft.width ~= 256 or table.find(ft.filled, 0) == nil then
-- layer 0 was emptied under us: size it back and re-fill.
end
```
## Reading back what the renderer did
Every call above states an intention. What the renderer made of it is a separate
document, published once per frame and read through these:
- `drawDiagnostics() -> { DrawDiagnostic }` — every renderable that is NOT
drawing what its material says. A surface rendering as the magenta
placeholder, one the renderer could bind nothing for, and one drawing a
program whose most recent compile failed all land here, each naming the entity,
the program asked for, the program bound, and the one cause. It covers every
renderable the renderer holds, whether or not a camera reached it — a row with
`observed = false` and `outcome = "notDrawn"` is the renderer's own resolution
for one this frame drew nowhere, so a broken surface off-screen reads the same
as one in frame. An empty result means every renderable the renderer holds is
drawing the program its material named. **Start here when a surface looks
wrong.**
- `material.renderState(key) -> MaterialObservation?` — the blend / cull /
topology / queue / depth key the renderer holds a material under, and whether
a pipeline exists for it. `nil` means the renderer holds no material under
that key, which is what writes reaching nothing on screen look like. `index`
is the material index its row is filed under, and `textures` the texture key
each slot of that row names, so a `setTexture` the renderer has taken up
reads there.
- `materialCost() -> { MaterialObservation }` — draws, instances, placeholder
draws and material-owned bind groups (`binds` set, `bindsElided` skipped) per
material, over the published frame.
- `shaderCost() -> { ShaderCost }` — pipeline build time and permutation count
per program, summed since engine start, beside the compile gate's word.
- `observe() -> RenderObservation` — the whole document the four above read.
`/zero/runtime/generated_materials` serves the same document as files. Every
`notDrawn` row names why no pass reached it in `notDrawnReason`:
`meshNotResident`, `hidden`, `layer`, `culled` or `viewCull`.
## renderer.destroy
- `destroy(handle) -> boolean` — free the GPU resource behind a `MeshHandle` / `TextureHandle`, routing by the handle's `category`.
## Parts
The module is a folder of parts, each a module of its own that `init.luau` requires:
- `renderer.refs`: guid minting and the coercion from whatever names a material, mesh or texture to the key the renderer indexes it by.
- `renderer.sources`: the `src` shapes `renderer.mesh.create` / `update` and `renderer.texture.create` / `update` take, and the bounds and counts raw geometry implies.
- `renderer.shading`: the readings `renderer.shadingOf` builds out of the document the renderer publishes.
## Usage
```luau
local renderer = require("@builtin::modules.api.engine.renderer")
local gpu = renderer.mesh.create({ positions = { ... }, indices = { ... } })
renderer.destroy(gpu)
```
# scene_instantiable (module)
The instantiation contract's shared implementation. An asset type opts into
scene instantiation by defining `instantiate(self, target?, opts?)` on its
behaviour `ref` table; this module carries the parts that mean the same thing
for every type, so a caller writes ONE piece of code against all of them.
```lua
local root, idMap = ref:instantiate(target?, opts?)
```
## The contract
**IN — the base opts.** `target` is an owning entity ref: the instance lands
under (or, for a hierarchy type like a bundle, onto) that owner. With no
target the type spawns a fresh root. `position`, `rotation`, `scale`, `name`
and `temporary` place that root and mean the same for every type. `rotation`
takes three numbers as pitch/yaw/roll in DEGREES, or four as a quaternion. A
type may honour more opts of its own — `params` for a type built from declared
inputs, `idMap` / `diff` / `sourceTag` for the bundle override contract — and
says so in its own `instantiate` docs.
**OUT — the two returned values.** Every type returns the same pair:
- **`root`** — the composed root, as an `EntityRef`. Composition is
**synchronous**: the root and everything the type built under it are live
the moment the call returns, so a caller can parent to it, read its
components and hand it on in the same statement. There is no frame to wait
for and no callback.
- **`idMap`** — the `originalId -> runtimeId` map naming what the composition
spawned, `{}` for a type with no addressable children. **Never nil.** A
component that re-composes the asset on every load (`Asset`) keeps this map
and passes it back in, which is how a cross-entity reference into the
composition — `SkinnedModel.skeletonRoot` pointing at a bone — survives a
reload.
The return is enforced, not merely described: `AssetRef` dispatches every
`ref:instantiate(...)` through `result` on the way out, whether or not the
type called it. A type that returns something else fails at its own call
rather than handing its caller a nil root or a map that is sometimes absent.
## Exports
- `M.root(self, target?, opts?) -> root` — stand the root entity for a type
that spawns one: parented to `target`, born temporary when
`opts.temporary`, named `opts.name` else the asset's own name, placed.
- `M.place(root, opts?) -> root` — apply the placement opts to a root the type
already has (the adopt path: a bundle exploding onto its target, a
sceneModule reconciling under one).
- `M.result(self, root, idMap?) -> (root, idMap)` — return through the
contract. Checks `root` is a live entity ref, normalises a missing map to
`{}`, and errors naming the asset type when either is something else.
- `M.isOwned(opts?) -> boolean` — whether a component drives this call. The
`Asset` / `SceneModule` components tag their own calls with `sourceTag`;
they hold the reference and re-compose on every load. An untagged call came
straight from `ref:instantiate(...)` and has no such owner.
- `M.own(root, self, idMap?) -> root` — hand an already-composed root to an
`Asset` component pointing at `self`, so the reference and its map persist
and the composition is rebuilt on the next load. The component adopts the
live composition rather than building a second one.
- `M.check(value, constraint) -> ok, reason?` — the `sceneInstantiable`
field-constraint validator, also registered under that kind on load.
## The field constraint
`Field.instantiableRef` emits `constraint = { kind = "sceneInstantiable" }`,
and this module registers the validator for it on load. Given a written value:
1. `nil` passes — the field is optional (no asset assigned).
2. Reads the value's identity — a bare string, or a table's `__ref` / `guid` /
`identity` / `name`.
3. Resolves it (`asset.resolve(identity)` — any category) and asks the
resolved ref `ref:canInstantiate()`: true iff the asset's type defines an
`instantiate` method.
This is what lets `Field.instantiableRef` accept by CAPABILITY rather than a
hardcoded type list — a new scene-instantiable asset type is accepted the
moment it defines the hook, with no edit to the field or its consumers.
# asset Module
Public Luau surface over the `__asset` Internal FFI namespace —
asset resolver, ref envelope builder, sidecar metadata.
## Purpose
Wrap the raw `__asset.*` FFI namespace in a typed Luau table that
gets auto-injected as `_G.asset` via the prelude. Three families:
- **Lookup** — `resolve`, `ref`, `typeRef`, `inspect`, `source`,
`identity`, `guid`, `meta`, `deps`. Every op accepts any name an
asset has (handle, guid, identity, path, bare name) and returns
the requested view.
- **Discovery** — `categories`, `list`, `containing`.
- **Generic `.metadata` sidecar** — `metadata`, `set_metadata`,
field-level `get_field` / `set_field` / `remove_field` /
`has_field`, tag helpers (`tags`, `has_tag`, `add_tag`,
`remove_tag`), and `validate`.
The previously-FFI `bundle.*` namespace was dissolved into the
bundle assetType (see `@builtin::assetTypes.bundle`);
that's not exposed here. The prelude mints `bundle` separately as
a thin Luau table grafted from `bundle_update`.
## Usage
```luau
-- Lookup
local cam = asset.resolve("@builtin::components.Camera")
local ref = asset.ref("animations.idle", "animation")
print(asset.identity(cam), asset.guid(cam), asset.source(cam))
-- Discovery
for _, c in ipairs(asset.categories()) do print(c) end
for _, sceneRef in ipairs(asset.list("scene")) do print(sceneRef.identity) end
local s = asset.containing("/zero/source/scenes/main.scene/scene.json")
-- Metadata sidecar (agent-editable)
asset.set_field(ref, "category", "movement")
asset.add_tag(ref, "looping")
print(asset.has_tag(ref, "looping"))
-- Structural validation
local v = asset.validate(cam)
for _, p in ipairs(v.problems) do print(p.severity, p.message) end
```
## Exports
- Lookup: `resolve`, `ref`, `typeRef`, `inspect`, `source`,
`identity`, `guid`, `meta`, `deps`.
- Discovery: `categories`, `list`, `containing`.
- `.metadata` sidecar: `metadata`, `set_metadata`, `get_field`,
`set_field`, `remove_field`, `has_field`, `tags`, `has_tag`,
`add_tag`, `remove_tag`, `list_fields`, `list_field_values`.
- Validation: `validate`.
# modules.api.engine.engine
The `engine` global's Luau implementation. Exposes `engine.mode` (edit
vs play), `engine.onModeChange(callback)` subscription registry, and
the mode-flip orchestration that fires the canonical onModeChange
dispatch through `ENGINE_MODE_WATCHERS`.
# proc
Code-authored, graph-backed procedural generation for the Zero engine.
A graph is one function of `g`: `proc.define(function(g) ... end)`. Nodes are called by
family and name (`g.<family>.<name>({ ... })`), inputs are declared with `g:input(name, default, opts)`,
the returned table is the graph's outputs, and `io.output` is how the graph stands in the world.
`builder.module/README.md` holds every rule of that form.
This module owns the whole procedural model: the graph builder + data model,
the operation registry, the type system, the lazy cached evaluator, deterministic scoped hashing, and the node-family op
implementations. Authored `.procGraph` graphs are persisted via
`procGraph.assetType`; the `procgen.preview` / `procgen.spawn` operations live in
`procgen.toolbox` and are invoked as tools: `tools.use("procgen", "preview", args)`
from a script or an agent's `tool_exec` script, or `zero procgen preview` in the
shell. Generated
meshes/materials/textures/bundles are persisted through their own `.assetType`.
An op family can also come from outside this package: a `.procPack` asset
registers its ops in the same registry, called as `g.op.<id>(...)` exactly like the ones
shipped here (`proc.registerPack(name, ops)` is what it registers through, and
what a test or a tool calls to hold a family for the life of one VM).
`terrain.*` is one such pack, shipped in `terrainSystem.package/procPacks/`
and covering a whole landscape; `guides { path =
"systems/terrainSystem/documentation/terrain" }` is its guide.
To find out what the registry holds, use the `procgen` toolbox: `searchNodes`
searches it and `describeNode` describes one node or op. `proc.search_ops(query)` and
`proc.schema(id)` are the same answers in-process, for a graph builder looking
something up while it runs.
# frame_budget
The share of a frame that cooperative engine work spends before it hands the
frame back.
Some engine work is one long sequence of small units run on a task: a scene
load applies one record after another, and the world-load `onRegister` sweep
fires one instance's hook after another. Run back to back in one frame, a long
sequence holds that frame for its whole length, and nothing else the engine
does (answering a call, drawing, input) happens until it is through. Asking
`due()` before each unit and yielding when it answers true runs the same work
across as many frames as it needs, a slice of each.
```luau
local FrameBudget = require("@builtin::modules.frame_budget")
for _, item in ipairs(items) do
FrameBudget.yield()
process(item)
end
```
- **One slice per frame, shared.** Each caller is charged the time it runs
between its readings of the slice in a frame (`task.runTime`), whoever runs
it, and the charges of every caller add up to the frame's slice. What the
rest of the frame runs (systems, components, other tasks) is not charged, so
a busy frame still gives the slice to the work. Two long pieces of work
running at once share a frame's slice rather than taking one each.
- **A unit is never split.** The first unit of a frame always runs, so a frame
holds at most the slice plus the one unit that crossed it. A unit that is
itself long stays one piece of work.
- **Code that cannot yield runs in its frame.** `due()` answers false outside a
coroutine that can yield, so a caller called from such code does all its
units in the frame it was called in, as it would without the budget.
A caller that does work of its own around the yield asks `due()` and calls
`wait()`, which yields to the next frame and opens that frame's slice as the
caller resumes; `yield()` is the two together.
Work whose unit is a native call that bounds itself by time is told how long
it may run: `remainingMs()` answers what is left of the current frame's slice,
or nil for code that cannot yield, which then runs the whole of its work in the
frame it was called in. The publish gate's script check is read this way: it
runs on the engine's worker pool and answers `nil, true` while it runs, and
where no worker takes it each call checks scripts for the time it is given:
```luau
local block, checking = __spacetime_vcs.scriptPublishBlock(FrameBudget.remainingMs())
while checking do
FrameBudget.wait()
block, checking = __spacetime_vcs.scriptPublishBlock(FrameBudget.remainingMs())
end
```
## The background lane
Some work is started early so it is ready when asked for, and no picture waits
on it, such as the search text an editor reads ahead of the first
`tools.search`, the skills and shader modules an agent or a build reads
later, the procedural nodes loaded ahead of a build's first plan, and the
language server's re-check of the files a play flip reads. `background(fn)`
runs `fn` on the background lane: every `yield`, `due` and `wait` its work
makes on that coroutine hands the frame back for as long as a hold on the lane
stands, and takes its slice as usual once none does.
```luau
FrameBudget.background(function()
for _, path in ipairs(paths) do
FrameBudget.yield()
warm(path)
end
end)
```
Work the picture waits on holds the lane while it runs: `holdBackground(key)`
until `releaseBackground(key)`. A world's entry holds it under `"world entry"`
from the moment the world is ready (its `onRegister` sweep) until the world
load reads `visually_complete` on the boot timeline (its scene drained, the
content it draws resident, nothing owed to its picture and no loading screen
over it), so the frames of the entry carry the world's load and its first
picture, and the background work runs in the frames before and after them. A
hold no one releases lapses after `BACKGROUND_HOLD_SECONDS` (or the seconds it
was taken for), with a warning naming its key, so work on the lane always runs
in the end. `backgroundHolds()` lists the keys holding the lane now, and
`backgroundWaits()` answers whether the calling code's next unit waits for it
(a walk with a clock of its own asks it between its pieces).
`FrameBudget.DEFAULT_MS` is the slice a call that names none spends. `spent()`
answers how much of the current frame's slice is gone.
A caller with a budget of its own reads `mark()` where its work starts.
`ranMs(mark)` answers how long it has run since, none of the time it spent
suspended; `cpuMs(mark)` answers the CPU time of its work since: those
stretches and the stretches of every coroutine it resumes, and every one they
resume, while it waits on them, which a machine whose cores are taken by other
work does not stretch, so a bound that refuses work for running too long
refuses the same work on a loaded machine as on an idle one, and work handed to
a coroutine as work run in place. A task it starts and waits for runs while it
is suspended, which `cpuMs` does not count.
# utils
Small stateless helpers used across the builtin module set: parse a
vec3-shaped value into the canonical `{ x, y, z }` map, normalise an
id list from string or table input, coerce a checkbox-shaped value
into a strict boolean, and list a table's keys in a stable order. No
engine dependencies, no module state.
## Exports
- `M.parseVec3(value: Vec3Like) -> Vec3Map?` — parse vec3 from array or map form, returns `nil` if unrecognised.
- `M.normalizeIds(value: IdListInput) -> IdList?` — turn a comma/space-separated string or array into `{ string }`.
- `M.parseCheckboxValue(data: CheckboxValue, fallback: boolean) -> boolean` — coerce bool/string/number/nil to a boolean.
- `M.sortedKeys(t) -> { string }` — every key as a string (a non-string key through `tostring`), ascending; `{}` for nil or a non-table.
- `M.sortedStringKeys(t) -> { string }` — only the string keys, ascending; `{}` for nil or a non-table.
- `M.sortedKeysAny(t) -> { any }` — every key as it is, grouped by type name in alphabetical order, numbers and strings ascending within their group, any other key by its `tostring` text.
Types:
- `Vec3Map = { x: number, y: number, z: number }`
- `Vec3Like = Vec3Map | { number }` — accepted input shape for `parseVec3`.
- `IdList = { string }`
- `IdListInput = string | IdList` — accepted input shape for `normalizeIds`.
- `CheckboxValue = boolean | string | number | nil`
## Usage
```luau
local Utils = require("@builtin::modules.utils")
local v = Utils.parseVec3({ 1, 2, 3 }) -- { x = 1, y = 2, z = 3 }
local ids = Utils.normalizeIds("a, b, c") -- { "a", "b", "c" }
local on = Utils.parseCheckboxValue("true", false) -- true
for _, name in ipairs(Utils.sortedKeys(options)) do
print(name, options[name])
end
```
## Notes
- Pure functions — no side effects, no engine calls. Safe to call at
module load time or from any context.
- `parseVec3` always returns the map form (`{ x, y, z }`) regardless of
whether the input was an array or a map. Callers downstream that
expect a particular shape should rely on the map form.
- `normalizeIds` returns the input table unchanged when it is already a
table — it does not validate that each entry is a string.
# preview
Render an asset's preview in the preview studio: an isolated camera, lit only
by its own three-point rig, over a neutral backdrop, that nothing in the scene
reaches. `ref:preview()` renders any asset by the recipe its type declares under
`preview:` in its `type.yaml`, and these are the primitives it calls: they spawn
temporary entities, frame an offscreen camera over them, render one frame,
read it back as a PNG, and tear the entities down.
## Surface
- `preview.fromEntities(makeFn, opts?) -> PreviewResult` — run `makeFn` to
instantiate entities, frame a camera to their bounds, render one offscreen
frame, and return the still PNG.
- `preview.fromRecipe(ref, recipe, opts?) -> PreviewResult` — render `ref` by a
declared recipe: `instantiate` stands it through its own `instantiate`,
`surface` paints the material its type's `ref.previewMaterial` returns on the
recipe's mesh, and `image` fits a file the asset holds to the frame on the
studio backdrop without rendering anything.
- `preview.backdrop() -> { r, g, b }` — the studio backdrop's colour in a
finished preview, 0-255.
- `preview.placeholderPng(reason, inputs?) -> string` — the placeholder
preview, a dark grey frame crossed through, recording `reason`.
- `preview.placeholderReason(ref) -> string?` — why an asset's `preview.png`
is the placeholder, or nil when it pictures the asset.
Staging an asset reserves its `preview.png` through the type's
`<type>.preview` derive hook. A preview that cannot be rendered (the asset
raises, its cook fails, the render device is gone) lands the placeholder
recording why, so the commit staging the asset lands; `zm status` names it as
a `placeholder` line while it is staged, and `zm derived retry` renders it
again.
`PreviewResult` is `{ available, imageBase64?, rendered?, width?, height?,
bounds?, stats?, reason? }` — `imageBase64` is the rendered PNG when `available` is true, and
`reason` explains why when it is false. `opts` is `{ size? = { width, height },
angle? = { yaw, pitch } }`.
A preview pictures its whole subject, however many entities it composes. While
the subject settles, its bounds are measured each frame by walking it in Luau
for up to `opts.entityBudget` entities (default 2000); a subject composing more
is measured by the capture framing alone, which reads each root's hierarchy
bounds from the engine.
## Example
local result = asset.resolve("gold", "material"):preview({ size = { width = 512, height = 512 } })
-- result.imageBase64 holds the rendered PNG (base64)
# camera Module
Public Luau surface over the `__camera` Internal FFI namespace —
script-facing camera queries.
## Purpose
Wrap the raw `__camera.*` FFI namespace in a typed Luau table that
gets auto-injected as `_G.camera` via the prelude. The engine-level
`scheduleRender` lives on the companion `__cameraBindings` Internal
namespace and is consumed directly by `Camera.component`; this
module is the small public surface scripts use to find the active
viewport camera.
## Usage
```luau
local camId = camera.main()
if camId then
local cam = entity(camId)
-- ...
end
```
## Exports
- `camera.main() -> string?` — entity id of the active viewport
camera, or nil if none is active this frame.
# ui Module
Public Luau surface over the `__ui` Internal FFI namespace — the
egui-backed UI system's full Luau-facing surface.
## Purpose
Wrap the raw `__ui.*` FFI namespace in a typed Luau table that gets
auto-injected as `_G.ui` via the prelude. Covers screens, styles,
themes, widget introspection, input simulation, scroll / area /
layout, per-widget responses, focus, validation, custom-widget
builders, and per-widget cross-frame state.
A screen is a plain widget tree (`{ type, id, style, props, children }`);
its `style` blocks, the named styles `ui.defineStyle` takes and the themes
`ui.registerTheme` takes are typed by the global `UiStyle`,
`UiThemeTokens` and `UiDockStyle` this module declares.
## Usage
```luau
-- Register a screen
ui.registerScreen("hud", {
type = "panel",
children = {
{ type = "label", props = { text = "Score: 0" }, id = "score" },
},
})
-- Read responses + drive focus
local r = ui.response("score")
if r and r.clicked then ui.focus("score-input") end
-- Themes + styles
ui.setTheme("dark")
ui.defineStyle("button.primary", { bg = "#3b82f6", padding = 8 })
-- Custom widget kinds
ui.defineWidget("badge", function(props, children)
return { type = "label", props = { text = "[" .. props.text .. "]" } }
end)
-- Per-widget state (cross-frame, screen-scoped)
ui.widgetStateSet("filterBar", "active", true)
print(ui.widgetState("filterBar", "active"))
```
## Exports
- Screens: `registerScreen`, `updateScreen`, `showScreen`,
`hideScreen`, `unregisterScreen` / `removeScreen`, `listScreens`,
`getScreenTree`, `screen`, `captureWindow`.
- Styles + themes: `defineStyle`, `defineStyles`, `useStyles`,
`setTheme`, `getTheme`, `listThemes`, `registerTheme`, `loadTheme`,
`resolveTheme`, `getToken`, `getTokens`.
- Widget introspection: `getWidgetTypes`, `getWidgetProps`.
- Input simulation: `click`, `scroll`.
- Background shaders: `registerBackgroundShader`, `setShaderUniforms`.
- Scroll / area / layout: `setScrollPosition`, `getAreaPos`,
`setAreaPos`, `getLayoutInfo`.
- Dock arrangement: `getDockLayout`, `getPersistentDockLayout`, `setDockWindowRect`.
- Responses + focus: `response`, `focus`, `blur`, `focusedWidget`.
- Text fields: `focusedTextField` (the field holding the keys, wherever it is
drawn), `typeText`, `typeKey` (type into it the way a keyboard does).
- Validation: `lastValidation`.
- Custom widgets + state: `defineWidget`, `unregisterWidget`,
`widgetState`, `widgetStateSet`, `widgetStateClear`.
# editorSelection
Named selection scopes for the editor. A scope is an independently
tracked, ordered set of typed refs plus a primary (the last ref added
or clicked). Distinct scopes never clobber each other, so viewport,
outliner, inspector and asset browser share one answer to "what is
selected" per kind.
A ref is `{ kind: string, id: string }` — a stable id, never a display
string, so rename/move never invalidates a selection.
## Exports
- `M.scope(name) -> Scope` — get/create a named scope handle.
- `M.set(scope, refs)` — replace refs in order; primary becomes the last.
- `M.get(scope) -> { Ref }` — refs in click order (fresh array).
- `M.primary(scope) -> Ref?` — last-clicked ref, or nil.
- `M.clear(scope)` — empty a scope.
- `M.toggle(scope, ref)` — add if absent, remove if present.
- `M.add(scope, refs)` — add each ref not already present; primary becomes the last added.
- `M.remove(scope, refs)` — remove each of `refs`; primary becomes the last remaining or nil.
- `M.contains(scope, ref) -> boolean` — membership by `(kind, id)`.
- `M.count(scope) -> number` — the scope's selection size.
- `M.subscribe(scope, fn) -> handle` / `M.unsubscribe(scope, handle) -> boolean`.
- `M.context() -> { scope, refs, primary }` — last-focused scope, for command ctx.
## Usage
```luau
local Selection = require("@builtin::modules.api.editor.selection")
local scope = Selection.scope("entity")
Selection.set(scope, { { kind = "entity", id = "player_1" } })
Selection.subscribe(scope, function() refreshInspector() end)
```
## Notes
- State lives in a fixed `_G` slot, seeded pre-seal by the boot chain
(`prelude.luau`); it survives hot-reload and edit↔play flips. Mutations
after boot write into nested tables only.
- `set` / `toggle` / `clear` mark their scope as last-focused, which drives
`context()` and therefore which scope commands act on.
- The service holds the editor's selection state in Luau. Refs handed back by
`get` / `primary` / `context` are copies, so a caller can hold or mutate them
without touching internal state.
# i18n
The player's language: which of a world's languages to show them, the
languages their platform says they read, the locale the engine chose for its
own text, the locales the engine offers, their own choice, and a signal when
any of it changes. The same `i18n` global in every VM.
```lua
local lang = i18n.pick({ "en", "pt", "es" }) -- "pt" for a Brazilian player
i18n.emulate({ "es-MX" }) -- try the world as a Mexican visitor; nil puts this machine's back
print(i18n.locale()) -- "en"
print(i18n.preferred()[1]) -- "pt-BR" on a device set to Portuguese (Brazil)
for _, l in i18n.offered() do print(l.tag, l.nativeName) end
local r = i18n.choose("pt-BR") -- refused unless pt-BR is offered
if not r.ok then log.warn(r.reason) end
local id = i18n.onChange(function(locale, preferred)
log.info(("now %s; platform %s"):format(locale, table.concat(preferred, ",")))
end)
i18n.offChange(id)
```
## How the locale is chosen
One chain, the first link that matches an offered locale deciding:
1. the player's choice (`i18n.choose`), kept on the device for their ZeroMind
account, or for the signed-out player;
2. the language ZeroMind shows the player (the `zeromindLocale` boot argument
ZeroMind's page passes, or the desktop `--zeromind-locale`), and the one
the page names when its reader picks another language while the browser
engine runs;
3. the platform's preferred languages, most preferred first;
4. `en`, the engine's source language.
A link matches an offered locale with the same tag, then one its tag
truncates to (`pt-BR-x-abc` to `pt-BR`), then one with the same language
(`pt` to `pt-BR`). The engine offers a locale once its manifest is launched,
and it offers `en` and `pt-BR`; a player none of whose links matches either
gets `en`. `i18n.sources()` names every link and the one that decided.
The chosen locale is also the one the engine names to ZeroMind on its requests
(`x-zeromind-locale`) and the one the text system picks fallback fonts for.
## API
- `i18n.pick(available) -> string`: which of the content's languages the
player reads (the first of `available` when none matches).
- `i18n.emulate(tags?) -> { ok, locale?, platform?, reason? }`: stand a
visitor's language list in; nil reads the platform's own again.
- `i18n.locale() -> string`: the chosen locale.
- `i18n.fallback() -> {string}`: the chosen locale's fallback chain.
- `i18n.preferred() -> {string}`: the platform's preferred languages.
- `i18n.offered() -> {Locale}`: `{ tag, name, nativeName, fallback }` per
offered locale.
- `i18n.choice() -> string?`: the player's own choice.
- `i18n.choose(tag?) -> { ok, locale?, decidedBy?, reason?, offered? }`:
choose, or clear with nil.
- `i18n.sources() -> Sources`: `{ locale, decidedBy, matched, choice,
zeromind, platform, signedIn, choiceKept }`; `choiceKept` is `device`, or
`run` in an offline engine, which keeps a choice for that run alone.
- `i18n.onChange(fn(locale, preferred)) -> id` / `i18n.offChange(id)`.
## Where the platform list comes from
| platform | source | changes reach the engine |
|----------|--------|--------------------------|
| Linux | `LANGUAGE`, `LC_ALL`, `LC_MESSAGES`, `LANG` | at boot |
| Windows, macOS | the user's language list | at boot and when the window regains focus |
| browser | `navigator.languages` | on `languagechange` |
| Android | the activity's configuration locales (the per-app language when set) | on the configuration change, without restarting the app |
# multiplayer Module
Public Luau surface over the `__multiplayer` Internal FFI namespace —
runtime multiplayer sync state and operations.
## Purpose
Wrap the raw `__multiplayer.*` FFI namespace in a typed Luau table
that gets auto-injected as `_G.multiplayer` via the prelude. Covers
connection, peers, ownership, rooms, edit-mode undo/redo, and
sync mode.
Note: the top-level `sync {}` declaration helper (used inside a
component to declare synced properties) is a separate global
function the engine registers; this module covers the
runtime `multiplayer.*` namespace only.
## Usage
```luau
-- Connection
multiplayer.connect("https://relay.example.com")
multiplayer.joinRoom(multiplayer.roomKeyFor(sceneGuid, "play"))
-- Peers
print("me:", multiplayer.getPeerId())
-- `latency` is the round trip to that peer, nil until one is measured (which
-- is what this client's own row reads); `rttMs` below is the relay link alone.
for _, p in ipairs(multiplayer.getPeers()) do print(p.name, p.latency) end
print("relay:", multiplayer.getDiagnostics().rttMs)
-- Ownership
if not multiplayer.isOwner(entityId) then
multiplayer.claimOwnership(entityId)
end
-- What is this entity replicating, and why is a property not arriving?
-- observeEntity is nil when the session holds no record for the entity;
-- explain answers either way.
local record = multiplayer.observeEntity(entityId)
if record then print(record.room, record.roomPeers, #record.components) end
local verdict = multiplayer.explain(entityId, "Health", "hp")
if not verdict.arriving then print(verdict.reason) end
-- Edit-mode operations (atomic undo entries)
multiplayer.beginOperation("move cube")
moveCube()
multiplayer.commitOperation()
multiplayer.undo()
```
## Exports
- Connection: `connect`, `disconnect`, `isConnected`, `getPeerId`,
`getPeers`, `getTickRate`, `getDiagnostics`.
- Rooms: `joinRoom`, `leaveRoom`, `getRooms`, `roomFor`. Room keys carry
five segments: `{worldGuid}/{profile}/{branch}/{mode}/{sceneGuid}`.
- Replication observation: `observe`, `observeEntity`, `observeComponent`,
`explain`, `syncTotals`, `heldMessages`. The same document is served at
`/zero/runtime/sync/replication`, `/zero/runtime/sync/entities/<id>` and
`/zero/runtime/sync/rooms`.
- Ownership: `isOwner`, `claimOwnership`, `releaseOwnership`.
- Edit-mode operations: `beginOperation`, `commitOperation`,
`cancelOperation`, `undo`, `redo`, `canUndo`, `canRedo`.
- Loopback (test harness): `loopback`.
- Mode: engine-level state, read and written via `engine.mode`.
# Module (asset type)
A module is Luau code that runs when other code calls it: other code
pulls it in with `require()` and calls its functions. It has no
lifecycle hooks or callbacks; nothing attaches it to an entity or runs
it every frame. Anything that is code can be a module: a whole game
system (rules, an inventory, a level generator, a match flow), a
helper, a format parser, a registry, a shared algorithm. The engine's
own APIs (`physics`, `input`, `audio`, `camera`, `entity`, `asset`,
`http` and the rest) are modules.
## When to use one
- You have logic you want to share across multiple components,
services, scenes, or tools.
- You have a registry, lookup table, or shared cache that callers all
read from / write to.
- You want a stable API surface (`M.fn`) other code can depend on.
If the code runs on an entity, driven by hooks and callbacks, use a
`.component`. If you want a
named UI of fields rather than functions, use a `.preset`.
## Where it lives
- Source: `/zero/source/.../<name>.module/`
- Identity: the source path with `/` written as `.` and each segment's
type suffix dropped — `/zero/source/demo/beats.module` is
`demo.beats`, and `/zero/source/kit.package/beats.module` is
`kit.beats`, the container's name kept and its `.package` suffix
gone. `asset.create` returns this string, `asset.resolve(...).identity`
reads it back, and the `require` forms below write it as
`<identity>`.
- Folder shape:
- `init.luau` (or `init.lua`) — module body. **Required.** Returns
a table (conventionally named `M`).
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
```luau
asset.create("module", "<name>")
-- Creates: /zero/source/<name>.module/
-- init.luau (canonical `local M = {} … return M`)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source, and that subfolder
-- leads the identity: `{ folder = "lib" }` produces `lib.<name>`.
-- `into` authors it inside a resolved container (a package, a toolbox),
-- whose own identity leads the same way:
asset.create("module", "<name>", { folder = "lib" })
asset.create("module", "<name>", { into = asset.resolve("myPkg.package") })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.module/` folder
indexes the asset and registers the module path with the resolver.
2. **Loading.** The first `require("<identity>")` runs
the file's body and caches the returned table. Subsequent requires
from anywhere return the **same table** — this is the
shared-state lever for "module-local" registries. The body runs in
an environment of the module's own: a name it declares without
`local` is readable by the module's own functions and by no other
script, so an export reaches its callers through the returned table
and nothing else. Requiring a component's folder runs its chunk the
same way, once, and its `update`, `start` and `public` stay in that
environment; a component runs on an entity through
`entity(id).component.add(name)`.
3. **Hot reload.** Editing the file re-runs the module body and folds
what it returns into the table already loaded, so that table keeps
its identity: a caller that captured it with `require` reads the new
source's functions and values through the reference it already
holds, and a later `require` returns that same table. A key the new
source drops goes away; a key something set at runtime stays. The
body's own `local`s start again from their initial values, so state
that must outlive an edit lives in `modules.state()`
(`guides { path: "core/scripting-and-tasks" }`).
4. **Identity resolution.** A module is reached by its `<identity>`,
and where the caller lives decides which spelling of it resolves.
For a module in a **world**, from a caller in that same world —
another module, a component, a scene entrypoint, or an `execute`
chunk:
- `require("<identity>")` — the identity on its own, resolved
against the caller's own root. It carries every folder segment,
so a module created with `{ folder = "demo" }` is
`require("demo.beats")`.
- `require("@root::<identity>")` — the same root-relative
resolution, written out.
- `require(".sibling")` — a module in the same folder, by its bare
name; `..name` steps up one folder, `...name` two.
Logs, stack traces and hot-reload notices name that same module
`@local.source.<identity>` — its key under the world source root.
The `<identity>` tail of that key is the form above, so a trace
reading `@local.source.demo.beats` is `require("demo.beats")`.
For a module in a **library** — content under
`/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's
root from anywhere: `require("@builtin::modules.transform")`.
Mounting a world as a library moves its files under such a root and
flips the caller root to `@<lib>::`, which is what keeps the
root-relative forms above resolving across the move.
## Discovery
- `asset.list("module")` — every registered module.
- `asset.inspect("<name>")` — public functions, source path, this
type README.
- `ls /zero/source/<name>.module` lists the files the folder holds.
## Authoring conventions
- Return a single `M` table from `init.luau`. Top-level statements
with side effects run on first require — useful for one-time
initialization, dangerous if they touch the engine before it's
ready.
- Write exported functions as `typed function`, not `function`: the
argument types are enforced at the call and the checker knows the
signature, so a caller's mistake is reported where they made it.
- Annotate exported functions with `--!desc` / `--!arg` / `--!return`
/ `--!example` so the LSP, `tools.list`, and `asset.inspect`
surface them. A function with no `--!desc` is reachable only by
someone already reading this file.
- Declare a VALUE with `Field.<kind>(default, mode, description)`, and
a table whose members are reached through a metatable with
`--!members <TypeName>` — the latter gives the surface its accepted
member set, its type, and its documentation from one table. See
`guides { path: "core/authoring" }` for all four rules and
`modules/api/engine/entity.module/members.module` for a worked
member table.
- Keep module state in module-local upvalues or in `modules.state()`.
A name the body declares without `local` lives in the module's
environment, which every run of the module shares: a function the
previous run left in place reads what the reload assigned. Module-locals start again from their
initial values with each hot reload; the table `modules.state()`
returns is the same table on both sides of every reload.
- Prefer focused modules over kitchen-sink modules. If two halves of a
module have no shared state, split them.
## Common pitfalls
- **Cyclic requires.** A `require` chain that loops will return the
partial table (the half built before the cycle was detected).
Design for one-way dependencies.
- **Engine-time side effects.** Don't `entity.spawn` at module
top-level — the engine may not be ready. Expose an `M.init` and
call it from a scene entrypoint.
- **Hot-reload + module-local cache.** A module that caches
expensive computation in upvalues loses that cache on reload —
fine for dev, but be aware in performance work.
- **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical.
- **Writing one while play runs.** A `/source` write made while play is
running lands on the play shadow, and a guarded play-exit discards it
unless it is kept. One `.module` write shadows `init.luau`, the
`README.md` and the `.metadata` together.
`vfs.write(path, bytes, { durable = true })` skips the shadow, and
`vfs.promotePlayShadow` keeps what is already on it — the `core/vfs`
guide has the model and what each route costs.
## Related types
- `.component` — for entity-bound state + lifecycle hooks.
- `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider.
- `.tool` — for a single agent-callable function with a YAML schema.
- `.package` — to group several modules + components + scenes into
one shippable folder.
## In the Inspector
Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
# sceneInstantiable
Can be placed in a scene. A type that lists `sceneInstantiable` under
`interfaces:` in its `type.yaml` guarantees that `instantiate` composes any of
its assets under or onto an owning entity, synchronously, and returns the live
root and the map naming what it spawned. A consumer places any such asset with
one call, `source:as("sceneInstantiable"):instantiate(target, opts)`, and it
works for types the consumer has never heard of: the `Asset` component, a
viewport drop, a procedural generator and a tool argument all place assets this
way.
## Implementing it
```yaml
# marker.assetType/type.yaml
interfaces: [sceneInstantiable]
```
```lua
-- marker.assetType/behavior.luau
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
local M = {}
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts)
root.component.add("Text3D", { text = self.name })
return Instantiable.result(self, root, {})
end,
}
return M
```
A type whose own `instantiate` means something else meets the member under
`M.interfaces.sceneInstantiable.instantiate`.
## The base inputs
`target` is the owning entity; with none, the type spawns a fresh root.
`opts.position`, `opts.rotation`, `opts.scale`, `opts.name` and
`opts.temporary` mean the same for every type, and `Instantiable.root` applies
them to a root the type makes (`Instantiable.place` to one it adopts).
`opts.idMap`, `opts.diff` and `opts.sourceTag` are what the `Asset` component
passes to every type: a type that spawns no addressable children ignores them.
`opts.detached` composes a permanent copy that nothing composes again. A type's
own extras (`raw`, `deferred`, `params`) travel in `opts` beside these, are
always optional, and never change a base input's meaning.
## Required behaviour
1. `root` exists on return, with everything composed under it.
2. `idMap` maps each original id to the spawned id; `{}` for none.
3. Passing the returned `idMap` back reproduces the same ids.
4. `temporary = true` keeps the root and everything under it out of the saved
scene.
5. Despawning `root`, or the composition the `Asset` component despawns, removes
everything the call put in effect.
The conformance suite, `sceneInstantiableConformance` beside this file, holds
one asset of every implementing type (or of the types a run names) to the base
options' meanings, the returned map reproducing its ids when passed back, and
a detached composition's live root. `asset.validate` of a world's own type runs
it over that type.
## Legacy types
A type that defines `M.ref.instantiate` and lists nothing (one written
before `interfaces:` existed, or defined by its `behavior.luau` alone)
implements `sceneInstantiable` with a warning (`interfaces.implied`) naming the
line to add.
# assetType runtime
The machinery that reads a `<typename>.assetType/behavior.luau` and turns its
declarations into live behaviour.
A `behavior.luau` is a table of declarations — `ref` methods, `modules` shared
code, an `events` schema, a `namePattern`, `refShapes`, and the `onCreate` /
`onRegister` / `onChange` / `onDelete` / `validate` / `settingsDefaults` /
`settingsCorrections` hooks. None of it runs itself. This is the code that
runs it, and it lives here because reading a type's declarations is the
**assetType type's own behaviour** — the same way `material.assetType` owns
what a `.material` does.
## Sub-modules
| Module | Reads | Responsibility |
|---|---|---|
| `ref.module` | `ref`, `modules` | Builds every `AssetRef` envelope, attaches the shared metatable, and dispatches per-type methods and shared modules onto it. Also owns edit-mode write-behind persistence. |
| `create.module` | `onCreate`, `namePattern`, `validate` | Backs `asset.create`: resolves the type, checks the name against its pattern, runs `onCreate` (or clones `template/`), and writes the instance. `validate.module` beside it checks a creation `opts` table against the type's `createSchema`. Before running `onCreate`, resolves the type's settings chain (below) and hands the result to the hook as `opts.settings`. |
| `settings.module` | `settings`, `settingsDefaults`, `settingsCorrections` | A type's declared settings schema and where its values live (`type.yaml`'s `settings:` block). `Settings.resolveForCreate` layers the schema's own defaults, the type's own `settingsDefaults(name, opts, asked)` hook (a DEFAULT the schema can't express — a name-derived convention, a fact read off a payload the caller handed it, a value following a field `asked` shows a higher layer naming; any later layer overrides it), the Preset Manager, an importer's settings, the caller's `settings` table, then the type's own `settingsCorrections(values, name, opts)` hook (a CROSS-FIELD CONSTRAINT the schema can't express, applied last over the fully merged values). A correction over a default/preset/importer value lands silently; a correction that would override what the caller's own `settings` table explicitly asked for refuses the creation instead, naming the field and why. Neither hook is ever handed a table to mutate; each returns what it wants changed (`settingsCorrections` may also return a `{ [field]: reason }` table for that refusal message). `Settings.cloneValues` deep-copies a values table — `create.module` hands `onCreate` a copy, never the table it stamps. `Settings.valuesOf` / `writeValues` read and write an asset's own values file. |
| `typeYaml.module` | `type.yaml` | The folder a type lives in and its parsed `type.yaml`, decoded once per content version of the file. `settings.module` and `inspector.module` read their blocks through it. `about` / `aboutAt` read a type's `about.yaml` (`intent`, `function`, `usage`), leaving out any key that is empty or still starts with `[[describe]]`; `aboutRows` and `aboutMarkdown` lay the texts out for the Inspector and the `types/<name>` guide. |
| `inspector.module` | `type.yaml`'s `inspector:` block | Which inspector a type declares for its assets (`inspector: { type: ... }` or `{ instance: ... }`), and the declaration that file returns — the sections it adds, the generic ones it replaces, and their order — or the problem that kept it from loading. |
| `onRegister.module` | `onRegister` | Fires an instance's once-only registration hook — on arrival, on world load, and for `@builtin` library instances. |
| `changeDispatch.module` | `onChange`, `onDelete`, `refShapes` | Routes a VFS source write or a folder delete to the enclosing typed asset's type hooks. |
| `refShapes.module` | `refShapes`, `ref` | Publishes what every `AssetRef<category>` answers to, so a member read on an asset-typed value is checked against that category's real surface. |
| `events.module` | `events` | The per-asset event runtime behind `ref.events`. |
| `instantiable.module` | `ref.instantiate` | The instantiation contract an asset type opts into: `root` stands the root entity, `place` applies the base placement opts to one the type adopted, and `result` shapes the `(root, idMap)` every `instantiate` returns. Also registers the `sceneInstantiable` field-constraint validator. |
| `interfaces.module` | `type.yaml` `interfaces:`, `interfaces`, `ref` | The interfaces a type implements: reads each `interface` asset, reads a type's marks from the references its `type.yaml` records under `interfaces`, runs every check and refusal of the declaration, and answers `implements`. |
| `declaration.module` | `type.yaml` | The type's decoded declaration, read once and held until a write inside an `.assetType` folder; what every question about a type as a whole reads. |
| `previewRecipe.module` | `type.yaml` `preview:` | How an instance's `preview.png` is produced: which of the four recipes (`instantiate`, `image`, `surface`, `custom`) the type declares, and what that recipe needs. |
## Reaching it
```luau
local rt = require("@builtin::assetTypes.assetType.shared")
rt.ref.loadTypeBehavior("material")
```
Fields resolve lazily. The prelude requires the sub-modules directly, in
dependency order (`ref`, then `changeDispatch`, `onRegister.install()`,
`refShapes.install()`) — a table that required all six on load would take that
ordering away from it.
# Generator
A live procedural generator: it binds a `.procGraph`, plays the graph's
timeline and stands each of the graph's outputs in the scene as children of
the entity it is on. Change a param and the output is made again in place; in
edit and in play alike, nothing it makes is written to the world's source.
```lua
local graph = asset.create("procGraph", "crate") -- a box with a `size` input; edit its init.luau
local e = entity.spawn("crate")
e.component.add("Generator", { graph = graph })
e.component.get("Generator").params = { size = 2 }
```
## Fields
| Field | What it does |
|---|---|
| `graph` | The `.procGraph` it plays. |
| `params` | Overrides for the graph's declared inputs, by name. |
| `output` | One declared output to stand; empty, the default, stands every output. A graph of the call form stands what its `io.output` calls show (the ones the named output reaches, when one is named); an output it names that no `io.output` of the graph shows is shown by the Generator itself, under the output's name, the way an `io.output` of it would show it. A graph of the older node form stands each output it declares, one root each. |
| `playOn` | What starts its clock in play mode: `"auto"` (default) plays a timeline with no end as soon as it binds and holds any other on its first frame; `"load"` plays on bind; `"manual"` waits for `play()`. In edit mode a Generator is not set to play, whatever `playOn` says: it shows the frame it is on until it is played. |
| `ending` | `"graph"` (default) does what the timeline declares; `"loop"` plays the range round and round; `"hold"` plays it once and stays on its last frame. |
| `speed` | How fast its clock runs: 1 (default) its own rate, 0 still, negative plays a timeline with an end backwards. |
| `diskCache` | Whether the outputs the graph caches load from, and are written to, the world's disk cache. On by default. |
| `bakedSnapshot` | The bundle an earlier engine stored with the scene for what the generator realized. In play it stands in place of cooking while the disk cache does not hold every output; the first commit that writes the disk cache for all of them clears it. Empty by default. |
| `cookBudgetMs` | Milliseconds of cook work a frame before a cook yields to the next frame. Unset by default: a cook then spends the part of each frame the frame's other work leaves. |
## Methods
`play()`, `pause()`, `seek(seconds)`, `seekFrame(frame)`, `loop()`, `hold()`,
`setFps(fps)`, `setRange(first, last)` and `setWallTime(on)` drive its clock,
on every peer. `getFrame()`, `getTime()`, `describeGraph()` and `playback()`
read it; `playback()` also says what running the graph costs and how each
output is drawn: `cost.cooks` counts the cooks it presented and `cost.cookMs`
the CPU milliseconds they ran, the frames they waited out apart, for a graph of
the call form as for one of the node form. `describeGraph()` describes the graph
bound, of either form. `cancelCook()` stops a cook in flight and leaves the last
output standing. `apply()` swaps the generator for the asset it makes: the
frame being presented becomes a bundle, and an `Asset` component standing it
takes the Generator's place; for a graph of the call form, the bundle holds what
its `io.output` calls show, each under the name it was shown under. The
`onFinished` event fires when a range played once reaches its end.
A timeline that runs in real time (`realTime = true`) has an end when its graph
states `frames` beside it (`g:timeline({ realTime = true, fps = 60, frames = 180 })`)
or when `setRange` gives it one; with neither it runs on and never finishes.
When the playhead of one with an end reaches its last frame, `ending` applies as
it does to any timeline: `"graph"` loops where the graph declares `loop` and
otherwise holds on the last frame and fires `onFinished` once; `"loop"` plays it
again from the start, a fresh simulation each time, without firing it; `"hold"`
stays on the last frame. `play()` plays a held one again from its start.
`playback().ends` is whether the timeline has an end, and `last` is its last
frame. A real-time timeline begins again, by `seek(0)`, a loop or `play()`, in
the runs its solvers hold on the device: a restart costs a rewrite like any
other present, and opens no cook.
## What it cooks again
A Generator cooks again, in edit mode and in play alike, when its graph's source is
edited, when its `graph`, `params`, `output` or `diskCache` change, and when anything
its graph was built from changes: a node the graph reaches (edited, or no longer
loading), a module the graph or one of those nodes requires while it builds, or a file
their builds read (`vfs.read` in a node or graph source, `proc.read` in a module they
call). A Generator that does not reach the change cooks nothing for it. Every node of
one cook is built from one version of each module and file.
A graph that does not build (its source, or a node it calls, raises while it is built)
leaves what the Generator stands standing: `playback().error` says why, the cook
history holds a cook of target `source` closed `failed` with the error, and once what
it failed on is fixed the Generator cooks again on its own.
## What it draws
An output drawn as instances (`drawn[output].as == "instances"`) is copies of one
mesh per piece, placed by a transform buffer: a forest is a trunk copy and a crown
copy per tree, a scatter one copy per item. A copy is no entity and holds no
collider, so the scene tree shows the Generator alone and `Physics.raycast` passes
through every copy. The renderer answers for them:
```lua
local id = generatorEntity.id
for _, pop in renderer.mesh.listInstanced() do
if pop.parent == id then
print(pop.meshGuid, pop.material, pop.instanceCount) -- one row per piece
end
end
local hit = renderer.raycast(eye, direction, 100) -- meets each copy's triangles
if hit and hit.instancedDraw then
print(hit.entityId, hit.instancedDraw.id, hit.instance) -- the Generator, the draw, which copy
end
```
`renderer.mesh.listInstanced()` lists every instanced draw with its `instanceCount`
and `parent` (the Generator's entity), each record itself the draw handle the
`renderer.mesh.instance*` calls take; `renderer.mesh.instanceWorlds(record)` reads
back where each copy stands. A ray hit's `instancedDraw.id` is the `handle` of the
record it met.
## What `playback()` answers
One table, typed `PlaybackState`. The tables in it keyed by name are maps,
read with `pairs`, never `ipairs`:
```lua
for output, d in pairs(generator:playback().drawn) do
print(output, d.as, d.count) -- "instances" or "entities", and how many
end
```
| Field | What it holds |
|---|---|
| `playing`, `heldByPause`, `held`, `realTime`, `wallTime` | The clock's state: running, held by a pause, held at the end of its range, a real-time timeline, wall time on. |
| `frame`, `time`, `first`, `last`, `frames`, `fps`, `loop`, `ends` | Where the playhead stands and the range it plays; `ends` is whether the timeline has an end. |
| `cookedThrough` | The last frame cooked ahead; reaching `last` means every frame is cooked. |
| `cooked`, `hits`, `steps`, `restarts`, `replacing` | Node cooks, cache hits, solver steps, solver restarts, and outputs built again whose earlier state still stands. |
| `error`, `cookError` | Why the graph's source does not load, and why its latest cook failed (led by the line of the call that failed, `path:line: g.<call> failed: <why>`), while they do. |
| `drawn` | By output name: `{ as, count, because?, pieces? }`, how the output's elements reach the screen. |
| `cost` | `{ frames, frameMs, cooks, cookMs, devicePresents, deviceMs, memoPresents, framePresents, realizeMs, drainMs, rewriteMs }`: `frameMs + cookMs` over `frames` is the script cost of a frame. |
| `nodes`, `ms` | By node id: how many times each node cooked, and its milliseconds. |
| `placement`, `placementByGraph` | By node id: where its cooks ran (`runs` "device", "cpu", "mixed" or "values"); and per node a graph used as a node stands as, the sums of its inner nodes. |
| `onDevice`, `offDevice`, `cpuNodes` | Whether a new time is presented on the device, what holds it to cooking when it is not, and how many nodes run on the CPU every frame. |
| `heldFrames`, `notHeldFrames` | Whether presents stand on the frames the engine holds, and why not. |
| `diskCache` | By output name: `{ key, frames, static, complete, hits }`, or `{ reason }` where the cache is not used. |
| `call` | For a graph in the call form, the report of its play. |
| `owner` | The name the generator's device runs are held under. |
`playback()` reads what the generator keeps as it runs, so it costs the same
however much its caches hold. `cookError()` answers its `cookError` alone, for
a caller that watches for a failed cook every frame. `heldBreakdown()` walks
everything the generator holds and states the Luau bytes: by field of its state
and of its play, `cacheBytes` for its node caches and `heaviestEntries` for the
largest entries of its play's node cache.
## What stands while it cooks again
What a Generator stands stays standing while it cooks again, and a present
replaces all of it at once: the shows a present makes stand together in the
frame its cook finishes, and what they replace goes in that frame. So no frame
stands nothing, and none stands part of one cook beside part of another. Each
output stands once: a param set it cooked before shows that set's output again,
and params set while a cook runs are cooked by the cook after it. A cook that
fails, or is cancelled, leaves what stood standing.
## Under an effect
An effect's play runs each graph of its entry on a Generator, a child of the
play's entity. `effectRef:play(entry, opts)` and the `Effect` component make
them and drive their clocks together, so a shot, an impact or a cast is a play
of an effect (`guides { path = "systems/effects/documentation/visual-effects" }`). The play's own
`playback()` adds its Generators' costs together.
Every play of one graph with the same params plays the frames the first one
cooked. A Generator of a graph with `playOn = "manual"` cooks every frame of the
timeline while it waits, and `playback().cookedThrough` reaching
`playback().last` says every frame is cooked.
## Related
- `guides { path = "systems/procgen/documentation/procgen" }`: graphs, ops,
timelines, effects and the live generator in full.
- The `procgen` toolbox: `spawn`, `adjust`, `apply`, `cancel`, `generators`,
`cooks`, `frames` and `onPresent` work on generators by entity, and `play`
plays a graph on the preview stage.
# fx
The fixed, data-driven device program set an effect play runs on. A graph reaches the device as data: a field
expression is compiled to an op list (`fx.ops.compileText`), words that a fixed element interpreter
(`kernels/fx_eval`) reads, so no program is built for a graph and a play never waits on a build.
## The op compiler
`fx.ops.compileText(text, retType)` reads the `let name: T = expr;` lines and the `return` of a field function (or the
whole function) and answers `{ ops, words, ret, lanes, slots, family, ... }`, or `{ refusal }` naming what the op set
does not hold. `fx.refusals()` counts every refusal by its reason.
An op list is SSA over a scalar bank of registers (values of one lane, up to 32) and a vector bank (values of two to
four lanes, up to 15), with the element's position in vector register 0. Pure ops that repeat are shared, ops no
returned value reads are dropped, and the field operator templates (division, remainder, square root, gather index,
unit hash) are one op each, except a remainder, which is a quotient, a product and a difference. `fx.ops.table` is the
opcode table: each op's code, its family (`core`, `rand`, `noise`) and whether it is a scalar form. `slot_get(k)` reads
word `k` of the dispatch.
## The interpreter
`fx.warm()` registers the three families of `kernels/fx_eval` once; `fx.ready()` says when they are built and
`fx.awaitReady()` waits. `fx.dispatchEval(job)` writes the job's row, column descriptors and op list into the owner's
chunk of rows and queues the family's program over the pages the columns stand in; the dispatch names the runs it
reaches and writes. `fx.dispatchCount()` counts the dispatches queued.
## The backend
`proc.substrate.withBackend("fx", fn)`, `setOwnerBackend(owner, "fx")` and `backend()` choose where work runs. Under
`"fx"`:
- `fieldc.evaluate` and `fieldc.runMap` run a field chain on the interpreter (`fx.map`);
- the element programs of `proc.device` that have a twin (`fx.twins`: fills, the index run, the word copy, an integer
run read as numbers, the bounded gather) are never built, and queue their op list;
- anything the fixed set does not hold runs the compiled program and is counted by `fx.refusals()`.
`proc.eval(graph, target, { backend = "fx" })` cooks under it.
# PostProcess Component
Applies a **stack of post-process effects** to the scene, declaratively, from a
single entity. Each effect references a `.shader` asset (`@domain: post-process`)
or a `postEffect` asset, and carries its own **configurable property values** — tuned like material
properties, with no shader edit required.
This is the load-time **reproducer** for post-processing: where an agent's live
`postprocess.add(...)` + `postprocess.setProperty(...)` calls produce effects
that vanish on reload, a `PostProcess` component re-registers the exact same
stack — with the exact same tuning — every time the scene loads. The persist
freeze converts live execute-origin effects into `.shader` assets + one entity
carrying this component, so **what you see is what you get** across save/reload.
## Properties
| Field | Type | Description |
|---|---|---|
| `effects` | array | The effect stack. Each entry: `{ shader | effect, priority?, enabled?, layer?, values?, textures? }`. |
| `shape` | `"global"` \| `"box"` \| `"sphere"` | Where the stack applies. Default `"global"` (unbounded). |
| `extents` | vec3 | Box region half-extents, world units. Default `{5, 5, 5}`. |
| `radius` | number | Sphere region radius, world units. Default `5`. |
| `falloff` | number | Soft-edge distance outside the volume the stack fades over. Default `0`. |
| `priority` | number | Order of this region against other `PostProcess` regions, added to each effect's own priority. Default `0`. |
| `display` | struct `{ curve, exposure }` | The display transform this region sets while it is live — `curve` (0 clamp, 1 Reinhard, 2 ACES, 3 Khronos PBR Neutral, 4 AgX, 5 AgX Punchy, 6 Tony McMapface, 7 Gran Turismo; default `4`, AgX) and `exposure` (multiplier on the scene's light before the curve, default `1`). Takes effect only when `setsDisplay` is `true` and `shape` is `"global"`. |
| `setsDisplay` | boolean | Whether this region writes `display` to the chain's `__display__` transform while it is live. Default `false`. |
Each effect entry:
| Key | Type | Description |
|---|---|---|
| `shader` | asset reference | The `.shader` asset (a `@domain: post-process` shader) this effect runs. Builtin shaders (`@builtin::shaders.post.vignette`, …) or scene-authored custom shaders both work. An entry names this or `effect`, exactly one. |
| `effect` | asset reference | A `postEffect` asset this entry applies, in place of `shader`. The entry is an application of it owned by `"<entity id>/effects/<index>"`: its `values` and `textures` are the values it states, its `layer` is stated when not empty, and the region's `priority` is added to the effect's own `order` (the entry's `priority` is not read). The effect's live values reach it like any application. |
| `priority` | number | Chain order within this region — lower runs earlier. Default `100`. |
| `enabled` | boolean | Per-effect toggle. Default `true`. |
| `layer` | `"all"` \| `"scene"` | Which composited image this effect grades: `"scene"` is the rendered picture before the UI reaches it, in the scene's own light; `"all"` is the picture fitted to the screen with every widget on it. Left empty, the entry follows its shader's `space` — a `light` shader grades `"scene"`, a `display` shader grades `"all"`. |
| `values` | table | Named property overrides `{ [prop] = value }`, applied via `postprocess.setProperty` after the effect is added — the configurable tuning. |
| `textures` | table | Texture bindings `{ [prop] = path }`, applied via `postprocess.setTexture` after the effect is added. |
An entry naming both `shader` and `effect`, or neither, registers nothing and is
reported by name in the log.
The component-level `enabled` flag (engine-managed, not declared here) toggles the
**whole stack**: disabling the component removes every effect (and restores the
chain's own display transform if this region set one); enabling it re-registers
them (`onEnable` / `onDisable`).
## Usage
```lua
entity.find("fx").component.add("PostProcess", {
effects = {
{ shader = "@builtin::shaders.post.vignette", priority = 0,
values = { intensity = 0.6 } },
{ shader = "@builtin::shaders.post.grayscale", priority = 10,
values = { intensity = 1.0 } },
},
})
```
Setting the display transform from a `global` region:
```lua
entity.find("look").component.add("PostProcess", {
setsDisplay = true,
display = { curve = 2, exposure = 1.5 }, -- ACES
})
```
Two `global` regions with `setsDisplay = true` both write `__display__` — whichever
registers last wins the frame. The regions setting it share one ordered record of
who is live, so they come off in any order: removing the newer of two leaves the
older one's display standing, removing the older leaves the newer one's, and
removing the last leaves whatever stood before any of them wrote.
The exposure package drives `__display__.exposure` on its own, from a GPU readback
each tick it meters. A region arriving or leaving sets the exposure and the
package's next readback sets it again, so with auto-exposure running the exposure
a region asks for holds for a frame while its curve holds for as long as the region
does.
## Methods
- `pp:getEffectNames()` — the live effect names currently registered, in stack order.
A name is `ppcomp-<entity id>-<n>` (`ppcomp-<entity id>.<instance name>-<n>` for a
named PostProcess), where `n` is the entry's position in `effects`. It stays the
same across scene rebuilds, play entry and exit, hot reload and a reload of the
saved scene, so `postprocess.setProperty(name, ...)` by a name read earlier keeps
reaching the effect.
- `pp:setProperty(index, prop, value)` — tune a property of one effect at runtime
(forwards to `postprocess.setProperty`), like editing a material property.
# generator_inspector
The `Generator` component's card on an entity. It replaces the card's generic
`settings` section with one built from the bound graph: the graph it runs, as
an asset picker, and which of its outputs it realizes; then groups — Inputs,
one row per input the graph declares in the control its type takes, each able
to take an expression over the graph's own time; Timeline, the transport,
scrubber, range, frame rate, looping and wall time; Cook, what is cooking, what
cooking has cost and the frame budget — and the Flatten action. The
component's `inspector.luau` returns this module, so the editor's inspector
framework (`edui.inspector.componentSections`) shows it wherever the component
is on an entity. While the clock runs, or the range is still cooking, the card
asks the panel to follow it.
Editing an input row writes the value into the component's `params`, which
regenerates the live output in place. A write the input's type cannot hold is
refused, and the row says why.
`buildFieldSpecs(graph, params)` is the pure row mapping: one spec per declared
graph input, sorted by name, carrying its kind, its current value (the param
override when set, else the declared default), its declared range, the asset
kind a reference input picks from, and whether the value changes over time.
# entityRef members
One table describing every member of the entityRef — the value `entity(id)`
returns.
```luau
--!members entityRef entity/proxy
local M: { [string]: Member } = {
id = { kind = "property", type = "string", doc = "This entity's id string." },
despawn = { kind = "method", type = "(self) -> ()", doc = "Remove this entity from the scene." },
component = { kind = "namespace", type = "{ [string]: any }", doc = "Script components attached to this entity." },
}
```
## Why one table
Three things need to agree about what an entityRef has, and they used to be
written separately:
| Consumer | What it takes from here |
|----------|------------------------|
| `ref.module` | The accepted-member set — a member not named here is refused, and the refusal lists these names. |
| The LSP | The `entityRef` type, generated from every entry's `type`. |
| `man` / `lsp.describe` | Each member's description and rendered signature. |
The `--!members entityRef` directive publishes the last two. Because all three
read this table, a member cannot be documented but unimplemented, or accepted
but undescribed.
## Declaring a member
`kind` says what the member IS, which is what a reader needs and what decides
how it renders:
- `property` — read as a value. Renders `entityRef.id -> string`.
- `method` — called. `type` is the whole signature, `self` first. Renders
`entityRef.rename(self, newName: string) -> ()`.
- `namespace` — carries its own members (`component`, `attribute`).
`type` is a Luau type expression. A type that does not parse degrades to `any`,
which answers every member access and quietly reverses the checking this exists
for — so prefer a shape that is true over one that is precise. Several
transform members are `{ [string]: any }` because the value really is a live
proxy answering `.x`, `[1]`, and `set`/`get`/`add`.
`doc` is one sentence, and `deprecated` names the path that supersedes it.
`example` is the line a reader copies, published on the member's page under
`Examples:`. A signature says what the call answers with; an example says what
to write with the answer, which is what a member answering a shape (an array
of identity strings, an array of records) needs beside its type.
## Where the members publish
The directive's second token is the doc path the surface is reached at, and
every member publishes there as well as under the subject's own name:
| Directive | A member lands at |
|-----------|-------------------|
| `--!members entityRef entity/proxy` | `entityRef/<member>` and `entity/proxy/<member>` |
| `--!members entityComponents entity/proxy/component` | `entityComponents/<member>` and `entity/proxy/component/<member>` |
| `--!members entityHierarchy globals/entity/hierarchy` | `entityHierarchy/<member>` and `globals/entity/hierarchy/<member>` |
The subject is a TYPE name, which is the spelling the checker and
`lsp.methods` use. The root is the spelling a reader who knows the CALL
writes. `entity(id).component.list()` reads at `entity/proxy/component/list`,
which is the page `man component.list` answers with and the entry
`/zero/docs/api/entity/` lists. A subject that declares no root publishes
under its own name alone.
## Adding one
Declare it here and implement it in `ref.module`. The member is then accepted
at runtime, typed by the checker, and documented — from this one edit.
# ref
Entity proxy metatable layer: a thin Luau metatable that calls into
the `__native_transform.*` / `__native_entity.*` flat FFI bindings and
serves the user-facing entity API:
`entity(id).localPosition = { x, y, z }`, `entity(id).despawn()`,
`entity(id).name`, etc.
After warm-up, steady-state allocation is **zero**: same `id` returns
the same proxy (weak-valued cache), sub-proxies are lazily allocated
once and cached on the proxy, and each method binding is a closure
created on first access and cached as `__m_<name>`.
## Exports
- `M.build(id: string) -> any` — entity proxy factory. Returns a cached proxy when one exists; otherwise allocates and caches a fresh one. Also bound as `_G.__build_entity_proxy`; its cache and metatable are bound as `_G.__entity_proxy_parts`, which the engine builds the proxies it hands scripts from, so both answer the same table for an id.
- `M.EntityProxyMT`, `M.PositionProxyMT`, `M.RotationProxyMT`, `M.LocalPositionProxyMT`, `M.LocalRotationProxyMT`, `M.LocalScaleProxyMT`, `M.LossyScaleProxyMT`, `M.TransformProxyMT`, `M.AttributeProxyMT` — exported metatables; consumers that want to extend the proxies can read them, but the proxies are sealed externally (every `__newindex` errors).
## Usage
```luau
local EntityProxy = require("@builtin::modules.api.engine.entity.ref")
local proxy = EntityProxy.build("some-entity-id")
proxy.localPosition = { 0, 1, 2 }
proxy.localRotation.eulerAngles = { 0, 90, 0 }
print(proxy.name)
proxy.despawn()
```
## Notes
- **World vs local space** (post Bevy hierarchy migration):
- `.position` / `.rotation` are world-space — engine back-computes
`Transform.{translation, rotation}` on set, decomposes the
world matrix on get.
- `.localPosition` / `.localRotation` / `.localScale` are
parent-relative direct reads/writes on `Transform.*`.
- `.lossyScale` is read-only world-space scale (approximate under
non-uniform parent scale + rotation; mirrors Unity).
- `.worldMatrix()` answers the whole composed object-to-world matrix as
16 column-major numbers, translation in elements 13, 14, 15 — the
placement the renderer draws the entity's geometry at, carrying the skew
a decomposition into position / rotation / scale folds away. Also
readable as `.transform.worldMatrix()`.
- Bare `.scale` was removed — accessing it raises an error pointing
callers at `localScale` / `lossyScale`.
- **Sealed proxies**: every proxy errors on `__newindex` (sealing). Mutations
go through `position.set` / `attribute.set` / etc., not direct field writes.
- **Caching**: the entity-proxy cache is keyed by `id` with weak values
(`__mode = "v"`), so dropped proxies are GC'd. Within one proxy, the
`M_PREFIX`-keyed cache survives until the proxy itself is collected.
- The `.component` sub-proxy is built by `__native_entity.component_subproxy`
— Rust-side helper that constructs the ~15-closure component-proxy
table once per entity. Subsequent `.component` accesses hit the
cached entry.
# renderer.atmospherics
`renderer.atmospherics`: the share of the air between the camera and a surface that reaches the image, and the holds that pin it.
# renderer.baseline
The renderer a caller began with: `renderer.markBaseline`, `renderer.resetToBaseline` and `renderer.releaseBaseline`.
# renderer.bounds
`renderer.bounds`: the extent a render feature publishes for a renderable it draws from its own buffers.
# renderer.captureView
`renderer.captureView`: the named camera passes a render feature publishes, each under a debug channel a capture selects.
# renderer.core
The renderer table every `renderer.*` namespace is defined on, the engine surfaces those namespaces call, the runtime registry a create files a resource in under the holder its scope names, and the handles each create hands out, held weakly so a resource nothing reaches any more is let go.
# renderer.debugPass
`renderer.debugPass`: resolves a debug-pass name to and from the channel it selects, for the built-in passes and the capture views.
# renderer.destroy
`renderer.destroy`: releases the runtime texture, material, mesh or render feature a handle, or a kind and an id, names.
# renderer.feature
`renderer.feature`: the registry of live render features, the context each one's `render(ctx)` runs with every frame, and their settings; `renderer.post`: the post stages; `renderer.output`: the output the frame is presented in.
# renderer.featureInputs
What a render feature's `render` reads, and whether any of it moved. A feature that states its inputs (`dependsOn`, `inputs`) has `render` run only on a frame one of them moved; on every other frame the engine runs the passes the last render handed over. Its settings in force are always one of those inputs.
- `settingsInForce(feat, levels)` answers a feature's settings at the quality levels in force, kept on its row until the authored settings or a level change.
- `NAMES` names each input a feature may state in `dependsOn` and what it stands for.
- `compile(mod, identity)` answers the inputs a feature module states, or nil for one that states none, and refuses an input it does not know by name.
- `holdsStill(feat, levels, frame)` answers whether every input stands as it stood at the feature's last render, so its passes can be replayed.
```luau
local FeatureInputs = require("@builtin::modules.api.engine.renderer.featureInputs")
local inputs = FeatureInputs.compile({ dependsOn = { "viewport", "camera.cell:2" } }, "example")
assert(inputs.viewport == true and inputs.cell == 2)
assert(FeatureInputs.compile({}, "example") == nil)
assert(not pcall(FeatureInputs.compile, { dependsOn = { "weather" } }, "example"))
assert(FeatureInputs.NAMES.lights ~= nil)
```
# renderer.featureTexture
`renderer.featureTexture`: sizes the shared feature-texture array a surface shader reads through `zero_feature_texture(uv, layer)`, sets its layers and reports its state.
# renderer.frameStats
What each frame submitted (culling, draws, skinning, morphs, uploads) and how the frames are paced: the frame pacing and activity readings, frames in flight, the present mode, the spectator mode, local layers and the frame-rate cap.
# renderer.holds
The reads every renderer cell a hold pins answers the same way. A hold on a cell such as `renderer.temporal` (the per-frame clock) or `renderer.atmospherics` (the share of the air that reaches the image) names who took it and the key it was taken under, so a caller reads who holds the cell, an exclusive hold is refused for every other key, and a hold whose task ended is handed back.
- `statedOwner(options)` answers the key `options.owner` states, or nil.
- `actor()` answers the id and display name of the caller the call is attributed to.
- `ownerLabel(owner, ownerName)` answers how a refusal names the holder.
- `holderIsGone(holder)` answers whether the task that took a hold was cancelled or died; `holdingTask()` answers the task taking a hold now.
```luau
local Holds = require("modules.api.engine.renderer.holds")
assert(Holds.statedOwner({ owner = "shot" }) == "shot")
assert(Holds.ownerLabel("abc", "Ada") == "Ada (abc)")
assert(Holds.holderIsGone(nil) == false)
```
# renderer.instanceData
`renderer.instanceData`: the per-entity lanes of the per-instance block a shader reads as `input.shader_data`, set and cleared by entity.
# renderer.letGo
The watch that releases a runtime texture, material, mesh or render feature mid-session once no script reaches a handle to it and nothing else holds it. It reads the renderer's handle sets every few dozen frames: a resource whose last handle the garbage collector took joins the watch and is judged against the runtime resource census, by the holders `renderer.collect` reads, and released once nothing holds it. A resource kept only by the component or scene load that created it stays while that owner does, and the log names an owner once it holds 64 of one kind that way, and again each time that count doubles. A render feature holds what it created through the handles it keeps and the passes it queues, which the census names as references, so a target whose handle the feature dropped and that none of its passes names any more is released while the feature stands. A texture or mesh the asset path uploaded under its asset's guid waits on the watch while that asset stands, and is judged from its holders once the asset index changes and the asset no longer answers. A texture a released material record named goes on the watch with it, the one the device holds for an asset included: that asset is the path the texture is read back by, so it is released once nothing else names it, the way a collection releases it.
- `new(host)` makes the watch over the handle sets, census and release the renderer hands it in `host`, and answers `{ start, rejudge, letGo }`: `start()` starts the task that reads the sets unless it is running, `rejudge(kind, guid)` marks a watched resource due a judgement at the next reading, and `letGo(kind, guid)` puts a resource a holder other than a handle let go of on the watch.
# renderer.lifetime
Runtime resource lifetime: `renderer.hold`, `renderer.release` and `renderer.references`, `renderer.collect`, and the let-go watch that releases a runtime resource once nothing holds it.
# renderer.material
`renderer.material`: the material records (a shader key, property overrides and texture-slot references) the renderer builds a bind group from, and what each one draws with.
# renderer.memory
The render device and what its memory holds: the GPU memory reading, the device generation, state, limits and errors, shadow memory and pages, the reflection environment, render targets and the pass schedule, texture memory, the texture budget and streaming, memory pressure, the material table and the texture bucket slack.
# renderer.mesh
`renderer.mesh`: the ZMSH codec, the guid-keyed CPU mesh store, the GPU meshes created from it, their clusters and level of detail, and the instanced draws of a mesh.
# renderer.observation
The renderer's readings of its pipeline and shader caches, its pending work, the frame it last drew (`renderer.observe`), the draw diagnostics, how a subject shades, what materials and shaders cost, and the material identity table.
# renderer.postStages
The frame's post stages: the ordered list of named seams every post effect runs at. Each stage states the colour space of the picture it holds (`light`, scene-referred light the display transform has yet to fit to the screen, or `display`, display-referred code values) and its resolution (`raster`, `output`, `reduced`, or `rasterToOutput` for a stage that starts on the raster and carries the picture to the output size). A render feature declares `stage = "<name>"` and a post-process chain shader `stage: <name>` in its `properties.yaml`; the engine schedules each from this list, a feature's passes inside the stage's band of orders at its pipeline phase and a chain effect at the stage's chain layer. `renderer.post.stages()` reports the list with the effects standing in each stage.
Inside a stage a feature's pass takes a local order from 0 up to `BAND`, and passes sharing an order run in the order they were enqueued, so a feature whose passes depend on one another (a chain over shared targets) can run them at one order, in sequence. A pass may name a stage of its own (`stage = "display", order = 2`): a feature whose work spans two stages, such as temporal antialiasing (its resolve in `temporal`, its sharpening in `display`), declares one and names the other on those passes. A chain effect takes its place among the chain effects of its stage by `priority`, a number, or `"last"`, after every numbered chain effect of the stage; chain effects sharing a priority, two `"last"` among them, run in the order they registered. The `ui` stage runs `afterUI` feature passes, then its chain effects, then `afterPost` feature passes, so an `afterPost` pass runs after every chain effect of the stage.
The presented frame (`renderer.presentedFrames`, a `capture` of `source = "presented"`) runs every stage. An offscreen render (a capture from a camera or a station, a render-to-texture camera) runs the render features of every stage up to `optics`, the film stages among them (`meter`, `optics`) only when its camera runs post-processing; when it fits the picture to the display it runs the `display` stage too: the display transform, the stage's render features and the chain's `display` layer. It runs the `ui` stage as well (its `afterUI` render features, the chain's `all` layer and its `afterPost` render features) when it renders the picture as the screen presents it: a capture does, and so does a render-to-texture camera with `textureColorSpace = "presented"`. Any other texture camera's picture takes the `ui` stage from the frame that shows it, and one with `textureColorSpace = "linear"` holds the scene's light and runs neither the `display` stage nor the `ui` stage.
Where the built-in effects run:
| stage | built-in effects |
|---|---|
| `lighting` | occlusion, reflections, indirect light, contact shadows, subsurface scattering, area lights, decals, splats, outlines, debug draws and diagnostic views |
| `medium` | aerial perspective, height fog, volumetric light |
| `preTemporal` | depth of field |
| `temporal` | temporal antialiasing |
| `postTemporal` | motion blur |
| `meter` | the exposure meter |
| `optics` | lens flare (render feature), bloom (chain) |
| `display` | the display transform, then the temporal upscale, debanding, edge antialiasing (FXAA) and sharpening (RCAS, CAS), then the chain's looks and the film grain (`lensFx.grain`, `priority = "last"`) |
| `ui` | the UI, then the cutscene fade and letterbox (`priority = "last"`) |
| `output` | the surface encoding |
The stages, in frame order: `lighting`, `medium`, `preTemporal`, `temporal` (one effect at a time), `postTemporal`, `meter`, `optics`, `display`, `ui` and `output`.
- `list()` answers every stage in frame order, each a copy: `{ name, film, space, resolution, single, runs, feature, phases, chain?, chainFirst }`.
- `isFilm(name)` answers whether a stage is one of the camera's film, the exposure meter and the lens light (`meter`, `optics`): a pass a render feature places there, naming no `postProcessing` and no `presented` of its own, is part of the camera's post-process chain, so a camera running no post-processing (a capture asking for the scene ungraded, an environment face) skips it, and `postProcessing = false` on the pass keeps it on every camera.
- `get(name)` answers the stage a name names, or nil and a message listing the stages there are.
- `index(name)` answers where a stage stands in the frame, 1 for the first.
- `chainLayer(name)` answers the chain layer (`scene`, `display` or `all`) a post-process effect declaring that stage runs at, or nil and the reason.
- `stageOfLayer(layer)` answers the stage a chain layer's effects run in.
- `stageOfPosition(phase, order)` answers the stage a render-feature pass placed by phase and order stands in.
- `BAND` is how many orders one stage's band at a phase spans: a declared feature's local order counts from 0 up to, and short of, it.
# renderer.rayTracing
Ray tracing: `renderer.setRaytrace` and the readings of the scene acceleration structure a ray-tracing render feature traces against, transmission shadows, and the main camera's view.
# renderer.refs
How `renderer.*` names a live resource. A runtime resource is filed under a v4 guid, minted from OS entropy or given by the caller; and each call that names a resource takes whatever the caller already holds (the key or guid, the handle `create` returned, the CPU handle `load` returned, or an `AssetRef`) and coerces it to the key the renderer's stores index it by.
- `makeGuid()` mints a guid; `validateGuid(guid, what)` answers `guid` when it is a v4 guid and raises at the caller's line when it is not.
- `materialKey(value, what)`, `meshKey(value, what)` and `textureKey(value, what)` answer the registry key or guid a value names, and raise a rejection that lists the accepted forms.
- `refField(t, name)`, `declaredCategory(value)` and `shapeName(value)` read a ref-like table the way the coercions do.
- `primaryBytes(ref)` answers an asset's primary content bytes, waiting for them under a coroutine when they are still on their way; `textureRefOf(value, what)` answers the ref a texture asset's content is read through.
```luau
local Refs = require("modules.api.engine.renderer.refs")
local guid = Refs.makeGuid()
assert(Refs.validateGuid(guid, "example") == guid)
assert(Refs.meshKey({ kind = "MeshHandle", category = "mesh", guid = guid }, "example") == guid)
```
# renderer.sampling
Anisotropic texture filtering, and where in a pixel the projection samples: its offset and jitter.
# renderer.shaderSources
The programs the engine compiled for each feature set a shader was asked for, and the WGSL the compiler received for a shader.
# renderer.shading
The readings `renderer.shadingOf` builds out of the document the renderer publishes every frame.
- `shadingSubject(value, what)` answers the id a shading question names: an entity proxy's id, an entity-id string, or the registry key of a material in any form a material answers to.
- `publishedRenderable(doc, id)` answers the row that answers for a subject: the entity's own row, or a row drawing with the material, a fault wherever there is one.
- `materialRow(doc, id)` answers the renderer's record for one material.
- `shadingFault(state, means, row)` builds the fault reading a row carries.
```luau
local Shading = require("modules.api.engine.renderer.shading")
local doc = { renderables = { { entity = "e1", material = "m1", substituted = false } }, materials = {} }
local row = Shading.publishedRenderable(doc, Shading.shadingSubject("e1", "example"))
assert(row.material == "m1")
```
# renderer.shadows
Shadow caching and its page breakdown, the skinned and blended batching switches and the skinning pose hold, the shadow configuration and sizing, the caster cutoff, shadow proxies, the shadow views and the shadow hero.
# renderer.sources
The `src` shapes `renderer.mesh.create` / `update` and `renderer.texture.create` / `update` take.
- `classifyMesh(src)` answers which mesh src it is (`SRC_GPU`, `SRC_CPU`, `SRC_GEOMETRY` or `SRC_BUFFERS`), and raises for a src that is none of them or a geometry src whose indices address a vertex its positions do not carry.
- `vertexRecordsToArrays(src)` turns geometry written as per-vertex records (`vertices = { { pos, normal?, uv?, uv1? }, ... }`) into the parallel flat arrays the upload takes.
- `boundsFromPositions(positions)`, `vecToAabb(min, max)` and `ZERO_AABB` are the bounds a mesh is created with; `geometryCounts(src)` answers the vertex and index counts raw geometry implies.
- `classifyTex(src)` answers which texture src it is (`TSRC_GPU`, `TSRC_CPU`, `TSRC_PIXELS` or `TSRC_TARGET`).
```luau
local Sources = require("modules.api.engine.renderer.sources")
local src = { positions = { 0, 0, 0, 1, 0, 0, 0, 1, 0 }, indices = { 0, 1, 2 } }
assert(Sources.classifyMesh(src) == Sources.SRC_GEOMETRY)
print(Sources.boundsFromPositions(src.positions).max.x) -- 1
```
# renderer.specShapes
The shapes a render feature's passes are held in. A spec frozen all the way down reads the same on every frame, so the engine keeps it as it read it. A spec a render hands over unfrozen is held as a frozen copy when it reads the same as one handed at the same place in an earlier render, so a feature that builds its specs afresh every frame costs the engine what one handing over frozen specs costs.
- `wholeFrozen(spec)` answers whether a spec and every table inside it is frozen and carries no metatable.
- `heldShapeOf(row, spec)` answers the spec to hand over at the feature row's next place: the held copy the spec reads as, a new held copy, or the spec itself once the place's specs keep moving.
- `placed` holds the placed copy of each frozen spec a stage placed, by the spec it was placed from, with weak keys.
```luau
local SpecShapes = require("@builtin::modules.api.engine.renderer.specShapes")
assert(SpecShapes.wholeFrozen(table.freeze({ kind = "fullscreen" })))
assert(not SpecShapes.wholeFrozen({ kind = "fullscreen" }))
local row = { shapes = {}, handedN = 0 }
local first = SpecShapes.heldShapeOf(row, { kind = "fullscreen", order = 1 })
assert(table.isfrozen(first))
row.handedN = 0
assert(SpecShapes.heldShapeOf(row, { kind = "fullscreen", order = 1 }) == first)
```
# renderer.splat
`renderer.splat`: decodes a Gaussian splat capture into the GPU-ready byte pools a render feature uploads.
# renderer.temporal
`renderer.temporal`: the clock a per-frame effect draws itself against, and the holds that pin it.
# renderer.texture
`renderer.texture`: the texture codec, the guid-keyed CPU texture store, the GPU textures created from it, the render targets, and the readings of a texture's pixels.
# renderer.visibility
What the renderer decides to draw before it draws it: the resolution scale and its mode, the quality tier, the upscaler, the viewport and picture sizes, the screen-size and cluster-error cutoffs, occlusion culling, raster shading, the scene's lighting, and the ray cast against the geometry it draws.
# result
The handle `asset.list` returns.
A query result **is** the array of matched `AssetRef` handles. Entry `1` is the
first match, `#rows` is the count, `ipairs(rows)` walks it, and anything that
accepts a list of refs accepts it unchanged. The handle adds methods on top of
that array through a metatable, so reading the result stays one expression.
```lua
local hero = asset.list({ type = "mesh", fields = { tags = "hero" } }):first()
local prop = asset.list({ type = "mesh", path = "/zero/source/props" }):random()
asset.list("material")
:filter(function(m) return m.name:find("rust") ~= nil end)
:each(function(m) print(m.identity) end)
```
## Methods
| Method | Returns |
|---|---|
| `:first()` / `:last()` | One entry, or nil when the query matched nothing. |
| `:random()` | One entry chosen at random, or nil. |
| `:count()` | How many entries matched. |
| `:isEmpty()` | Whether nothing matched. |
| `:each(fn)` | The same result, after calling `fn(entry, index)` in order. |
| `:map(fn)` | A new result holding `fn(entry, index)` per entry. |
| `:filter(predicate)` | A new result holding the entries kept. |
| `:searchable()` | A new result without the deprecated assets, the ones a search or a picker offers. |
| `:sort(comparator?)` | A new, ordered result; ordered by identity when the comparator is omitted. |
| `:toArray()` | The entries as a plain table, without the handle. |
`:map`, `:filter`, and `:sort` return new results carrying the same methods, so
they chain. `:sort` leaves the result it was called on as it is.
## Ordering
`asset.list` already returns its matches ordered — by identity unless the query
asks for another field with `order` — so `:first()` names the same asset on
every call. `:sort` is for orders the query cannot express, such as one computed
from an entry's fields.
## What the handle does not change
The metatable carries `__index` alone. Length, `ipairs`, `pairs`, `next`,
`table.*`, and serialisation all read the array part, so a result behaves
exactly as a plain array everywhere those are used.
# asset_warmup
`asset.warmup` — a **read-only closure inspector**.
Returns the transitive set of assets that the CPU-residency system *would* load
when the given asset enters `/runtime/` — i.e. the asset plus everything
reachable through its declared content references. It does **not** itself change
residency or touch bytes:
```lua
local closure = asset.warmup("@builtin::meshes.cube")
-- → the asset + every texture/material/mesh it transitively references
```
Residency is owned by the engine's reference-counted CPU-residency system, which
acquires the closure on a `/runtime/` enter (usage 0→1) and releases it on the
last drop (→0), loading/unloading bytes at the per-node 0↔1 boundaries so a
texture shared by two materials stays resident until BOTH are gone. This helper
just lets scripts and agents **inspect** that closure (debugging, "what would loading
X pull in?") without any side effect — it avoids `asset.resolve` (which fires the
BlobStore prefetch) and uses the side-effect-free `asset.guid` / `asset.deps` /
`asset.identity`.
The closure is the generic `.refs` graph, so this is fully type-agnostic —
material/mesh/user-types all resolve the same way with zero per-type knowledge.
By default it follows `asset_ref` / `component` (content) edges and skips
`asset_type` (structural) / `require` (code); `opts.vias` overrides. Deduped by
guid via an explicit work-stack so diamonds appear once and cycles terminate.
Installed onto the FFI `asset` namespace by the prelude.
# proc.anim
Values that change over a graph's time. An animated value is an InputRef (`kind = "animated"`), so it sits wherever a constant sits: any param of any node, any field of a record param, any element of an array, any socket. The evaluator resolves it at the graph's current time and hands the op the plain value, and the node's cook key folds that resolved value, so a node cooks again on the frames where a value it reads differs.
Four forms make one:
```luau
proc.anim.keys({ { 0, 10 }, { 2, 400, "smooth" }, { 5, 50 } }, { after = "loop" })
proc.anim.expr("8 + sin(t * 2) * 4")
proc.anim.math("mul", 60, proc.anim.expr("1 - t"))
proc.anim.input("distance")
```
- `keys(keys, { before?, after? })` interpolates numbers, records of numbers (`{ x =, y =, z = }`) and arrays of numbers component by component. Each key is `{ time, value, ease? }` with time in seconds; `ease` shapes the segment arriving at the key: `"linear"` (default), `"step"`, `"smooth"` or `"cubic"`. `before` / `after` say what the value does outside its keys: `"hold"` (default), `"loop"`, `"pingpong"` or `"extend"`.
- `expr(source, vars?)` is one Luau expression over `t` (seconds), `frame`, `fps`, `duration`, the math library's functions and constants by bare name, `clamp`, `lerp`, `smoothstep` and a deterministic `noise(x)`; `vars` names further numbers it reads, each a number or another animated value.
- `math(op, a, b)` is `a <op> b` at every time, `op` one of `OPERATIONS` (`add`, `sub`, `mul`, `div`, `min`, `max`, `pow`).
- `input(name)` is the value a play's input `name` holds at the clock it is sampled at.
`sample(anim, clock)` answers the plain value at a clock (`{ time, frame, fps, duration }`); `is`, `reads`, `inputNames`, `of`, `count` and `digest` inspect animated values and the graphs that hold them.
Part of `@builtin::systems.procgen.proc`; reached as `proc.anim`.
# proc.builder
What a graph builder hands the author, in the call form: `proc.define(function(g) ... end)`.
- `g.<name>(args)` adds a node of the node asset the name resolves to, by asset identity: the nodebox and the
node's folder name (`g.points.disc`), a path (`g["/zero/source/fx/ring.procNode"]`), `~` (the nearest package,
effect or world root: `g["~/ring"]`), a guid, or a short name (`g.disc`). A path, `~` name or identity ending in
`.procNode` or `.procGraph` names an asset of that kind alone; one without the suffix names either, so where a
node and a part share a name it states the suffix. A name that matches two nodes, and a name that matches none,
are errors that name the candidates. Each call is recorded in the graph by the node's
guid. Arguments are a table naming inputs or positional values in the node's input order.
- What a call answers: a node with one output answers that output's socket, and reading that output by the name
the node declares for it answers the same socket (`g.material.pbrMat({}).material` is `g.material.pbrMat({})`); any
other name is a member of the value, and for a node whose output the source states to be a Geometry, any name
but a class, `names` and `material` is refused where it is read, naming the output. A node with several answers a
record of sockets by output name (`local f = g.core.normals.face(geo); f.geometry, f.area`), a node with none
answers nothing. The record does not depend on declaration order. The record handed whole to an input that
takes one value is refused where it is handed, naming the outputs to read (`.value`, `.report`).
- A name is called this way only for a node written in the call form (`builder.callsByName(path)` says which). A
name no node answers to is refused naming the nearest names a call resolves.
- A node's own source reaches its package's modules and assets with `require("~.<name>")` and
`asset.resolve("~.<name>", type)`: `~` there is the nearest `.package` folder, wherever the node sits in it.
- `g.op.<name>(args)` (and `proc.op.<name>`) adds a node of an op, for library nodes built on the ops. An op that
is a graph built with `g:node` (the `procNodes/` of the procgen package, registered under their graph ids) is
refused at the call, naming its folder and the node written in this form that answers to the same name
(`'g.op.points.filter' is .../procNodes/pointsFilter.procNode, a graph built with g:node, ...; call
g.points.filter`). An id no op carries is refused naming the ops that start the same way.
- `g:input(name, default, opts)` is typed by the default: `Float`, `String`, `Bool`, `Vec3`, `Color`, `List<T>`,
`Record` with its fields. `opts` takes `min`, `max`, `options`, `description`, `optional`, `plain` and `type` for a
default that does not state its type or no default at all. An empty table default with a stated `type` is that type's
empty value (`g:input("entities", {}, { type = "List<Entity>" })`). A vector written as a plain table reads its
components by name whichever form it was written in, the reading an op's params take: `{ 0, 0, 0, 1 }` answers `.w`,
and a pair (`{ a, b }`, `{ x, y }` or `{ x, z }`) answers its second component as `.y` and as `.z`.
- An input declared `plain = true`, an input with `options`, and an input of type Bool or String is a plain value
while the graph is built: `g:input` answers the value itself, `if`, comparisons and loops over it are allowed, and
it passes into calls as a constant. `plain = true` is how a count, a vector, a record or a list that chooses the
graph's structure is declared (`g:input("storeys", 5, { type = "Int", plain = true })`, `g:input("edges",
{ { bays = 3 } }, { plain = true })`): the graph is built again for each value it is given, it is not animated, and
it takes no per-element field. Any other number and vector input is a socket, which changes without a build and
takes animated values and fields. A table value reaches the build as a frozen copy. The graph records the plain
values it was built with in `graph.plain`, and each such declaration in `graph.inputs[name].plain = true`.
- Sockets take `+ - * / % ^ // ..` and unary minus, `math.*` (every function of the `math` table but `random` and
`randomseed`, which a graph refuses: they draw from state outside it, and `field.rand`, `field.random` and `rand.unit`
draw from a seed) and `vector.*` (each a `math.<name>` node; a function that returns several values, `math.frexp` and
`math.modf`, returns the node's outputs in order, as it does on numbers;
`vector.create` over sockets is `math.vec2`, `math.vec3` or `math.vec4` by its component count), `x.name`,
`x.name = v` and `x[name] = v` for a computed name (which rebind `x`), `x[class][name]`, `x[n]`, and
`for index, item in list do ... end`. A source loaded
through `builder.prepareSource` reads plain `math`, `vector` and `rand` over sockets unchanged; `define` loads a
node or graph entry that way when it names them.
- `vector.create` has the width of its component count whether its arguments are sockets or numbers: two numbers
answer the Vec2 value `{ x, y }` and four the Vec4 value `{ x, y, z, w }` (what `math.vec2` and `math.vec4` make
of numbers), and three a Luau vector. `orient = vector.create(0, 0, 0, 1)` writes a Vec4 column.
- `g.compare(a, op, b)`, `g.where(cond, a, b)`, `g.pick(choice, alternatives)`, `g:fold(n, init, fn, opts)`,
`g:state(name, columns)`, `g:step(dt, substeps, fn)`, `g:check(cond, message)`, `g.has(geometry, class, name)`,
`g.producer(value)` and `g.copy(socket)` record the constructs the evaluator knows.
- `g:state(name, columns)` states the columns a step keeps, `{ [name] = { type, count } }`, as values the plan knows:
literals and inputs, records and lists of them, and what constructs and a `pure` `io.luau` call make from them. A
pure call's answer stands even when its arguments are cooked (a call reading the attribute names of a source's
points), so a `for` over its answer may add a column per name (`schema["s_" .. name] = specs[name]` over
`specs.keys`), and a step body writes them by the same names.
- `g:check(cond, message)`: a `cond` known while the graph is built refuses the build with the message (a true one
records nothing); a `cond` that reads a socket is recorded for the plan or the cook to answer. The build of a
node's own defaults, which is what indexes the node, holds such a refusal instead of raising it (`graph.refusals`),
and `forInputs` states it where the node is called or cooked as it stands, so a check over a plain input fires when
the call gives it the refused value.
- A plain Luau table filled inside a `for` body over sockets keeps one element (`rings[#rings + 1] = v`,
`table.insert(rings, v)`): the body is one pass for every item. `builder.check` refuses it with the code
`socket-loop-append`, naming the form to write: a local declared before the loop and assigned inside it, read after the
loop, where it is the list of every pass's value.
- `g.copy(value)` of a record or a list written in the graph (`g.copy({ total = 0 })`) is a value of its own that
member writes rebind, so a `for` body that fills it carries it from pass to pass.
- A class view made with a socket key (`names[i]`) and read as a value is a node of the scope it was made in, whichever
loop body first reads it.
- A `for` body is one pass that stands for every item. `index` is the item's place (a socket, from 1). A value built
outside the body that the body reads or assigns (`geometry[class][name] = v`, `record.name = v`,
`record[name] = v`) is carried: each pass starts from what the pass before left, the first from the value as it
stood before the loop, and after the loop the value is what the last pass left. The loop records the carries in
`scope.carries[id] = { init, result }` and the refs `loop_index`, `loop_carry` (the value at the start of a pass)
and `loop_result` (the value after the loop). A value the body only reads reads as it was. The emitter writes a
carrying loop as it was authored: a local that starts as `g:copy(value)`, the body's assignments to it, and the loop
reading that local after it (`proc.emit`).
- `g.clock.placement` (16 numbers, column after column), `g.clock.inverse`, `g.clock.rotation` (`{ x, y, z, w }`)
and `g.clock.entity` answer where the graph stands in the scene it is cooked in: each is a `construct.scene` node
that reads the scene the cook is handed (a graph standing on no entity has the identity placement and no
entity). `g.transform.point(p)`, `g.transform.direction(d)` and `g.transform.rotation(q)` carry a world position,
direction or quaternion into the graph's space through the inverse placement; each takes plain values, sockets or
Fields.
- `g:fold(n, init, fn, { stop = "changed" })` or `{ stop = function(before, after) return <Bool> end }`; `fn` returns
the state only. The fold runs `n` passes and ends early at the first pass whose stop holds.
- `g.element` is the element a Field evaluates over: `g.element.id` (Int), `g.element.P` (the position leaf that
`fieldc.withPosition` substitutes, also written `g.element.point.P`) and `g.element.<class>.<column>` for a column
of the domain the field stands in. Each read is a socket, so `g.element.id * 1.0` is a math node.
- `rand.unit(seed, ...scope, id)` (a global in a node source, also `builder.rand.unit`) is the Float field of unit
draws keyed by the seed, the scope (`graphId, nodeId, channel`, or `graphId, compositePath, nodeId, channel`) and
the element `id`, last (`g.element.id`). It adds an `io.luau` node
`{ module = "@builtin::systems.procgen.proc.fieldc.leaves", fn = "rand", args = { seed, { ...scope }, id },
returns = { "Any" } }` and answers its `value`.
- `geometry.names[class]` lists the attribute names a class holds (a list socket the plan answers);
`geometry[class].count = n` assigns the domain count, so `count` is no column's name (a value per element written
under it is refused); `geometry.material = m` assigns the material. `names` is
read by that name on any socket: what is read off it by a class (`geometry.names.point`) lists the names, and any
other read (`record.names[2]`, `record.names`) is the member a record holds under that name, as `count` and `keys`
are. `material` is assigned by that name on any socket.
- A member, an item, a column or the names of a value built outside a fold, step or stop body that the body reads
first is a node of the scope the value was built in: the body and every later fold read the one value, which the plan
writes once. A read keyed by a socket of the body (a fold's index) stays in the body.
- `g.clock.time`, `.frame`, `.delta` and `.duration` are sockets; `.fps`, `.frames`, `.loop` and `.realTime` are the
timeline's values.
- Luau's `< <= > >= == ~=` over a socket, and `and`, `or`, `not`, `if` and `while` that test one, have no value
while the graph is built. `builder.check(source)` names each one with the `g.*` form to write, and `define` holds a
node or graph entry to it. `and` and `or` test their left operand alone, so `plain or socket` passes. The check
follows names block by block as Luau scopes them: a local, a loop variable or a function parameter is its block's
own, and a parameter of a function that is not a fold, step or stop body is not known to be a socket (a comparison
over one is refused when the graph is built). Plain inputs are not sockets to the check. A plain Luau table indexed by a socket (`LANES[values.type]`) answers nil
while the graph is built, so the check refuses it with the code `socket-table-index`, which names `g.pick`.
- A list of values holds a nil as a value: `{ a, nil, b }` is three, and the second is a constant of nothing.
## Building a graph for other plain values
A graph whose plain inputs change structure is built again for the values a cook was given.
- `builder.forInputs(graph, inputs)` answers `graph` while its plain inputs hold what the build used, else the graph
built again from `graph.source` with the values `inputs` states (an input it leaves out takes its default); values
are compared by content, a record or a list included, and the result is cached by the source text and the values,
so a node written again is built again. `builder.KEPT_BUILDS_PER_SOURCE` of a source's builds are held, the ones
used last; a build past them stays found while something else holds its graph (a play cooking it) and is built
again once nothing does. `builder.keptBuildCounts()` answers how many builds are held and the source nodes they hold,
which the memory ledger states (keeper `kept builds`), and `builder.letGoKeptBuilds()` lets go of them. A build for other values keeps what the cook already made: only the nodes the new values change cook.
A plain input given an animated value, a per-element field or a value held on the device is refused by name. It answers `nil, reason` when the source cannot be built again or a value
is outside the input's options.
- An optional input with no default (`g:input(name, nil, { optional = true })`) is nil while the graph is built for a
call that leaves it unwired, and its socket otherwise, so `if input == nil then ... end` in a node source is decided
by what the call wired. The declaration states `wiring = true` and the graph records the wiring it was built for in
`graph.wiring[name]`; `forInputs` builds the graph again for a cook given no value for such an input (`values[name]
== false` states none in `rebuild` and `withInputs`).
- `builder.rebuild(graph, values)` builds again unconditionally; `builder.withInputs(values, fn)` runs a function
that calls `proc.define` and gives that graph the values. A node asset called with a plain value records it as a
constant param; the evaluator reads a node's graph through `forInputs` with those params.
## What a build resolves once
A build resolves each name once. The first call of a name `g.<name>(...)` in a build finds the node asset the name
answers to; the build keeps the asset, its inputs and outputs, and the envelope its calls record, and every later call
of that name in the same build takes them. Each `building` frame (a graph source, or a node source loaded by a call)
holds its own, by the graph's source and the name, on the thread that runs the build; a builder function written inline
(`proc.define(function(g) ... end)` with no source file) has no frame, and the graph it builds holds the memo until
`run` returns. The memo ends with the frame, so a node written between two builds is resolved again by the next, and builds on other threads share nothing. The `Info` of
a node asset is kept by the node graph it was read from, and the line of each call is kept as a number that `siteOf`
states as `path:line` where it is read. `builder.setResolveMemo(false)` switches all three off for the builds after
(the answer is the setting before), and `builder.resolveCounts()` answers the calls that resolved a name (`resolved`)
and the calls a kept answer served (`hits`).
## What a build is made against
A graph source that has a base is built against it. The base of an entry source is the graph the last
`proc.takeHandOff` of its folder gave a Generator (`builder.setBase(graph)`, `builder.baseOf(entry)`), held weakly.
When the run of a build ends, a pass compares every node the run made with the base's node of the same id (`compareNode`
of `proc.eval.replan`, and the node's `op` field by field). A node that is equal is replaced in `graph.nodes` by the
base's own table, which is frozen, along with the tables under its inputs and params; a node that differs, or that the
base does not hold, is frozen where it is. The scopes are compared and the ones that differ are listed; they stay the
build's own tables. The graph states the result in `_diff`: `changed` (the ids of the nodes that differ or are new),
`removed` (the ids of the base's nodes the build did not make), `scopes` (the ids of the scopes that differ), `added`,
the counts of the nodes and scopes, `against` (the base, held weakly) and the edit counts of both graphs when the pass
ran. The planner (`replan.dirty`) reads it while the graph and the base stand as they did then, and compares only the
nodes it lists.
- A node that keeps the base's table keeps the place the base gave it in the order the nodes were made in. When this
build made it elsewhere, the graph states the new place in `_moved`; `builder.seqOf(graph, id)` answers the place a
node holds, and `graph:toJSON()` states the nodes with it (`builder.documentNode(graph, id, node)` is one node as the
document states it), so a document and an emitted source are those of a build that made every node itself.
- A table two graphs share is frozen, so a write into one raises. `proc.edit` replaces a node it writes into by a copy
of its own (the node, its `inputs` and its `params`) before it writes, and `builder.againstCounts()` counts those
copies beside the passes run (`passes`), the nodes filed from the base (`reused`), the nodes listed (`changed`) and the time the passes took (`ms`).
- `builder.setBuildAgainstBase(false)` switches the pass off for the builds after (the answer is the setting before).
A build of a source with no base, a build for other plain values (`forInputs`, `rebuild`) and a build of a node asset
are the graph their run made.
## What a build reads
A node or graph source is compiled with `builder.compile(src, "@" .. entry)` and run as a build with
`builder.building(entry, fn, ...)`. While a build runs, the source sees a `vfs` whose `read`, `readAsync` and
`readBounded` note each file for that build, and `builder.read` (`proc.read`) notes a file read from a module the
build calls into. When the build ends, the files it read are recorded against its entry source, replacing what its
earlier builds read: `builder.readsOf(entry)` lists them and `builder.readersOf(file)` the entry sources whose last
build read a file. A write of such a file is a `proc.sourceChanged` of each of those sources. `builder.forget(folder)`
drops the source text and the built graph the builder holds for a node or graph, so the next build that reaches it
runs its source again. The modules a build requires are recorded by the engine, which tells the node or graph type
through `onDependencyChange` when one of them re-runs.
## The wiring of each run of `graph.module`
`graph.module` binds its wiring into the builder (`builder.bind`) each time its body runs, with the metatable of the
graphs that run makes as `helpers.graph`, and the builder keeps that wiring on the metatable. A graph is wired by the
run that made it: `builder.run` declares its outputs, a value is wired into its refs, and `rebuild` builds an inline
graph again, each through the wiring of the graph's own run. The body runs again whenever the require cache lets go of
the module while a module that took its functions keeps them (`proc.define` is `graph.module`'s `define` as `proc`
loaded it), as a reset of the scripting state to a mark taken before the module loaded does; the graphs of both runs
are then built side by side.
## What a graph records
A call-form graph states `surface = "call"`. Each node it makes carries `call = true`, `seq` (the order it was made
in, which the emitter writes it back in) and `scope`. A node asset is `op = { __ref, type = "procNode", name }`; an
op is its id string; a construct is `op = "construct.<kind>"` with `construct = <kind>`. `graph.scopes` holds each
`for`, `fold`, `stop` and `step` body, `graph.states` each `g:state`, `graph.plain` the plain input values.
Each call and scope also records the line of the graph's source it was written on, `path:line`
(`builder.siteOf(graph, id)`), in a table the graph's document leaves out, so where a call sits moves no hash. The
plan carries it onto each call it writes out (`plan.flat.origins[<flat id>].site`, the graph's own calls in
`plan.flat.sites`), and a cook's failure is read at it: `describeFailure(flat, err)` of the eval module
(`@builtin::systems.procgen.proc.eval`) answers
`<path>:<line>: g.<call> failed: <why>`, the line being in the deepest source the person can edit.
The `inputs` of a construct node are refs (a constant is `{ kind = "const", value }`); `params` are constants.
| construct | inputs | params | answers |
|---|---|---|---|
| `member` | `value`, `name` | | the member of `value` |
| `member_set` | `value`, `name`, `to` | | `value` with the member written |
| `item` | `list`, `index` | | the item |
| `column` | `geometry`, `class`, `name` | | the column read (a read of `count` is the domain count) |
| `column_set` | `geometry`, `class`, `name`, `value` | | the geometry with the column written |
| `column_remove` | `geometry`, `class`, `name` | | the geometry without the column |
| `count_set` | `geometry`, `class`, `count` | | the geometry with that class's domain count set to `count`; a value per element is refused (no column is named `count`) |
| `material_set` | `geometry`, `material` | | the geometry with its material set |
| `names` | `geometry`, `class` | | the List of attribute names the class holds, answered at plan |
| `has` | `geometry`, `class`, `name` | | a Bool answered at plan: whether the class holds the column |
| `check` | `cond` | `message` | nothing; a `cond` that is false when cooked is an error stating `message` |
| `compare` | `a`, `b` | `op` (`eq neq lt le gt ge`) | a Bool |
| `where` | `cond`, `a`, `b` | | `a` where `cond` holds, else `b` |
| `pick` | `choice`, `alternatives` | | the alternative the choice names: by option name, by a list position (a false choice the first, a true one the second), or by `false` and `true` keys |
| `producer` | `value` | | a record answered at plan that states what produced `value`: `{ kind = "const", value, plain }` (`plain` is true for a number, string, boolean or vector, a Field that holds one value everywhere and a table that is no Field), `{ kind = "animated", readsTime, inputs }` (a curve over the play's inputs and time; `inputs` lists the names), `{ kind = "input", name }`, `{ kind = "node", op, inputs }` (the node as the author wired it, each of its inputs the same record one level down, or `{ kind = "unwired" }` where the call gave none) or `{ kind = "unknown" }` where only a cook can say; a record or a list is `{ kind = "record" }` or `{ kind = "list" }` of what its entries are. Every answer also states `readsTime` (whether the value can move with the clock: a curve that reads it, a value only a cook answers, or anything made of one), `moves` (whether a curve that reads the clock stands in what the value was made of: false for a value only a cook answers) and `ops` (the names of the nodes it was made through, the outermost first). A comparison or a pick over it folds. A fold whose body reads it is written out pass by pass, so each pass answers for the value it reads |
| `step_sample` | `step`, `value` | | the value of an animated `value` at the step's time |
| `step_between` | `step`, `index` | | the fraction (0 to 1) of the step's movement that source `index` of the step has covered; the evaluator defines it |
A call that has several outputs names them in refs: `{ kind = "node_output", node, output = "<name>" }`; a node with
one output has `output = nil`.
### Refs
The v1 refs (`const`, `graph_input`, `node_output`, `list`, `record`, `animated`) and:
| ref | stands for |
|---|---|
| `loop_item { loop }`, `loop_collect { loop, ref }` | the item of a `for` scope, and the list of `ref` over every item |
| `fold_value { scope }`, `fold_index { scope }`, `fold_result { scope }` | the value and the index (from 1) of a fold pass, and the value after the last pass |
| `fold_before { scope }`, `fold_after { scope }` | the state before and after a pass, inside a fold's `stop` function; `scope` is the `stop` scope |
| `step_state { scope }`, `step_index { scope }`, `step_result { scope }` | the state record, the step record (`dt time graphTime index first start`, with `step_sample` and `step_between`), and the state the step reached |
| `state { name }`, `clock { field }`, `engine` | declared state, the clock's field, the engine API namespace |
| `element { field, class? }` | the element a Field evaluates over: `field = "id"` its index, `field = "P"` its position leaf (no class), else the column `field` of the domain `class` |
### Scopes
`graph.scopes[id]` is `{ kind, parent, seq, ... }`:
- `for`: `list`, `item`.
- `fold`: `count`, `init`, `result`, and `stop` when it states one: `"changed"` (the pass ends the fold when the
state it produced equals the one it read) or `{ scope = <id of a stop scope> }`.
- `stop`: a scope whose `parent` is its fold. Its nodes read `fold_before` and `fold_after`; `result` is the Bool
ref the fold stops on. It is evaluated after each pass.
- `step`: `dt`, `substeps`, `result`.
The `plain` table of a graph and the `plain = true` flag of an input declaration state which inputs are build-time
values.
Part of `@builtin::systems.procgen.proc`.
# proc.compiled
Array kernels for the ops a quick-geometry model is built from. A kernel runs once over the flat arrays of a piece and answers the arrays the op's node cooks, so a piece comes out of Luau loops over arrays and not out of a graph of device dispatches.
A piece is `{ positions, normals?, uvs?, indices }`: three numbers a point for `positions` and `normals`, two for `uvs`, and the 0-based point numbers of each triangle in `indices`. A kernel is `(piece, params) -> (piece, info?)`; `geometry.merge` takes a list of pieces.
Kernels: `geometry.merge`; `deform.taper`, `deform.twist` and `deform.bend` (the deformers a model graph states as a field over `P`); `core.weld` (points within a distance merge, the lowest-numbered of each group standing for it); `geometry.subdivide` (`linear` and `loop`, one to three levels); `geometry.bevel` (the steps its node's README states, answering the node's `info` record with the piece: `bevelledEdges`, `pairedEdges`, `cornerPatches`, `width`, `requestedWidth`, `maxWidth`, `clamped`, `segments`, `vertexCount`, `triangleCount`).
Every kernel writes its output through `f32`, the precision a mesh stores, and takes sine and cosine from `trig.sincos`, one function of arithmetic alone, so the arrays are the same on every target.
- `register(op, kernel)` and `kernel(op)`: the kernel table, by the op's name.
- `f32(array)` and `round(x)`: round to the nearest `f32`.
- `trig.sincos(angle)` and `trig.acos(x)`: the sine and the cosine of an angle in radians, and an inverse cosine, from arithmetic alone.
- `normals(piece)`: the vertex normals of a piece, each triangle weighted by its area, summed in triangle order with every operation an `f32` one.
- `faceScaled(a, b, c)`: the direction a triangle's corners (vectors) wind around, scaled by twice its area.
Part of `@builtin::systems.procgen.proc`; required as `@builtin::systems.procgen.proc.compiled`.
# proc.device
The passes every op composes to work over elements on the device: counts that live in a buffer, prefix sums (`scan`), compaction (`compact`), gathers and scatters bounded by a device count, a free list of slots (`freeList`), sorts, reductions, histograms, edge lists and appends clamped to what a run can hold. No call loops over elements in Luau: each records dispatches, and the element counts they work to are words in device buffers written by one pass and read by the next, so no pass waits on the CPU to learn how many elements there are. Runs are sized to a capacity the CPU knows; the count says how much of the run is live. A count is a one-word run read as a u32; an index is carried in an f32 run, exact up to 2^24.
Part of `@builtin::systems.procgen.proc`; reached as `proc.device`.
# proc.diskcache
A graph output's cooked value on disk, so a Generator loads what was cooked instead of cooking it again. What is stored is the value an output hands to realization (geometry and its columns, instance sets, prefabs and bundles, materials and generated textures), and loading realizes it the way a cook's value is realized. The store is per graph and shared by every Generator on it:
```
/zero/source/_cache/procgen/<graph guid>/<index key>.index
/zero/source/_cache/procgen/<graph guid>/<content hash>.cook
```
An index names one way of cooking the graph (the graph as it stands, its params, the frame rate and range its timeline plays, the live state it reads) and maps each frame to the content it produced; content is stored once per distinct output, named by the SHA-256 of its bytes. `provide` registers what a generator stores, `store` writes it (committing the world does this first), `readIndex`, `contentFor` and `load` read it back, and `prune` deletes what no index names. Nothing is written inside an asset's folder.
Part of `@builtin::systems.procgen.proc`; reached as `proc.diskcache`.
# proc.edit
Editing a procedural graph as nodes and wires: the picture of a Graph a node editor draws (`view`), the catalogue of ops a node can be added from (`catalogue`, `search`), and every change a person makes to it (`addNode`, `removeNode`, `connect`, `disconnect`, `setParam`, and the graph's inputs and outputs: `setInput`, `removeInput`, `renameInput`, `updateInput`, `setOutput`, `removeOutput`, `renameOutput`). Each change edits the Graph in memory and answers `(ok, why?)`; writing the result into the asset is `proc.saveSource`. Ports named `in:<name>` and `out:<name>` stand for the graph's own inputs and outputs. Node positions are the editor's own and live beside the asset in `layout.json` (`loadLayout`, `saveLayout`).
Part of `@builtin::systems.procgen.proc`; required as `@builtin::systems.procgen.proc.edit`.
# proc.emit
A Graph written back as the Luau that builds it. `source(graph, { header? })` renders a call-form graph as `proc.define(function(g) ... end)` and a graph of `g:node` calls as the function that fills `proc.graph(id)`: declared inputs first, then each node in dependency order with its wiring, then the graph's outputs. `openingComment(source)` answers the comment a source opens with. `proc.emit` and `proc.saveSource` call it, so a graph a tool restructures lands back in its asset as source an author reads and edits.
Part of `@builtin::systems.procgen.proc`; required as `@builtin::systems.procgen.proc.emit`.
# proc.eval
Lazy topological evaluator of a graph target, with per-eval memoization and cycle detection.
Part of `@builtin::systems.procgen.proc`.
## Graphs built in the call form
A graph built with `proc.define(function(g) ... end)` has `surface = "call"`. It records nodes (ops and
node assets), scopes (`for`, `fold`, `step`), declared state and the refs between them. It has no output
the evaluator is asked for: every node nothing reads is cooked from.
```lua
local play = eval.play(graph, { inputs = { count = 8 } })
local report = play:present({ time = 0, frame = 0, fps = 30, duration = 0 })
play:release()
```
`eval.play(graph, opts)` plans the graph, cooks from every node nothing reads and keeps what those nodes
return. `play:present(clock)` cooks at a clock (`{ time, frame, fps, duration }`; a `duration` above 0 is a
timeline with an end, where a seek replays from the start), `play:setInputs(inputs)` gives the graph other
inputs, `play:handle(id)` answers what a node cooked from answered last, `play:report()` says what happened
and `play:release()` lets go of everything the play holds, the Handles its output nodes answered included.
What a play stands in the world goes over to a present all at once. A present opens a stage (`eval.openStage`):
every show its cooks make (an `io.output`'s `show`) is prepared and set aside, and once the present's pulls are
cooked the stage commits (`eval.commitStage`) and every show stands in that frame. A present that replaces nothing (a
play's first) commits with `yields` instead: the shows stand in the order they were made, and the frame goes back
between two of them once the frame's slice is spent, so a stage of many shows stands over the frames that follow. A
value that stood and that the present supersedes (a node's Handle cooked again, an output node no plan holds any more) is set
aside as well (`opts.standingRetired`) and let go of right after the commit, each release on a task of its own
(`eval.releaseStanding`), so the world never holds part of one present beside part of another. A present that raises
stands none of its shows, drops the nodes that made them (`eval.forgetValues`), and leaves what stood standing for the
next present to replace. A value that stands is never kept per key on a timeline with an end: a key it held before is
cooked again, and its show made again, when it comes back. A present cooks with the inputs the play holds when it
starts: inputs `setInputs` gives it while it runs are the next present's.
A show of an output reconciles onto the entities the last show of that output stood under the same place, by element
id. The place is the entity the graph stands on (the scene's `entity`); for a graph that stands on no entity it is the
play's own (`play.showPlace`), which a play names on its thread while it presents or moves on the device
(`eval.standOn`, read by `eval.standingPlace`) and a play started with `inherit` takes over. Two plays that stand on no
entity show beside each other, and releasing one leaves the other standing on its own runs.
Every call-form graph cooks through the plan, whoever asks: `proc.eval(graph, target, opts)` of a graph with
`surface = "call"` plans it (`opts.inputs`, `opts.clock`), cooks what the plan waits on and then the target through
the flat graph, and a node asset used as an op cooks its graph the same way. `output:<name>` names an output of the
graph (`flat.outputs` holds each one lowered), and the nodes the eval cooked into its own cache are released apart
from what the answer reaches. Each node cooks at `opts.clock`: an animated value it reads, handed straight to an op
or through a node asset's input into a field op (`fieldc.pcallSampling`), holds its value at that time; one that
becomes a field stays a live field, rewritten for a later time without a cook.
`proc.historyKey` and `proc.liveDigest` of a call-form graph are queries of the same plan: the plan is made, read
and keyed exactly as a cook makes, reads and keys it (what it waits on is cooked, its leaves are keyed), and only the
final read of the flat graph answers the key or the digest. So a key asked before an eval and after it is the same,
and a plan a query made is kept keyed for the cooks after it.
`eval.plan(graph, opts)` is the plan alone, and `eval.references(graph)` the assets and ops the graph's calls
reach, by guid and id, without cooking.
### The document
```
graph.surface "call"
graph.nodes[id] { op, inputs = { socket = ref }, params = { name = ref | value }, scope = scopeId? }
graph.scopes { [id] = { kind = "for", list = ref } | { kind = "fold", count, init, result }
| { kind = "step", dt, substeps, result }, parent = scopeId? }
graph.states { [name] = { columns = ref } }
graph.inputs { [name] = { type, default, ... } }
graph.outputs { [name] = { ref } } -- what a graph used as a node gives
```
`op` is an op id (`"device.kernel"`, or `"op.device.kernel"`), a node asset
(`{ __ref = guid, type = "procNode", name }`) or `"construct.<kind>"`.
### The graph's hash
`proc.depHash(graph)` (`eval.depHash`) is the hash of two things: the document without its nodes (id, version,
metadata, timeline, inputs, outputs, composites, scopes, states, surface, plain values; `graph.documentHeader`) and the
sum of the nodes' digests, mod 2^52. A node's digest is the hash of its id and of the node as the document states it
(`builder.documentNode`: the node, with the place a build gave it when that is not the one its table holds). The sum
does not depend on the order of the nodes, so two documents of the same nodes hash equal however their nodes are held,
and a document read back from JSON hashes as the graph it was written from.
A graph keeps its sum with the count of edits it was stated at (`eval.depSum`). A graph built against its base
(`_diff`, see the builder README) states it as the base's sum less the digests of the base's nodes that the build
changed, removed or moved, plus the digests of those nodes in the new graph; the nodes it filed from the base are not
read. A graph with no base, one edited since the build, and a document state it from every node (`eval.depHashWhole`
is that sum, the definition the patched sum equals). `eval.depHashCounts()` answers the sums patched (`patched`), worked
out from every node (`whole`) and found kept (`held`), and the digests made. `eval.setDepHashFromNodes(false)` returns
to the hash of the serialized document folded in one pass; the two give different numbers for the same graph, so a key
built from a hash (a composite's version, the disk cache) misses once when the setting moves.
The refs are the v1 refs (`const`, `graph_input`, `node_output`, `list`, `record`, `animated`) and:
| ref | stands for |
|---|---|
| `loop_item { loop }` | the item of the `for` scope in the copy being written out |
| `loop_collect { loop, ref }` | the list of `ref` in every copy of the `for` scope |
| `loop_index { loop }` | the place (from 1) of the item in the copy being written out |
| `loop_carry { loop, carry }` | a value built outside the `for` scope as a pass begins: the value before the loop for the
first copy, what the copy before left for every other |
| `loop_result { loop, carry }` | the same value after the last copy |
| `fold_value { scope }`, `fold_index { scope }` | the value and the index (from 1) of the pass of a fold |
| `fold_result { scope }` | the value after the last pass |
| `step_state { scope }`, `step_index { scope }` | the state record and the `step` record of a step body |
| `step_result { scope }`, `state { name }` | the state the step has reached |
| `clock { field }` | `time`, `frame`, `fps`, `duration` or `delta` of the graph's clock |
| `engine` | the engine API namespace |
### The plan
- A node asset built in the call form is written out where it is called, its inputs bound to what the
call was given. A call nothing reads is cooked from through every output it declares.
- A `for` body is written out once per item of its list, a `fold` body n times in a chain, a `pick`
takes the one alternative its choice names. A copy is keyed by its content, so reordering, inserting
or removing items cooks only what is new.
- A count or a list a scope needs is a plan value: a constant, an input, or the answer of a node, which
the plan cooks and lists in `report.waits`. A column left on the device is not a plan value; reading it
back with `transfer.readback` is, and the wait names the readback. The length a scope was written
out for is watched: a cook that answers another length plans the graph again.
- A `where` whose condition the plan knows takes one alternative. What only the other alternative stands on is not
written out, and a call nothing reads that stands on any of it is not written out either (the nodes a node asset
leaves unread are written after every alternative of the plan is decided), so nothing reachable only through the
untaken alternative is cooked while the plan is made. A node of the graph itself that nothing reads is always
cooked.
- A `for` scope's `carries` (`{ [id] = { init, result } }`) chain the copies: copy 1 starts a carried value at `init`
and copy n+1 at what copy n's `result` lowered to; a `loop_result` read after the loop is what the last copy left.
- A step becomes one solver node. Its state is one record of device Columns per play (`g:state(name,
{ column = { type, count } })` allocates them zeroed). The columns a state allocates are stated through plan
values: a literal record, or a record a fold fills or constructs read off a list or an input (per-source columns,
counts from `list.count`, names from `geometry.names`), whose counts the plan cooks and lists in `report.waits`.
A `member` or `item` read inside the body of a value the plan knows (a count or a list a fold inside the step is
written out for) is answered while the plan is made. The step record carries `dt`, `time`,
`graphTime`, `index` and `first`. The body runs `substeps` times in each fixed step of `dt` seconds.
Pausing holds the state, a seek back replays from the start on a timeline with an end, and a changed
value the step reads begins it again.
### A plan is made once
A graph is planned once for the values its plan stands on, and every later cook of it reads that plan.
- A plan stands on the registry (`registry.revision()`), on the graph its plain inputs build, on the values of the
inputs it read (as keys), on the animated values it read at the clock, on the answers it waited on and the nodes
it cooked for a count or a list, and on the modules it required (by what their files hold). A cook reads a kept plan
after asking each of those again (`expand.stillStands`); a plan that no longer holds is made again, and a plan that
does is read.
- The body of a node asset is planned once for each structure its calls give it and kept (`expand.bodyCounts`): a
plan made again reads the kept body, and the nodes it writes out are the ones it wrote before. A kept body stands
while its asset's source is as it was and every definition it was written out from (the asset's own, and each op
and node asset it calls, at any depth) is the one the registry holds. A node registered again lets go of the bodies
that reach it and no other, so an edit of a node cooks again what the node reaches and nothing beside it. A call is
compared with a kept body by what its leaves hold, without reading them: a plan reads the inputs of the bodies it
uses, at any depth of calls, and none that only a body it compared and did not use reads.
- A kept body of `minNodes` (16) flat nodes or more is settled once, when it is kept, and each call it answers is one
`construct.call` node that names the body and binds its leaves (`expand.setBodyCalls`, `expand.bodyCounts`: `called`,
`callBodies`, `callRefused`); a smaller body, a body that shows or emits something or stands on live state, and a call
that binds an animated value are written out at the call. The call runs the body as the nodes of the graph that holds it
(`eval.runCallBody`), its nodes under the ids they would have written out; the plan's `counts.nodes.called` counts the
call nodes.
- A node the plan cooks while it is made is keyed over the flat graph as it stands then. The passes after emission
rewrite nodes of that cone (an expression folded, a node read by none taken out), so a made plan lets go of the keys
its flat graph holds (`eval.forgetHeldKeys`): the keys held for what the flat graph held while it was made go, and the
next eval derives them from what it holds.
- A Field that states what it computes (`proc.fieldc`'s `_expr`) is keyed by that statement and the operands it
names, not by the closure it samples with: a field written out again keys as it did.
- Each answer and node the plan waited on is held by the key of its cone, without a cook. The leaves a cone stands on
are named once, when the plan is kept (`expand.keyWatches`): the graph inputs it reads, the animated values, the
constants that hold a device value (a Geometry, a Column) or an asset reference, and the nodes that read live state;
the ops, their versions, the plain constants and the wiring are fixed by the plan and the registry. A read asks the
evaluator for the key of each leaf as it stands now (`opts._leafKeys`: a device value is keyed by the run it stands
on and the writes the run has had, an asset reference by what the asset's files hold) and compares
them with the keys the watch stood at. A watch whose leaves are unmoved holds and cooks nothing; a watch whose leaf
moved is cooked again, only its cone, and holds when it answers what it answered, and the keys it stands at are
renewed. A plan that cooked a node reading the clock, a play's input or a live run, or whose cone stands on a
solver or an op that always cooks, is not keyed: each of its watches is cooked again on every read.
- A plan made against its base, which it took the tables of, takes the base's leaf list, leaf index and the cone of each
node (`expand.keyWatches(plan, dynamic, base, reach)`; `expand.setWatchesCarried(false)` walks every cone). The cones of
the nodes the edit reached (`reach`, from `eval.moveKeys`) and of the nodes it let go of are dropped, and only the
watches whose roots hold no cone are walked; the rest keep the places they stood on. The places keep their numbers: a
leaf that no cone and no watch holds any more is a tombstone (`kind = "dead"`, key 0) that no list names, and when the
tombstones are at least 64 and outnumber the leaves the next plan walks whole. A registry that moved since the base
was keyed, a base that is not keyed and a plan that wrote its own tables are walked whole. `expand.counts()` answers
the plans carried and walked whole (with the reasons), the watches kept and walked, the nodes walked, the tombstones
and the compactions.
- A kept plan also holds the answer of each target it was cooked for (up to four a plan, and sixteen plans at a time),
filed by the keys of the target's cone: a cook of `proc.eval` that shares no node cache with its caller, finds the
cone unmoved and passes no `stats` or `cookRecord` is answered with a copy of the held answer (a Geometry or a Column
is cloned, a list or a record of them rebuilt), and cooks nothing. An answer holding anything else (a Handle, a
Field) is not held. The held answers stand on at most 64 MB together (`eval.setKeptAnswerBytes`), counted as the
device bytes of the runs each stands on and the bytes it holds on the CPU (`eval.keptAnswerBytes`): the answer held
longest ago is let go of first, and an answer larger than the bound is not held. The held answers are let go of with
the plan, by `eval.letGoAnswers()`, and with the cooks the plans recorded by `proc.releaseCache()` called with no
argument (`eval.letGoKept()`).
- A plan is kept unless it registered a step solver or wrote a run of the device into itself (a `for` over
geometries). A plan that stands on a run of the device holds by the key of its cone, and is made again when the key
moves. `eval.planCounts()` answers how many plans were made and read (`made`, `reused`), the milliseconds each took
(`madeMs`, `reusedMs`), `notKept`, the plans that could not be kept by what stood in the way, `served`, the cooks
answered from a held answer, and `notKeyed`, the kept plans whose watches are cooked again on every read, by why.
- `engine` is the engine namespace, a constant. A member read or an item read out of constants, out of a record or a
list a call wrote, is the ref written there and costs no node; `engine.require` of a module named by a constant is
the module, required while the plan is made and asked for again each time the plan is read.
- The plan is made in slices of `budgetMs` (5 ms) when the caller can yield; a cook over the plan hands a frame back
after `cookBudgetMs` (100 ms).
- A cook that shares no node cache with its caller keeps none: nothing is keyed or filed, what the plan cooked while it
was made (or asked again) and what the cook makes stand in one table by node, and all of it is released as the cook
ends but what the answer reaches. A Field that is the answer keeps the runs its leaves read; they stand as long as
it does. What the answer reaches takes in the values a geometry's columns carry (a packed piece's `Mesh` record and
the geometry its `mesh` holds): a value names what it carries and does not own through `__proc_carried`. A value a
node of the cook made that the answer reaches only through what it carries is handed to the value carrying it
(`substrate.holdCarried`) before the answer is copied or let go of: it stands while any holder of it stands (a copy
of a holder is a holder) and goes with the last of them. A column that owns its values (a detail value) owns the
geometries and columns in it and lets go of them with itself, so what it carries is what they carry. A node that
lists what its passes made (`eval.ownedBy`, a fold or a `for` over geometries) lists the carried values its answer
reaches that the values it was handed do not, and none a column owns. A store keeps what its entries carry from
the release of a cook (it is among what the store holds), and a store shared by plays counts, among the values an
entry lets go of with the last entry holding them, only the values the entry owns: a carried value is its maker's.
- A node of a plan that stands is held to the contexts its producers operate in once, takes the label of its refusals
from one string, and takes its params prepared once when every one is a constant.
### A cook after a change is run from a list (`cookrun`)
A kept plan whose cone stands on numbers (graph inputs holding a number or a Bool) is cooked node by node while those
numbers move. The recording wraps the plan's cone re-check and the cook together: the first such cook after the plan
was made is recorded as a compute list and the next one is recorded beside it; the words that differ between the two
recordings (a dispatch param, a word of a write) must each be the value of one leaf in both, and become the slots of
the second list. A cook after that runs the list with the leaves' values in its slots, asks the recorded plan-time
read-backs again, runs the watches that are not nodes (modules, animated values, the registry stamp) and answers a
device copy of the list's columns (`cookrun.counts()`: `recorded`, `diffed`, `replayed`, `verified`, `mismatched`,
`readbackChecks`, `dispatches`, `refused` by why): no node is cooked and no buffer is allocated but the copy. What
makes a recording stand, and what ends it:
- Two recordings are one cook when they make the same dispatches over the same programs and workgroups, bind buffers
one for one, and write the same number of words; a run placed at another offset (`zero_base_*`, a write offset) is
a placement. A first cook that uploads a mirror of a CPU column makes the pair differ once, so the comparison is
tried again on the next cook (twice at most). A moved leaf that is no word of the list is refused by name, since its
value reaches the device by a write the recording did not hear.
- A cook that read the clock, a play's input or a live run, and an answer that cannot be copied are not recorded.
- A `cpu.call` is first handed the geometries it is given with their columns on the device standing in as columns that
answer their type, width, length and run (`substrate.structureOf`): a call that asks for no numbers (the names of the
columns a class holds, the types a join decides) moves nothing off the device and records no read-back. A call that
asks a stand-in for its numbers, fails, answers a stand-in, declares a return that is no plain value, or is handed a
geometry counted on the device or a part is made again over the drained inputs, and its read-back is recorded.
- Every node whose cook read back from the device (every `transfer.readback`, whatever the traffic of its thread
counted, and a drained `cpu.call`) is recorded as a read-back row: its inputs, whether they were drained, and a
digest of its plain outputs. A node that holds nodes of its own is asked again by their rows. After the list has run
each row is asked again; one that answers another value than it did ends the recording and the cook is made node by
node, answering correctly. A read-back whose outputs are not plain data is not recorded. A graph that reads a figure
that moves with its inputs (the bounds of a mesh, a volume) answers another value at every cook; one that reads the
whole number or the verdict that figure comes to (a power of two, 0 for a solid) answers the same.
- A count the device holds is not a read-back row: a node states the room it is allocated (`device.bound`) and the list
runs the count on the device inside that room. A count the cook states no room for is allocated twice what the cook
measured, in powers of two, and a room is never smaller than an earlier recording of the entry allocated
(`Run:room`). The room a count of a number takes is a decision of the cook: the list is run again for every number
that takes the same room, and for a number that takes another the recording is let go of and made again.
- A recording holds the guards its nodes state (`Run:guard`, `device.guard`, `device.bound` without a room): words of the
device the list writes, which are 0 while the cook's conditions hold. After a replay the words are asked for without
waiting (`substrate.deferredReads`, counted apart from `readbacks`), and the cook of the entry that follows reads
the answers that have landed (at most eight replays ahead; past that the latest words are read at once). A word other
than 0 lets the recording go, so that cook is made node by node and recorded again: it raises the refusal the
condition states, or allocates a count that outgrew its room four times the room (`counts().guarded`).
- The first replay of a list is held to the cook of the same values made node by node, column for column; a
difference ends the recording (`mismatched`). A list that dispatched a kernel declaring `determinism: float_order`
(a float sum whose threads arrive in any order) is held to f32 columns that agree to the rounding of a sum taken in
another order.
- A buffer a cook lets go of while it is recorded stays until the recording goes (`substrate.deferReleases`): the list
names it, and a replay writes it.
- A changed key of any other leaf (a Geometry input, a constant device value, an animated value), a plan made again
and a registry change let go of the recordings; at most six plans hold recordings.
- The recordings of two threads do not meet: a dispatch, a write and a release belong to the recording of the thread
that made it.
- The first replay answers a copy word for word onto runs of its own (`cookrun.deviceCopy`) and is held to the cook.
Every replay after it answers a share of the runs the list wrote (`cookrun.handOut`; `counts().shared`): a Geometry
clone, the columns of which share the runs, costs the caller nothing to make. The recording names every holder of
those runs (a clone of a share is named too); before the list runs again it moves the holders still out onto a copy
of the runs, so an answer a caller holds across cooks keeps the values it was handed (`counts().detached`). The held
answer of a plan is always a copy.
`cookrun.setEnabled(false)` cooks every cook node by node.
A `g:fold` of three passes or more over device state is planned as one `construct.fold_run` node (`foldrun`): the body
is built once as a flat graph with the inputs `state` and `index`, the first pass is cooked while a compute list
records it, and every later pass queues that list over a copy of the state, so a pass after the first cooks no node.
`foldrun.counts()` answers how many passes were recorded, replayed and cooked, and how often a body was refused a
list, by why. A body cooks each pass on its own when it reads `index`, when the state holds something the list cannot
follow (a record, a text, a readback), when a pass makes a state of another shape, or when the fold sits inside
another recording. `foldrun.setEnabled(false)` writes the folds of the plans made after out once per pass.
A fold whose state is made of numbers and Fields alone, and whose first pass answers Fields stating what they compute
without working on the device, is one loop inside the chain that reads its state (`fieldc.loop`): the pass is cooked
once more over Fields standing for the state and for the place of the pass, and the count is one of the chain's
numbers. A fold cooked a pass at a time nests each pass's chain in the next, so its kernel grows with every pass; run
as a loop, the chain's text and its kernel are the same whatever the count. `foldrun.counts().looped` counts the folds
run that way. A pass that reads its state at another point (inside `field.substitute`) is cooked a pass at a time: the
loop holds the state at the element it runs for.
The shape of a state names each column it holds; a column carried as values (a record, a text) and a detail value stand by the
evaluator's key of what they hold (`eval.keyOf`), under which a geometry or a column a record holds stands as the runs
it reads and the writes they have had.
### How a step runs
A step solver's definition (`construct.step.<id>`) is registered under the content of its body, and every plan that
writes that body runs it. It holds the body's nodes, inputs, outputs and exports; the flat graph the body was
written in is read by the plan that writes it, while that plan is made. A step solver plans its body once (`proc.eval.stepplan`), when
the state takes its first step.
A body reads the nodes outside it through exports: each ref to the output of a node is exported once, under the node and
the output it names, and every later read of it in the body is the same export. Any other ref is exported under the key
`eval.keyOf` makes of it.
- A node of the body that depends on neither the state, the `step` record, an animated value nor the scene is STATIC:
it is cooked once, with the first step, and read as it stands by every later step (`opts.fixed` of the evaluator).
The plan reads only the nodes the next state stands on.
- What is left is the device work of a step. The first step of each distinct set of `step` values the body reads (its
`dt`, `first`, `progress`, ..., and the animated values it reads, as the device sees them: the f32 they round to) is
cooked with every dispatch and every write it makes into a device buffer kept as one compute list over buffers
the solver holds, and the next state written back into the state's own columns by the last dispatches of the list.
Every later step with those values queues the list: the dispatches read the state's columns where they stand
and write the next state into them. A step that runs from a list cooks no node and allocates no buffer.
- The columns of the state are written in place, so what a step presents is a copy of them made on the device.
- Up to six sets of `step` values are kept. A body the plan cannot stand on is cooked a step at a time with its
static nodes still read as they stand, and says why in `report.steps[<step id>].reason`: a node of the body reads
the clock, a play's input, a live run or the scene; the body reads values back from the device to the CPU; the
next state is not a record of Columns the state's own shape; or a `step` value the body reads takes a new value in
more than six steps (a body that adds `step.time` to a column, say).
- `play:report().steps[<step id>]` holds `steps`, `replays`, `recorded`, `interpreted` (steps cooked node by node),
`plannedDispatches` (what one list queues), `plannedWidest` (the largest size one dispatch of that list states it
is queued at that no live count on the device bounds: the elements a kernel runs over, the words a copy or a cast
moves, or the words of the longest run a pack moves; a dispatch that reads a live count works over the live
elements alone), `dispatches` (queued in all), `allocations` and `uploads`
(buffers made and uploads done by steps), `ops` (nodes cooked in steps, by op), `staticNodes`, `variants`, `mode`
(`replay` or `cook`), `reason` and `keyValues` (the `step` values of the last step).
- `stepplan.setPlanning(false)` makes the solvers begun after cook every step node by node, which is how a planned
body is held to the numbers a cooked one gives.
A state column the next state names as a Field, a number or a vector is evaluated into a column of the state's own
length and type.
A schema can state that a column's live elements are fewer than its length. A count column is one UInt or Int element
that states its capacity, `{ type = "Int", count = 1, capacity = n }`: it holds a live count of up to `n`, read where a
count is read (the live count a class takes with `points.point.count = state.extent`, the domain of a kernel). A column
that states `live = "<count column>"` holds its live elements as far as that count:
- the body reads it carrying the count as its live count;
- the next value the body names for it as a Field, a number or a vector is evaluated over the live elements of the
count's next value, each element reading the columns it reads as they stand (a column read at the element's own
place is copied into the kernel's column table as far as that count, and a column it gathers from is copied whole),
and a Column carrying a live count is written over that count; either way the rest of the column keeps what it held;
- what a present copies of it is its live elements, and the copy carries the copy of the count.
So the next state of a large column whose live elements are few is evaluated and written over those few. A Field the
body itself writes into a geometry (`attribute.set`) is evaluated over the class's capacity.
### Constructs
A construct is a node the evaluator itself knows: `construct.member`, `construct.item`,
`construct.member_set`, `construct.column`, `construct.column_set`, `construct.column_remove` and
`construct.engine` and `construct.select` are cooked; `construct.pick`, `construct.compare` and `construct.where` are
written out in the plan (a compare of two constants is their answer, a `compare` otherwise calls the `math.lt`, `le`,
`gt`, `ge`, `eq` or `ne` node of its operator, and a `where` over a condition the plan does not know is a
`construct.select` node). `construct.select` chooses
`a` where `cond` holds and `b` where it does not: numbers, vectors and Fields element by element (`math.where`), and a
Geometry, a record or a text by a condition that is one value, which a condition over the elements of a column is not
(it is refused naming `g.pick`). A Column or a Geometry a construct reads from a record or a list is a clone of it.
`construct.expr` is the arithmetic of a graph as one node. The plan writes each operator (`+ - * /`, `math.*`, `vector.*`,
`g.compare`) as a `cpu.call` of a function of `fieldc.operators` and the `construct.item` that reads its result, and
after the flat graph is written out it gathers every connected set of them, with the `x`, `y`, `z` and `w` reads of their
results and the `g.where` choices between them that a condition per element makes, into one `construct.expr` whose `tape`
lists the steps (`{ fn, args }`, `{ fn = "where", choice = true, args }` or `{ lane, args }`, each operand a `leaf`, an
earlier `step` or a `const`) and whose `leaves` are the values the steps read. A condition is per element when it
stands on an element field or on a column of the elements of a class; the cook makes both alternatives of such a choice
and chooses between them element by element, so the plan decides nothing for it. A `construct.select` whose condition
is one value the cook answers, or whose alternatives are whole values, stays a node. Each call step runs through
`callrun.invoke`, the call `cpu.call` makes, and the node answers the last step. `flat.folds[id]` lists the flat id of the
call or choice each step stands for, and `describeFailure` reads a failing step at that call. A node the plan, a watch or
an output names, and a member written for another alternative of a choice than its reader, stays a `cpu.call` and a
`construct.item`; a member a decision names is the root of an expression of its own. An expression holds members a cook derives a number through (a replay of a recorded list works those out
again for other values of the graph's inputs) or members it does not, never both. The expressions whose tapes state the same steps hold one frozen tape table, filed by a text that states
the tape exactly (a number by its bits, a vector by its three components, a string with its length), and each node holds its
own `{ kind = "const", value }` reference to it (`expand.setTapesShared`).
`construct.member` reads `count` and `keys` of a plain list or record (the number of members, the sorted names of a
record or the places of a list; a value that is nothing has none), `count`, `type` and `lanes` of a Field (the length
of the longest column its chain reads, its element type, its components; a Field that reads no column has no length,
and the read refuses naming `geometry.point.count`, `column.count` and `g.field.index({ domain })`), and `count`, `type` and `lanes` of a Column.
`construct.member` also reads `x`, `y`, `z` and `w` of a vector (a Field of that component for a Field, a Column of that
component for a Column of Vec2, Vec3, Vec4 or Quat), the classes of a Geometry, its `material` and its `names` (the
attribute names each class holds). On a class of a Geometry a read of a `detail` column answers the value the detail
holds. `count` of a Column or of a class of a Geometry is the live count when the elements are an appended or compacted
output (a Column of one word, which a kernel with a `domain_count` binding reads the live count through, and a kernel
without one runs over the capacity); `capacity` of either is the number of elements the run is allocated for. A record a
graph holds under a name a class goes by (`point`, `vertex`, ...) is read and written as a record: `x.point.name` is the
member of the member.
`construct.column`, `construct.column_set` and `construct.column_remove` take `edge` beside `point`, `vertex`,
`primitive` and `detail`: an edge is a unique point pair of the primitives, so the class counts them and a column
written on it is one value per edge. `count_set` takes the four stored classes.
`construct.column_set` writes a Column, a Field evaluated over the class it is written into, a vector or a number, a
record or a text (one value for every element, a constant Record or String column) or a list of records or texts (one
to an element, held in a Record or String column on the CPU); a record whose fields are numbers is a record, and a list
of numbers is a vector. A column that is the structure of a geometry (`point.id`, `vertex.pt`, `primitive.vstart`,
`vcount`, `curve` and `closed`) holds whole numbers: a number, a Field or a Column written to it is stored as an Int,
and so is a value written to a column that already holds Int. A detail value is held as itself, a record among them,
and `construct.column_remove` removes it. The
inputs of every construct take nothing as a value: an optional input a call left out reaches them as nothing.
`construct.scene { what }` answers where the graph stands in the scene it is cooked in (`entity`, `placement`,
`inverse`, `rotation`); it is read as `g.clock.placement` and the other names, and as `g.transform`.
### What the plan answers
A construct that answers while the plan is made cooks the nodes it reads (a wait in `report.waits`, a readback
named as one) and records the answer, which is what the play compares to decide whether the plan still stands.
- `check { cond } message`: a condition that is false refuses the play with the message.
- `has { geometry, class, name }` is the Bool of whether the class holds the column; `names { geometry, class }` is
the list of attribute names the class holds. A `for` over the names has one copy per name.
- `fold` with `stop`: after each pass but the last the stop is answered, and the fold ends at the first pass whose
stop holds. `"changed"` holds when the pass left its state as it found it (numbers by value, a Column or a
Geometry by what its runs hold: a device run read for the comparison is a readback wait). A stop function's scope
reads `fold_before` and `fold_after` and its result is the Bool. The report's fold scope states `copies`,
`stop` (`"changed"` or `"function"`) and `stopped`; each answer is a wait named "the stop of fold '<id>' after
pass <n>".
- A node asset called with plain inputs (an input with options, or of type Bool or String) is the graph its source
builds for those values (`builder.forInputs`); a play built for other plain inputs plans again.
Constructs cooked as nodes:
- `count_set { geometry, class, count }`: the geometry with the class's element count set. A number sets it; a
live count Column (an appended output's) becomes the live count over the capacity it carries, and a one-word Column
that carries no capacity becomes the live count over the elements the class holds; arithmetic over a
live count (`kept.indices_count * 6`, a Field over live counts) is evaluated on the device as one word, and the
class is as large as that arithmetic reaches when every count it reads is full (`substrate.atCapacity`).
- `material_set { geometry, material }`: the geometry carrying the material (a Material value, an asset reference
or a name; nothing for none).
- `step_between { step, index }`: how far from 0 to 1 the step has come through the span of graph time the present
covers; `step_sample { step, value }` is the value, which a step body samples at the step's time.
The step record carries `dt`, `time`, `graphTime`, `index`, `first`, `start` (the time the step began at) and
`progress`.
An `element` ref is the Field the graph's `g.element` stands for: `id` and `P` are fields the field compiler fuses
into the chain they sit in; a column of the evaluation domain is `fieldc.element(field, class)`.
### Cooking
Every play cooks into one store of the world, filed by content key (the op, its version, the seed, the
params and the keys of the inputs): a node of any graph that cooks the same op over the same inputs
is cooked once. A value that holds an asset reference is keyed by what the asset's files hold, so
editing a module a node calls cooks the node again. The nodes a play pulls from and every step are the
play's own.
An output node answers a Handle (a table with a `release` function). `cpu.call` owns its list of
results: a Handle in it is released when the cook is superseded and when the play ends.
A present evaluates the pulls whose keys can have moved and leaves the others standing with the Handles they hold. A
pull stands when the plans made since it was evaluated reached none of the nodes its key stands on (`moveKeys` files
them), it was evaluated at this clock, with these inputs, at this registry revision and before the play last moved on
the device, no module or asset a cook read was edited, and its cone holds no solver, no graph used as a node, no live
read and no CPU registration. A pull whose cone reads the scene stands while the digest of the scene state the plan
reads (`play:liveDigest()`) is the one it was evaluated at. A play that takes over the node cache of the play it replaces
takes the Handles with it.
The device shape of a plan (`eval.timeOnDevice` with `keptWith`: which nodes keep the play's time from reaching it through
live values alone) is the sum of the share each node of its flat graph holds. A plan made against its base states it
from the base's: the nodes the plan wrote anew are taken again and every other node keeps its share
(`eval.deviceShapePatches()` counts these, `eval.deviceShapeWalks()` the walks of every node). The causes are listed in
node id order.
### What a Field reaches (`fieldreach`)
A Field stands as its expression was when it was made, so the runs it reads (`fieldreach.terms`: Columns and
Geometries, a Geometry expanded into its columns when a walk meets it) and the values it owns that release
something (`fieldreach.claims`) are facts about the Field, answered once for it and held while its `_expr` and
`_parts` are the tables the answer was made from. A Field built over another takes that one's answer and what it adds,
and a Field whose answer is one other Field's shares that list, so a walk that meets a Field costs the number of runs
the chain reads and not the length of the chain. The answers are held weakly, by the Field and by the tables they
were made from, and list only runs and owning values. `stats.walked` counts the tables the walks visited
(`fieldreach.visited`) across the evals that filled the stats table.
### What procgen keeps (`proc.memory`)
Every play, whoever started it, and each module-level cache that holds procgen state (the kept bodies, the builds of
sources for other plain values (`kept builds`), the answers kept plans hold, the frames timelines keep, the world store
the plays share) is a keeper. The world store is two keepers: the
entries a node of a play stands on (`world store`) and the entries resting for a later claim, which no node stands on
(`world store, resting`, `eval.restingCounts(store)`). Both read the store whether a play holds it or it rests once the
last play that held it was released (`play.worldStore()`). The shared cook caches other than the world store that rest
once their last holder let go (`proc.restingCaches()`) are the keeper `shared caches, resting`, stated at the bytes each was
measured at as it began to rest and let go of the one that rested longest ago first (`proc.letGoRestingCaches`); a cache
someone holds is never let go of, and is the keeper `shared caches, held` (`proc.heldCaches()`), stated at the device bytes
of the runs held for its owner and its entries, at tier 5. A world store entry begins to rest holding its values on their
buffers alone: the arrays a read brought back to the CPU go, and the claim that stands on the entry next reads them again.
`proc.memory.report()` answers
`{ total, luau, budget, tiers, plays, keepers, byPart, commits, dropped, pending, relief }`: the bytes each keeper holds, a play by
part (`graph`, `plan.flat`, `plan.inlined`, `plan.origins`, `plan.reuse`, `plan.cones`, `plan`, `nodeCache.values`, `nodeCache.pulled`,
`nodeCache.entries`, `nodeCache.solvers`, `play.coneMemo`, `play.stats`, `play`) with the tier of the state, and the bytes the Luau
heap holds (`luau`). A part states its bytes from counts kept where its state is filed and let go of: a plan's flat node count
and rows, a node cache's entries, solvers and the entries whose values were let go of (`eval.cacheCounts(cache)`, kept by
`fileEntry`, `dropEntry` and the store's writes), the kept bodies' flat nodes (`expand.bodyCounts()`, `kept` and the `bytes`
they hold). The kept bodies are held to a budget of bytes of their own as well, the bodies used longest ago going first
(`expand.bodyBudget()`, `expand.setBodyBudget(bytes)`). The budget starts at a sixteenth of the memory the process can address
(`proc.memory.shareOfSystem("bodies")`, from `renderer.deviceMemory().system.addressableBytes`) and at 256 MB where the system
states none; the resting shared caches (`proc.setRestingBudget(bytes)`) start the same way (`shareOfSystem("resting")`). While
the engine's memory pressure stands at low or above (`proc.memory.heldBack()`, which reads the level once for each frame) the
kept bodies and the resting caches have a budget of 0, so a play made then keeps nothing behind it. The bytes one unit
costs are `proc.memory.PER`, fitted to the heap that letting each part go gave back. The tier of a part is what letting it go
costs: 1 a table made again when read (the table of origins the flat graph and the profile file by flat id, the cook times, the
answers kept plans hold, the frames timelines keep), 2 a node cache value, kept body, resting world store entry or resting shared cache cooked or
planned again where an edit or a later play reaches it, 3 the play's edit state (the plan's reuse record and cones and the answers kept for the pulls: the next plan is made
without its base), 4 the cache as a whole, 5 (`proc.memory.STANDS`) what a present stands on, which no budget lets go of.
With a budget (`proc.memory.setBudget(bytes)`; none by default) the ledger reads its total at the commit points: after
`Play.replan` has made its plan the play's, after a present settles, and on a pressure signal (`proc.memory.signal`). Over
the budget it lets go of tier 1, then 2, 3 and 4, the module-level keepers first and then the plays used longest ago first,
until the total is at 80% of the budget. A tier can be switched off (`proc.memory.setTier(tier, false)`).
The ledger also answers the engine's memory pressure (`engine.onMemoryPressure`, `proc.memory.relieve(level)`): at `"low"` it lets go
of tiers 1 and 2, at `"critical"` of every tier, whatever the budget, at once when no present or plan is running and otherwise at the
next commit point. A let-go that fails stays pending: the first failure raises, each later commit point tries it again and a retry that
fails again raises nothing, and `report().relief` states `{ level, error?, failedRetries }` until a commit carries it out (nil once it has). A play whose present
or plan is running is left whole, and when one runs besides the play that commits, the check waits for the next commit point.
`report().dropped` lists the commit points that let go of state: the budget, the total before and after, the bytes by tier and
the keepers and plays that gave them.
What each tier lets go of, and why a play answers what it answered: tier 1 is made from the plan when read (`expand.originsOf`,
`profile.originsOf`). Tier 2 is `eval.letGoValues`: an entry that no pull answers and nothing stands on in the world is left a
trimmed one (no key, no values), as `trimToBound` leaves one, and the values it held are released unless another entry, the
world store, a value a handle stands on or a registration the device rewrites reaches them (`registration.reads` lists what a
rewrite reads and lands in), and a value that holds a live run is left to its registration; the next cook that reaches the node
derives its key from its inputs and makes the values again. A kept body let go of is planned again where a call needs it, as
with `expand.setBodiesEnabled(false)`, whether or not a play holds a reuse record: a plan answers the same plan, keys and reads
from kept bodies and from bodies planned afresh. A resting world store entry let go of (`eval.letGoResting(stores, count)`,
the one that rested longest ago first) is released with every value it holds that no other entry holds, and a later play
that reaches its key cooks it again. Tier 3 is `expand.dropReuse` and `expand.dropCones` and a play without its answers
(`play.coneMemo`): the next plan has no base, which is a plan made as a first one, and its dirty set names the ledger
(`withoutBase`); the cones are keyed whole and the plan's watches are read by cooking them, as with
`expand.setWatchesCarried(false)`; the device shape is stated from every node (`eval.deviceShapeWalks`). Tier 4 is tier 2 for
every entry, the pulls' too, while the handles the play shows stand.
# fieldc
A Field is a per-element expression. `fieldc` holds what a Field is made of and how it runs: a chain of templates over a position leaf, an element number, column reads and numbers is written as one WGSL function and runs as ONE dispatch of `kernels/map`, wherever it is consumed. Nothing dispatches per operator.
## Where a Field is evaluated
```luau
local column = fieldc.evaluate(field, domain, opts)
```
The one entry point a consumer of a Field calls (a kernel's input, an attribute write, an output): `device.kernel` for a Field bound to a column input, `attribute.write` for a Field value, and every other node that needs a Column.
- `field`: a Field, a Column, a `BufferRef` (a device column handed through `cpu.call`), a number or a vector record. A Column an op hands a chain as an operand is a leaf of the chain, read where it is held.
- `domain`: a number of elements, or a Geometry (its `opts.class` elements, points by default), whose attributes the leaves reading the evaluation domain bind.
- `opts`: `{ class, count, type, clock, where, label }`. `type = "Int"` writes i32 words (a Field tagged Int does so by default). `clock` is `{ time, frame, fps, duration }`: animated values are first sampled there. `where` names the caller in a refusal.
- Answers a Column of the domain's count. Raises, naming what refused, when the chain cannot be written as a function: a chain whose last field is a `Field.fn` (a Luau function of the element) states no expression, and the refusal says so. A constant Field (`proc.Field.constant`) is the same value at every element, as a number is.
- The first evaluation of a chain whose kernel is new waits, in a thread that can yield, for the device to build it (`compute_abi.readyForDispatch`). Inside a deferral of program waits (the one a `proc.eval` opens) its dispatch is queued behind the kernel at once instead, and the kernels of one eval build side by side. A kernel the device refuses raises, naming the caller and the compiler's message, at the evaluation, at the first read behind its dispatch, or at the end of the eval, so no evaluation answers a column no dispatch wrote. A thread that cannot yield does not wait.
A chain holding an animated value or a live run answers a live column. `fieldc.liveRuns` finds it and `fieldc.tick(runs, clock)` rewrites it each frame: the animated values are sampled at the clock and written into the numbers the dispatch reads, and the dispatch runs again into the same run. An animated input therefore changes the result every frame without a cook.
## Fields the nodes make
| Construct | Module | Answers |
|---|---|---|
| `fieldc.field(v)` | `fieldc` | any socket value as a Field: Field, Column, BufferRef, number, vector, animated value |
| `operators.apply(name, ...)` | `fieldc.operators` | `math.*`: the plain result over numbers and vectors, a Field over a run or a Field |
| `fieldc.element(name, class?, width?)` | `fieldc` | what `g.element` stands for: `"id"`, `"P"`, or a column of the domain (`g.element.point.N` is `element("N", "point")`) |
| `leaves.elementId()` | `fieldc.leaves` | the element number, an Int Field (`g.element.id`) |
| `fieldc.position` | `fieldc` | the position leaf `p` (`g.element.P`, and an unwired `field.position()`): the domain's `point.P` where the chain is evaluated over a Geometry, the point `fieldc.withPosition` names inside a substitution; `fieldc.evaluate` refuses a chain that reads it over a number of elements with no geometry |
| `leaves.context(class, name, width?)` | `fieldc.leaves` | an attribute of the evaluation domain |
| `leaves.rand(seed, scope, id)` | `fieldc.leaves` | the unit draw, equal to `hash.unitFloat` to the bit |
| `leaves.call(fn, args)` | `fieldc.leaves` | a function of a prelude shader module of `kernels/` |
| `leaves.gather(column, index)` | `fieldc.leaves` | a run read at computed elements |
| `leaves.substitute(field, position)` | `fieldc.leaves` | the chain read at another point (`fieldc.withPosition`) |
| `leaves.index(domain)` | `fieldc.leaves` | an Int column of 0 to n - 1 |
| `fieldc.loop(count, init, probes, answers)` | `fieldc` | the state after `count` passes of a fold written once over `fieldc.loopProbes(strides)`: one loop of the kernel, its count one of the chain's numbers |
An animated value that becomes a Field (`fieldc.field`) is the live field holding its value at a time: inside a node's cook, the time of the clock the cook runs at (the evaluator runs each cook through `fieldc.pcallSampling`), so a curve handed to a node asset and read by a field op follows `opts.clock` of `proc.eval`; outside any cook, time 0. It stays a live field: a present for a later time rewrites the run it lands in (`fieldc.tick`), and the node is not cooked again for the time.
`fieldc.op(field, wgsl, stride, args)` binds a Column or a `BufferRef` among `args` as the run it is, the way `fieldc.field` does, so a field op given a column reads it where it lives on the device and nothing is read back.
`leaves.call` (the `field.call` node) calls a function of a module of `kernels/` that compiles inside a field chain's kernel. The first call into a module compiles a `kernels/map` variant that includes it and waits for the device's verdict; a module written for one kernel (`walk_core`, `walk_advance`, `hash_walk`, the `bvh_*` and `intersect_core` modules, each naming what its includer binds or declares) does not compile there, and a call of its functions is refused naming the function, the module and the compiler's message.
A Field made by these answers `f.x`, `f.y`, `f.z`, `f.w` as the Field of that component. Components are Fields, so the Field of a vector is built from them with `operators.vec2`, `operators.vec3` or `operators.vec4`; Luau's `vector.create` takes numbers.
## How the leaves reach the kernel
A chain's leaves are columns. `kernels/map` states every leaf's shape in its `cols` table and reads up to as many leaves as one dispatch has storage buffers for (`compute_abi.directLimit`: 8 per stage on every target, less the table, the numbers and the output, so 5 for `map`) straight from the buffer of the leaf's own run, at no cost beyond the binding. A chain of up to 5 leaf columns is the one dispatch of `map` and nothing else. Leaves past those are copied into the table, one copy dispatch each.
`fieldc.bindSpec(spec, { direct })` makes the table; `direct` is the list of leaf slots read from their own runs (`compute_abi.directPlan(columns, limit)`), and the variant is made with the same list: `program:variant({ specialize = ..., direct = { cols = direct } })`. Without `direct` every leaf is copied into the table.
A recorded list holds those copies as dispatches that fill the table. The stage pass (`proc.fusion`) reads a table packed in the same list from the runs its columns were packed from: a `map` that stands in a stage binds each packed leaf's run through the page the run stands in (`compute_abi.unpackedOf`, `columns` slots read from `NAME_u<k>` at the word less the column's first), and the copies leave the staged list. A `map` that runs as recorded (a stage of one member, a kernel that is not built, a list that is not staged) runs after the copies, which stay in the list it stands in. A copy stays in the staged list when a run it reads is written between the copy and the last read of the table, and when a dispatch that is not such a `map` reads the table.
`fieldc.operators` folds numbers: every operand a number or vector gives a number or vector. A narrower operand widens to the widest (a number applies to every component, a shorter vector reads 0 where it has none). Division and remainder by 0, the square root and the logarithm of a value at or below 0 answer 0.
## The walk step contract (for `kernels/walk`)
A walk kernel takes its per-walker function as a Field spec, the way `kernels/map` takes `TEMPLATE`.
```luau
local spec = fieldc.walkSpec(step, { width = 2, count = walkers, done = stop })
-- a state of 8 floats: lanes 0 to 3 in `step`, lanes 4 to 7 in `high`
local wide = fieldc.walkSpec(low, { width = 8, count = walkers, high = high })
local bound = fieldc.bindSpec(spec)
-- specialize = spec.specialize; bind cols = bound.cols:buffer(), u = bound.u
```
- `width`: floats per state, 1 to 8. `step` is the next state's lanes 0 to 3, a Field of `min(width, 4)` components; above 4, `opts.high` is the Field of the `width - 4` components of lanes 4 to 7.
- The state is read through `fieldc.walkState(count, first?)`: `count` (1 to 4) lanes from lane `first` (default 0), all inside lanes 0 to 3 or all inside lanes 4 to 7. A state of 8 floats is read as two leaves, `walkState(4, 0)` and `walkState(4, 4)`. The nodes `field.walk_state({ count, first })` and `field.walk_index()` are these leaves in a graph.
- `step` and `high` are written over the state leaves, `fieldc.walkIndex()` (the step number k, from 0), `leaves.elementId()` (the walker's number), Column reads (one value per walker, or a gather at a computed index) and numbers.
- `opts.done`: an optional Field<Float> over the same leaves; the walker stops before step k when it is not 0.
- `spec.specialize` is a table of the specialization values the walk kernel takes, ready to hand to `device.kernel` / `program:variant` as its `specialize` value: `WALK_STEP` (`zero_walk_chain_step(s, s_hi, k, id)`), `WALK_STEP_HI` (`zero_walk_chain_step_hi(s, s_hi, k, id)`, or `s_hi` when `width` is 4 or less), `WALK_DONE` (`zero_walk_chain_done(s, s_hi, k, id)`, or `false` when there is no `done`) and `WALK_PRELUDE`, the module-scope WGSL that defines those functions, preceded by the preludes the chain calls. Lanes 0 to `width - 1` of `s` (lanes 0 to 3) and `s_hi` (lanes 4 to 7) are the state.
- The functions read its leaves through a `cols` columns binding (`cols_f32(slot, i, 0u)`, `cols_vec3(slot, i)`, `cols_i32` for Int runs) and its numbers through `u_get(k)`: the kernel declares those two bindings exactly as `kernels/map` does. `fieldc.bindSpec(spec)` answers the table (`cols`) and the numbers buffer (`u`) to bind; `release()` lets both go.
- A read past a run's end reads its last element.
## Other entry points
`fieldc.mapSpec(chain, count, domain, { position })` writes a chain as one function for `kernels/map` and `fieldc.runMap(spec)` runs it. `fieldc.compile` / `fieldc.column` write the same chain as a kernel of its own, for the consumers that bind buffers directly.
# proc.fields
The value types of the procedural-generation type system beside the Geometry: `Field<T>`, `PointCloud`,
`Population`, `Texture`, `Material`, `Prefab` (also `Template`), `Bundle` and `Ramp`. Part of
`@builtin::systems.procgen.proc`; each is re-exported on `proc` (`proc.Field`, `proc.Texture`, ...).
- **`Field<T>`**: a lazy per-element value. `Field.constant(t, values)`, `Field.fn(t, stride, f)`,
`Field.buffer(t, stride, buf)`, `Field.context(t, stride, class, name)` (an attribute of the domain it is
evaluated over) and `Field.gpu(...)` (backed by a GPU buffer); `:sample(id)` answers the `stride` components,
`:materialize(count)` a flat `count*stride` array, and `:release()` frees a GPU-backed field.
`Field.transform(offset, orient, scale)` is a per-element transform whose three parts are fields of their own,
so each compiles to the device; `:transformParts()` hands them back. `fields.over(domain, fn, ...)` runs `fn` with
`domain` as the domain fields are evaluated over.
- **`PointCloud`**: the value a `.procNode` input declared `PointCloud` receives (`proc.substrate.toPointCloud`);
every other input, and every op, takes points as a `Geometry` (`proc.geometry.new`). `PointCloud.new(positions)`
(flat stride-3 array); `:count()`, `:position(id)`, `:setAttribute(name, field)` / `:getAttribute(name)` /
`:attributeNames()`, and detail attributes through `:setDetail` / `:getDetail`.
- **`Population`**: live instanced-draw registrations (`Population.new({ draws, recipe })`); `:count()`,
`:setParent(entity)`, `:bytes()` and `:destroy()`.
- **`Texture`**: an RGBA image: `Texture.new(width, height, data)` (an 8-bit image, values 0-255), `Texture.solid(width, height, rgba)`,
`Texture.floats(width, height, data)` (a float image from a Luau array), `Texture.bytes(...)`, or `Texture.gpu(...)`
for one the device holds; `:dimensions()`, `:pixel(id)`, `:cpu()`.
- **`Material`**: a record of a shader, its property values and its texture slots: `Material.pbr(opts)`,
`Material.shader(opts)`, `:setTexture(slot, ref)`.
- **`Prefab`** / **`Bundle`**: entity records (`Prefab.new(records)`, `Bundle.new(records)`, `:count()`).
- **`Ramp`**: values keyed along [0, 1] (`Ramp.new(t, positions, values, interpolation?)`, `:sample(t)`).
Every value carries a `__proc_type` tag that `proc.types.typeOf` reads (`"Field<Vec3>"`, `"PointCloud"`,
`"Population"`, `"Texture"`, ...).
# proc.fusion
The dispatches of a recorded compute list that compute one element each, made into one dispatch per chain. A per-element kernel declares in its `bindings.yaml` that it is one (`fusion:`): the function `element(i)` that is its value at `i`, the guard that leaves a thread out, and the binding it writes. A dispatch whose output nothing else needs is absorbed into the dispatch that reads it, which calls its `element` function in place of the read, so a chain is one generated kernel; a dispatch no answer depends on is dropped. `plan`, `build`, `fuse` and `apply` make and apply the fused list, `stages` and `applyStages` schedule a list's per-element dispatches into stage kernels by dependency level, `setEnabled` turns fusion on or off, and `counts` and `stageCounts` report what was fused. Dispatches of one program that touch no run of one another, at one step of a level, are one dispatch of the program's job form (`fusion.jobs`): the program's own text as a kernel whose dispatch carries a row for each of them, naming the page and the words each binding's run stands in, the params of the job and the workgroups it takes. A program that cannot take that form is named in `stageCounts().jobBreaks`.
Part of `@builtin::systems.procgen.proc`; required as `@builtin::systems.procgen.proc.fusion`.
# proc.geometry
CPU geometry container (positions/indices/normals/uvs) + bounds, normal recompute, and renderer.mesh.create args.
Part of `@builtin::systems.procgen.proc`.
# proc.graph
The graph data model and its definition entry: the nodes a graph holds, the normalized `InputRef` edges between
them, its inputs and outputs, and its JSON (de)serialization. Required as
`@builtin::systems.procgen.proc.graph`; the top-level `proc` module re-exports its entries as `proc.define`,
`proc.graph(id)` (`new`), `proc.fromJSON` and `proc.op`.
`define(function(g) ... end)` builds a graph in the call form, whose authoring surface is `proc.builder`: nodes
called by asset identity (`g.points.disc({ ... })`), inputs typed by their defaults (`g:input`), sockets that take
Luau's operators, members, columns and `for`, and the declarations a graph states about itself: `g:describe` (what it
makes), `g:output` (what it gives), `g:family`, `g:timeline`, `g:still` and `g:cost`. The result is a graph with
`surface = "call"` that records each node by the guid of the asset it calls.
`refusedInput(graph, name, value)` names why a value is not one an input holds. `fromJSON(doc)` reads a graph
document back and `graph:toJSON()` writes it.
Part of `@builtin::systems.procgen.proc`.
# proc.hash
Deterministic, portable scoped hashing for the procgen evaluator.
`scoped(seed, graphId, compositePath, nodeId, channel, elementId) -> number`
folds its arguments with 32-bit FNV-1a (via an exact 16-bit-split `mul32`)
and a final avalanche, producing a bit-identical `u32` on native, WASM, and
Android. `unitFloat(...)` maps the same scope to a value in `[0, 1)` for
deterministic random draws.
No `math.random` / `os.time` / float transcendentals — determinism is the
contract. The per-element scope (`elementId`) keeps a given element's draw
stable as unrelated element counts grow.
# proc.kernel
A compute dispatch declared as a procgen op. `defineKernelOp(spec)` turns a `.computeShader` identity, a param-packing function and an optional work set into an ordinary op def, the kind `proc.register_op` and `proc.registerPack` take. The op's first declared input picks the dispatch shape: a `Field` input dispatches element-wise (the shader's first buffer is what a run reads, its second what it writes, sized by `params.count`), and a `Raster` input dispatches per tile over the raster layer `spec.layer` names, with the numbers `pack(op, grid, tile)` answers as its parameter buffer and `workset(op, raster)` naming the tiles it touches. `paramsBuffer`, `sharedZeroMask`, `sharedNoMaskCommon` and `sharedZeroPayload` are the shared buffers such a dispatch binds.
Part of `@builtin::systems.procgen.proc`; reached as `proc.kernel`.
# proc.meshSettle
The cluster level of detail of a mesh a procedural result stands as. `settle(mesh, opts?)` watches a mesh that has just been made: once it has stood unreplaced for a second its geometry is still, and it takes the baked LOD hierarchy a static mesh draws. A mesh built on the device becomes static geometry under its own guid first, and the runs it drew from are let go of. A result cooked again before then replaces the mesh, so geometry that changes frame after frame never reaches the bake queue. The work runs on the background lane of the frame budget (`@builtin::modules.frame_budget`), a unit at a time inside each frame's slice, and waits out a hold on that lane.
Part of `@builtin::systems.procgen.proc`; required as `@builtin::systems.procgen.proc.meshSettle` by what stands a result as a mesh: the Generator, the translation layer and the preview.
# proc.noise
Deterministic, portable value/gradient noise. Part of
`@builtin::systems.procgen.proc`.
Built on the integer-lattice hash in `proc.hash` (`latticeCell2/3` /
`unitCell2/3` — the corner hashes of one cell, each bit-identical to the
matching `hashInts` call): every lattice corner's random value/gradient is
integer-derived, and the only
continuous math is the quintic fade + linear interpolation. No float
transcendentals and no `math.random`, so the result is bit-identical on native,
WASM, and Android — which is what makes a procedural texture reproducible
everywhere. Exposes `value2`/`value3`, `gradient2`/`gradient3`, and `fbm`.
# proc.ops (op families)
The op families procgen's own ops are defined in. Each family module exposes `ops(deps...)`, the map of op id to op
def that a `.procPack` returns; the packs under `procgen.package/procPacks/` register them, the same asset any author
outside this package contributes a family through. This index re-exports the family modules by name (`sources`,
`geometry`, `normals`, `subdivide`, `extrude`, `bevel`, `sweep`, `boolean`, `decimate`, `sdf`, `groups`, `attribute`,
`topology`, `curves`, `field`, `points`, `instances`, `prefabs`, `entity`, `scene`, `textures`, `sinks`, `sim`), so a
family is reached without knowing which folder it sits in.
```luau
local families = require("@builtin::systems.procgen.proc.ops")
local defs = families.sources.ops(proc.geometry) -- { ["mesh.box"] = def, ... }
```
Calling a registered op is a different surface: `proc.ops.<family>.<op>(...)` on the top-level `proc` module, and
`g.op.<id>({ ... })` inside a graph.
Part of `@builtin::systems.procgen.proc`.
# proc.parity
The machinery behind the procgen rewrite's parity harness (`procgenParity`), its sheet tests (`procgenSheet`) and the `procgen.coverage` tool.
- `parity.json`: `entries` holds one entry per current op. Each names its new composition (`new`, node ids as `nodebox.name`, or `nodebox.*` for any node of a nodebox), its class (`exact`, `meaning` with an `invariant`, `gone` for a named decision with a `note`, `unmapped` where the sheet names no counterpart), and `tolerance` the comparison reads. An entry that states `decided` (the text of the ruling that accepts the difference between the op and its node) keeps running: the value differences its comparison finds are reported as accepted, under the verdict `decided`, and are held to nothing, while a node that raises and the cost findings stay findings (`accepting`, `decidedLines`). `budgets` states, per op, the read-backs its node may make (`{ "<op>": { "readbacks": n } }`); an op without one may make as many as the current op does. `types` maps a socket's type to the fixture a case builds for it. `tolerance` holds the global bounds (`attribute`, `bounds`, `picture`, `costRatio`, `costFloorMs`). `suites` names, per parity suite, the nodeboxes whose entries it compares (`suites()`); `onNodes` names, per on-nodes suite, the existing suites it runs with their ops answered by their nodes, and `onNodesLeft` the suites no on-nodes suite runs. `cases` holds a case per op that needs more than the defaults and names only content the library ships. A parity suite states the cases whose inputs are its test fixtures in the `cases.json` of its folder (`{ "cases": { "<op>": case } }`), since the library ships its test content nowhere; `cases()` is both together, one case per op, and an engine whose library leaves the suite out finds no case for those ops.
- A case states `params`, `fixtures` (a fixture by input socket), `node` (the new node a multi-node entry compares against), `nodeBy` (`{ param, nodes = { value = node } }`: for an entry whose op one node per value of a param answers, the node an existing suite's call reaches for each value, which `standIns` runs; a value it names no node for is refused), `rename` (`inputs`, `params`, `outputs`: the new node's names where they differ, `false` leaves a name out), `compare` (`bounds`: a Geometry is held to its bounds alone, for an output whose element layout differs by design; `ramp`: two ramps are held to the values they read at the same positions), `sink` (`asset` or `handles`: the op writes to the world, each side under its own name and what it wrote is compared and removed), `world` (entities spawned for the run; `scene` takes the run's root scene, `settle` waits until the op runs on them), `tolerance` (bounds that replace the global ones for this case, `{ attribute = 0.05 }`: for an op whose values come from the device's sampler, whose fixed-point weights and decode answer within a fraction of a percent of the exact blend a node computes), `ignore` (outputs left out), `unreachable` (the sentence that says why the harness has no fixture for the case; the entry then counts as a harness error) and, for an op that is a solver over a timeline, `suite` and `describe` (the group of an existing suite that holds its comparison; `deferred` leaves that group to the suite's own run and states the entry pending, for a group that costs the suite's whole time a second time inside this one).
- A fixture is a name (`mesh`, `points`, `curve`, `positionField`, or a type named in `types`), a current op run on its own fixtures (`{ op, params, inputs, output }`; the new side builds it through the node that replaces the op when the entry for that op names exactly one, so a ramp, a group, a prefab, a raster or an Sdf a node reads is one that library made; `shared: true` makes both sides take what the current op makes, for inputs the entry under test is held to and the op that made them is not), a node run on its own fixtures (`{ node, params, inputs, output }`, a new node by id), a list (`{ list }`), a record (`{ record }`) or a literal (`{ value }`). A case's `newInputs` are fixtures only the new side takes, for an input the current op states as a param (a texture the node reads where the op names the asset).
- `sheet.json`: the composition sheet's expectations: the eight ops, the 24 kernel families with their tallies (the family `fx`, the passes of the fixed program set, is named by no node) (a kernel asset `<kernel>_<pass>` belongs to the family `<kernel>`), the layers, the L2 ids as the core package names them, `universalUses` (the L2 nodes every row may call), one row per node family (the kernel families, L2 nodes and ops a node of the row may name; `authorKernel` for rows whose nodes run a kernel the author names; which nodes may stand on one kernel family alone), and the reported numbers.
`scan()` finds the new parts in the library: the nodes of every built-in nodebox wherever its package keeps it, the kernel families with their pass assets, and the modules that sit beside nodes. `analyze(src, ...)` reads a node's source: the nodes it calls (`g.<name>(...)`), the ops it names (`op.<name>`), the kernel families it names, a structural hash per call, and WGSL text in its strings. `rowViolations(scan, node)`, `dispatchViolations(scan, node)` and `directCallers(scan)` state what a node breaks of the sheet. `valuesHold(result)` reads a comparison's values alone, which is what lets an existing suite run on the nodes of an op whose cost is over. `assess(scan, entry)` states where an entry stands (`decided`, `unmapped`, `pending`, `ready`); `compare(scan, entry)` runs a ready entry's current op beside its node; `checkCase(entry)` runs the current op on the entry's case. `redirect(map, fn)` runs `fn` with `registry.get` answering a new node for each op id in `map`; `runSuite(name, redirect)` runs an existing suite's cases through the test framework's own runner, and `runSuiteOnNodes(scan, name, ops)` runs it as it stands and with its ops answered by their new nodes. `report(opts)` is the coverage report.
A comparison states cost as separate numbers (`result.cost`): `oldMs` (the current op's CPU time), `planMs` (the evaluation outside the nodes' own cooks: expanding the call form, lowering refs and constructs, scheduling, with the plan's share of the waiting taken out), `cookMs` (the CPU time the nodes' cooks spend, summed over the nodes no other cooked node's id holds and at most the evaluation's wall time, with their share of the waiting taken out), `waitMs` (the time in `task.wait`, the frames that passed, shared between the cooks and the plan by the read-backs each made, or by the time each spent when no counted read-back was made), `dispatches` (device dispatches queued), `readbacks` (read-backs the substrate counted) and `frames` (frames that passed during the evaluation). A Field in an output is read over the Geometry its side was given, a Column by its values, and a Bool answers 1 or 0. The cost ratio of `tolerance` is applied to `cookMs` against `oldMs`; the read-back count is asserted against the op's budget on its own, so a read-back removed from a node shows as `frames` falling to zero. Times are the median of three runs; counts are the last run's.
A comparison states its values and its cost apart. `result.valueFindings` are the differences in what the node answers and `result.costFindings` the cost and read-back findings (`result.findings` holds both). `verdict(assessed, result)` reads them as `value` (`equal`, `differ`, `missing` for an attribute, layer or column the new output lacks, `raised` for a node that failed on the case's inputs, `harness` for a case whose inputs could not be made, `skipped`, `decided`) and `cost` (`within`, `over`, `none`); `summary(scan)` counts every entry under exactly one of `pass`, `costOver`, `differ`, `missing`, `raised`, `harness`, `skipped` and `decided` and reports the same per family (the nodebox of the entry's first new node) with the median and worst cost ratio.
What is compared where the two libraries carry a value differently: a Geometry by its live counts (a domain allocated at a capacity compares its live front), a Raster layer by layer at the grid's cell centres, a Texture by size, channel count and texels (bytes scaled to 0 to 1 and held to half a byte step), a count the new library holds on the device as a one-word column by its value, a Population against the instanced points by instance count, and a list of numbers against a list of records of numbers as one layout finding that says whether the numbers agree.
# proc.placement
Where a graph stands in the world, as a 4x4 matrix held as 16 numbers column
after column: the layout `entity:worldMatrix()` and
`camera.viewData().viewProj` answer in.
A graph is evaluated in its own space, whose origin is the entity it stands on.
A Generator draws what it makes under its entity, so the graph's origin stands
where the entity does, and an effect built at the origin works wherever it is
played. A node that pulls from the scene (`scene.fetch`, `terrain.ground`,
`sim.scene_colliders`) reads that origin from the scene the evaluation hands it,
`ctx:scene().origin()`, and takes what it reads from the world into the graph's
space. A graph evaluated standing on no entity has the world's origin for its
own (`proc.placement.IDENTITY`).
`mul`, `inverse`, `point`, `scale`, `rotation`, `turn` and `conjugate` are the
matrix and quaternion steps such a node takes.
# proc.preview
Type-dispatched visualization of any proc value. `visualize(value, name?, opts?)` materializes the value into temporary scene entities and answers `{ entities, framing?, stats, cleanup }`: a Geometry draws as a mesh, a population of points carrying a Mesh as one merged Geometry, bare points as a marker cube at every point, a `Field<T>` as a heatmap on a quad, a Material as a lit sphere wearing it, a Texture on a unit quad, and a Prefab or Bundle as the persisted bundle instantiated. `cleanup()` despawns everything it spawned. `shows(value)` and `isDrawn(value)` say whether it has a picture for a value. `markedPoints(value)` answers bare points the device holds as a population of marker boxes, which the translation layer draws as one instanced draw a play moves on the device. The `procgen` toolbox's `preview` tool drives capture on top of it.
Part of `@builtin::systems.procgen.proc`; reached as `proc.preview`.
# proc.records
Record kinds: the values a graph moves that become assets when saved (a material, a mesh, a texture, a user's own).
`proc.record({ name, asset, applies?, fields?, live?, release?, save?, load? })` defines a kind; a `.procRecord` asset's
`init.luau` returns one. A record carries its kind's guid as `kind`; the node that writes it states the kind on the
geometry's detail attribute `records` (`{ [guid] = reference }`), and output, export and import find the definition
there. `save` and `load` default to the asset type's own `graph.write` and `graph.read`. A kind whose `live` value holds
something (a scratch asset) states `release`, which output calls once nothing stands on the value.
Part of `@builtin::systems.procgen.proc`.
# proc.registry
The operation registry: register/lookup/schema/search/help for procedural ops.
## Where a node works
Every node works in a context (`proc.registry.contexts()`), and may read from the scene or assets beside its inputs
(`pulls`) or write to them beside its outputs (`pushes`). The registry answers them for a `.procNode` without
running it:
- `nodeInterfaceContext(guid)`: what the node's source states (a node written as a table returns `context`), else what
its `.metadata` states, else what its nodebox's `.metadata` states for every node it holds, else the one context
every op and node its outputs come from operates in.
- `nodeInterfaceReach(guid)`: `{ pulls, pushes }`, read the same way (the source, then the node's `.metadata`, then
its nodebox's).
A `.metadata` states them as `"context": "sim"`, `"pulls": "scene"`, `"pushes": "asset"`. A value outside the known
contexts, or outside `scene` / `asset`, is left out with a warning naming the file. A node of a nodebox that works
elsewhere than its box states its own (`sim.particles` is a geometry node in the `sim` box). Each function refuses a
guid that is not a string and answers nil for a guid no node holds.
Part of `@builtin::systems.procgen.proc`.
·computeshader · born here
❒asset # proc_field_noise (compute shader)
2D value-noise field: `dst[i] = value2(seed, coords[i] * freq)`. One GPU thread
per element. Re-implements `proc.noise.value2` — the integer FNV-1a lattice hash
(`proc.hash.hashInts`) is bit-exact-portable, so the `u32` hash here matches the
Luau `bit32` hash exactly; the quintic-faded bilinear interpolation runs in `f32`
(vs the CPU's `f64`), bounded to `f32` rounding.
It reads `coords` (one `vec2<f32>` per element) and writes `dst` (one `f32` per
element); `seed` (int, default 0) and `freq` (float, default 1.0) are its params.
The `gpu.noise` op (`proc.gpu.eval("noise", { input = coords, count = n, seed = 7, freq = 0.1 })`)
dispatches it and returns `dst` as a GPU-backed `Field`.
·computeshader · born here
❒asset # proc_field_scale (compute shader)
Element-wise scale of an `f32` field: `dst[i] = src[i] * scale`. One GPU thread
per element. Reads a storage buffer (`src`), writes a storage buffer (`dst`), and
multiplies by the `scale` params uniform.
The `gpu.scale` op (`proc.gpu.eval("scale", { input = f, count = n, scale = 2 })`)
dispatches it and returns `dst` as a GPU-backed `Field`.
·computeshader · born here
❒asset # proc_raster_apply_accumulator
Folds one tile's fixed-point accumulator into a layer, clearing the
accumulator for the next batch.
`proc.raster`'s `Raster:resolveAccumulator(layerName, scratchName, work?)`
runs this after `proc_raster_edge_add` has folded in what a neighbour pushed
across the seam, then refreshes `layerName`'s apron so the next step reads a
consistent neighbourhood.
It reads `params` (lane 0 holds the tile's stored-cell stride), adds each cell of
`delta`, an `atomic<i32>` accumulator in units of 1/65536, into the same cell of
`field`, and sets that cell of `delta` to 0. One thread per stored cell, apron
included, in 8x8 workgroups.
·computeshader · born here
❒asset # proc_raster_apron
Refreshes one tile's apron ring of one layer from the neighbour tile that
owns those cells, one dispatch per (destination tile, neighbour direction).
`proc.raster`'s `Raster:exchangeAprons(name, work?)` drives it, over every
neighbour pair a work set touches. Any iterative raster kernel op whose
per-cell result depends on a previous step's neighbourhood needs its written
layer's apron refreshed this way between steps, or a later step reads a
neighbour's stale interior instead of what that neighbour actually computed.
`params` describes the block in stored-cell coordinates: lane 0 holds (stride,
block width, block height, 0) and lane 1 holds (destination x0, z0, source x0,
z0). It reads the block from the neighbour's `src` and writes it into this
tile's `dst`, one thread per cell of the block in 8x8 workgroups. The same
shader moves an edge band and a corner square.
·computeshader · born here
❒asset # proc_raster_copy
Copies one raster tile into another, cell for cell, apron included.
`proc.raster` runs it for its channel set's checkpoints, restores and clears,
and for `Raster:copy()`. A checkpoint is a copy of every live channel tile
taken as the state after a stack index, so an edit to an op after that index
restores the copy instead of re-running the ops up to it. A clear is the same
copy with a zeroed tile as the source. `Raster:copy()` duplicates every layer's
tiles so a mutating op leaves the original untouched.
`dst`'s length decides how many cells are copied, so the two tiles must be the
same shape.
It reads `src` and writes `dst`, one thread per cell, apron included, 64 to a
workgroup.
·computeshader · born here
❒asset # proc_raster_edge_add
Adds a neighbour tile's apron-ring fixed-point accumulator into this tile's
interior, one dispatch per (destination tile, neighbour direction).
`proc.raster`'s `Raster:resolveAccumulator(layerName, scratchName, work?)`
drives it, before folding the accumulator into `layerName` and refreshing
`layerName`'s apron. Droplet and thermal erosion both accumulate this way —
any tiled kernel op whose per-cell result can spill across a tile seam needs
the same fold.
`params` describes the block the way `proc_raster_apron` takes it: lane 0 holds
(stride, block width, block height, 0) and lane 1 holds (destination x0, z0,
source x0, z0), the source block in the neighbour's apron ring and the
destination in this tile's interior. It reads the neighbour's accumulator `src`
as plain integers and adds each non-zero cell into this tile's `dst` with an
atomic integer add, one thread per cell of the block in 8x8 workgroups.
# proc.substrate
The substrate a graph carries: a geometry, its four domains (point, vertex, primitive, detail) and the named columns over them. A point is a position and an identity; a vertex is one primitive's use of one point; a primitive is a run of vertices (a face, a curve or a volume); detail is the geometry itself, one element. An attribute is a named, typed column over one domain. A numeric column is a `substrate.createBuffer` handle, the engine's one buffer primitive, so the handle a column holds is the one a kernel runs over and a compute shader binds; a column of a type a buffer cannot express (text, a reference, a record) is carried as values and placed on the device interned. `Geometry`, `Column` and `Domain` are the value types; `fromArrays`, `fromPositions`, `fromCurves` and `fromPointCloud` build a geometry. A geometry clone holds the numeric columns of its source themselves, so `column` answers a column several geometries may share: read it with `column`, hand its buffer to a reader with `readableBuffer`, and take a column to write (`set`, `writeRun`, `buffer`) with `geometry:writable(domain, name)`, which gives the geometry a column of its own first. A write through a shared column is refused, naming `writable`. `man proc.substrate` lists every function with its arguments.
Part of `@builtin::systems.procgen.proc`; reached as `proc.substrate`.
# proc.translate
Turning a geometry into scene things, and keeping them that way. For each attribute on the domain being translated it asks the engine whether a component answers to that name: one that does carries that component's data across the elements, and one that does not stays data the graph carries. An attribute named after a component holds that component's value whole, one record per element; an attribute a component declares as feeding one of its fields (`ecs.Transform` declares that `P` feeds its position) carries that field on its own. `cook` gathers what a frame's attributes hold for each component, and `apply` presents a cooked frame: it spawns and despawns exactly the difference in the element list, adds and removes components, and writes only the fields whose digest moved. Elements standing as entities stand as the hierarchy they state: an element's `name` names its entity, and its `parent`, the `id` of another element, hangs it under that element's entity; both are written when the elements, their names or their parents change. `man proc.translate` lists every function with its arguments.
Part of `@builtin::systems.procgen.proc`; reached as `proc.translate`.
# proc.types
The procgen type system: core type tags + socket assignability for graph validation.
Part of `@builtin::systems.procgen.proc`.
# preview.derive
The worker entries of the `<type>.preview` derive hooks that `preview` registers for every asset type with a preview recipe.
- `fingerprint({ snapshot })` answers the digest of the snapshot's fingerprint lines, the value `preview.inputsFingerprint` states for the same content.
- `compute` raises: a preview renders on the engine thread, through `preview.renderForReservation`, which the hook names as its `engineCompute`.
```luau
local fingerprint = require("modules.preview.derive").fingerprint({ snapshot = snapshot })
```
# generator.stored
A Generator's stored result: what its cook stood in the scene, written into the world as engine-native records and stood again from there in any process that shows the same graph with the same params, with procgen not loaded.
- `key(graphGuid, params, output)` names a result from the manifest and the params alone: the graph's checksum, the checksum of every asset it references (world content followed at any depth, library content by its own checksum), procgen's own version (its package's checksum), the params in canonical form and the output named. `version(graphGuid, params, output)` answers that key with the way of cooking it stands for (`way`: the same parts with what the library version decides left out) and the library version.
- `write(owner, graphGuid, key, opts)` writes what stands under the Generator's entity: each entity it realized as a record (its components, its native components with each mesh and material by address), each instance set with its placements, and what moves with time on the device as the compute lists that rewrite it (`remainder`). Blobs are named by the SHA-256 of their bytes and written before the record; a blob already present, or a record already filed under the key, is not written again.
- `read(graphGuid, key)` answers the record filed under a key, `stand(owner, record)` stands it (meshes from their stored bytes, materials from their records, entities born temporary, instance sets at their placements, the device runs and their programs), `tick(standing, time)` runs the stored rewrites at a time of the result's timeline, `frameWork(standing)` states what a frame of them queues on the device, and `release(standing, ownerGone)` takes it all down.
A frame of the stored rewrites is one dispatch (`fused`): `stand` makes one kernel of every program the rewrites dispatch and a command table of every entry they recorded, in order (each dispatch's program, threads, the page, first word and length of each run it binds, and its parameters; each write's words and where they go). The kernel binds the result's pages and the table, and runs every entry in its one workgroup with a storage barrier between each and the next; each frame writes the values the curves give into the table's slot area and dispatches it. The table is built again when the page group moves this result's runs. While the kernel compiles, the rewrites replay as recorded. Rewrites the kernel cannot state (a program that synchronizes its workgroup, reads where its thread stands in it, or binds anything but arrays of words, scalars and vectors; runs standing in more pages than it can bind) replay as recorded, one dispatch per recorded dispatch, and `frameWork` names why.
A result lives under `/zero/source/_cache/procgen/<graph guid>/`: `<key>.result` (the record), `<sha256>.zmsh` (meshes), `<sha256>.bin` (instance placements and device runs), `<sha256>.wgsl` (program sources), `<key>.<way>.version` (the way of cooking it stands for, holding the library version) and `<key>.published` (present once a published version of the library wrote or stood it). A record names each entity by its place in the result, so two processes that cook one key write the same bytes.
The store keeps one result per way of cooking a graph's output. `mark(graphGuid, version)` writes a result's marks; a Generator in an edit session marks the result it writes or stands. `retire(graphGuid, version, previous)` runs after a Generator writes a result: it removes every other result of the same way (one another version of the library cooked) and the result the Generator stood for before a param or graph edit, with their marks and every blob no remaining record names. A result a published version of the library marked stays until a published version writes the next, since a player's engine runs a published version (`published()` reads which version the engine runs), and a result a Generator of this process stands for (`hold(holder, key)`) stays while it does.
The `Generator` component requires this module itself, and loads the parts `~.generator` installs only once it cooks.
# compute_abi Module
The kernel ABI of a `.computeShader`. A `bindings.yaml` that uses the ABI
extensions is lowered to the plain bindings and WGSL the engine compiles; this
module parses, lowers, compiles variants, allocates outputs, packs column tables
and dispatches.
## Purpose
A kernel is one asset that serves many shapes of data. `bindings.yaml` states:
```yaml
bindings:
- { name: cols, kind: columns, access: read }
- { name: src, kind: buffer, access: read, element: T }
- { name: dst, kind: buffer, access: read_write, element: T, count: "len(src)" }
- { name: hits, kind: buffer, access: read_write, element: vec4<f32>, capacity: "n * 4", append: true }
specialize:
- { name: T, options: [f32, i32, vec2<f32>, vec3<f32>, vec4<f32>] }
- { name: FOLD, options: [add, min, max, mean, set] }
- { name: BODY, kind: source }
determinism: exact
```
- `columns`: a table of columns in one storage binding (header: the column count, then four words a column: first word, lanes, count, kind). WGSL reads it through `NAME_count(c)`, `NAME_lanes(c)`, `NAME_f32/i32/u32(c, i, lane)`, `NAME_vec2/3/4(c, i)`; `access: read_write` adds `NAME_set_*`. Columns named at specialization are constants `NAME_col_<column>`.
- `count` / `capacity`: the size, in elements, of an output the host allocates. The expression uses `n` (the dispatch size), the shader's params, `len(binding)`, `max`, `min`, `ceil`, `floor` and `+ - * / ( )`.
- `live: true`: on an output of `count: "n"`, the output carries the live count its dispatch ran over (the count the `domain_count` binding was handed), so a reader of it takes the live elements only.
- `append: true`: the output carries a live counter, `NAME_count`, bound right after it. `NAME_store(slot, v)`, `NAME_set_count(n)`, `NAME_count_value()`, `NAME_capacity()` are generated. `NAME_append(v)` (unordered, atomic) is generated for `determinism: float_order` only.
- `specialize`: compile-time parameters. Type options become `alias NAME = type;`, named options become `const NAME: u32` plus `NAME_<option>`, and `kind: source` parameters replace the identifier with text.
- `when` on a binding: a condition over the specialization options, `NAME=option` or `NAME=option|option`. The binding exists in the variants whose option holds and is left out of the others. Terms separated by spaces all hold (`COUNT=device STAGE=table`); alternatives separated by `;` hold when any one does (`COUNT=plain; COUNT=device STAGE=table`). Two bindings may share a name when their conditions never hold together.
- `// @when NAME option option` ... `// @end` in the WGSL: the lines between them stay in the variants where the specialization `NAME` takes one of the options and are blanked in the others (the lines keep their numbers). Blocks may nest. Code that reads a binding a variant leaves out sits in such a block.
- `bits: true` on a binding states that its words are raw bits (an f32 held in a u32 word, an atomic word): a column of another element type bound to a read binding that states it is bound as it is, where an i32, u32 or f32 read binding takes a column of another element type cast by value.
- `determinism`: `exact` or `float_order`. An `exact` shader that calls `NAME_append` is refused.
- `workgroup`: the workgroup size the body declares (default 64).
- `page` / `column`: a kernel binds each arena page once and reaches the runs standing in it by offset. `- { name: PA, kind: page, access: read_write, atomic: false }` is one storage binding of u32 words (`atomic: true`: `atomic<u32>` words); `- { name: pos, kind: column, page: PA, element: vec3<f32>, access: read }` is a run of the page, with no binding of its own. A kernel of thirty columns over three pages has three bindings, whatever the runs' offsets are. A column gets `NAME_len()`, `NAME_get(i)`, `NAME_word(w)` and, unless `access: read`, `NAME_set(i, v)` and `NAME_set_word(w, v)`; an index past `NAME_len()` reaches the last element. On an `atomic: true` page a one-lane column also gets `NAME_atomic_exchange`, `NAME_atomic_min` and `NAME_atomic_max`, the integer ones `NAME_atomic_add`, `_and`, `_or`, `_xor`, and an f32 column `NAME_atomic_add` (compare-and-swap loops where the hardware has no atomic). Each column adds the params `col_base_NAME` (the word its run starts at in the page) and `col_len_NAME` (its elements). `abi.pageBinding(lowered, { [column] = handle | name })` answers the page each page binding takes and those params, from `substrate.placement`, and raises when the columns of one page binding stand in different pages. Runs made inside `proc.substrate.withPageGroup(key, fn)` stand in pages the group owns, in the order they were made, so work that asks for the same shapes in the same order binds the same pages every play. A buffer of its own (not an arena run) is a page of one column. At most eight pages bind in one kernel (the storage-buffer cap).
Every scalar or vector `buffer` binding gets `NAME_get(i)`, `NAME_len()` and, unless `access: read`, `NAME_set(i, v)`. A `vec3` element is stored as a flat scalar array, matching a column of vec3 that is 12 bytes an element. `zero_n()` is the dispatch size.
## Usage
```luau
local abi = require("@builtin::modules.compute_abi")
local schema = abi.parse(bindingsYaml)
local program = abi.program({ key = "my_kernel", schema = schema, wgsl = body })
local variant = program:variant({ specialize = { T = "vec3<f32>" } })
local run = variant:run({ n = 4, inputs = { src = srcBuffer } })
local values = abi.read(run.outputs.dst.buffer)
```
A computeShader asset reference exposes the same through `ref:program()`.
## API
| Function | Does |
|---|---|
| `abi.parse(text)` | `bindings.yaml` to `{ bindings, params, specialize, determinism, workgroup }`; a text parses to one schema, the same table each time it is read |
| `abi.isExtended(schema)` | whether the schema uses an extension |
| `abi.lower(schema, wgsl, spec)` | the lowered source, bindings, params and host slots |
| `abi.compile(key, lowered, label)` | compile a lowered variant once, answering its dispatch key |
| `abi.program(def)` | a program; `program:variant(spec)` lowers and compiles a variant. A program over the schema and source of the one standing under its key is that program, with the variants it has lowered |
| `variant:run(env)` | allocate outputs, bind, dispatch; answers the outputs and live counters. `env.outputs[binding]` is a buffer (or `{ buffer, count?, capacity?, counter? }`) the dispatch writes in place of an allocation; an appended output given one keeps the count its `counter` holds. The engine holds a dispatch whose program is still building, and every later command over its buffers, until the program lands, so a read of an output asked for after the run sees what the dispatch wrote. The first run of a variant waits for its program to be built and raises when the device refused it; inside a deferral (`abi.deferProgramWaits`) it is queued at once and the program noted |
| `abi.deferProgramWaits()` / `abi.endProgramWaits(deferred, settle)` | open a deferral of program waits on the calling thread, and end it: while it is open, the first runs of programs still building are queued without waiting, so the programs of one piece of work build side by side; the outermost end with `settle` waits once for every program noted, raising for one the device refused |
| `abi.readyForDispatch(key, label)` | make a program one a dispatch can be queued on: noted inside a deferral, waited for elsewhere |
| `abi.checkDeferredPrograms()` | raise for a program the calling thread's deferral noted that the device refused since; called once a read behind its dispatches has landed |
| `abi.table(columns, opts)` | pack columns into one buffer for a `columns` binding |
| `abi.evaluate(text, vars, lengths)` | evaluate a count expression |
| `abi.read(buffer, asU32?)` | read a buffer back, waiting for the frames it takes |
# json
JSON encode/decode library for Luau. Encodes Lua values to JSON
strings and decodes JSON strings back to Lua values. Used for
communication with the Rust side of the engine, the VFS read/write
bridge, and any wire-format that needs JSON.
Pure Luau, no engine dependencies. Compact and pretty-printed
encoders, plus a hand-rolled decoder that streams the input by position
so it works under WASM as well as native.
## Exports
- `Json.encode(value: any, indent?: string, currentIndent?: string) -> string` — compact encode. Functions / unknown types and NaN/Inf encode as `null`.
- `Json.encodePretty(value: any, indentStr?: string) -> string` — pretty-printed encode with sorted object keys (diff-friendly).
- `Json.encodeArgs(...: any) -> string` — encode varargs as a JSON array.
- `Json.null` — the value that stands for JSON `null` inside a table. A key set to nil is left out of the encoded object; a key set to `Json.null` is written `"key":null`, which is how a request names a field it clears. `decode` answers `null` as nil.
- `Json.decode(str: string) -> any` — decode a JSON string. Returns the decoded value, or `nil` + error message on failure. The string is one JSON value with optional whitespace around it; anything else after the value is a failure naming the character and its position.
## Usage
```luau
local Json = require("@builtin::modules.json")
local widget = { type = "button", text = "Click Me" }
local compact = Json.encode(widget) -- '{"text":"Click Me","type":"button"}'
local pretty = Json.encodePretty(widget, " ")
local decoded = Json.decode(compact)
local v, err = Json.decode("oops") -- v = nil, err = error message
```
## Notes
- Object keys are sorted alphabetically in both encoders for consistent
output across runs.
- Numeric keys on objects are stringified at encode time (JSON has no
numeric keys). Pure-integer key sets get detected as arrays via
`isArray` and encoded with brackets.
- NaN, +Inf, -Inf encode as `null` — JSON has no representation. Round
trips through `decode` recover `null` (Lua `nil`), so they don't
preserve.
- Unicode `\uXXXX` escapes decode to UTF-8 by hand to stay WASM-safe.
Only the BMP is covered; supplementary planes via surrogate pairs
are not.
- Functions encode as `null`.
- Decode is character-streamed — no regex, no `string.match` patterns
on the whole input — so the line-and-column information needs to be
reconstructed from the position offset.
# procgen.results
What procgen made, kept in the world by what it is, so a process that needs the same output reads it instead of making it. An author's engine makes an output once and writes it here; entering play, a later boot, a collaborator's engine and a player's engine read the bytes it wrote.
- A space is one kind of output (`pieces`: the meshes of quick-geometry pieces; `fxprogram`: the programs of effect entries). It lives under `/zero/source/_cache/procgen/<space>/`: `<key>.record` (JSON: what the output is, the version of the code that made it as `maker`, and the blobs it names by address) and `<sha256>.<ext>` (each blob, named by the SHA-256 of its bytes).
- `key(space, text)` names an output by what it is made from alone, so a record stays readable across versions of the code that makes it. `version(paths)` states the version of that code (the checksums of the library paths named).
- `writes()` answers whether this process makes outputs and keeps them: an engine that authors the world, in edit mode and in the play of an editor session (its writes go to the world's source past the play's shadow). A runtime engine, a player's, takes any record it finds; an author's engine makes the output again where a record's `maker` is not the version it runs.
- `read(space, key)`, `blob(space, address, ext)`, `put(space, bytes, ext)` (writes a blob once and answers its address) and `write(space, key, record)` (files a record, after the blobs it names).
A world keeps what is under `_cache` like any other content, so `zm add`, `zm commit` and `zm push` carry it to every engine that opens the world.
Part of `@builtin::systems.procgen`; required as `@builtin::systems.procgen.results`.
# Shader (asset type)
A shader is a WGSL program that runs on the GPU. Materials reference shaders and
supply property values; renderable entities reference materials, not shaders
directly. This README is the canonical reference for writing **every** kind of
shader — it covers all domains, the surface authoring contract, the material
property schema, the engine library functions you can call, and how a shader
registers and compiles.
> New to how shaders, materials, meshes, and textures relate as assets and live
> GPU resources? Read `core/resource-model` first.
## Folder shape
A `.shader` is a folder asset:
```
<name>.shader/
shader.wgsl # the WGSL body (required)
properties.yaml # the material property schema (optional; surface shaders)
README.md # a one-paragraph description of THIS shader (required)
.metadata # asset metadata
```
Each file carries a committed `.meta` sidecar pinning its stable guid. The
identity is `<name>` (the `.shader` suffix strips).
A shader's material properties are exactly the ones its `properties.yaml`
declares: a shader with no `properties.yaml` declares none, and the engine
reads no property from the WGSL body. A `.wgsl` file standing on its own,
outside a `.shader` folder, is WGSL source rather than a shader: a material
draws with the `.shader` folder that holds it as `shader.wgsl`. Materials and other assets
reference a shader by **AssetRef** (a typed, guid-backed handle), never by a raw
string.
## Domains
The first line of `shader.wgsl` declares the domain:
```wgsl
// @domain: surface
```
| Domain | What it is | You write |
|---|---|---|
| `surface` | A material on a mesh (the common case). | `fragment()` (+ optional `vertex()`/`vertex_clip()`). The engine generates everything else. |
| `post-process` | A full-screen pass over the rendered frame, in the space it declares (bloom, vignette, grade). | `fragment(in: PostInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `screen` | A standalone full-screen visual (UI background, procedural). | `fragment(in: ScreenInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `sky` | The sky background (a fullscreen material). | `fragment(in: SkyInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. |
| `compute` | GPU data processing, no rasterization. | An `@compute @workgroup_size(...)` entry over storage buffers; you write the `@group/@binding` lines yourself. For compute work, the `.computeShader` assetType (see below) generates them for you. |
`// @domain:` resolves the names above and `postprocess` / `screenspace` / `ui`
as further spellings of `post-process` and `screen`. A body carrying no
`@domain:` line is `surface`. `shaderRef:domain()` answers the domain a body
declares, a further spelling as the domain it names. Any other name is refused where the shader
registers, with an error naming the spellings that resolve, so a shader reaches
the renderer only under a domain the compiler scaffolds.
Particles are drawn and simulated through these domains like anything else: the
particle package's `particle_sprite` and `particle_mesh` are `surface` shaders,
and its simulation, culling and sorting steps are `.computeShader` assets.
## Texture coordinate space
A shader that samples a texture through a coordinate it builds itself declares
which space that coordinate lives in, on a line beside `@domain:`:
```wgsl
// @domain: surface
// @uv_space: world
```
| Value | The coordinate | A material's `uv_scale` means |
|---|---|---|
| `mesh` (the default) | The mesh's own UV attribute, `input.uv`. | How many times the texture repeats across a surface. |
| `world` | The fragment's world position, as a triplanar projection samples. | How many times the texture repeats per world unit, so a larger surface carries more. |
Texture residency reads the declaration to work out how finely a frame samples
each texture: a material laying eight copies of its texture across a surface
samples each copy at an eighth of the surface's size, and the mip level that
serves it is three levels coarser than the surface's own footprint implies.
Leaving the line out puts the shader in mesh space, which is what sampling
`input.uv` is. `renderer.textureStreaming().textures` reads back the span each
texture was measured at and the level that span asked for.
**Compute shaders have their own assetType.** A `.computeShader/` folder gives compute the same zero-scaffolding contract surface/sky/post/screen get: you write only `@compute fn main` (+ helper fns/structs, **no `@group/@binding` lines**) and declare bindings in a sibling `bindings.yaml` (storage buffers, textures, samplers, storage textures, plus a `params:` uniform); the engine generates the `@group(0)/@binding(N)` declarations. Dispatch it through a resolved reference (`asset.resolve("name", "computeShader"):dispatch(...)`). See the `.computeShader` assetType README and `man compute`.
**Surface**, **sky**, **post-process**, and **screen** shaders all get
engine-generated scaffolding — you write only `fragment()` and declare properties in
`properties.yaml`; the engine generates the entry points and the group(1) material
interface. (Each domain's `fragment` takes a domain-specific input instead of
`FragmentData`: `SkyInput`, `PostInput`, or `ScreenInput` — see "Sky shaders" and
"Post-process & screen shaders" below.) Compute shaders get the same treatment via
the separate `.computeShader` assetType (write only `@compute fn main`, declare
bindings in `bindings.yaml`). The `compute` domain here writes its own
entry points directly — see `man compute`.
## Surface shaders
A surface shader writes **only** the parts that are unique to it. The engine owns
all the scaffolding — the vertex stage, every render-mode entry point
(`vs_main` / `fs_forward` / `fs_gbuffer`), group(0) (camera, transforms, lights,
shadows, and the material rows), and the material interface generated from
`properties.yaml` (`material` and your texture slots). Adding a render path never
touches your shader.
Inside `fragment()` you have access to exactly four things — nothing is hidden:
1. **`input: FragmentData`** — the interpolated per-fragment surface data the
engine hands you: world position, world normal, uv, view direction, vertex
colour, and more. Every field is in the `FragmentData` table below.
2. **`material.*` and your textures** — the material inputs **you** declare in
`properties.yaml`. The mapping is mechanical: a scalar property named `foo`
becomes `material.foo`; a texture property named `bar` becomes `bar` (the
texture) and `bar_sampler` (its sampler). `material` has **exactly** the fields
your `properties.yaml` declares and no others — to add an input, add a property.
List what a shader exposes with `shaderRef:getProperties()` or
`asset.inspect("<name>")`.
3. **Engine state** — the scene's camera, lights, time, and shadows that the
renderer binds for every surface shader. In a surface shader `uniforms.*`
(sun direction/colour, ambient, `camera_pos`, `time`) and the punctual
lights (`zero_point_light(i)`) are always in scope (a post-process shader
has neither; its section below names what it reads instead); the shadow functions come from `#include "@builtin::shaderModules.shadows"`,
and the light of the sky, the reflection probes and the light-probe volumes
from `zero_pbr_surroundings_light` in `@builtin::shaderModules.pbr_shading`. This is how
you light a surface **without** the prebuilt PBR — see "Engine state" and
"Writing your own shading" below.
4. **Library functions** you `#include` (see "Library includes").
A shader and its property schema go together. The two files below are a complete
surface shader:
`properties.yaml` — declares the material inputs:
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
- { name: roughness, type: float, default: 0.5, min: 0, max: 1 }
- { name: metallic, type: float, default: 0.0, min: 0, max: 1 }
- { name: base_color_texture, type: texture, default: white }
```
`shader.wgsl`; those declarations are read as `material.base_color`,
`material.roughness`, `material.metallic`, and the `base_color_texture` /
`base_color_texture_sampler` pair:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.pbr_shading" // the PBR helpers — see "Library includes"
fn fragment(input: FragmentData) -> vec4<f32> {
var s = zero_pbr_default_surface(input);
s.albedo = material.base_color.rgb
* textureSample(base_color_texture, base_color_texture_sampler, input.uv).rgb;
s.perceptual_roughness = material.roughness;
s.metallic = material.metallic;
return vec4<f32>(zero_pbr_shade(input, s), material.base_color.a);
}
```
`fragment()` returns the final colour. The engine forces no lighting model on
you — flat, toon, PS1, dithered, or PBR are all just different `fragment()`
bodies. Calling `zero_pbr_shade` is opt-in.
### The two surface bodies, and what each gives up
A surface shader exposes one of two entry points, and which one decides how
much of the shader the engine can see:
| Body | The engine gets | PBR debug passes and the G-buffer read |
|---|---|---|
| `fn fragment(input: FragmentData) -> vec4<f32>` | the finished pixel, and the surface behind it where the body hands one over: `zero_pbr_shade` hands over the `PbrSurface` it lights, and a body that lights itself hands over its own with `zero_publish_shaded_surface` | the surface the body handed over; where it handed none, the debug passes draw magenta, the "no data here" marker |
| `fn surface(input: FragmentData) -> PbrSurface` | the surface (albedo, roughness, metallic, emissive, normal, occlusion), which the engine then lights | the surface |
Both are first-class: `fragment()` is what you want when the shader owns its
own look, `surface()` when you want engine lighting. `capture { pass = "albedo" }`
(and `roughness` / `metallic` / `ao` / `emissive`) answers about your material
for either body wherever the engine has the surface — writing the same
`PbrSurface` behind `surface()` or behind `fragment()` + `zero_pbr_shade` gives
one answer per channel. `pbr.shader` exposes `surface()`.
#### Handing the engine the surface a self-lit body draws
A `fragment()` body that lights itself by its own math (toon, cel, flat, PS1,
dithered) states the surface it draws with one call, always in scope in a
surface shader:
```wgsl
zero_publish_shaded_surface(albedo, normal, emissive, perceptual_roughness, metallic, occlusion);
```
| Argument | Type | What it states |
|---|---|---|
| `albedo` | `vec3<f32>` | the colour the surface reflects, linear, in [0, 1] |
| `normal` | `vec3<f32>` | the world-space normal the body shades with (normal map applied) |
| `emissive` | `vec3<f32>` | the light the surface gives off, linear |
| `perceptual_roughness` | `f32` | 0 a mirror, 1 fully rough |
| `metallic` | `f32` | 0 a dielectric, 1 a metal |
| `occlusion` | `f32` | the material's own ambient occlusion, 1 none |
The call changes nothing about the pixel the body returns; it states what that
pixel is a picture of. The last call before `fragment()` returns is the one
the engine reads, and it reads it into:
- **The debug passes**: `albedo`, `roughness`, `metallic`, `ao`, `emissive` and
`reflection` answer with the stated surface instead of magenta, and `normal`,
`shadow` and `shadow_depth` read the stated normal.
- **The G-buffer**, on the deferred render path: its normal (`@scene.normal`,
`zero_scene_normal`) carries the stated normal, and its material
(`@scene.material`, `zero_scene_material`) the stated albedo, metallic and
roughness. Every screen-space feature and full-frame pass that reads the
surfaces reads these, among them screen-space reflections, contact shadows,
capsule occlusion, area lights, the environment lighting and radiance cache
passes, surface weather, temporal antialiasing's surface restate, and a
post-process effect or render feature reading the surface helpers.
A `fragment()` body that hands over nothing leaves the G-buffer holding the
triangle's interpolated normal, a base colour equal to the colour it returned
brought into [0, 1] by its largest component, metallic 0 and roughness 1, so
a pass that reads roughness takes it for a fully rough dielectric.
The emissive argument reaches the `emissive` debug pass. The light a surface
gives off is already in the colour its body returns, so it adds nothing to the
frame; `@scene.emissive` holds the light a later pass stamps onto the surface.
A cel-shaded body, its surface handed over:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.pbr_shading" // zero_pbr_surroundings_light
fn fragment(input: FragmentData) -> vec4<f32> {
let n = normalize(input.world_normal);
let albedo = zero_take_scene_decal(material.base_color.rgb);
let sun = normalize(-input.light_direction);
// The sun's N·L rounded to the nearest third: 0 on a face turned from the sun.
let band = round(max(dot(n, sun), 0.0) * 3.0) / 3.0;
let lit = input.light_color * input.light_intensity * band / ZPBR_PI
+ zero_pbr_surroundings_light(input, n, albedo);
zero_publish_shaded_surface(albedo, n, vec3<f32>(0.0), 1.0, 0.0, 1.0);
return vec4<f32>(albedo * lit, material.base_color.a);
}
```
`capture { pass = "normal" }` is a geometry read rather than a material one, so
it answers for every shader: the normal of the surface where one was handed
over, and the interpolated normal of the triangle where none was. It is the same
normal the frame's normal buffer carries, which is what a screen-space pass
reading `@scene.normal` sees.
`shaderRef:shadingModel()` reports which one a shader ended up with —
`"engine-lit"` for `surface()`, `"self-shading"` for `fragment()`.
#### Decals on a self-lit body
A decal projector stamps its colour over the opaque surfaces before anything
shades (`@scene.decal`). `zero_pbr_shade` lays it over the base colour it
lights, so a `surface()` material and a `fragment()` body lighting through
`zero_pbr_shade` show the decal lit and shadowed like the rest of the surface.
A body that lights itself takes the decal the same way by passing its base
colour through one call before its lighting:
```wgsl
let albedo = zero_take_scene_decal(material.base_color.rgb);
```
A body that takes none gets the decal laid over the colour it returned, unlit,
and over the albedo it published.
### Optional vertex hooks
```wgsl
// Displace geometry in OBJECT space. Runs on skinned meshes too (it sees the
// already-skinned, morph-applied local position). Return the modified vertex.
// The `v` parameter is immutable (WGSL function params are), so copy it into a
// `var` first and modify that.
fn vertex(v: VertexData) -> VertexData {
var out = v;
out.position += out.normal * sin(out.time) * 0.1;
return out;
}
// Post-transform vertex hook (runs AFTER the engine's world/skin/projection). Two
// things you can do here, separately or together:
// * move `clip_position` — vertex jitter, PS1 snapping, render-resolution lowering;
// * write `color` — PER-VERTEX (Gouraud) shading: light the vertex from its
// world_normal + the light context and the engine forwards the result into the
// interpolated `vertex_color` the fragment reads.
fn vertex_clip(v: ClipVertex) -> ClipVertex {
var out = v;
// Gouraud: Lambert sun + ambient, evaluated once per vertex (flat-banded shading).
let n_dot_l = max(dot(v.world_normal, -normalize(v.light_direction)), 0.0);
let lit = v.ambient_color * v.ambient_intensity + v.light_color * v.light_intensity * n_dot_l;
out.color = vec4<f32>(v.color.rgb * lit, v.color.a);
out.clip_position = round(out.clip_position * 80.0) / 80.0; // PS1 snap
return out;
}
```
#### Geometry built per instance: grass, kelp, hair cards, debris
`vertex()` knows which vertex of which instance it places:
`VertexData.vertex_index` is the vertex's index in its mesh and
`VertexData.instance_id` the instance's slot, whose lanes
`zero_object_data(v.instance_id, lane)` reads. A hook can therefore build its
geometry rather than displace it: a strip mesh drawn thousands of times by
`renderer.mesh.drawInstanced`, each copy shaped, sized and bent from the lanes
of its `instanceDataBuffer`, becomes a field of grass blades, kelp fronds or
hair cards that sway with `v.time`. Being a surface shader, it is lit,
shadowed (it casts the shape the hook built), motion-vectored and fogged like
the rest of the scene. The rendering-instance-data guide
(`guides { path = "topics/rendering-instance-data" }`) has a worked blade
field; a render feature's raster pass (`types/rasterShader`) is the
hand-written alternative, a vertex and fragment program with its own pipeline.
#### Declaring how far a hook moves geometry: `vertexBoundsDilation`
Static geometry is culled per cluster against its bounds as authored. A hook that moves vertices — wind sway, an outline hull, a vertex wave — can move them outside those bounds, and the cull then drops clusters whose displaced triangles are still on screen. Declare the farthest the hook moves any vertex, in world units, as a `vertexBoundsDilation` float property, with a default that covers the shader's own properties across their ranges:
```yaml
properties:
- { name: sway, type: float, default: 0.5, min: 0, max: 4 }
# 0.4 x sway, at sway's largest value.
- { name: vertexBoundsDilation, type: float, default: 1.6, min: 0, max: 100 }
```
Each material sets its own value (a material that sways less can set less, one moved farther sets more), and a material that sets none takes the default. The cull adds the material's value to every bound in its frustum and occlusion tests (not to the level-of-detail cut). A shader with a hook and no `vertexBoundsDilation` property is named once in the engine log when it compiles; no camera view culls its geometry, by frustum, screen size or occlusion, so every camera draws it wherever it stands.
### Structs the engine passes you
`FragmentData` (input to `fragment()`):
| Field | Type | Meaning |
|---|---|---|
| `world_position` | `vec3<f32>` | fragment world-space position |
| `world_normal` | `vec3<f32>` | interpolated geometric normal (normalized) |
| `world_tangent` | `vec4<f32>` | xyz = world tangent, w = handedness (mikktspace) |
| `uv` | `vec2<f32>` | primary texture coordinates (perspective-correct) |
| `affine_uv` | `vec2<f32>` | the same UVs interpolated **without** perspective correction — the PS1 texture "swim". Always available; sample with it instead of `uv` for affine texture mapping |
| `vertex_color` | `vec4<f32>` | interpolated per-vertex colour (white if unset; carries per-vertex lighting if `vertex_clip()` wrote it — see Gouraud below) |
| `view_position` | `vec3<f32>` | camera world position |
| `view_direction` | `vec3<f32>` | normalized world-space direction the camera sees this point from: toward the camera's position under a perspective projection, against its forward axis (the same for every point) under an orthographic one |
| `light_direction` | `vec3<f32>` | directional (sun) travel direction, unit length; surface→sun is `-light_direction`. Where no sun reaches the camera it points straight down |
| `light_color` | `vec3<f32>` | sun colour |
| `light_intensity` | `f32` | sun intensity; 0 where no sun reaches the camera |
| `ambient_color` | `vec3<f32>` | the colour of the scene's flat ambient term, one colour for every direction. The light of the reflection probes and the light-probe volumes along a normal, which a PBR surface takes as well, is `zero_pbr_surroundings_light`; a sky light adds the sky's light to the surface the G-buffer holds on the deferred path, and `zero_pbr_surroundings_light` holds it on the forward path (see "Engine state") |
| `ambient_intensity` | `f32` | the flat ambient term's intensity as it reaches this pixel: the scene's ambient occlusion is already in it (times `ambient_visibility`), so a crease darkens under the ambient with no work in the shader |
| `ambient_visibility` | `f32` | the share of the light of its surroundings that reaches this pixel: 1 minus the scene's ambient occlusion here, 1 where nothing occludes it. Multiply it into any light of the surroundings you gather yourself (a sky colour, a reflection-probe or environment sample); `ambient_intensity` already carries it. `zero_scene_bent_normal(input.frag_coord.xy, n)` names the direction the open part of the hemisphere faces, `n` where no pass wrote one |
| `frag_coord` | `vec4<f32>` | framebuffer pixel coords (xy) + depth (z) — for screen-space dither |
| `receives_shadows` | `f32` | per-instance: > 0.5 if this surface receives shadows |
| `material_index` | `u32` | per-instance: the index standing for the material this surface draws with — the number `renderer.materialIdentity()` maps to a name |
| `instance_id` | `u32` | per-instance: the instance's slot, the value `VertexData.instance_id` carries. `zero_normal_matrix(input.instance_id)` is the transform that turns an object-space normal into a world normal |
| `shader_data` | `array<vec4<f32>, 4>` | per-instance: this entity's own four `vec4` lanes — its `ecs.ShaderData` component's `lane0`..`lane3`, or what `renderer.instanceData.set` put in them (zero until something does). A procedural graph's elements set them through the `data0`..`data3` attributes |
| `front_facing` | `bool` | true for front faces (double-sided shading) |
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
`shader_data` is the per-instance channel, and it is what lets ONE material serve
many entities that differ in a value — a dissolve at its own progress per subject,
a hit flash at its own age, a fill level per instance. The alternative is a
material per entity, which is a separate pipeline binding and a separate row in
the material table for every one of them.
```wgsl
const DISSOLVE_LANE: u32 = 0u;
fn fragment(input: FragmentData) -> vec4<f32> {
let progress = input.shader_data[DISSOLVE_LANE].x;
...
}
```
```lua
-- one material on twenty entities, each at its own progress
renderer.instanceData.set(subject, 0, progress)
renderer.instanceData.clear(subject) -- back to zero lanes
```
The engine attaches no meaning to a lane: a shader and whatever writes it agree
what each one carries. Name the indices in the module that writes them.
`renderer.instanceData.laneCount()` is how many there are. The same lanes reach a
hardware-instanced population through `renderer.mesh.drawInstanced`'s
`instanceDataBuffer`, on slots no entity owns.
`VertexData` (in/out of `vertex()`): `position` (object-local, model-scale + morph
applied; on a skinned mesh, where this frame's pose holds it), `rest_position`
(object-local, where the vertex stands at rest: before its morph targets and its
pose, the same place every frame, so a pattern or a placed image laid in it stays
on the skin however the skeleton moves it; on a mesh no skin poses, the position
as the mesh stores it; in a depth view, the position), `normal`, `uv`, `color`,
`time`, and which vertex of which instance it
is: `instance_id` (`u32`, the instance's slot — `zero_object_data(v.instance_id,
lane)` reads the lanes the fragment gets as `shader_data`) and `vertex_index`
(`u32`, the vertex's index in its mesh). Both hold the same values in the colour
pass, the depth views, every shadow page and the previous-frame evaluation, so
geometry a hook builds from them — a blade placed and bent by its instance's
lanes, a strip shaped by its vertex's index — lands in the same place in each.
The rendering-instance-data guide has a worked blade field.
`ClipVertex` (in/out of `vertex_clip()`) — the post-transform vertex. Read context:
`clip_position`, `world_position`, `world_normal`, `uv`, `view_position`,
`view_direction`, `light_direction`, `light_color`, `light_intensity`,
`ambient_color`, `ambient_intensity`, `time`, `view_proj` (the view-projection of
the frame being evaluated), and where the vertex stands on its instance:
`local_position` (its position in the mesh, after `vertex()` and before the
instance's world transform), `object_origin` (the world position of the instance's
origin), `object_scale` (the world length of the instance's x, y and z axes) and
`object_axes` (`mat3x3<f32>`, the world direction of those axes, unit length) —
what a camera-facing card, a shard grown about its own base, or anything placed
per instance is built from. **Writable:** `clip_position` (snap /
jitter) and `color` (write a lit colour here for per-vertex Gouraud shading; the
engine forwards it to the interpolated `vertex_color` — left untouched, the mesh's
own vertex colour passes through).
`vertex()` and `vertex_clip()` run in the vertex stage, which reads the frame
uniforms (`uniforms.*`, and the `ClipVertex` members built from them), the scene
buffer (`zero_object_data`, `zero_object_visuals`, the node transforms), the
material interface and a `read` buffer property. The point, spot and area lights
(`zero_point_light`, `zero_punctual_projection`), the shadow maps, the
environment and light probes, the feature textures, the scene depth, colour and
reflection copies and a `@group(2)` buffer the shader declares `read_write` are
visible to the fragment stage alone: read them in `fragment()` or `surface()`. A
shader whose vertex hook reaches one fails to compile, and the error names the
stage, the binding and the calls that reach it.
### Each hook runs twice: this frame and the one before it
A vertex hook decides where the surface IS, so it also decides where the surface
WAS. The engine runs every hook a shader declares a second time, over the same
vertex standing one frame back — the previous-frame position stream, with
`time` = the clock that frame was drawn at and (for `vertex_clip()`)
`view_proj` = the view-projection it was drawn with. The motion vector the
renderer publishes is taken between the two results, so a displacement that
moves with time reports the velocity of the displaced surface, and a
displacement that does not move reports the motion of the transform alone
because the identical offset appears on both evaluations and cancels.
What that asks of a hook:
- **Take the frame from the argument.** `v.time` is the clock of the evaluation
being run; `uniforms.time` is always this frame's. A displacement built on
`uniforms.time` is identical on both evaluations, so its motion vector cancels
to exactly zero. The same holds for `v.view_proj` against
`uniforms.view_proj`: a clip hook that rebuilds its position from world space
through `uniforms.view_proj` reprojects the previous frame with this frame's
camera, and reports no camera motion at all. The wind helpers come in both
shapes for this reason — `zero_wind_sway_at_time(world_pos, stiffness, v.time)`
inside a hook, `zero_wind_sway(world_pos, stiffness)` outside one.
- **Anchor a wrap to `uniforms.time`.** A displacement that jumps discontinuously
— a falling drop that restarts at the top, a looping offset — differences its
jump as velocity on whichever frame it wraps. Compute the wrap COUNT from
`uniforms.time` and the position within the cycle from `v.time`, and both
evaluations share the same cycle, so the surface reports the speed it fell at.
`@builtin::shaders.rain_material` and `snow_material` do exactly that.
The per-vertex attributes (`world_normal`, `uv`, `color`) and the lighting and
camera-position context are this frame's on both evaluations, so a hook that
displaces along its normal reports the motion of the transform plus this frame's
displacement.
## Engine state — point lights & shadows
This is what the renderer binds for a **surface** shader. A post-process
shader reads none of it: its engine state is `PostEngineData` (see
"Post-process & screen shaders"), and a full-frame effect driven by the scene's
lights takes the render-feature route that section names.
The common lighting state — the sun (`input.light_direction` / `light_color` /
`light_intensity`), the scene's flat ambient term (`input.ambient_color` /
`ambient_intensity`), the camera (`input.view_position` / `view_direction`), and
`input.time` — is already on `FragmentData`, so most shaders never touch the raw
engine state. The flat ambient term is one colour for every direction; the
light the reflection probes and the baked light-probe volumes hand a surface
along its normal comes from `zero_pbr_surroundings_light(input, n, albedo)`
(`@builtin::shaderModules.pbr_shading`), which holds the flat term as well and is
the ambient light a PBR surface is lit by. The sky's light reaches a surface
through a sky light (`@builtin::systems.sky.skyLight`). On the deferred path it
adds that light to every lit pixel by the surface the G-buffer holds there: a
self-lit body's is the one it publishes (see "Handing the engine the surface a
self-lit body draws"), so a body that publishes its surface takes the sky's
light a PBR surface takes. On the forward path, and for every surface the
G-buffer pass does not draw (transparent, water), the sky light fills the
environment's sky slot and `zero_pbr_surroundings_light` holds its diffuse
light. The one thing not
on `FragmentData` is the punctual-light array (its length varies), which is always
in scope. A scene can hold up to 1024 lights, so a fragment walks the ones the
light grid lists where it stands, which hold every light that can reach it:
| Expression | Type | Meaning |
|---|---|---|
| `zero_lights_near(world_pos)` | `ZeroLightsNear` | the lights that can reach a fragment at `world_pos`; `.count` of them |
| `zero_light_near(near, k)` | `u32` | the index of the `k`th of them, for `zero_point_light` |
| `uniforms.point_light_count` | `u32` | number of lights the frame shades under, every one of them |
| `zero_point_light(i)` | `PointLightData` | one point or spot light (fields below) |
| `zero_punctual_projection(i)` | `PunctualProjection` | a spot or area light's projection: `view_proj`, the frustum its cookie and shadow are placed by, and `cookie_layer` |
`PointLightData`: `position`, `radius`, `color`, `intensity`, `direction`,
`cone_outer_cos`, `cone_inner_cos`, `kind` (0 = point, 1 = spot).
Shadows come from `#include "@builtin::shaderModules.shadows"`:
- `compute_directional_shadow_factor(world_pos, normal, light_dir) -> f32` — 1.0 lit, 0.0 fully shadowed.
- `compute_spot_shadow_factor(...)` / `compute_point_shadow_factor(...)` / `compute_area_shadow_factor(...)` — one shadow shape each.
- `compute_punctual_shadow_factor(light_index, world_pos, normal) -> f32` — the row's own shape, read off its `kind`, for a loop that walks the punctual lights and does not want the switch.
- `zshadow_light_reach(light_index, world_pos, normal, object_channels) -> f32` — how much direct light that row puts on a surface on those light channels: the channel mask, falloff, cone or rect orientation, and the cosine, times intensity. Zero exactly where the light contributes nothing.
## Writing your own shading
The engine forces no lighting model — `zero_pbr_shade` is just one option. You can
light a surface yourself from the state above. Here is a complete custom-lit
(Lambert diffuse) surface that takes the engine's lights and surroundings and
no PBR BRDF:
```wgsl
// @domain: surface
#include "@builtin::shaderModules.pbr_shading" // zero_pbr_surroundings_light; brings in the shadow functions
fn fragment(input: FragmentData) -> vec4<f32> {
let n = normalize(input.world_normal);
let albedo = material.base_color.rgb;
// Directional (sun) light: Lambert N·L, attenuated by its shadow.
let sun = normalize(-input.light_direction); // surface -> sun
let sun_shadow = compute_directional_shadow_factor(input.world_position, n, input.light_direction);
var direct = input.light_color * input.light_intensity * max(dot(n, sun), 0.0) * sun_shadow;
// Point + spot lights: the ones that can reach this fragment.
let near = zero_lights_near(input.world_position);
for (var k = 0u; k < near.count; k = k + 1u) {
let pl = zero_point_light(zero_light_near(near, k));
let to_light = pl.position - input.world_position;
let dist = length(to_light);
let l = to_light / max(dist, 1e-4);
let atten = max(1.0 - dist / max(pl.radius, 1e-4), 0.0);
direct += pl.color * pl.intensity * max(dot(n, l), 0.0) * atten;
}
// A Lambert surface sends back albedo / π of the direct light on it,
// the diffuse lobe of the PBR model.
var lit = direct / ZPBR_PI;
// The light of the surroundings: the flat ambient, the reflection probes
// and the baked light-probe volumes, with the scene's ambient occlusion in
// it — the ambient light a PBR surface takes. It is irradiance already
// weighed for a diffuse surface, so it takes no π.
lit += zero_pbr_surroundings_light(input, n, albedo);
// The surface this pixel draws, for the debug passes and the G-buffer; a
// sky light adds the sky's light to the surface stated here.
zero_publish_shaded_surface(albedo, n, vec3<f32>(0.0), 1.0, 0.0, 1.0);
return vec4<f32>(albedo * lit, material.base_color.a);
}
```
The example declares `base_color` in its `properties.yaml`:
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
```
- **Unlit:** skip the lights and return your colour directly.
- **Toon / PS1 / custom:** start from the body above and band, quantize, or warp
it however you like. Keep the direct light over π and `zero_pbr_surroundings_light`
as the ambient term, and the surface stands at the brightness of the PBR
materials around it; the flat
ambient (`input.ambient_color * input.ambient_intensity`) alone leaves out the
reflection probes and the light-probe volumes.
- **PBR:** build a `PbrSurface` and call `zero_pbr_shade` (see "Library includes")
instead of writing the BRDF by hand. It hands the engine the surface itself.
## Material properties — `properties.yaml`
A surface shader declares its material properties in a sibling `properties.yaml`.
The engine GENERATES the entire group(1) interface from it — the uniform struct
(`material.<name>`) plus a texture/sampler pair per declared texture. You write
no `@group`/`@binding` lines.
```yaml
properties:
- { name: base_color, type: color, default: [1, 1, 1, 1] }
- { name: roughness, type: float, default: 0.5, min: 0, max: 1 }
- { name: metallic, type: float, default: 0.0, min: 0, max: 1 }
- { name: emissive, type: color, default: [0, 0, 0, 1] }
- { name: base_color_texture, type: texture, default: white }
- { name: normal_texture, type: texture, default: flat_normal }
```
| `type` | WGSL field type | Notes |
|---|---|---|
| `float` | `f32` | optional `min`/`max` for editor sliders |
| `float2`/`float3`/`float4` | `vec2/3/4<f32>` | |
| `color` | `vec4<f32>` | linear RGB colour and alpha, default is `[r,g,b,a]`; the shader reads it as written |
| `int` | `i32` | |
| `bool` | `u32` | |
| `texture` | `texture_2d<f32>` + `sampler` | `default:` is a built-in texture name (`white`, `black`, `flat_normal`) |
A `color` holds linear RGB, the space lighting is computed in, the way `base_color` multiplies a colour texture's
linear sample. A colour picked from a picture or written as a hex code is sRGB, and written as it is it reads paler
and less saturated than picked: convert it first, `color.toLinear(assert(color.hex("#ff8800")))` (`{ r, g, b, a }`:
`#ff8800` is `{ r = 1, g = 0.246, b = 0, a = 1 }`), and write that.
In the shader you read scalars as `material.<name>` and sample textures as
`textureSample(<name>, <name>_sampler, uv)`. A texture slot with no bound texture
samples its default, so a shader can always sample — no presence flag needed.
`vertex()` reads the same material interface, so a height or deformation map
drives displacement from the slot it was bound to. A vertex stage has no implicit
derivatives, so sample it at an explicit mip there:
`textureSampleLevel(<name>, <name>_sampler, uv, 0.0)`.
## Sky shaders
A `// @domain: sky` shader draws the sky as a fullscreen pass. You write **only**
`fn fragment(in: SkyInput) -> vec4<f32>` — the colour along the view ray for each
pixel — and declare tunables in `properties.yaml` exactly like a surface shader
(read as `material.<name>`, textures via `textureSample(<name>, <name>_sampler, uv)`).
The engine generates the fullscreen `vs_main`/`fs_main`, the group(1) interface,
and reconstructs the world-space ray; there is no separate sky renderer — a sky
material runs through the same material pipeline, just on a fullscreen triangle.
A sky pipeline binds group(0) and the group(1) interface alone, so a sky that
reads a `buffer` property or any other `@group(2)` binding fails to compile, and
the error names the binding and the calls that reach it.
`SkyInput` (the only argument) carries:
| Field | Type | Meaning |
|---|---|---|
| `ray_dir` | `vec3<f32>` | normalized world-space ray through this pixel |
| `ndc` | `vec2<f32>` | screen position in NDC `[-1, 1]` |
| `sun_direction` | `vec3<f32>` | unit vector TOWARD the sun (from the directional light) |
| `camera_pos` | `vec3<f32>` | world-space camera position |
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
| `constants` | `SkyConstants` | what the shader's `sky_constants()` returned for this draw (zeros when it declares none) |
```wgsl
// @domain: sky
fn fragment(in: SkyInput) -> vec4<f32> {
let up = max(in.ray_dir.y, 0.0);
let col = mix(material.horizon_color.rgb, material.zenith_color.rgb, up);
return vec4<f32>(col * material.exposure, 1.0);
}
```
Day/night comes from `sun_direction.y` (the directional light's elevation), so a
sky shader never needs a time-of-day uniform — orient the light and the sky
follows. The builtin sky shaders (`procedural_sky`, `solid_sky`, `cubemap_sky`,
`equirect_sky`) are all authored this way; author a custom sky material and point
a `Skybox` component at it.
`fragment()` runs once for every pixel of the view and every texel of each
environment-capture face. A value that holds for the whole draw (a colour mixed
from the material and the sun's elevation, a `cos` of an angular size, an
exponent derived from a property) goes in an optional
`fn sky_constants(in: SkyConstantsInput) -> SkyConstants`, which the generated
vertex stage evaluates once per draw. `fragment()` reads its result as
`in.constants`. `SkyConstantsInput` carries `sun_direction`, `camera_pos` and
`time` (the same values `SkyInput` holds), `sky_constants()` reads the material
as `material.<name>` like `fragment()`, and `SkyConstants` is eight `vec4<f32>`
slots, `v0` to `v7`, packed however the sky likes:
```wgsl
// @domain: sky
fn sky_constants(in: SkyConstantsInput) -> SkyConstants {
let day = clamp(in.sun_direction.y * 2.0, 0.0, 1.0);
var c: SkyConstants;
c.v0 = vec4<f32>(mix(vec3<f32>(0.02), material.zenith_color.rgb, day), day);
c.v1 = vec4<f32>(mix(vec3<f32>(0.01), material.horizon_color.rgb, day), 0.0);
return c;
}
fn fragment(in: SkyInput) -> vec4<f32> {
let up = max(in.ray_dir.y, 0.0);
return vec4<f32>(mix(in.constants.v1.rgb, in.constants.v0.rgb, up), 1.0);
}
```
A branch on an `in.constants` value is taken or skipped by every pixel of the
draw together, so a term that only contributes some of the time (stars at
night) costs nothing while it is off. The vertex stage has no implicit
derivatives, so a texture read in `sky_constants()` is `textureSampleLevel`.
## Post-process & screen shaders
`// @domain: post-process` and `// @domain: screen` shaders are authored exactly
like surface and sky — you write **only** `fn fragment(in: PostInput) -> vec4<f32>`
(post) or `fn fragment(in: ScreenInput) -> vec4<f32>` (screen) and declare tunables
in `properties.yaml` (read as `material.<name>`, textures via
`textureSample(<name>, <name>_sampler, uv)`). The engine generates the fullscreen
`vs_main`/`fs_main` and the group(1) material interface. **There are no
`uniforms.params[i]` slots** — that convention is retired; every input is a named
property.
A **post-process** shader's `properties.yaml` carries one further, top-level key
beside `properties:` — `space`, either `light` (the default) or `display`:
```yaml
space: display
properties:
- { name: amount, type: float, default: 1.0, min: 0, max: 1 }
```
`light` is the scene's linear radiance — what every surface, the sky and every
`afterLighting` feature write, unbounded above 1.0. `display` is the code values
the `__display__` pass leaves behind after applying exposure and its tone curve
— the 0-1 range a colourist's tool and a dithered or quantized effect expect.
`postprocess.add`'s `opts.space` overrides what the asset declares for one
registration. The chain converts at both ends of an effect that runs on a
segment in the other space, so a light-space vignette still darkens a frame
graded after `__display__`, and a lookup table built from a `.cube` export
always sees the code values it was authored against, wherever the chain
runs it.
`space` also decides which layer a registration that names none lands on: a
`light` shader grades `scene`, the segment holding the scene's own light, and a
`display` shader grades `display`, the picture after `__display__` and before
the UI lands on it. So `postprocess.add("glow", asset.resolve("~.shaders.bloom",
"shader"))` thresholds highlights that still stand above 1.0, and a lookup
table registered the same way reads the code values it was built for and leaves
every screen in the colours it declares. `opts.layer` names one explicitly —
`"all"`, after the UI, is what an effect that must grade the interface says.
A post-process shader may also declare the post stage of the frame it runs in,
`stage:` — `optics` (the `scene` layer), `display` (the `display` layer) or
`ui` (the `all` layer); `renderer.post.stages()` lists every stage with the
colour space and resolution its picture is held in. A registration takes the
declared stage unless `opts.stage` or `opts.layer` names another seam, and a
stage the frame does not have, or one only render features run in, is refused
naming the stages there are:
```yaml
space: display
stage: display
properties:
- { name: amount, type: float, default: 1.0, min: 0, max: 1 }
```
A **post-process** shader's `properties.yaml` carries a further, optional
top-level key — `passes:`, the pass list the frame draws through, in order:
```yaml
space: light
passes:
- { name: bright, entry: bright, scale: 0.5, inputs: [scene] }
- { name: down1, entry: downsample, scale: 0.25, inputs: [bright] }
- { name: up0, entry: upsample, scale: 0.5, inputs: [down1, bright] }
- { name: composite, entry: composite, inputs: [scene, up0] }
```
Every pass's entry — `fn <entry>(in: PostInput) -> vec4<f32>` — lives in the
one `shader.wgsl` the assetType recompiles on. `scale` is the fraction of the
view a pass draws at; the LAST pass takes none, since it draws at the view's
size and writes the chain's output. `lines`, optional, is a frame height the
pass's size is measured against: a pass declaring `lines: 1080` draws at the
size it has in a 1080-line view of the same shape, `scale` times 1080 texels
tall and as wide as the view's shape makes it, so each of its texels spans
the same share of the view's height at every output resolution and a filter
measured in its texels covers the same share of the picture on a phone, a
monitor and a 4K screen. A pass that would draw larger than the view draws
at the view's own size. `maxLines`, optional, is the tallest view the pass's
size is measured against: a pass declaring `scale: 0.5, maxLines: 1080` draws
at half of a view 1080 lines tall or shorter, and at the size it has in a
1080-line view of the same shape on a taller one, 540 texels tall at 1440 and
at 2160 lines, so it costs a 4K screen no more texels than a 1080p one while a
smaller view draws it at its own half. A pass declares one of `lines` and
`maxLines`. `inputs` names what a pass reads —
`"scene"`, the chain's input for this effect, or the name of an EARLIER pass —
and `inputs[0]` is what `zero_sample_scene(uv)` reads inside that pass's body;
every input, `inputs[0]` included, is also reachable by index through
`zero_pass_input(i, uv)` and `zero_pass_input_size(i)`, below. The one place
the two reads of `inputs[0]` disagree: in an effect whose declared space
differs from the segment it draws on, `zero_sample_scene` converts a `scene`
input into that space while `zero_pass_input(0, uv)` hands back the segment's
own, unconverted value. A shader declaring no `passes:` is one pass whose
entry is `fragment`, and its generated WGSL is byte-identical to what it is
without the key.
A pass that is not the last writes a scratch target the effect owns — in the
space the shader declared, at the size its `scale` and `lines` or `maxLines` give it —
allocated on the first draw and replaced whenever the size changes. `engine.params`, below,
carries the drawing pass's own index, the fraction of the view it draws at
(its `lines` or `maxLines` applied), and its first input's texel size, so one shader body serves every
level of a chain built this way.
The worked example is the bloom: `@builtin::shaders.post.bloom` declares
sixteen passes — a threshold pass, seven downsamples, seven tent upsamples and
a composite — out of four entries, since the seven downsamples share one and
the seven upsamples share another, each level reading the one below it through
`zero_pass_input`, telling itself apart by its own size (`engine.resolution`)
and its inputs' (`zero_pass_input_size`), and weighing itself by the share of
the frame's height its texel spans. Its own README
walks the declaration.
A declaration is refused at compile time — reported through `compileStatus()`,
`postprocess.add`'s second return value, or a live effect's
`status()[i].error` — for: an entry `passes:` names that `shader.wgsl` does
not define; an input naming a later pass, or naming neither `scene` nor an
earlier pass; a `scale` outside `(0, 1]`; a `scale`, a `lines` or a `maxLines` declared
on the last pass; a negative or non-finite `lines` or `maxLines`; a pass declaring both
`lines` and `maxLines`;
a `buffer` property (group(2) carries the pass inputs); or a shader whose
group(0) plus declared texture slots plus widest pass's inputs ask for more
than the 16 FRAGMENT sampled textures one shader stage has.
A **post-process** shader runs as a full-screen pass over the already-rendered
frame. Its `fragment` argument and framework helpers:
`PostInput`:
| Field | Type | Meaning |
|---|---|---|
| `frag_coord` | `vec4<f32>` | framebuffer pixel coords (`@builtin(position)`) |
| `uv` | `vec2<f32>` | screen UV, `(0,0)` top-left … `(1,1)` bottom-right |
Framework helpers (always in scope — no include needed):
| Call | Returns | Meaning |
|---|---|---|
| `zero_sample_scene(uv)` | `vec4<f32>` | the rendered scene colour at `uv`, converted into the space this effect declared (`zero_scene_light` is the same call, for content that reads it by that name) |
| `zero_scene_depth(uv: vec2<f32>)` | `f32` | scene depth at `uv` — a screen UV here, where the surface domain's `zero::scene_depth` module takes a pixel coordinate under the same name (exact texel — an R32Float copy). Reversed: 1.0 is the near plane, 0.0 the far plane and empty sky, so a nearer surface reads GREATER and `d > 0.0` means "a surface was drawn here" |
| `zero_linear_depth_through(d, engine.view_proj, zero_camera_position())` | `f32` | that sample as a distance in metres along the camera's view axis, read through the camera that drew it: its near and far planes and its kind of projection — the one inversion of the reversed range (`zero_linear_depth(d, near, far)` is the perspective inversion given the planes themselves) |
| `zero_scene_motion(uv)` | `vec2<f32>` | per-pixel screen-space motion vector at `uv` |
| `zero_pass_input(i, uv)` | `vec4<f32>` | the pass's declared input `i`, at `uv`. Input 0 is what `zero_sample_scene` reads |
| `zero_pass_input_size(i)` | `vec2<f32>` | that input's size in texels, so one entry serves every level of a chain |
| `zero_view_size()` | `vec2<f32>` | the size in pixels of the view the pass draws for: the frame the chain delivers, whatever fraction of it the pass draws at. A filter measured against it (a fraction of the frame's height) holds one look at every output resolution |
| `zero_camera_position()` | `vec3<f32>` | the world position of the camera the render being drawn looks from — the camera `engine.view_proj` belongs to, so on a capture or a render-to-texture camera it is that camera's. With a world position reconstructed from `zero_scene_depth(uv)` and `engine.inv_view_proj`, `normalize(world - zero_camera_position())` is the view ray |
| `zero_scene_surfaces_drawn()` | `bool` | whether the scene's surface channels (the helpers below) hold the surfaces of the render being drawn: true on the deferred path from `afterOpaque` on, false on the forward path, which draws no G-buffer |
| `zero_scene_normal(uv)` | `vec3<f32>` | the world-space normal of the surface at `uv` (`@scene.normal`), unit length; +Z where no surface stands, (0, 0, 0) where `zero_scene_surfaces_drawn()` is false |
| `zero_scene_surface_flags(uv)` | `u32` | the surface flags the geometry pass wrote at `uv` (`@builtin::shaderModules.surface_flags`' `ZERO_SURFACE_FLAG_*`, in scope with the helper); 0 where `zero_scene_surfaces_drawn()` is false |
| `zero_scene_material(uv)` | `ZeroGbufferMaterial` | what the surface at `uv` IS (`@scene.material`): `.base_color`, `.metallic`, `.perceptual_roughness`, each in [0, 1], unpacked by `@builtin::shaderModules.gbuffer_material`, which the surface group includes |
| `zero_scene_shaded(uv)` | `vec4<f32>` | what the surface at `uv` SENT (`@scene.shaded`): its shaded colour, linear, with its coverage in alpha |
| `zero_scene_emissive(uv)` | `vec4<f32>` | the radiance passes stamped on the surface at `uv` (`@scene.emissive`) |
| `zero_display_exposure()` | `f32` | the exposure in force: the gain `__display__` multiplies the scene's light by before its curve, the value this frame's display pass draws with (1 where the chain carries none). Light times it is light in the units the picture shows it at, so a threshold judged against `light * zero_display_exposure()` picks the same highlights at every exposure |
| `zero_middle_grey()` | `f32` | for an effect in light: the light `zero_sample_scene` reads that the picture shows as middle grey, 0.18 over the exposure in force on a segment holding the scene's light and 0.18 on a segment `__display__` already drew. What a grade pivots its contrast on, so middle grey holds where the picture shows it at every exposure |
| `zero_picture_white()` | `f32` | for an effect in light: the light the picture's white stands at, the peak a grade holds. 1 (the white an SDR picture peaks at) on a segment `__display__` already drew, and 0 on a segment holding the scene's light, which has no peak |
Engine data uniform `engine` (a `PostEngineData`):
| Field | Type | Meaning |
|---|---|---|
| `resolution` | `vec4<f32>` | `x`=width, `y`=height, `z`=1/width, `w`=1/height |
| `time` | `vec4<f32>` | `x`=elapsed seconds, `y`=dt, `z`=frame index |
| `view_proj` | `mat4x4<f32>` | this frame's view-projection |
| `prev_view_proj` | `mat4x4<f32>` | last frame's view-projection (motion) |
| `inv_view_proj` | `mat4x4<f32>` | inverse view-projection (world-space reconstruction) |
| `params` | `vec4<f32>` | `x`=this pass's own index, `y`=the scale it draws at, `zw`=1/size of its first input — for a pass the post-process chain draws. A pass a `renderFeature` fragment pass draws carries that feature's `spec.params` here instead; a shader declaring `passes:` is always drawn by the chain, so the two never meet in one shader. |
| `exposure` | `vec4<f32>` | `x`=the exposure in force (what `zero_display_exposure()` reads) |
| `camera_position` | `vec4<f32>` | `xyz`=the world position of the camera being drawn (what `zero_camera_position()` reads) |
| `surfaces` | `vec4<f32>` | `x`=1 where the surface helpers read the render's own surfaces (what `zero_scene_surfaces_drawn()` reads) |
| `view` | `vec4<f32>` | `x`=width, `y`=height, `z`=1/width, `w`=1/height of the view the pass draws for (what `zero_view_size()` reads); the same as `resolution` on a pass drawn at the view's size |
The engine fills all of it **per render target**. A registered effect runs over
the live viewport's frame AND over every offscreen one — a `capture` from a
world-space station or orbiting an entity, a capture of a named camera, a
render-to-texture camera — and in each of those, `view_proj`, `prev_view_proj`
and `inv_view_proj` are the camera THAT render was drawn from, while
`resolution` is that target's own pixel size. So a pass reconstructing world
space from `zero_scene_depth(uv)` reconstructs against the station and lens the
capture asked for, and an offscreen frame is a picture of the effect as it
stands at that station. (A render feature's passes reach an offscreen render the
same way, against the same camera — the `renderFeature` assetType README carries
that half, including `@frame.camera`, its own per-target camera input.)
**The scene's surfaces.** The surface helpers above read the deferred path's
G-buffer, the same channels a render feature names as `@scene.normal`,
`@scene.material`, `@scene.shaded` and `@scene.emissive`, by screen uv at the
exact texel (the channels are at the scene's raster size, so a pass at a
`scale`, or after an upscale, reads the surface that stands at that point of
the picture). A shader that names any of them compiles with the surface group,
`group(3)`, which spends four of the stage's sampled textures beside its own
slots and pass inputs; the render keeps a channel only while a running effect,
or a render-feature pass's shader, reads it; a channel counts as read when an
entry point of the compiled shader reaches its helper, so a helper in an
included function nothing calls reads nothing. They hold this frame's surfaces
at every layer of the chain and at every render-feature phase from
`afterOpaque` on. With temporal antialiasing running, every layer of the chain
reads the normal and the material restated at each pixel's centre, with no
sub-pixel offset, so an outline found in the normals holds still under a still
camera; `zero_scene_shaded` and
`zero_scene_emissive` read the raster's own, with its sub-pixel offset. The
renderFeature type README states the whole contract by stage and path.
The forward path draws no G-buffer, so there every helper reads zero and
`zero_scene_surfaces_drawn()` false: a look that needs the surfaces draws a
picture of its own there (from depth, say) instead of reading a wrong one, and
`postprocess.status()` names the channels the effect `reads` and, after a frame
it drew with the substitute, the `substituteReason`.
```wgsl
// @domain: post-process
fn fragment(in: PostInput) -> vec4<f32> {
let c = zero_sample_scene(in.uv);
if !zero_scene_surfaces_drawn() || zero_scene_depth(in.uv) <= 0.0 { return c; }
let n = zero_scene_normal(in.uv);
let m = zero_scene_material(in.uv);
let rim = pow(1.0 - abs(n.y), 4.0);
return vec4<f32>(mix(c.rgb, m.base_color, rim * material.amount), c.a);
}
```
**Lights.** A post-process shader reads no light data: `uniforms`,
`zero_point_light(i)` and the light grid are the surface framework's, and a
post shader naming them does not compile. An effect driven by the scene's
lights (light shafts, a glow around each lamp, a scatter through fog) is a
render feature pass at a scene phase (`afterDepthPrepass` through
`afterLighting`) that binds `@scene.lights`, the punctual-light buffer (the
renderFeature type README states its layout), with `@frame.camera` for the
camera; the beams lights throw through the air are already the built-in
`VolumetricLighting` component, whose `lightScattering` render feature
(`@builtin::systems.volumetrics`) marches the view rays through the scene's own
lights.
An offscreen render keeps no view history of its own, so `prev_view_proj` there
holds that same matrix rather than the frame before it, and a pass taking camera
motion from the two reads none. On the viewport the pair is a frame apart, so
camera motion is the one reading a capture answers differently from the screen.
`postProcessing = false` on a capture is the one control that takes the chain
off the frame it returns; it names the camera property the ephemeral capture
camera is built with, so it scopes to that one capture. What a capture opts out
of is the registered effects; `__display__` still runs on it, so the exposure
and tone curve that turn the scene's light into a picture are on what a capture
returns.
A diagnostic capture (`albedo`, `normal`, `motion_vectors`, …) bypasses
`__display__` itself, since a channel like that is a reading of the scene
rather than a graded picture of it. The environment-cube capture bypasses it
too, and for the same reason: a probe face carries radiance into the cube
array, and `__display__` would fit that radiance to a display's code values —
a picture of it rather than the value the PBR indirect term multiplies into
its lighting.
A complete post-process effect — a vignette via `fragment()` + `properties.yaml`:
`properties.yaml`:
```yaml
properties:
- { name: intensity, type: float, default: 0.5, min: 0, max: 1 }
- { name: radius, type: float, default: 0.75, min: 0, max: 1 }
- { name: softness, type: float, default: 0.45, min: 0, max: 1 }
```
`shader.wgsl`:
```wgsl
// @domain: post-process
fn fragment(in: PostInput) -> vec4<f32> {
let color = zero_sample_scene(in.uv);
let intensity = max(material.intensity, 0.01);
let radius = max(material.radius, 0.01);
let softness = max(material.softness, 0.01);
let center = in.uv - vec2<f32>(0.5);
let dist = length(center);
let vignette = smoothstep(radius, radius - softness, dist);
let darkened = color.rgb * mix(vec3<f32>(1.0), vec3<f32>(vignette), intensity);
return vec4<f32>(darkened, color.a);
}
```
The asset above **defines** the effect. It enters the frame when something
registers it:
```luau
postprocess.add("vignette", asset.resolve("~.shaders.vignette", "shader"), { priority = 200 })
```
The registration names no layer, so the effect grades the layer its `space`
belongs to: this vignette reads light, so it runs on `scene`, over the picture
before the UI reaches it. Registering it is the one step that makes it render,
so a world's chain holds exactly the passes its content asked for. Editing the shader body afterwards
recompiles every effect registered from it, in place — the pass keeps its enabled
state, priority, layer, tuned property values and bound textures, and draws the
new pixels on the next frame. `postprocess.remove(name)` takes it back out of the
chain and leaves the asset alone.
Drive the named properties at runtime with `postprocess.setProperty(name, prop,
value)` and bind texture properties with `postprocess.setTexture(name, prop, path)`
(both keyed by the **property name**, never a slot index — see the post-process
section of `man shaders` / the `postprocess.*` API).
Read them back with `postprocess.describe(name)`: it carries the chain state
`postprocess.status()` lists for that effect, the `properties` schema it was
registered with, and the `values` each of those properties currently holds. Before
the effect exists, `shaderRef:getProperties()` on the asset names the same schema,
so what a pass takes is answerable either side of the registration.
A **screen** shader is a standalone full-screen visual (UI background, procedural
pattern). `ScreenInput` mirrors `PostInput` (`frag_coord` + `uv`); there is no scene
to sample, so it has no `zero_sample_scene` helpers. Its `engine` uniform is a
`ScreenEngineData`:
| Field | Type | Meaning |
|---|---|---|
| `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world |
| `scroll` | `f32` | UI scroll offset |
| `resolution` | `vec2<f32>` | render-target size in pixels |
| `mouse` | `vec2<f32>` | mouse position |
| `velocity` | `f32` | scroll velocity |
```wgsl
// @domain: screen
fn fragment(in: ScreenInput) -> vec4<f32> {
let t = engine.time * 0.5;
let col = vec3<f32>(
sin(in.uv.x * 3.14159 + t) * 0.5 + 0.5,
sin(in.uv.y * 3.14159 + t * 0.7) * 0.5 + 0.5,
material.brightness
);
return vec4<f32>(col, 1.0);
}
```
## Library includes
A library module is a **`.shaderModule` asset**: it only EXPOSES functions and
structs and does nothing on its own (exactly like a Unity `.cginc`). You must
call what you include. Include one by its identity, the same string you would
hand `asset.resolve`:
| Include | Exposes |
|---|---|
| `@builtin::shaderModules.pbr_shading` | `struct PbrSurface { albedo, normal (world), metallic, perceptual_roughness, emissive, occlusion }`; `zero_pbr_default_surface(FragmentData) -> PbrSurface`; `zero_pbr_shade(FragmentData, PbrSurface) -> vec3<f32>` (the full forward PBR lighting); `zero_pbr_indirect_visibility(FragmentData, PbrSurface) -> ZpbrIndirectVisibility` (the share of the surroundings' light each indirect lobe takes from the scene's ambient occlusion: `diffuse` with the light a crease bounces back, `specular` from the open cone around the bent normal, and `specular_traced`, the material's own occlusion alone, for the part of the reflection a screen-space trace found); `zero_pbr_shade_with_visibility(FragmentData, PbrSurface, ZpbrIndirectVisibility) -> vec3<f32>` (the same lighting with that share stated by the caller); `zero_pbr_surroundings_light(FragmentData, n, albedo) -> vec3<f32>` (the diffuse light the surroundings hand the surface along `n` as `zero_pbr_shade`'s diffuse lobe takes it — lightmap, flat ambient, reflection probes, light-probe volumes, the sky light's diffuse light where the G-buffer pass does not draw the surface, the scene's occlusion — for a self-lit body to multiply by its colour); `zero_pbr_sun_visibility(FragmentData, PbrSurface) -> vec4<f32>` (the sun as it reaches the surface: rgb what translucent casters and a medium leave of it, a the share its shadow maps leave, zero where it puts no light on the surface), which a surface scales on its own terms and hands back in `PbrSurface.sun_visibility` |
| `@builtin::shaderModules.shadows` | `compute_directional_shadow_factor(...)`, `compute_spot_shadow_factor(...)`, `compute_point_shadow_factor(...)`, `compute_area_shadow_factor(...)`, `compute_punctual_shadow_factor(...)`, `zshadow_light_reach(...)`; each light's `_with_kernel` form takes a shared `ZShadowKernel` (`zshadow_kernel()`) so several lookups of one fragment derive its filter rotation once |
| `@builtin::shaderModules.engine_bindings` | the group(0) declarations (camera, transforms, lights, shadow maps) — surface shaders get this implicitly; include it directly only for advanced raw access |
| `@builtin::shaderModules.shadow_bias` | `zshadow_offset_receiver(...)`, `zshadow_directional_depth_bias(...)` and the rest of the bias math, as pure functions |
| `@builtin::shaderModules.texturing` | `ztex_stochastic(...)` (tile without a visible repeat grid), `ztex_blend_normals(...)` (reoriented normal blending) |
| `@builtin::shaderModules.periodic_noise` | Value noise that repeats along x, for a pattern laid around a circle (a sky over the azimuth, a ring): `zero_azimuth(dir)` (the azimuth about +Y as a fraction of a turn, wrapping along -X), `zero_periodic_noise(p, period)`, `zero_periodic_fbm(p, period, octaves, lacunarity)` (each octave fits a whole number of cells in `period`, so the sum repeats every `period` and a pattern whose x runs over one period per turn closes with no seam), `zero_wrap_cell(cell, period)` and `zero_hash21(p)` for a lattice of one's own |
| `@builtin::shaderModules.parallax` | Parallax occlusion for any lit shader with a height map: `zero_parallax(depth, max_steps) -> ZeroParallax` (the relief's depth in UV units, its steps, its fade distances and whether R is height or depth); `zero_parallax_march(FragmentData, height_texture, height_sampler, uv, ZeroParallax) -> ZeroParallaxHit` (the UV to read every map at, with `ddx`/`ddy` for `textureSampleGrad`); `zero_parallax_sun_visibility(FragmentData, PbrSurface, height_texture, height_sampler, hit, ZeroParallax) -> vec4<f32>` (the sun with the relief's self-shadow, for `PbrSurface.sun_visibility`, marched only where the sun lights); `zero_parallax_self_shadow(...)`