# scene.clean
Clear the active scene down to a protected keep-set.
Every argument is optional, and with none only the player setup is kept:
- `keep` — a selection to protect besides the player setup, for example every
entity carrying a `Light` to keep the lighting.
- `keepPlayer` — `false` removes the player setup too, a full empty.
- `dryRun` — `true` reports what would go and changes nothing.
By default only the player setup survives (every `PlayerPrototype` subtree and
every `PlayerSpawn`), so a clean never orphans the player. `keep` protects a
CATEGORY of entities — a `scene.find` query on `component` / `attribute` /
`tag` / `under` — not a single named entity.
A clean is a LIVE mutation only: it does not write the saved `scene.json`, so
`scene.revert` undoes it and `scene.save` commits it. If the scene has unsaved
edits, clean refuses (to avoid folding its removals into work no revert could
restore) — save or revert those edits first. There is no confirm/force flag.
The guard does not apply while play mode runs unpaused.
Returns `{ removed, kept, intent }`, plus a `warning` when the clean left the
scene with no lights.
# scene.cost
Which loaded scene is costing the frame time. Ranks every loaded layer by what its entrypoint's `update` / `editorUpdate` costs, timed where the tick runs and attributed to the layer that owns it — the answer to "the scene is slow and the profiler's script rows do not account for it", because a scene entrypoint's per-frame tick is not a component and does not appear among them. `totalMs` is a sum across the window since the last reset (or engine start) and `avgMs` is the per-tick cost, which is the per-frame cost for a tick that runs every frame. Answers in edit mode as well as play.
# scene.create
Create a NEW scene from a template and load it.
Arguments: the new scene's `name`, the `template`, and an `opts` table. Naming
a scene and omitting the template returns the template catalog.
`template` is typed: `"empty"` (blank canvas), `"flat"` (ground + lighting, no
player), `"player"` (ground + lighting + the canonical reusable player a joining
user's avatar replaces — prefer this over hand-rolling a player), `"menu"`
(lighting only, no ground, no player). Omit the template to get the catalog of
templates and what each contains; an unknown value errors with the valid
choices. Pass `opts.startup = true` to also make the new scene the world's
startup scene.
The scene is minted as a fresh asset and loaded. Returns
`{ scene, template, contains, startup? }`, or `{ templates }` when the template
is omitted.
# scene.find
The single entity-discovery tool. It reads the flat live population, so
it reaches **runtime clones, temporary entities, and detached roots** —
the entities a hierarchy walk from a scene root silently misses.
Pick a search axis (each a **list**, so many candidates resolve in one
call):
- `name` — name terms, matched as substrings by default (`muzzle`, `flash`).
- `component` — entities carrying any of the named components (`Light`, `Camera`).
- `attribute` — entities whose attribute `name` holds `value` (`team` = `red`).
Multiple axes = union; each hit reports **which** criterion matched, so
you learn the right wording.
Modifiers:
- `substring` (default `true`) — case-insensitive name-part matching, so
`"muzzle"` reaches `muzzle_light_ent_620d…`. Set `false` for exact.
- `includeInternal` (default `false`) — entities marked internal are excluded
unless you opt in.
- `roots` — top-level entities only. `maxDepth` — cap the hierarchy depth.
- `under` — only descendants of these entities (by name or id).
`ancestorsOf` — only ancestors of these.
- `additive` (default `false`) — search only the active scene, or set
`true` to also search loaded overlay (additive) scenes.
- `limit` — cap the returned matches; `total` still reports the full count.
## Projections — `include`
By default a hit says *which* entity matched. `include` makes the query
answer the question outright, so you inspect a set in **one call**
instead of querying and then interrogating each entity. `include` is a
list of the projections below: `under` set to a room with `include` naming
`transform` and `componentValues` returns every entity in the room with its
placement and its live component values.
| Projection | Adds to every match |
|---|---|
| `transform` | `position = { x, y, z }` (world), `rotation = { x, y, z, w }` (world quaternion), `eulerAngles = { x, y, z }` (degrees), `scale = { x, y, z }` (local), each an **array** |
| `componentValues` | `componentValues`: each component's **live** field values, keyed by component name |
| `attributes` | `attributes`: the entity's attributes as `{ name = value }` |
| `scriptComponents` | `scriptComponents`: every script-component instance the live entity carries, as `{ type, identity, instance }` |
The `transform` vectors are arrays, the vector shape the scene and
entityOps tools take and report, so a projected `position` passes
straight to `entityOps.transform`. Read them by index: `position[1]`,
`position[2]` and `position[3]` are x, y and z, while an entity proxy
holds the same value keyed `x`, `y`, `z`.
Every match already carries `components`, the **names** of its
components, without `include`; their live values are the
`componentValues` projection. Nothing else is added unless `include`
names it. An unrecognised projection is an error listing the accepted
ones and naming the one to write instead (`include = { "components" }`
points at `componentValues` and `scriptComponents`, `"position"` at
`transform`). Projections read the **live** entity, so a component
added in the same frame reports its values here even though the entity
census has not caught up.
Returns `{ matches, total, truncated, searchedAxes }`, each match a
`{ id, name, parent, depth, components, layer, matched }` with the FULL
canonical id and name, plus whatever `include` asked for.
## Writing the query under its parameter name
The tool's one parameter is named `query`, so the search fields can be
written under that name or beside it, and both spell the same search: a
`name` of `ground` with `include` naming `transform` reads the same inside
`query` as beside it.
A field written both inside `query` and beside it is refused, naming
the field.
# scene.list
List the scenes available to load: the world's own scenes and the builtin library scenes.
Takes an optional `scope`: `"world"` (default, the scenes this world authored), `"library"` (builtin `@builtin::` scenes: templates, demos, canonical setups) or `"all"`. Returns `{ scenes = { { name, identity, path, scope, loaded, active } }, scope, count }`, where `scope` on each entry is `"world"` or `"library"` and `loaded` / `active` say whether the scene is currently loaded or the active layer. Load one with `scene.load`.
```lua
scene.list()
scene.list("library")
```
# scene.load
Load a scene snapshot into the live world.
Takes the scene `name`, as `scene.list` reports it (for example `main`), a
builtin scene identity, or a scene path.
Loads via `layers.load(name)` and records `name` as the toolbox's last
scene name, so a later `scene.save` with no name persists back to the
same snapshot. Returns `{ loaded = name }`.
# scene.loadedLayers
The scene LAYERS loaded into the live world right now.
Takes no arguments. Reports the root scene plus any additive overlays (editor UI, effect passes)
currently loaded — one record per layer with its `name`, backing `scene`,
`status`, `visible`, whether it is `additive`, and whether it is the `root`.
This lists loaded LAYERS (the runtime state), not the scenes available to load —
for that use `scene.list`. Returns `{ LoadedLayer }`.
# scene.observe
What every scene load did, and what each loaded scene costs. One read carrying the last load's report — what it produced, the root it replaced and the overlays that went with it, the entity counts on each side, how long each phase took, and every failure it produced with the entity, component or lifecycle hook it is about — plus a per-layer inventory of what the engine attributes to each layer and the per-frame cost of each layer's entrypoint tick. Recorded at each load's own completion point and read lazily, so nothing is measured per frame beyond the tick timings themselves. Answers in edit mode as well as play mode.
# scene.playable
Whether the world is ready to play right now (could someone jump in and play it), what is still missing when it is not, and when it first became ready, read without entering play. The world is playable when its scene's play entry would spawn a player the person controls (a PlayerSpawn naming a well-formed PlayerPrototype, a body carrying a component that holds an input map, the camera the player sees through, and touch controls when the person is on a touch device), or when the agent building it has stated a version is ready. The answer is the `playable.state()` record: `playable`, `source` (`"scene"`, `"agent"` or `"both"`), `missing` (what the scene still lacks, each with a `code` and a message), `player`, and `since` / `first` (when the current stretch began and when the world first reached it since it was opened).
```lua
tools.use("scene", "playable") -- read it
tools.use("scene", "playable", { wait = 60 }) -- wait for it; adds timedOut
tools.use("scene", "playable", { declare = true, by = "DotBot", note = "First version ready" })
tools.use("scene", "playable", { withdraw = true }) -- withdraw that statement
```
# scene.player
The scene's player setup, in one tool.
What it does depends on the arguments:
- none — report the intent, the prototypes (body and camera wiring) and the spawns.
- the intent `"none"` — a playerless scene; removes every PlayerPrototype and PlayerSpawn.
- the intent `"spawns"` — a player per joining user; authors the default setup if missing.
- the intent `"spawns"` with a `roles` table — reshapes the player: swap the
avatar with `body`, make it first-person with `behavior`, or wire an existing
camera entity with `camera`.
The intent is typed: `"spawns"` or `"none"`. `"spawns"` on a scene with
no PlayerPrototype authors the canonical setup — humanoid body,
third-person camera (OwnerOnly), a spawn at the origin — the same shape a
fresh scene ships and the `player` template produces. `"none"` strips the
player machinery entirely.
The `roles` table (second argument) reshapes the player and implies
`"spawns"`:
- `body` — an entity name/id to adopt, **or** an avatar asset ref
(`@builtin::avatars.minimal_player`) that repoints the body's avatar. A
joining user's own avatar replaces this body socket, so reuse the
canonical setup rather than hand-rolling one.
- `camera` — an entity carrying a Camera component; moved under the
prototype and scoped OwnerOnly so each joining user gets their own view.
- `behavior` — any `cameraBehavior` component (built-in or authored) set
on the player camera's `Camera.behavior`.
- `prototype` — picks one when the scene has several.
Setting anything saves the scene.
The report names the root scene layer's `intent` and `scene` path, and lists
every PlayerPrototype and PlayerSpawn the loaded layers hold. In play the
scene holds each authored prototype as the captured template a joining player
is cloned from; the report lists it through the spawn that names it, with
`template = true`. With no scene loaded as the root layer the report carries
`unloaded` in place of `intent` and `scene`, saying so and how to load one,
and the setters refuse until a scene is loaded.
The behavior is attached to the player camera's entity as a component of its own type, so it is tuned there: `component.get("<its type>")` on the camera entity and set its fields. A `component.add` of that type writes its values onto the attached instance instead of adding a second one.
# scene.reload
Re-run a loaded scene's build.
Takes an optional scene `name`; without one the active root scene is rebuilt.
`scene.load` of a scene that is already loaded and unchanged is an
idempotent no-op, so editing an entrypoint and loading it again rebuilds
nothing. This unloads and re-loads the layer in place, running the
entrypoint's build again — in edit mode, so iterating on a build script
does not mean flipping to play and back through the play shadow.
A rebuild saves the scene, the way a write to `build.luau` does: `scene.json`
holds what the reload built, so the next play loads it, and unsaved edits in
the scene are saved with it. A library scene (under `/libs/`) is rebuilt in
the live scene alone, and its files stay as the library states them.
Returns `{ reloaded = <name>, built = true, content = n, editorOnly = n,
saved = bool }` once the layer has been rebuilt (`saved` is false for a
library scene), `{ reloaded = <name>, built = false, reason, message }` when
the build did not run, or `{ error = "..." }` when no matching layer is
loaded.
# scene.remove
Remove entities from the active scene.
Takes the targets to remove: one name or id, several of them, or a selection
such as every entity carrying a `Light`. The default floor is the
entity named `ground`.
Targets are entity NAMES or ids, arrays of them, `scene.find` records, or a
`scene.find` query — so you delete a selection without looking it up first. Each
target is removed with its whole subtree.
A remove is a LIVE edit of the scene: `scene.revert` undoes it, and
`scene.save` writes it into the scene's `scene.json`, which is the file
`zm add` stages and `zm commit` records. To clear a scene while keeping the
player setup, use `scene.clean` instead.
Returns `removed`, one `{ id, name }` record per removed target, and
`playerHint` when a target was part of the player setup.
# scene.replace
Replace a loaded scene's **content** with another scene's content. The
target scene keeps its identity (guid, name, place in the world); its
files — `scene.json`, `entrypoint.luau`, everything else in the scene
folder — become copies of the source's, and the scene reloads so the
world reflects the swap immediately.
Takes the source scene (a scene name or a builtin identity such as
`@builtin::scenes.test_arena`) and an `opts` table holding `dryRun` and
`scene`.
Targets the active scene unless `opts.scene` names another loaded
scene. Target content files the source doesn't have are removed;
identity sidecars are untouched. `dryRun = true` reports exactly which
files would be written and removed, plus the entities the source
declares, without touching anything.
# scene.revert
Discard a scene's unsaved edits and restore its saved `scene.json`.
Takes an optional scene `name`; without one the active scene reverts.
The undo for `scene.clean` / `scene.remove` and any edit-mode change, and the
counterpart to `scene.save`. Every edit since the last save lives in the
scene's dirty overlay until you commit it; this throws that overlay away and
respawns the scene from its saved state.
Because the dirty overlay belongs to the scene ASSET (not the runtime layer), a
revert works whether or not the scene is currently loaded — pass a `name` to
revert a specific scene, or omit it for the active one. This reverts only the
edit-mode dirty overlay; it is not the play-mode baseline restore.
Returns `{ scene, discarded }` — `discarded` is true when unsaved edits were
thrown away, false when the scene was already clean.
# scene.save
Save the loaded scene named `name` back to its own `scene.json`.
Takes an optional scene `name`; without one it saves the last-used scene name
(`main` until another is loaded or saved).
Resolves the scene by name via `layers.find` and saves that scene — saving
scene A never writes scene B. Errors when no scene by that name is loaded.
Returns `{ scene = name }`.
# scene.setStartup
Make the currently active scene the world's startup scene.
Takes no arguments: it pins whatever scene is live now as the scene the world
auto-loads every time it loads, so after building or loading a scene you call
this to make it stick across world reloads. There is no clear/unset — a world
with no startup scene has no scene context and every script fails, so that is
not a valid choice.
The current startup scene shows in `scene.summary`. Returns `{ scene }` — the
name of the scene now set as the world startup.
# scene.toolbox shared module
Cross-tool sharing for the `scene.*` toolbox: the hierarchy snapshot core
(`snapshot`, `findAll`, `leaf`) that backs tree / findAll /
findByComponent / summary, and the last-scene-name state that save / load
share. Tools call these functions; the functions call engine APIs.
# scene.spawns
The scene's spawn points. `scene.player` decides whether a scene spawns
players and what they become; this decides **where they arrive** — the
PlayerSpawn entities themselves.
With no argument it reports every spawn. `"add"` places one (an `opts.position`
says where), `"set"` reconfigures one (`opts.spawn` names it, `opts.rotation`
turns it) and `"remove"` deletes one.
## What a spawn decides
- **Its transform** — where a joining player's body lands while `placement`
is `at_spawn_transform`, and its forward axis is the direction they face.
The edit-mode debug overlay draws that as a ring, a heading arrow and a
standing capsule, so a spawn is visible where it stands.
- **Its prototype** — which PlayerPrototype subtree gets instantiated for the
joining user. A spawn whose prototype is unset or no longer resolves cannot
spawn anyone; the report says so (`prototypeResolves`) and the overlay draws
it red. In play the scene holds the prototype as the captured template each
joining player is cloned from, and the spawn's prototype resolves to that
template.
- **team / role / maxPlayers / spawnPolicy** — the PlayerSpawn component's own
fields, carried onto the players it spawns.
## Picking a spawn
`opts.spawn` names the spawn to act on, by name or id. With one spawn in the
scene it is implied; with several it is required, and an unmatched name is an
error listing what the scene has. On `"add"` the same field names the new
entity instead.
New spawns are parented alongside the spawns already in the scene (else under
the scene's `Spawns` container), so spawn points stay collected in one place.
Mutating saves the scene.
# scene.summary
High-level "what's in the scene" report, and the call that counts the entities
in the scene or in one group of it.
Every option is optional: `limit`, `under`, `fields` and `includeInternal`.
Returns `{ entityCount, rootCount, roots, truncated, more?, under?,
activeCamera, player, startupScene }`: the visible entity count, the
top-level rows (with their hierarchy fields), the active camera id, the
player setup with the verb that changes it, and the world's startup scene.
`roots` carries at most `limit` rows, 20 when the call names none. `limit = 0`
answers the counts, camera, player and startup scene alone, the read to make
when the rows are not the question. `rootCount` is always the full count, and
`truncated` with `more` says when rows were left out. An answer to a call naming
neither `limit` nor `fields` carries `narrowWith`, the options that shorten it.
`under` names entities (an id, a name, a proxy, or an array of them) and scopes
the report to what is beneath them: `entityCount` counts their descendants and
`roots` holds their children. A reference that names no entity is refused by
name. `includeInternal = true` counts entities marked internal too.
`fields` keeps only the named fields of the answer: `{ fields = { "entityCount" } }`
answers the count alone, the cheapest read to repeat while a scene changes. A
name no answer carries is refused, and the refusal lists the fields.
For the full structure, `scene.tree` renders the hierarchy itself, and
`scene.find` with `roots` set lists every root.
# scene.tree
Render the entity hierarchy as an indented tree — the quick "what is the
current structure" view.
Takes an optional target and an options table. With no target it renders the
whole active world, 4 levels deep; a target such as `player` renders just that
subtree; `depth` of 2 shows the roots and their direct children.
Each line shows the entity's name and its component types; children nest
under their parent. Anything deeper than `depth` (or beyond the node
budget) is summarized as an explicit `… +N below` count instead of being
silently dropped.
Options:
- `depth` (4) — levels to expand; 1 is just the roots.
- `components` (true) — annotate each entity with its component types.
- `includeInternal` (false) — include entities marked internal, and their subtrees.
- `limit` (500) — the node budget.
Returns:
```lua
{
text = string, -- the rendered tree (print this)
roots = { { id, name, components?, childCount, children?, omitted? } },
total = number, -- entities in scope (full subtrees)
shown = number, -- nodes rendered
truncated = boolean, -- depth or budget cut something
}
```
The target is an entity id, a name (every matching entity), a proxy, or an
array of them; omit it for the whole world from its roots. Children sort by
name, so repeated calls give stable output.
# scene.whyPartial
Answer why a loaded layer is not whole. Returns the nearest cause from a closed set — `loaderRaised`, `entrypointCompileFailed`, `entrypointBodyRaised`, `entrypointRaised`, `buildRaised`, `entityFailed`, `parentMissing`, `parentRefused`, `parentAbandoned`, `componentUnresolved`, `componentRefused`, `subscriberRaised`, `updateRaised` — with the engine's own words for it and the full list of failures, each naming the entity, component identity or lifecycle hook it is about. A layer that produced everything its scene declared reports `ok = true` and no reason.
# toolbox (asset type)
A toolbox is an asset grouping set of `<tool>.tool` assets around one area of work. Each tool in
it becomes callable under the toolbox `<toolbox>.<tool>`, and is a shell command,
`zero <toolbox> <tool> <args>`; `guides core/tools`, "A tool's command line", covers its
flags, paths, `render.luau` and exit status.
## When to group tools together
When creating tools for the engine, a common theme should be identified and
and a toolbox created to house them, this allows each individual operation
to be easily accessible instead of being scattered in a million places.
## Sharing functionality between tools
A toolbox features ability to define functions that code inside each individual tool
inside it can access, this is usefull when establishing helpers etc so you dont have
to duplicate code for each new tool you write.
A `shared.module` inside the toolbox root is where this code lives,
each tool inside a toolbox can access its functions by requiring it with `require(".shared")`.
```luau
-- <toolbox>.toolbox/shared.module/init.luau
local M = {}
-- One step a tool reports in its result.
export type Step = { name: string, ok: boolean, detail: string? }
--!desc Check that a numeric argument lies within bounds.
--!arg arg The argument's name, for the error.
--!arg value The value passed.
--!arg min The lowest value allowed.
--!arg max The highest value allowed.
--!return The value; raises naming the argument and the range when it lies outside.
--!example "count", 12, 1, 100
typed function M.range(arg: string, value: number, min: number, max: number): number
if value < min or value > max then
error(string.format("%s must be between %s and %s, got %s", arg, tostring(min), tostring(max), tostring(value)))
end
return value
end
--!desc A byte count as a readable size.
--!arg bytes The count.
--!return The size in B, KB, MB or GB.
--!example 2681107
typed function M.size(bytes: number): string
local units = { "B", "KB", "MB", "GB" }
local i = 1
while bytes >= 1024 and i < #units do
bytes /= 1024
i += 1
end
return if i == 1 then string.format("%d %s", bytes, units[i]) else string.format("%.1f %s", bytes, units[i])
end
--!desc A step for a tool's result.
--!arg name What the step did.
--!arg ok Whether it succeeded.
--!arg detail What happened, when there is more to say.
--!return The step.
--!example "copy textures", true
typed function M.step(name: string, ok: boolean, detail: string?): Step
return { name = name, ok = ok, detail = detail }
end
--!desc The asset of `kind` that a caller named, looked up by that name.
--!arg kind The asset type to look in.
--!arg name The name the caller passed.
--!return The asset; raises naming the kind and name when nothing matches.
--!example "material", "gold"
typed function M.named(kind: string, name: string): AssetRef
local ref = asset.tryResolve(name, kind)
if ref == nil then
error(string.format("no %s named '%s'", kind, name))
end
return ref
end
return M
```
This shared code should be limited to being used by the tools inside it,
dont put general functionality you might need otuside the toolbox into its shared module.
Instead reference those in the shared module should you wish to utilize something.
A benefit the shared module shares with the tools own code is that it allows
the author to write code that has computed references, meaning eg resolving
an asset from a computed variable `asset.resolve(<type>,name)` that is normally
not allowed in other parts of the engine surface, due to said references not being
recorded.
This is usefully for utilizing tools to handle operations that are called by users/agents
and are dynamic in nature, such as finding/inspecting/testing assets, or content based on an input etc.
When writing a shared module, you should follow standard module practices, please see `module.assetType` readme.md
for more indepth information.
## Describing the toolbox
When writing the readme for your toolbox, ensure you focus on the overall
area what the toolbox focuses on, rather than listing individual tools inside it,
discovery surfcaces already group tools and toolboxes together so a toolbox can be discoverd
by the tools it hosts and doesnt require separately maintaining a list of the tools in it's readme.
## What are tools and when do i create ones?
Tools are typed operations with a known serialized output format, made to enable efficient operation in the engine and provide an easily callable interface for operations around a topic.
They are also useful in that they can be called from a multitude of surfaces, from `execute`, to `bash` to `tool_exec`
to users Tools portion in the edui.
A toolbox and its tools differ from eg a module that has multiple callable functionm in that they might return anything,
and come with no guarantee that the output is meant to be inspected directly, where as tools are meant to perform an self contained operation and return results/info/relevant data in a readable format, including eg. image data.
Whenever you identify an operation that requires specific orchestration and or is something that could be a repeated operation and makes it easier to manage the project/task or when you want to expose logic written in `luau`
to the other call surfaces like `bash` under its `zero` command,you should reach for creating a toolbox.
Toolboxes also come in handy for limiting control/inputs, exposing a limited set of functionality in a clean manner or ensuring the caller doesnt have to understand the entire code.
For comparison, you could think of toolboxes as programs, and the tools inside them as commands.
A package might contain tens of tousands of lines of code, dozens of modules, components etc,
a toolbox turns that surface into a system that any agent/user can then utilize without having
to read or understand the code inside.
Its the UI equilevant to operations.
For the indepth explanation of what `tool.assetType` is and does, read it's readme.
# tool (asset type)
A tool is one named operation: a single luau `typed function` inside a toolboxe's `<name>.tool` asset,
callable as `<toolbox>.<tool>`. The function's signature is the tool's interface,
so anyone can call it correctly without reading its code.
A tool is also a shell command, `zero <toolbox> <tool> <args>`; `guides core/tools`,
"A tool's command line", covers its flags, paths, `render.luau` and exit status.
Each tool has a declared input shape and return shape; the engine wraps each call's
result in an envelope.
## Why use a tool?
Tools are typed operations with a known serialized output format, made to enable efficient operation in the engine and provide an easily callable interface for operations around a topic.
They are also useful in that they can be called from a multitude of surfaces, from `execute`, to `bash` to `tool_exec`
to users Tools portion in the edui.
Compared to say a `module.assetType`, that might contain multiple functions with varying shapes, experct references or specific formats of tables as input and could return potentially anyting including flat tables.
that has multiple callable functionm in that they might return anything a tool is meant to be called with a serialized value, and return a serialized value.
A tool is meant to perform an self contained operation and return results/info/relevant data in a readable format, including eg. image data.
Whenever you identify an operation that requires specific orchestration and or is something that could be a repeated operation and makes it easier to manage the project/task or when you want to expose logic written in `luau`
to the other call surfaces like `bash` under its `zero` command, it propably should be a `<name>.tool` asset.
## How tools are written
In its simplicity, a tool is a single Typed luau function that returns a value.
written plainly, in its basic form it could look like this.
```luau
-- probe.toolbox/onCall.tool
--
-- Fire when a named function runs, seeing its arguments and what it returned.
--- A toolbox offered shared module, that in this case,contains a type shared by the tools in their toolbox.
local shared = require(".shared")
local M = {}
export type OnCallResult = {
ok: boolean,
id: string?,
result: string?,
error: string?,
}
--!desc example tool
--!arg path target path for the operation
--!arg opts `{ notice, when?, run?, capture?, label?, limit?, cooldown?, freeze?, silent? }`.
-- `capture` is Luau, compiled against the hit's context the way `run`
-- is, that returns a picture for the hit — a capture tool you aim:
-- `return tools.use("capture", "fromEntity", { entity = entity })`. It
-- runs once the hit is recorded, and the hit's notice then carries the
-- picture under `shot`, delivered as a picture.
--!return `{ ok, id, result }`.
--!example "arg1", arg2
typed function M.gatherResults(path: string, opts: shared.ArmOpts): OnCallResult
local modulePath, key = splitPath(path)
--- the tool code implementation
local results = myCodeResults
--- the tool call returns a table with keys, that is then wrapped in a return envelope.
return { ok = true, id = results.id, result = results.gathered }
end
return M
```
Now when called, the tool runs and returns the envelope with the inspectable results.
## Why return plainly, and fail by raising
Every caller gets a tool's outcome in the same form, success or failure, so
return the value itself and raise an error when the tool can't do its job. A
tool that returns its own `{ ok = false }` reads as a success that happened to
return that table. Make the error say what to do instead: the caller reads it
and acts on it.
## What the shell prints
`zero <toolbox> <tool>` prints the text the tool's `render.luau` states: a
module in the tool's folder returning one function `(result) -> string |
{ out, err?, exit? }`. A returned string is the output, and `{ out, err?, exit? }`
sets the output, the standard error text and the exit status. A call that raises
exits 1, and a command line the shell cannot bind to the tool's parameters exits 2.
## When to answer later instead of blocking
A caller waits for the tool to return, and might be calling multiple tools at the same time.
Should your call run past the waiting threshold in order to return, even if it yields
it comes back as a handle to a background task that will then complete on its own,
but require the caller to separately read the task results.
For a call that is small, answering inline with the result is better. When a
tool can tell that this particular call will be long (a big bake, a large
batch, a slow fetch), it hands itself to the background with
`task.background()` early, so the caller gets the handle at once and carries on
with other work.
## When to post a notice
The return value is the answer to what was asked. A notice is for what the
caller needs to know besides that: a side effect it didn't ask for, a return to one that has no caller,
notices should be treated as a way to make sure your tool can return quickly, when you arent sure how
long it takes for the results to be ready. It allows the agent to continue working, and then react when
the notice fires. `notices.post` delivers it to the caller,
and an agent that is idle is woken by it, so the caller learns it without
polling. Name in it what to do about it. A notice for something the return
value already says is noise.
## Returning more than text
Tools also support returning images, that the agent can then directly read from the tool response, regardles
of what surface they used to call the tool.
Images also work on notices, so you can eg attach visual results to the eventual outcomes of
your tool results and the agent will see them the second the notice fires.
## What a tool may do that other code may not
A tool, and code only tools call, may act on whatever an input names, resolving
an asset by a name that only arrives with the call. That is what makes a tool
the place for operations that depend on what they are given. Tools are for
working on a world rather than running in the game: a component may not call
one unless it declares `declare { componentSafe = true }`, and a tool doesn't
call another tool, so logic several tools need goes in the toolbox's shared
module or exist elsewhere.
For information how to group tools and organize them, and how they are called read `toolbox.assetType` readme.
## In the Inspector
Tool: how the tool is called (its signature), what it does, each argument, what it returns, and its examples, with **Open** for its source.
# Module (asset type)
A module is a reusable, stateless (or globally-stateful) Luau library
that other code pulls in with `require()`. Modules are the unit of
factored-out logic in a world: helpers, math libraries, format
parsers, registries, shared algorithms.
## When to use one
- You have logic you want to share across multiple components,
services, scenes, or tools.
- You have a registry, lookup table, or shared cache that callers all
read from / write to.
- You want a stable API surface (`M.fn`) other code can depend on.
If the logic is bound to one entity, use a `.component`. If you want a
named UI of fields rather than functions, use a `.preset`.
## Where it lives
- Source: `/zero/source/.../<name>.module/`
- Identity: the source path with `/` written as `.` and each segment's
type suffix dropped — `/zero/source/demo/beats.module` is
`demo.beats`, and `/zero/source/kit.package/beats.module` is
`kit.beats`, the container's name kept and its `.package` suffix
gone. `asset.create` returns this string, `asset.resolve(...).identity`
reads it back, and the `require` forms below write it as
`<identity>`.
- Folder shape:
- `init.luau` (or `init.lua`) — module body. **Required.** Returns
a table (conventionally named `M`).
- `README.md` — instance-level documentation. **Required.**
- `.metadata` — agent-editable tags + free-form fields. **Required.**
## How to create one
```luau
asset.create("module", "<name>")
-- Creates: /zero/source/<name>.module/
-- init.luau (canonical `local M = {} … return M`)
-- README.md (instance README template)
-- `folder` places it in a subfolder of /source, and that subfolder
-- leads the identity: `{ folder = "lib" }` produces `lib.<name>`.
-- `into` authors it inside a resolved container (a package, a toolbox),
-- whose own identity leads the same way:
asset.create("module", "<name>", { folder = "lib" })
asset.create("module", "<name>", { into = asset.resolve("myPkg.package") })
```
## How it operates
1. **Registration.** Writing `init.luau` into a `.module/` folder
indexes the asset and registers the module path with the resolver.
2. **Loading.** The first `require("<identity>")` runs
the file's body and caches the returned table. Subsequent requires
from anywhere return the **same table** — this is the
shared-state lever for "module-local" registries. The body runs in
an environment of the module's own: a name it declares without
`local` is readable by the module's own functions and by no other
script, so an export reaches its callers through the returned table
and nothing else. Requiring a component's folder runs its chunk the
same way, once, and its `update`, `start` and `public` stay in that
environment; a component runs on an entity through
`entity(id).component.add(name)`.
3. **Hot reload.** Editing the file re-runs the module body and folds
what it returns into the table already loaded, so that table keeps
its identity: a caller that captured it with `require` reads the new
source's functions and values through the reference it already
holds, and a later `require` returns that same table. A key the new
source drops goes away; a key something set at runtime stays. The
body's own `local`s start again from their initial values, so state
that must outlive an edit lives in `modules.state()`
(`guides { path: "core/scripting-and-tasks" }`).
4. **Identity resolution.** A module is reached by its `<identity>`,
and where the caller lives decides which spelling of it resolves.
For a module in a **world**, from a caller in that same world —
another module, a component, a scene entrypoint, or an `execute`
chunk:
- `require("<identity>")` — the identity on its own, resolved
against the caller's own root. It carries every folder segment,
so a module created with `{ folder = "demo" }` is
`require("demo.beats")`.
- `require("@root::<identity>")` — the same root-relative
resolution, written out.
- `require(".sibling")` — a module in the same folder, by its bare
name; `..name` steps up one folder, `...name` two.
Logs, stack traces and hot-reload notices name that same module
`@local.source.<identity>` — its key under the world source root.
The `<identity>` tail of that key is the form above, so a trace
reading `@local.source.demo.beats` is `require("demo.beats")`.
For a module in a **library** — content under
`/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's
root from anywhere: `require("@builtin::modules.transform")`.
Mounting a world as a library moves its files under such a root and
flips the caller root to `@<lib>::`, which is what keeps the
root-relative forms above resolving across the move.
## Discovery
- `asset.list("module")` — every registered module.
- `asset.inspect("<name>")` — public functions, source path, this
type README.
- `ls /zero/source/<name>.module` lists the files the folder holds.
## Authoring conventions
- Return a single `M` table from `init.luau`. Top-level statements
with side effects run on first require — useful for one-time
initialization, dangerous if they touch the engine before it's
ready.
- Write exported functions as `typed function`, not `function`: the
argument types are enforced at the call and the checker knows the
signature, so a caller's mistake is reported where they made it.
- Annotate exported functions with `--!desc` / `--!arg` / `--!return`
/ `--!example` so the LSP, `tools.list`, and `asset.inspect`
surface them. A function with no `--!desc` is reachable only by
someone already reading this file.
- Declare a VALUE with `Field.<kind>(default, mode, description)`, and
a table whose members are reached through a metatable with
`--!members <TypeName>` — the latter gives the surface its accepted
member set, its type, and its documentation from one table. See
`guides { path: "core/authoring" }` for all four rules and
`modules/api/engine/entity.module/members.module` for a worked
member table.
- Keep module state in module-local upvalues or in `modules.state()`.
A name the body declares without `local` lives in the module's
environment, which every run of the module shares: a function the
previous run left in place reads what the reload assigned. Module-locals start again from their
initial values with each hot reload; the table `modules.state()`
returns is the same table on both sides of every reload.
- Prefer focused modules over kitchen-sink modules. If two halves of a
module have no shared state, split them.
## Common pitfalls
- **Cyclic requires.** A `require` chain that loops will return the
partial table (the half built before the cycle was detected).
Design for one-way dependencies.
- **Engine-time side effects.** Don't `entity.spawn` at module
top-level — the engine may not be ready. Expose an `M.init` and
call it from a scene entrypoint.
- **Hot-reload + module-local cache.** A module that caches
expensive computation in upvalues loses that cache on reload —
fine for dev, but be aware in performance work.
- **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical.
- **Writing one while play runs.** A `/source` write made while play is
running lands on the play shadow, and a guarded play-exit discards it
unless it is kept. One `.module` write shadows `init.luau`, the
`README.md` and the `.metadata` together.
`vfs.write(path, bytes, { durable = true })` skips the shadow, and
`vfs.promotePlayShadow` keeps what is already on it — the `core/vfs`
guide has the model and what each route costs.
## Related types
- `.component` — for entity-bound state + lifecycle hooks.
- `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider.
- `.tool` — for a single agent-callable function with a YAML schema.
- `.package` — to group several modules + components + scenes into
one shippable folder.
## In the Inspector
Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
# shared
Cross-tool helpers for the [name] toolbox. Every tool inside the
toolbox can pull these in with `require(".shared")`. Holds the small
set of helpers that more than one tool needs: toolbox-wide parsers,
validators, formatters or shared state. Per-tool implementation stays
inside each `<x>.tool/init.luau`.
## Usage
```luau
local shared = require(".shared")
typed function M.someTool(id: string): { id: string }
return { id = shared.normalizeId(id) }
end
```
A tool returns its value, and `error(message)` fails it. The text
`zero [name] <tool>` prints, the error text and the exit status are set
by the tool's `render.luau`.
## Notes
- Keep helpers pure where possible: no engine calls, no state, so they
are safe to call from any context.
- Per-tool implementations own their own `--!desc` / `--!arg` /
`--!return` / `--!example` annotations.
# assetType (asset type)
An asset type says what a kind of asset is: the files an asset of the kind is
made of, the code that gives it behaviour, the interface a person uses to work
with it, and how it is found, pictured and checked. A `<typename>.assetType/`
folder declares a type called `<typename>`, and every `<name>.<typename>/`
folder is an asset of it. `assetType` is itself a type, so a type is an asset
like any other: it is created, versioned, installed and contributed the same way.
## Making a type
`asset.create("assetType", "<typename>")` scaffolds a type. The type registers
the moment its folder is written, anywhere under `/zero/source/`, and from then
on `<name>.<typename>/` folders are its assets. An asset of a type that is not
registered yet is not an asset, so make the type first.
A type folder is a root: `~.x` in any file inside it names the type's own `x`,
wherever the type is installed. Keep the type's whole implementation inside its
folder and reach it that way.
What a type folder must hold is set by this type's own `type.yaml`, the same way
every type's `type.yaml` sets what its assets hold. `asset.validate` on a type
reports anything missing, and the scaffold produces a folder that passes.
## What sets your type's schema (`type.yaml`)
`type.yaml` is the structural contract every asset of the type is checked
against. The keys below are the ones the engine reads; a key not listed here is
ignored.
| Key | What it controls |
|---|---|
| `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. |
| `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. |
| `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. |
| `is_container` | Whether the suffix stays in the identities of what the asset holds. |
| `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. |
| `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. |
| `is_text_default` | Whether the asset's files are text unless stated otherwise. |
| `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. |
| `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. |
| `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. |
| `files: { required, optional }` | The files an asset holds (below). |
| `allow_unlisted` | `false` reports every file the type does not declare. |
| `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. |
| `settings:` | Typed per-asset settings (below). |
| `inspector:` | The interface people use for the type and its assets (below). |
| `preview:` | How an asset is pictured (below). |
| `references:` | Names of other assets the type's files carry (below). |
| `indexing:` | What search reads for each asset (below). |
| `describe:` | How a missing description is generated (below). |
### The files an asset holds
Each entry under `files.required` or `files.optional` is
`{ path, kind: file | folder, one_of_group?, content? }`. `*` in a path matches
within one segment. Entries that share a `one_of_group` are satisfied by any one
of them. `content` lists checks on the file's bytes:
| Check | Passes when |
|---|---|
| `non_empty` | the file has content |
| `json_field { key, type?, non_empty?, accept? }` | the JSON holds the key (a dotted path) with that shape |
| `yaml_field { key, type?, non_empty?, accept? }` | the same for YAML |
| `described { keys?, headings?, message? }` | the file says what the asset is (see "Ask your assets to say what they are") |
Each check takes a `message`, which is what the author is told when it fails.
### Settings
`settings: { values, schema: { type | instance, export? } }` gives every asset
typed settings. `values` names the file an asset's values live in; `schema.type`
declares one schema for the whole type, and `schema.instance` names a file each
asset declares its own in. `asset.create` writes the resolved values, and a write
to the values file reaches `onChange` with what changed.
## The human side (`inspector.luau`)
A type is used by people through its Inspector, and without one the type is
usable only from code. The Inspector is the type's interface for a person: for a
procedural graph it is the graph editor, for a kit it is the tracking view of
what the kit holds and what is still missing. Writing it is part of writing the
type.
`inspector: { type, instance? }` in `type.yaml` names the files. `type` is the
interface for the type itself and for its assets; `instance` names a file an
asset may ship to add its own. Each returns:
```luau
return {
sections = { { id = "graph", title = "Graph", build = function(ctx) ... end } },
replace = { contents = { ... } }, -- replace a default section by id
order = { "graph", "contents" }, -- section order
}
```
`build(ctx)` receives the asset and builds the section. A section's `title`, and
the text its rows carry, is a string or an `i18n.text` value read from a catalog
(`i18n.text("inspectors.mesh.title")`), which follows the editor's language. `asset.create("assetType",
...)` scaffolds a working `inspector.luau` to start from. `asset.validate` on a
type that names no inspector, or names one that does not load, reports it.
## Say what your type is for (`about.yaml`)
Every type carries an `about.yaml` that says what the type is for, in three
plain-language texts:
```yaml
intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering."
function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text."
usage: "You choose it by name for your UI or your text, and the text appears in that typeface."
```
- **`intent`** is what the type is for in someone's game, in the words a game maker uses. Up to 800 bytes.
- **`function`** is how it works today: what an asset of it is made of and what the engine does with it. Up to 1500 bytes.
- **`usage`** is what a person or an agent does with one. Up to 1200 bytes.
Write about the type as a whole, not one asset of it, and say what it does now.
Agents read these texts to learn when to reach for the type and how; people
searching find the type by them. The scaffold starts each text with
`[[describe]]` and a note on what to write; a text that still starts that way
counts as not written. `services describe` can write them.
They show up in `asset.inspect` as `detail.about`, in
`assetTypeRef:getAbout()`, at the end of the type's `types/<typename>` guide,
and at the top of the type's Inspector.
## Ask your assets to say what they are
A type can require each asset to carry a description: a file, written by the
author or generated, saying what the asset is and what it is for. Declare it with
a `described` check:
```yaml
files:
required:
- path: "README.md"
kind: "file"
content:
- { check: "described", message: "Say what this widget is for and where it goes." }
```
A file that is missing, empty or still has a line starting with `[[describe]]`
fails the check, and so does a YAML file whose named `keys` are missing or over
their `max_bytes`, or a Markdown file missing a named heading. `asset.validate`
names the asset, and a push that carries it is refused with `message`.
`services describe` finds such assets and writes their descriptions.
`describe:` steers what is generated:
```yaml
describe:
guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI."
examples:
- "<identity of an asset of this type whose description reads well>"
```
An example is an asset of your type whose description is a true, written one,
never a placeholder and never the asset being described; with none, leave
`examples` empty. A type whose assets the model cannot perceive (a sound, a
motion) says so in `guidance`, and the description is drawn only from what the
asset's own files state.
Start the file unwritten in your `template/`: a heading and one line starting
with `[[describe]]`, never example content, which every new asset would carry
verbatim. A type whose assets say what they are through their own content (a
mesh, a texture) declares no check.
## The type's code (`behavior.luau`)
`behavior.luau` returns one table. These are the keys the engine reads from it;
anything else on the table is the type's own.
### What the type's assets can do
| Key | Shape | What the engine does with it |
|---|---|---|
| `ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every asset of the type: `ref:name(...)`. |
| `modules` | `{ [name] = require(".x") }` | Code the type's assets reach with `asset.containing(__FILE__).modules.<name>`. |
| `events` | an events schema | Events an asset fires. Readers subscribe through `ref.events.<name>:connect(...)`; the type fires them. |
| `refShapes` | `{ [method] = function(self) -> (typeExpr, source?) }` | The result type of a `ref` method for one particular asset (below). |
| `namePattern` | a Lua pattern | The names `asset.create` accepts for the type's assets. Default `^[A-Za-z][A-Za-z0-9_]*$`. |
| `derive` | `{ output, module, compute, fingerprint, matches?, required?, timeout? }` | A file computed from the asset when it is committed; a `required` one holds the commit until it lands. |
Some `ref` names mean the same for every type, and the engine calls them:
- **`instantiate(self, target?, opts?) -> (root, idMap)`**: puts the asset in a scene. Defining it is what makes the type scene-instantiable. Its return is a contract (below).
- **`inspect(self) -> detail`**: what `asset.inspect` reports for the asset beyond the common record (below).
- **`preview(self, opts)`**: renders the asset's picture; it wins over the type's `preview:` recipe.
- **`previewMaterial(self) -> { material }`**: the material a `surface` preview paints.
- **`saveDefinition(self)`**: writes the asset's in-memory edits back to its files in edit mode.
Some names are answered for every asset before the type is asked, so a `ref`
entry of the same name is never reached: `getSource`, `getBytes`, `getText`,
`exists`, `deps`, `canInstantiate`, `canPreview`, `preview` (which calls yours
when you define one), `meta`, `runtime`, `events`, `typeRef`, `modules`, and the
residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`,
`gpu_resident`.
### When the engine calls the type
| Hook | Signature | When it runs |
|---|---|---|
| `onCreate` | `(name, opts) -> { [path] = contents }` | On `asset.create`. Returns the files of the new asset, laid over the type's `template/`. Annotate `opts`: its type is the schema `asset.create` checks the caller's arguments against. A `""` key writes a single loose file. |
| `onReplace` | `(dest, files) -> files` | On an `asset.create` over an asset already at `dest`, after `onCreate`, so what the author added can be carried into the replacement. |
| `onRegister` | `(self)` | Once per asset, when it first registers: when the world loads, on a live `asset.create`, and when an asset arrives later (installed, pulled, synced). This is what makes an asset take effect the moment it is written. |
| `onChange` | `(ref, change)` | On every write to a file inside an asset of the type. `change` is `{ path, asset, type, kind, origin }`, plus `settings` and `settingsChanged` for a write to the settings values file; `kind` is `edited` or `seeded`, `origin` is `local` or `remote`. Filter on `change.path`. Writes to one asset arrive in order, each after the hook for the one before has finished, and the hook may wait on what it reads. A write the hook makes inside its own asset arrives later like any other, so keep the hook convergent. |
| `onDependencyChange` | `(ref, change)` | When a module the asset's code requires is re-run, or a name the asset carries starts resolving. `change.kind` is `dependency`. |
| `onDelete` | `(ref)` | When an asset of the type leaves the world: deleted, or the world it is in is swapped away. |
| `validate` | `(ref) -> { { code, message, severity?, path? } }` | On `asset.validate`, after the `type.yaml` checks, for the type's own rules. `severity` defaults to `error`. Runs on every push, so a type's rules hold at publish. A hook that fails reports `validate.hook_failed`. |
### Settings hooks
| Hook | When it runs |
|---|---|
| `settingsDefaults(name, opts, asked) -> table` | Once per `asset.create`, for values the schema's defaults do not give. |
| `settingsCorrections(values, name, opts) -> (corrections?, reasons?)` | On every settings write. A correction to a field the writer named refuses the write, giving the reason. |
| `settingsDerivedDefaults(values, explicit, changed)` | On a settings write, for fields derived from others. |
| `normalizeSettings(values, stored?)` | On every read and write, to map an earlier spelling of a field to the current one. |
| `settingsHealed(values, stored)` | On a read, to repair stored values. |
| `settingsSchemaProblem(schema, ref) -> string?` | When an asset's own schema is read; a returned string refuses the schema. |
`creationInputs` (`{ [opt] = true | selectorOpt }`) names `asset.create` options
that are inputs to the type rather than settings.
### Reloading
An edit to `behavior.luau` reaches existing assets with no restart.
## How an asset is pictured (`preview:`)
| `kind` | The picture is | The type provides |
|---|---|---|
| `instantiate` | the asset placed in the preview studio through its `instantiate` | `ref.instantiate` |
| `image` | a file the asset holds, fitted to the frame | `source: { files }`, the candidate files in order |
| `surface` | the asset painted on a mesh | `mesh`, and `ref.previewMaterial` |
| `custom` | whatever `ref.preview` returns | `ref.preview` |
```yaml
preview:
kind: surface
mesh: sphere
```
`angle: [yaw, pitch]` turns the camera. The studio owns the light, the backdrop
and the framing, so an asset pictures the same in every world. A type with no
`preview:` that defines `instantiate` still answers `ref:preview()`.
A picture is rendered when something asks to view it (the editor showing the
asset, `ref:preview()`), when previews are generated on request
(`assets.generatePreviews`), and when the asset is staged. An edit alone
renders nothing. The picture records what it was made
from, so a stale one is told from a current one.
## The names your type's assets hold (`references:`)
Where your type's own format or API carries the name of another asset, declare
it here:
```yaml
references:
keys: # a top-level key of the type's files that holds a name, or a table of them
- { key: "shader", type: "shader" }
args: # an argument of a call, counting from 1
- { call: "g:node", position: 2, type: "procNode" }
fields: # a field of the options table a call takes
- { call: "fx.beam", field: "material", type: "material" }
```
`type` is the category the name resolves in. `asset.declareReferenceKey`,
`asset.declareReferenceArg` and `asset.declareReferenceField` declare the same
from a script.
## What search reads (`indexing:`)
`indexing:` is how assets are found. Search reaches an asset only through what
its type's `indexing:` names, and adds nothing of its own. That includes you: an
asset indexed badly is one you cannot find later, when you are making something
else and need it. A type whose assets are never looked for says `indexing: none`.
```yaml
indexing:
data: # text, read from the asset's files
- role: identity
extractor: verbatim
source: { file: "README.md" }
- role: interface
extractor: symbols
source: { files: ["init.luau"] }
- role: implementation
extractor: verbatim
source: { files: ["init.luau"] }
content: # the picture
- role: identity
modality: image
source: { file: "preview.png" }
facets: # what a query filters and re-ranks by
file: ".metadata"
rigged: { type: bool, from: { components: { contains: SkinnedModel } } }
roughness: { type: number, filter: range, from: { file: "mat.yaml", field: "floats.roughness" } }
```
**Roles.** Each `data` and `content` entry has a `role`, and a query matches in
two slots:
- **`identity`**: what an asset is. For anything you look at, the picture; for anything else, the text that says what it is.
- **`capability`**: what it does and how it is made. `interface` (the signatures or shape a caller uses) and `implementation` (the body) both count as capability, and a type with code usually declares both.
Ask what a person would recognise an asset of the type by, and what it does, and
point each role at the file that says it. For text, that is the asset's
description: the file your template starts with a `[[describe]]` block, which the
author writes or `services describe` fills in (see "Ask your assets to say what
they are").
**`data`.** `extractor: verbatim` embeds a file's text as it is; `symbols` embeds
the declared signatures of code. `source` is `{ file }` or `{ files: [...] }`.
Never index a file name (`source: { field: name }`): one
or two words carry nothing to match.
**`content`.** `modality: image` embeds the picture itself, so a text query
matches what the asset looks like. A type whose assets are looked at makes the
picture its identity.
**`facets`.** What a query narrows and re-ranks the matches by. `file` is embedded
whole, so keys nobody declared in it are still found. Each further key is
computed for every asset and states a value for every one, including `false`: a
file can imply "not rigged" but never say it, and a query separates rigged from
unrigged only because the unrigged ones say `rigged: false`. A key is
`{ type: bool | number | enum, filter?: range, from }`, where `from` is
`{ file, field }` (a field of one of the asset's files, dotted for nesting),
`{ metadata: key }`, or `{ components: { contains | any_outside } }` (what the
asset's entities carry).
## What blocks a push
A push checks every asset it carries against its type. These refuse it:
- a required file that is missing, a `content` check that fails, a `described` file not written yet;
- an error from the type's `validate`.
Unlisted files and warnings do not. A `described` file blocks only a push that
changes the asset. When a push is refused, the message names each asset and what
it lacks. `world.publishBlockers()` and `zm status` read the same list without
pushing.
## Typing a result from the asset (`refShapes`)
A `ref` method whose result depends on the asset (one entry per child folder, per
row of a config, per control a map declares) can only be annotated as
`{ [string]: Thing }`, which accepts any key. `refShapes` states the result for
each asset instead: a function returning a Luau type expression for that asset,
and the module whose types the expression uses. Read the asset; never run it.
```lua
-- inputMap.assetType/behavior.luau
M.refShapes = {
activate = function(self): (string, string)
local names = {}
for _, control in ipairs(M.ref.controls(self)) do
table.insert(names, control.name .. ": Handle")
end
if #names == 0 then return "", "" end
return "{ " .. table.concat(names, ", ") .. " }", "@builtin::modules.zinput.scheme"
end,
}
```
With it, `map.jump:onPressed(fn)` is checked and `map.noexisting` is reported.
A per-asset type applies where the call site names which asset: a component
field whose default names it, or an annotation `AssetRef<"inputMap", "<identity>">`.
`asset.resolve(name, category)` carries only the category, and a name computed
at runtime carries nothing, so calls on those keep the declared return. The type
belongs to the call's result: index it there, or bind what you need from it
there, and the names stay checked.
`require("@builtin::assetTypes.assetType.shared.refShapes").published()` shows
what was published: `categories` (each type's method surface) and `returns`
(per-asset results by identity, then method). An identity missing from
`returns` was never published. Results are recomputed when an asset is written;
at most 64 assets of one type are read.
## Putting an asset in a scene (`ref.instantiate`)
A caller writes one piece of code against every instantiable type, so what
`instantiate` returns is fixed:
```lua
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts)
-- compose the asset under `root`, now
return Instantiable.result(self, root, idMap)
end,
}
```
**In.** `target` is the entity the asset lands under, or onto for a hierarchy
type; with none, the type spawns a new root. `position`, `rotation` (three
numbers in degrees, or a quaternion), `scale`, `name` and `temporary` mean the
same for every type: `Instantiable.root` applies them to a root you make,
`Instantiable.place` to one you adopt. Document any options of your own in the
hook's `--!arg` docs.
**Out.** `(root, idMap)`. `root` is the composed root, live when you return:
build synchronously, never defer to a component's `awake`. `idMap` maps each
original id to the spawned one, so a component that composes the asset again on
every load can pass it back in and keep references into the composition. Every
call goes through `Instantiable.result`, which refuses a root that is not live
and turns a missing `idMap` into `{}`.
## Inspecting an asset (`ref.inspect`)
`asset.inspect(ref)` builds a record every asset shares (`identity`, `name`,
`guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`,
`description`, `tags`), then calls `ref.inspect(self)` for the type's own
`detail`:
```lua
M.ref = {
inspect = function(self)
-- read the asset's own files, never runtime state: inspect works on an asset
-- that has not been compiled, uploaded or registered
return { --[[ what makes this asset what it is ]] }
end,
}
```
Without it, the record is the shared part alone, and an agent inspecting the
asset learns nothing of what it is. A hook that raises leaves `detail` empty and
sets `record.warning`.
## Discovery
- `asset.list("assetType")`: every registered type.
- `asset.inspect("<typename>")`: the type, its README and its `about.yaml` texts.
- `asset.resolve("<typename>", "assetType")`: the type itself.
# reflections system
Screen-space reflections — a polished floor reflects what stands on it, wet
ground reflects what is above it, and metal picks up its surroundings, all from
geometry the camera can already see.
Environment reflections describe a surface's surroundings in general. They
cannot show the character walking across the floor, because that character is
not in the environment — it arrived this frame. Screen-space reflections read
the frame the engine has just drawn, so anything visible can appear in anything
reflective, with nothing authored per surface.
What that buys and what it costs are the same thing: only what is **on screen**
can be reflected. A reflection of something behind the camera, or off the edge
of the frame, is not there to find. So reflections fade out toward the screen
edge rather than cutting off, and where a ray finds nothing the surface keeps
the shading it already had.
## Using it
Reflections are a render feature. List it on the scene's `RenderFeatures`
entity with the settings it should run under, and it persists with the scene:
```lua
local id = entity.spawn("render features").id
entity(id).component.add("RenderFeatures", {
features = {
{ feature = "@builtin::systems.reflections.ssr", settings = {
intensity = 1.0, -- how much of the reflection reaches the image
maxDistance = 40, -- how far a reflection ray travels, world units
quality = "auto", -- low | medium | high | ultra, or auto (the device's tier)
} },
},
})
```
Every setting is live: edit one in the inspector and the reflections follow.
`renderer.feature.schema("@builtin::systems.reflections.ssr")` lists every knob
with its default.
For code that adjusts reflections at runtime — a quality slider, a cutscene,
weather turning pavement wet — the module is the hand on the same knobs:
```lua
local ssr = require("@builtin::systems.reflections.ssr")
ssr.set({ intensity = 0.6, quality = "medium" }) -- any subset; the rest is kept
ssr.get() -- the settings in force
ssr.active() -- are the passes running
ssr.clear() -- the passes down
```
`set` brings the feature up when none is live, and an `intensity` of 0 takes
it down; the same feature is found rather than stacked when `RenderFeatures`
already runs it.
## What the knobs do
| field | effect |
|---|---|
| `intensity` | How much of the reflection reaches the image, in [0, 1]. 0 turns reflections off and releases the passes. |
| `maxDistance` | How far a reflection ray travels, in world units. |
| `thickness` | How thick a surface is assumed to be, in world units. A ray passing behind one by more than this went past it rather than onto it. |
| `roughnessCutoff` | Perceptual roughness up to which a surface takes the full screen-space reflection. Above it the reflection hands over to the probes and the sky, and is gone 0.1 higher. |
| `quality` | `low` / `medium` / `high` / `ultra` — how many steps the march spends and how many neighbouring rays a pixel gathers — or `auto` (the default), which follows the device's quality tier (`renderer.qualityTier()`): `high` on a desktop, `medium` on a handheld and at the medium tier, `low` at the low tier. `ssr.drawn()` reports the level in force and the sampling it spends. |
| `edgeFade` | How far from the edge of the screen reflections fade out, in UV. |
`roughnessCutoff` is the one to understand first. Every pixel traces one ray
drawn from the lobe its roughness describes, and gathers the rays of its
neighbours that stand on the same surface, so a rough floor shows a bright
sign as the soft, stretched streak its lobe spreads the sign into, and a
mirror shows it sharp. Up to the cutoff a surface takes the full screen-space
reflection. Above it the reflection hands over to the probes and the sky, and
it is gone 0.1 higher, so the hand-over has a soft edge in place of a line. The
default, 0.75, covers wet asphalt and polished stone. A scene that states a
lower cutoff (0.4 was the old default) leaves those surfaces to the probes.
Where the screen holds only part of a surface's lobe (the lobe reaches off the
edge of the frame, or behind the camera) the reflection covers the part it
found and the probe or sky fills the rest.
`maxDistance` and `quality` trade against each other: quality sets the step
count, so a long distance at a low quality samples coarsely and reflections
thin out at range. They thin rather than disappear because the hit refinement
adapts to the step size on its own.
How much of a reflection shows through is the surface's own Fresnel term, taken
from the G-buffer's metallic. Metal takes nearly all of it; a dielectric floor
takes a few percent head-on and much more at a grazing angle — which is why a
wet road reads dry underfoot and mirror-like down the street.
## How it renders
`ssr.renderFeature` runs two compute passes at the `afterDepthPrepass` seam,
before anything shades. `ssr_trace` draws one ray per pixel from the pixel's
GGX lobe (a visible-normal sample; a mirror, below roughness 0.1, keeps its
one reflection ray) and marches it against this frame's depth. The surface's
normal and roughness come from the G-buffer as the previous frame left them,
reprojected through the previous view-projection. The pass writes where each
ray hit and how confident the hit is, or the direction it travelled when it
found nothing. A rough pixel's ray marches fewer steps, because the next pass
blurs what the rays find.
`ssr_resolve` gathers each pixel's lobe over its own ray and the rays of up to
twelve neighbours (4 at `low` and `medium`, 8 at `high`, 12 at `ultra`),
weighing every ray against the pixel's own lobe and counting a neighbour only
where it shows the same surface. The light at a hit is read from the colour
the previous frame ended with, where the hit stood then. The resolve
accumulates the result over frames in a history target (one image pair per
view), holds that history to the spread of the rays it gathered, and writes the
scene's reflection channel, `@scene.reflection`: the light of the rays that
found something on screen, and the share of the lobe those rays cover.
A material reads that channel the same frame, at its own pixel, inside its
environment term: it mixes the traced light over the probe and the sky by the
share of the lobe the screen answered, so what the screen did not find comes
from the environment, and the material's Fresnel, roughness and tint weigh the
result into the pixel as they weigh any environment. The reflection stands
where the camera is now; only the light in it is a frame old. The `reflection`
capture pass shows it. Where the trace found nothing the channel holds zero and
the material reflects its environment alone.
A blended material (a `blend` other than `opaque` or `cutout`) reads none of
the channel. It draws over the depth the trace ran against, so the channel at
its pixel holds the reflection traced for the opaque surface behind it. A
blended pane of glass reflects its environment, or the reflection its shader
traces for itself through `@builtin::shaderModules.screenReflection`.
A camera drawing a diagnostic pass holds readings in its colour target rather
than light, so the passes have no light to read from that frame: such a frame
is drawn lit first, unpresented, the passes run for that, and the diagnostic
reads the channel gathered for where the camera stands now. A capture drawn
once, or a camera drawn again from a new station, is drawn lit first for the
same reason, so its first frame holds a reflection (without accumulated
history, so it shows more grain than a continuously drawn view). The march
steps uniformly in screen space and compares in world space; the full account,
including why thickness is tested after refinement rather than during the
march, is in the render feature's own readme.
Each view that draws the feature holds three screen-sized images of its own: the
rays and the history pair, about 50 MB at 1080p for the viewport.
The pass takes its camera from `@frame.camera`, so reflections are correct in
offscreen captures and render-to-texture cameras, not only the live viewport.
## The demo scene
The scene `@builtin::systems.reflections.demo.polished_floor`, loaded with the `scene.load` tool, is a polished
stone floor with three coloured pillars standing on it, under an afternoon
sky, with the feature listed on the scene's `render_features` entity. The
floor reflects the pillars and a player walking across it; delete the entity
and it mirrors the sky alone. `demo/polished_floor.scene/build.luau` is the
whole scene as code, materials included.
## Files
```
reflections.package/
ssr.renderFeature/ -- the trace and resolve passes, and the settings they take
ssr_trace.computeShader/ -- draws and marches one lobe-sampled ray per pixel
ssr_resolve.computeShader/ -- gathers each pixel's lobe, accumulates, writes the reflection channel
ssr.module/ -- ssr.set / .get / .clear / .active, the runtime hand on them
ScreenSpaceReflections.component/ -- the older one-feature component; RenderFeatures is the list
demo/polished_floor.scene/ -- the showcase: a polished floor, three pillars, the feature on one entity
```
# volumetrics
Volumetric (3D-texture) rendering, end to end, in one package. Built
entirely on the engine's generic `compute.*` GPU primitives — no
Rust changes are needed to author new volumetric content.
## Layout
| Asset | Identity | Role |
|---|---|---|
| `Volume.component` | `@builtin::systems.volumetrics.Volume` | Attach a 3D voxel texture to an entity; stands it in the scene through the entity's transform AABB, hidden by what stands in front of it. |
| `VolumetricSky.component` | `@builtin::systems.volumetrics.VolumetricSky` | Clouds in the sky: one per scene, the procedural cloud layer lit by the scene's sun (through the physical atmosphere's air and sky when a `PhysicalAtmosphere` stands in the scene), drawn by `volumetricSky.renderFeature` with no composite authored. |
| `VolumetricLighting.component` | `@builtin::systems.volumetrics.VolumetricLighting` | Light shafts, god rays and glowing air: light scattering between the camera and the scene, drawn by `lightScattering.renderFeature`. |
| `ParticipatingMedium.component` | `@builtin::systems.volumetrics.ParticipatingMedium` | Mark an entity as fog/smoke/dust the camera sees through and that shades the sun on what is under it. |
| `Smoke.component` | `@builtin::systems.volumetrics.Smoke` | Smoke rising from the entity's position: a chimney's column, steam, a smoulder, a black column over a big fire, smoke signals; lit by the scene with a shadow of its own. |
| `Fire.component` | `@builtin::systems.volumetrics.Fire` | Fire with its smoke at the entity's position: a campfire, a torch, a bonfire, a building on fire, an explosion's fireball; flames glow along a blackbody ramp and a flickering point light halfway up them lights the surroundings. |
| `plume.module` | `@builtin::systems.volumetrics.plume` | The smoke and fire plumes `Smoke` and `Fire` hold, from a script: styles, sizes, quality levels; fills a volume each drawn frame and stands it with `Volume:draw`. |
| `mediaTransmittance.module` | `@builtin::systems.volumetrics.mediaTransmittance` | The registry of media and the settings every media pass reads. |
| `mediaShadow.renderFeature` | `@builtin::systems.volumetrics.mediaShadow` | Writes the sun the media take to `@scene.sunOcclusion` and marches each view ray through the media. |
| `volume.module` | `@builtin::systems.volumetrics.volume` | Builders (`noise`/`sphere`/`box`/`wrap`) + the `.zvol` header reader + occupancy + brick paging + the per-entity raymarch dispatch + the draws standing in the scene (`Volume:draw`). |
| `volume.renderFeature` | `@builtin::systems.volumetrics.volume` | Runs every standing draw's march and composite for each view the frame draws, against its camera and depth. |
| `VolumeSequence.component` | `@builtin::systems.volumetrics.VolumeSequence` | Play an open volume sequence through an entity's transform AABB. |
| `volumeSequence.module` | `@builtin::systems.volumetrics.volumeSequence` | A run of `.zvol` frames streamed through a fixed ring of resident volumes. |
| `volumeDemos.module` | `@builtin::systems.volumetrics.volumeDemos` | Shared pipeline for the showcase scenes (fill + emissive raymarch + composite). |
| `volumetricSky.module` | `@builtin::systems.volumetrics.volumetricSky` | The cloud layer: tiling noise, weather map, raymarch, TAA and composite orchestration. |
| `volumetricSky.renderFeature` | `@builtin::systems.volumetrics.volumetricSky` | The cloud layer's passes for every view the frame draws, brought up by `VolumetricSky`. |
| `volumetricLighting.module` | `@builtin::systems.volumetrics.volumetricLighting` | The light-scattering settings, set from code. |
| `lightScattering.renderFeature` | `@builtin::systems.volumetrics.lightScattering` | The light-scattering passes, brought up by `VolumetricLighting`. |
| `shaders/*` | `@builtin::systems.volumetrics.shaders.*` | Compute shaders `volume_raymarch`, `volume_draw`, `plume_fill`, `volume_pages`, `volume_pack`, `cloud_noise`, `cloud_weather`, `cloud_raymarch`, `cloud_taa`, `cloud_layer_surfaces`; shaders `volume_draw_composite`, `cloud_layer_composite`, `cloud_layer_blit`, `cloud_sky_composite`; shader modules `volume_march`, `cloud_light`, `cloud_surface`, `cloud_shell`. |
| `importers/vdb_to_zvol.importer` | (auto-discovered) | `.vdb` → dense `.zvol` via the `openvdb` WASM plugin (procedural fallback when the plugin isn't loaded). |
| `presets/cumulus_default.preset` | `@builtin::systems.volumetrics.cumulus_default` | Canonical full `VolumetricSky` weather preset. |
| `demo/*.scene` | `@builtin::systems.volumetrics.demo.*` | `sdf_solids`, `smoke_plume`, `nebula`, `godrays`, `zvol_viewer`, `sky`, `showcase`, with their fill shaders. |
The guide `systems/volumetrics/documentation/README` (`guides { path = ... }`)
names the component for each effect, clouds, fog, light shafts, a fog or smoke
volume and the sky, with what each does and costs.
## Path convention — fully-qualified builtin identities
Every intra-package reference uses the asset's fully-qualified builtin
identity, the same convention every other builtin package follows:
```luau
local Volume = require("@builtin::systems.volumetrics.volume")
local Sky = require("@builtin::systems.volumetrics.volumetricSky")
local V = require("@builtin::systems.volumetrics.volumeDemos")
-- shader identities, e.g. asset.resolve("@builtin::systems.volumetrics.shaders.volume_raymarch")
```
Qualified identities are caller-independent: they resolve identically
from a module, a scene entrypoint, or a component. Caller-relative
(`.sibling`) requires are deliberately avoided here because the
component runtime caller identity is `@builtin::components.<Name>`, so a
`.sibling` require from a component resolves against the wrong root.
(An earlier revision of this package used a `~volumetrics` package-root
alias for relocatability; that alias is not resolvable on current main,
so the package uses qualified identities throughout.)
## Usage
```luau
-- Per-entity volume. The component resolves the name through `Volume.get`,
-- so a volume paged into a brick pool renders from the pool under the same
-- name:
local Volume = require("@builtin::systems.volumetrics.volume")
local cloud = Volume.noise({ name = "cloud", size = 64, scale = 4 })
cloud:buildSparse({ brickSize = 8 })
cloud:releaseDense()
entity(id).component.add("Volume", { volumeName = "cloud", density = 6.0 })
-- Procedural sky:
local sky = entity.spawn("sky")
sky.component.add("VolumetricSky", {})
preset.apply("cumulus_default", { entity = sky.id, component = "VolumetricSky" })
-- VDB import: drop a `.vdb` into the VFS; the importer writes a `.zvol`
-- alongside it. Load it with the zvol_viewer demo scene.
-- Animated run: one `.zvol` per frame, played through a bounded ring.
local Seq = require("@builtin::systems.volumetrics.volumeSequence")
Seq.open({ name = "plume", frames = framePaths, resident = 3, fps = 24 })
entity(id).component.add("VolumeSequence", { sequenceName = "plume", density = 6.0 })
```
## Plugin dependency
The VDB importer delegates real OpenVDB parsing to the `openvdb` plugin
in the builtin library, `@builtin::plugins.openvdb`. Without the plugin
the importer falls back to a deterministic procedural torus so the
pipeline stays functional.
# [scene_name]
One-paragraph description of what this scene is — the level, screen or
area it represents, and when the world loads it. This README describes
*this* scene; what a scene is and how loading works live in the scene
assetType README.
## Contents
- What the entity hierarchy holds — the terrain, props, lights and
spawn points a reader should expect to find.
- Which player intent `scene.json` declares (`"spawns"` places the local
player and its camera on join; `"none"` leaves both to the entrypoint).
## Entry point
- `entrypoint.luau` — what it sets up when this scene loads, and
anything a caller has to do before loading it.
# UI Templates — main scene
The startup scene for the **UI Templates** world. `scene.json` materializes a
ground plane, ambient + directional lighting with a procedural sky, and the
standard multiplayer player setup (a `PlayerPrototype` with body + `CameraRig`
under `PlayerSetups`, and a `PlayerSpawn` under `Spawns`). `entrypoint.luau`
holds the lifecycle callbacks (all commented out by default).
This world collects reusable, ready-to-read **UI screen templates** authored
against the `ui.*` CSS-parity surface. Each template is a self-contained script
under `/source/ui/` that registers and shows an `ui` screen. Current templates:
- `ui/p5_menu.luau` — a Persona 5 main-menu lockup: a font-family list resolving
the bundled **Arial Black** face for the blocky title, clip-path polygons for
the torn wedge / octagon badges / row tears, CSS transforms, `-webkit-text-stroke`,
text-shadow, and a repeating-linear-gradient halftone field. Run it with
`execute { file = "/source/ui/p5_menu.luau" }` to display the screen.
# hdrChart
The synthetic HDR chart as a scene: `@builtin::shaders.post.hdrChart` drawn
in place of everything, first in the post chain, so the display path is read
against known light with no lighting in between.
## Contents
- `HdrChart`: a `PostProcess` holding the chart at priority -1000 as its
colour wedge (`pattern = 3`): eleven columns from -4 to +6 stops, the top
half a saturated blue light at the column's middle-grey luminance and the
bottom half that grey. Change the pattern with `postprocess.setProperty` on
the effect, or draw the chart from code with `postMetrics.chart.show`.
- `ReferenceCamera`: a camera to hold the viewport; the chart covers the
whole frame it draws.
The scene's `player` intent is `none`. `postMetrics.chart.reference` builds
the picture a display curve should present for the chart, which
`postMetrics.flip` holds the presented chart against.
# exposureWedge
The exposure reference: known light, read at any exposure.
## Contents
- `GreyWedge`: 21 patches of middle grey (0.18) at -10..+10 stops, one stop
per patch, left to right (`postReference_greyWedge`, unlit).
- `ColorChecker`: the 24 ColorChecker Classic patches, each its published sRGB
value as linear reflectance (`postReference_colorChecker`, unlit).
- `GreySphereLeft` / `GreySphereRight`: two 18% grey spheres lit by `Sun`, a
white directional light of intensity 1 from over the camera's left
shoulder.
- `ReferenceCamera`: the station every reading is taken from, an isolated
camera on black with no ambient term, so the light in the frame is the
charts' own and the sun's.
The scene's `player` intent is `none`. Put the viewport on the camera with
`camera.setEditorOverride(entity.find("ReferenceCamera").id)`, or capture it
with `capture.fromCamera`. Sweep `__display__`'s `exposure` by powers of two
to walk the wedge through the display curve.
# banding
The banding reference: smooth gradients an 8-bit display path quantises.
## Contents
- `ReferenceCamera`: an isolated camera on black at `{0, 0, 6}`, framing the
two ramps.
- `DarkRamp`: light from 0 at the left edge to 0.1 at the right
(`postReference_darkRamp`, unlit): an undithered 8-bit encode climbs it in
steps several pixels wide.
- `SkyRamp`: a sky-blue ramp from 0.02 to 0.6 (`postReference_skyRamp`,
unlit), a clear sky's gradient.
- `FogCamera`, `FogGround`, `FogLight` and `DarkFog`: a second station, at
`{1000, 1, 0}`, looking down a lit grey ground into dark fog
(`@builtin::shaders.post.fog`, density 0.03, fog colour 0.01 / 0.012 /
0.02). The fog is a `PostProcess` box around that station, so it grades
the frame only while the viewport camera stands there: the dark fog ramp
is the ground fading into it toward the horizon.
The scene's `player` intent is `none`. Put the viewport on the station to
read (`camera.setEditorOverride(id)`); `postMetrics.banding` reads a ramp's
longest flat run, and `postMetrics.scopes.zebra` marks the contours.
# quickGeometry
Model a scene in Luau with three.js-shaped code. A `build.luau` or a `.sceneModule` builds `Group`s and `Mesh`es from geometry constructors and materials; at the end of the build the tree is stored in the scene as data, drawn by one `Generator`, and nothing runs per frame.
A bare box reads as a placeholder. Every geometry takes **modifiers** that turn it into a modelled shape: round its edges, taper it, bend it, drill it, smooth it, or build it from a profile or cross-sections. A build whose parts are mostly bare boxes and planes logs a warning that names them.
## Using it
The nouns are globals in a scene's `build.luau` and a `.sceneModule`'s entry script: `sceneNouns` and `quickLighting` join both scripts' contexts, so the engine binds their exports when it loads the script, and the language server knows the same names.
```luau
function content()
local paint = MeshStandardMaterial({ color = "#b0332f", metalness = 0.45, roughness = 0.28 })
local steel = MeshStandardMaterial({ color = "#aab2ba", metalness = 1, roughness = 0.25 })
local body = Mesh(BoxGeometry(1, 1, 1):round(0.14), paint, "rounded_box")
body.position:set(0, 0.8, 0)
local block = Mesh(BoxGeometry(1.1, 1.1, 1.1):subtract(CylinderGeometry(0.3, 0.3, 2, 24)), steel, "drilled_block")
block.position:set(1.5, 0.8, 0)
local hull = Mesh(LoftGeometry({
{ shape = EllipseShape(0.45, 0.28), z = -1.2, scale = 0.25 },
{ shape = EllipseShape(0.45, 0.28), z = -0.55, scale = 0.95 },
{ shape = EllipseShape(0.45, 0.28), z = 0.4, scale = 1.0 },
{ shape = EllipseShape(0.45, 0.28), z = 1.2, scale = 0.3, offset = { y = -0.06 } },
}), paint, "hull")
hull.position:set(3.2, 0.8, 0)
end
```
The same code works in a `.sceneModule`'s builder, where `inputs` declare what a placement may set.
A module joins those contexts with `--!context sceneBuild sceneModule` in its leading comment block, the way these two do. A world's own module joins the same way, and its exports become globals in every build script beside the nouns. A name that starts with `_` stays inside its module. A module that exports `_beginRun` and `_finish` has them called around every run of a build. The `script_context` module's README covers contexts in full.
## Parts
- `Group(name)` holds other objects. `Mesh(geometry, material, name)` draws a geometry.
- `object.position`, `object.rotation` (Euler angles in radians, XYZ) and `object.scale` take `.x`, `.y`, `.z` and the vector methods `set`, `setScalar`, `copy`, `add`, `sub`, `multiplyScalar`, `clone` and `toArray`; calls chain.
- `parent:add(a, b, ...)` nests objects under another, and their poses are then in the parent's frame; an object added elsewhere moves. `parent:remove(a, ...)` takes them out, and a removed object is not drawn until it is added again. `object.parent` and `object.children` hold the tree.
- `object.visible = false` leaves the object and everything under it out of the scene. `object.userData` is a table for your own values.
- `object:lookAt(x, y, z)` or `object:lookAt(Vector3)` turns the object so its +Z axis points at a point in its parent's frame; the object's position and the point are numbers.
- `object:clone(recursive)` copies the object, its pose, components and (unless `recursive` is false) what is under it; the copy shares the geometry and material and is placed like a new `Mesh`. `object:traverse(fn)` calls `fn` on the object and everything under it, and `object:getObjectByName(name)` finds one.
- `object:addComponent(type, data)` puts an engine component on the entity a part becomes (`Physics`, a collider, a `Joint`). A part whose pose follows a formula is drawn as an instance and takes none.
- An object that never moves and carries a component becomes an entity named for it, with its parent and local pose; one that never moves and carries none is folded into the object above it. A moving object's leaves are drawn as instances.
## Geometry
| Constructor | Shape |
|-------------|-------|
| `BoxGeometry(width, height, depth)` | box |
| `CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded)` | cylinder; a cone when one radius is 0 |
| `ConeGeometry(radius, height, radialSegments, heightSegments, openEnded)` | cone with its apex up |
| `SphereGeometry(radius, widthSegments, heightSegments)` | UV sphere |
| `TorusGeometry(radius, tube, radialSegments, tubularSegments, arc)` | torus |
| `TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q)` | torus knot |
| `CapsuleGeometry(radius, length, capSegments, radialSegments)` | capsule |
| `PlaneGeometry(width, height, widthSegments, heightSegments)` | flat rectangle |
| `CircleGeometry(radius, segments)` | flat disc |
| `RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength)` | flat annulus |
| `TetrahedronGeometry`, `OctahedronGeometry`, `IcosahedronGeometry`, `DodecahedronGeometry` `(radius, detail)` | regular polyhedra; `detail` above 0 rounds them toward a sphere |
| `LatheGeometry(points, segments)` | a profile of `{ x = radius, y }` points revolved around Y |
| `ExtrudeGeometry(shape, { depth, curveSegments })` | an outline extruded along +Z |
| `ShapeGeometry(shape, curveSegments)` | a flat, filled outline |
| `TubeGeometry(path, tubularSegments, radius, radialSegments, closed)` | a circle swept along a curve |
| `LoftGeometry(sections, { caps })` | a surface through cross-sections along Z |
| `BufferGeometry()` | a mesh from your own arrays |
| `mergeGeometries(list)` | several geometries as one |
Every geometry also takes `translate(x, y, z)`, `rotateX/Y/Z(angle)` and `scale(x, y, z)`, which move it.
### Outlines and curves
`Shape()` records an outline with `moveTo`, `lineTo`, `quadraticCurveTo`, `bezierCurveTo` and `absarc`. `EllipseShape(rx, ry, segments)` and `RoundedRectShape(width, height, radius, segments)` return ready outlines. `CatmullRomCurve3(points, closed)` and `HelixCurve(radius, turns, height)` return curves for `TubeGeometry`.
### Loft
`LoftGeometry` takes sections in order, each `{ shape, z, scale?, offset? }`: an outline, where along Z it stands, a scale (a number or `{ x, y }`) and a move (`{ x, y }`). `caps = false` leaves the ends open. A body, a hull, a fuselage or a bottle is a loft.
### Custom arrays
```luau
local triangle = BufferGeometry()
triangle:setAttribute("position", Float32BufferAttribute({ 0, 0, 0, 1, 0, 0, 0, 1, 0 }, 3))
```
`setAttribute` takes `position`, `normal` and `uv`; `setIndex(list)` gives triangle indices; without normals they are computed and shared across triangles (`computeVertexNormals()`).
## Modifiers
A modifier changes the shape in its own frame, before `translate`/`rotate`/`scale` move it, and modifiers stack in the order called.
| Modifier | Effect |
|----------|--------|
| `:round(radius, segments)` | round every edge with that radius |
| `:bevel(width, segments, angle)` | round only edges sharper than `angle` degrees; `width` is how far it reaches onto each face |
| `:subdivide(levels, mode)` | split every triangle into four, `levels` 1 to 3 times; `"loop"` (default) also smooths, `"linear"` only adds points |
| `:smooth()` | one round of Loop smoothing |
| `:taper(amount, axis)` | scale the cross-section by `1 - amount * d` at distance `d` along `axis` (`"y"` by default) |
| `:twist(angle, axis)` | turn the shape about `axis` by `angle` radians per metre along it |
| `:bend(curvature, axis)` | curve it along `axis`; `curvature` is 1 over the bend's radius in metres |
| `:subtract(other)`, `:union(other)`, `:intersect(other)` | combine with another closed solid, which stands where it was moved to |
`subtract`, `union` and `intersect` take one shape and one shape; merge parts after combining. Both must be closed solids (a box, cylinder, sphere, torus, capsule or polyhedron, or a bevelled or smoothed one).
## Materials
`MeshStandardMaterial({ color, roughness, metalness, emissive, emissiveIntensity, opacity, side })` and `MeshBasicMaterial({ color, opacity, side })`. A colour is a `Color`, a hex string (`"#a3141b"`), a number (`0xa3141b`), a name (`"red"`) or `{ r, g, b }`; hex colours are sRGB. `side = "double"` draws both faces; an `opacity` below 1 blends.
## Math
`Vector3`, `Color` and `MathUtils` come from the same module as the other nouns and are described in the [math](math.module/README.md) module's README: vector methods and operators, colours from hex, names and HSL, and clamp, lerp, smoothstep and a seeded random.
```luau
MathUtils.setSeed(3)
for i = 1, 12 do
local post = Mesh(CylinderGeometry(0.05, 0.05, 1):round(0.01),
MeshStandardMaterial({ color = Color():setHSL(i / 12, 0.5, 0.5) }), "post" .. i)
post.position:set(i * 0.5, 0.5, MathUtils.randFloatSpread(0.2))
end
```
## Motion
Write a pose as a formula of `Time` (seconds) and the `Expr` functions `sin`, `cos`, `sqrt`, `atan2`, `abs`, `min`, `max`, `mod` and `floor`, with `+ - * / ^`:
```luau
local angle = Time * 6.28
piston.position.y = 1.74 * Expr.cos(angle) + Expr.sqrt(32 - 3 * Expr.sin(angle) ^ 2)
crank.rotation.z = -angle
```
The formula is stored with the scene and runs on the device each frame; children follow their parent's motion.
## Lighting
```luau
Lighting({ background = "#0c0f12", environment = 1, sun = { color = "#fff1dc", intensity = 1.6, position = { 18, 30, 22 } } })
PostProcessing({ exposure = 0.9, toneMapping = "aces", bloom = { threshold = 1.05, intensity = 0.55 } })
```
A scene setup places a whole lighting composition as one asset. The V8Dyno scene places `studioLighting`, a studio backdrop, a warm key light and a sky light that lights the model from the backdrop:
```luau
asset.resolve("@builtin::systems.quickGeometry.studioLighting", "sceneSetup"):instantiate(nil, { name = "lighting" })
```
## Where it lives
Each build ends by spawning one entity named `model` with a `Generator` on the `ModelGraph` graph in this package. The tree is the Generator's `objects` and `channels` inputs, stored in `scene.json`; the shapes are made by the nodes of the `shape` nodebox and the modifiers by procgen's `geometry.*` nodes. Names that two parts share get a numeric suffix.
# [scene_name]
A campfire clearing to start a world from: a low wooded bowl at the edge of a
pond, a path from the spawn to the fire, three log seats and a bench round it,
a lantern on a post beside it, and a sky that runs through the day from 17:30,
with clouds drifting over. Players arrive on the path facing the fire.
Everything here is yours to keep, change or remove. All of it hangs under one
entity, `clearing`, so one call clears it and leaves the player setup:
```luau
tools.use("scene", "remove", { "clearing" })
```
## Parts
Each part directly under `clearing` carries a `role` attribute, so a part is
found, kept or removed by what it is for:
| Part | `role` | What it is |
|---|---|---|
| `lighting` | `sky` | The scene setup `@builtin::scenes.clearing.lighting`: the sky and its hour, the sun that follows it, ambient light, a sky light and height fog. |
| `clouds` | `sky` | A `VolumetricSky` cloud layer, lit by the sun at every hour. |
| `ground` | `ground` | The terrain, the path over it and a `HeightfieldCollider` holding the same heights. |
| `pond` | `ground` | Pond water from the Tidewater package (`@tidewater::tidewater.components.WaterBody`, installed when the world was made), reeds round its edge and a `Water` volume that floats what falls in. A world without Tidewater gets a plain still surface instead. |
| `campfire` | `prop` | A ring of stones and logs, a `Fire` at medium quality, and a collider that keeps players and the camera out of the flames. |
| `seats` | `prop` | Three log seats and a plank bench, each with a collider. |
| `lantern` | `prop` | An iron lantern on a post, with a warm point light that casts shadows. |
| `plants` | `decor` | Trees, bushes, rocks, grass and flowers, scattered from a seed. |
```luau
tools.use("scene", "find", { attribute = { name = "role", value = "decor" } })
tools.use("scene", "remove", { attribute = { name = "role", value = "prop" } })
```
`PlayerSetups` and `Spawns` stand beside the clearing: the player prototype
(a humanoid avatar and an orbiting follow camera) and the spawn on the path.
## Packages
A new world made with this scene installs the Tidewater water kit as a library
(`/source/libs/@tidewater`, pinned at one version), and the pond is its water.
Its guides say what else it does: lakes, rivers, waterfalls, floating and
swimming. `world.uninstallLibrary("@tidewater")` takes it out; the next rebuild
of this scene then draws the plain surface.
## Changing it
`build.luau` states the whole clearing as code, and `scene.json` holds the baked
result. The terrain and the scatter come from one seed and the functions at the
top of the file: change `SEED` for another clearing with the same plan, move
`POND`, `PATH` or `SPAWN`, or edit `heightAt` for another landform. Each part is
one section of `content()`; deleting a section removes that part at the next
rebuild.
The hour is a value of the scene setup:
```luau
local setup = entity.find("lighting").component.get("SceneSetup")
setup:set("sky/backdrop/timeOfDay", 21) -- night
setup:set("sky/backdrop/autoCycle", false) -- hold the hour
```
The day runs while the game plays, on the session clock, so every player sees
the same hour; it holds still in edit mode.
## Entry point
- `entrypoint.luau` holds the scene's load and per-frame hooks, all commented
out until needed.
# Test Suite (asset type)
A **test suite** is a registrable asset that bundles one group of
automated engine tests. Each `<name>.testSuite/` folder holds an
`init.luau` whose body registers a suite (and its tests) against the
test framework this **type** ships in its `shared.module/`, reached
with `asset.containing(__FILE__).modules.shared`, plus a `README.md`
describing what the suite validates.
Test suites are the engine's regression net. Every Luau-facing system —
FFI bindings, components, the renderer, the VFS, multiplayer, the input
stack — ships its coverage as one or more `.testSuite` assets. Because a
suite is an ordinary registrable asset, a new system or package adds its
own tests by dropping a `.testSuite` folder next to its code; nothing
central (the runner, the shell script, CI) has to be edited.
## When to use one
- You added or changed a Luau-facing capability and want a permanent
regression guard for it.
- You fixed a bug — add a test that reproduces it so it can't silently
come back (the `bug_regression` suite is the canonical home for
one-test-per-issue guards).
- A package or system ships behavior that should be validated on every
CI run.
If you just want to *manually* exercise something once, use `execute`
directly — don't author a throwaway suite.
## Where it lives
- World suites: anywhere under `/zero/source/`.
- Package / system suites: anywhere under the package, e.g.
`…/voxelEngine.package/tests/voxel_grid.testSuite/`.
- Identity: the folder stem (`strip_suffix: true`), e.g. `vfs`. Suite
**names must be unique** across the whole tree — the runner and CI
key on the stem.
## Folder shape
```
<name>.testSuite/
├── init.luau # registers the suite via Test.describe / Test.it
├── README.md # what this suite validates + how to run it
└── .metadata # agent-editable tags + free-form fields
```
The type declares only those three files and does not set `allow_unlisted`,
so a suite may ship fixture files (helper `.module` folders, sample data)
alongside `init.luau`, but `asset.validate` reports each one as a
`structure.unexpected_file` warning. The warning does not block publishing.
## How to construct a new suite
1. Create `<name>.testSuite/init.luau`. Reach the framework the type
ships, then declare the suite with `Test.describe(name, fn)` and
each test with `Test.it(name, fn)`. Documentation is authored as
doc-comments the engine's doc parser extracts statically: a
top-of-file `--!desc` for the suite, and a `--!desc` (what the test
checks) plus `--!pass` (the condition that must hold) directly above
each `Test.it`.
```lua
--!desc Spawn / despawn / exists / find over the entity API.
local Test = asset.containing(__FILE__).modules.shared
Test.describe("Entity Lifecycle", function()
--!desc entity.spawn(name) creates an entity and returns its proxy.
--!pass The returned id is a non-empty string and entity.exists(id) is true.
Test.it("spawn returns a stable string id", function()
local id = entity.spawn("probe").id
Test.expect(type(id)).toBe("string")
Test.expect(entity.exists(id)).toBe(true)
end)
end)
return true
```
2. Create `<name>.testSuite/README.md` describing the suite (what system
it covers, notable edge cases, how to run just this suite).
3. That's it. No registration step, no runner edit. The next test run
discovers the suite via `asset.list("testSuite")`.
See `template/` for a copy-ready skeleton (the templater fills in the
`[name]` markers).
## How to run tests
- **All suites** (writes `/source/tmp/test_results.md` + `.json`;
refused in play mode). A bare `run()` covers the world-authored
suites; `"*"` adds the baked `@builtin` library:
```lua
return tools.use("tests", "run", "*")
```
- **One suite directly** (instance-direct — runs only this suite):
```lua
return asset.resolve("vfs", "testSuite"):run()
```
- **From inside the engine** (agent loop): the `tests` toolbox —
`tools.use("tests", "list")`,
`tools.use("tests", "run", { suite = "vfs" })`,
`tools.use("tests", "compare", before, after)` to diff two runs and
surface NEW failures. See the toolbox README.
A suite whose `init.luau` runs without registering a single `Test.it` with
the framework the runner reads has run nothing, so its run fails with a
`registers at least one test` record naming the suite. An installed
package's suite registers with the same framework the runner reads: the
engine runs one copy of the framework its asset type ships, whatever
version the package recorded.
## Discovery commands
```lua
asset.list("testSuite") -- every registered suite, as AssetRef handles
asset.inspect("vfs") -- summary for one suite
asset.resolve("vfs", "testSuite") -- handle { guid, identity, path, type }
tools.use("tests", "list") -- { count, suites = { { name, identity, path, origin, testCount? } } }
```
## Authoring conventions
- **One suite per asset.** Keep a suite focused on one system; large
systems split into multiple `.testSuite` assets (e.g. `zinput_state`,
`zinput_events`, `zinput_actions`).
- **No `await()` inside `Test.it()`.** The framework runs synchronously;
for multi-frame behavior use the per-test context `t.waitFrames(n)`
(see the framework README).
- **Clean up.** Entities the runner can't attribute are despawned
automatically, but prefer `Test.afterEach` for deterministic cleanup.
- **Write fixtures via `Test.tmpPath`.** Any file a test writes to the VFS
must go under its per-test sandbox: `Test.tmpPath("Foo.component/init.luau")`
→ `/zero/source/tmp/tests/<suite>/<test>/...`. That root is under
`/source/tmp/` (excluded from world saves + multiplayer sync, so it never
clogs the synced VFS) and is torn down per-test and again at end-of-run,
regardless of pass/fail/crash. Call it INSIDE the test body. For a fixture
shared across tests in one block, write under `Test.TMP_ROOT` directly
(survives per-test cleanup, still swept at end-of-run). Never hand-roll a
bare `/source/<name>` path — it persists and syncs.
- **Idempotent.** A suite must produce the same result run twice and
must not depend on ordering between suites.
- **Never silence the LSP.** No `--!nocheck` / `---@diagnostic disable`
in a suite — fix the underlying type/global instead.
- **Declare a call that is wrong on purpose.** A test asserting that an API
rejects a wrong-typed or wrong-arity call carries `--!expect-error <code>`
on the line above that call (`--!expect-error type-mismatch`), which is
also how the call runs under the strict gate of `execute`. The checker
holds the line to it: once the API starts accepting the call, the
directive reports `expect-error-unfulfilled`. A cast to `any` keeps quiet
through that change, so the directive is the form a rejection test uses.
## Common pitfalls
- **Duplicate stem.** Two `.testSuite` folders with the same stem
collide; the runner warns and skips the duplicate, and `--list` fails.
Pick a unique name.
- **Forgetting `return true`.** Harmless but conventional — every suite
ends with `return true`.
- **Deferred mutations.** `despawn` / `setParent` / scene clears apply
next frame; verify their effects with `t.waitFrames` or a follow-up
query, not in the same frame.
## Related types
- **`.module`** — reusable Luau library (a suite often requires the
system module under test).
- **`.tool`** — agent-callable function; the `tests` toolbox tools are
`.tool` assets.
- **`.component`** — script component; component behavior is frequently
what a suite exercises.
## In the Inspector
Tests: how many tests the suite declares and their names, parsed without running it, and **Run**, which runs this suite alone in edit mode and reports its passed, failed, skipped and quarantined counts.
# temporalTorture
The temporal reference: the content a temporal resolve gets wrong, under
temporal antialiasing.
## Contents
- `ReferenceCamera`: the station every reading is taken from, at
`{0, 1.5, 9}` looking down -Z; `CutCamera` is a second station
(`{6, 3, 6}`, turned 40 degrees toward the scene, priority -1). A camera
cut is the viewport going from one to the other
(`camera.setEditorOverride(id)`), the frame a resolve has to drop its
history on.
- `TemporalAntiAliasing`: the scene's temporal antialiasing at its defaults.
- `SiemensStar`: 36 spokes of 0.9 on 0.02 (`postReference_siemensStar`,
unlit); toward its centre the spokes are narrower than a pixel.
- `Wire0`..`Wire4`: horizontal wires 0.016 units thick, thinner than a pixel
at this distance (`postReference_white`, unlit).
- `FencePost0`..`FencePost16` and `FenceRail0` / `FenceRail1`: a fence of
thin white posts at a regular pitch, the pattern a jittered resolve
shimmers on.
- `Fan` with `FanBlade0`..`FanBlade3`: four white blades turning at 8 radians
per second (`Mover.spin`).
- `FastObject`: a lit grey cube carried round a 2-unit circle at 3 radians
per second (`Mover`) in front of `CheckerBackdrop`, a 64-cell checker
(`postReference_checker`).
- Everything stands on the scene's dark clear colour, so thin geometry is
read against a flat field.
- `Sun` and `Ambient` light the lit parts.
The movers turn while the engine plays (`engine.mode = "play"`); in edit mode
the scene holds still.
The scene's `player` intent is `none`. Put the viewport on `ReferenceCamera`
and read consecutive frames with `renderer.presentedFrames({ frames = n })`;
`postMetrics.temporalVariance` reads how much each pixel changes across them.
# [scene_name]
One-paragraph description of what this scene is — the level, screen or
area it represents, and when the world loads it. This README describes
*this* scene; what a scene is and how loading works live in the scene
assetType README.
## Contents
- What the entity hierarchy holds — the terrain, props, lights and
spawn points a reader should expect to find.
- Which player intent `scene.json` declares (`"spawns"` places the local
player and its camera on join; `"none"` leaves both to the entrypoint).
## Entry point
- `entrypoint.luau` — what it sets up when this scene loads, and
anything a caller has to do before loading it.
# Tessellation Showcase
Every surface in this scene starts as a **flat two-triangle plane**. The
`Tessellation` component subdivides each triangle into thousands of GPU
micro-triangles and displaces them along their normals from a **height map**,
turning flat geometry into rich relief — no authored high-poly meshes.
The entrypoint drives the same component with four procedural height maps:
| Piece | Height source | What it shows |
| --- | --- | --- |
| Rocky mountains | 5-octave value-noise fBm | Natural terrain from a flat plane |
| Sand dunes | Low-frequency swells | Smooth rolling forms |
| Ocean swell | Crossed sine waves | Repeating wave crests |
| Before / after | Bold ridge grid | Same box, flat vs. tessellated |
## What it demonstrates
`Tessellation` sits next to a `Model` + `Material`. It reads the entity's
current mesh, subdivides each triangle into `4^level` micro-triangles, and
displaces them from the material's displacement map — the entity's PBR
material renders the result. A single flat box + a height map becomes a
detailed surface entirely on the GPU.
## Running
Load the scene and enter play mode. The height maps are generated
procedurally on load, so the showcase is fully self-contained.
# dofChart
The depth-of-field reference: four focus charts at known distances under a
lens focused on one of them.
## Contents
- `ReferenceCamera`: an isolated camera on black at `{0, 1, 0}` looking down
-Z.
- `Lens`: a `DepthOfField` focused at 4 units, f/1.4, 50 mm.
- `FocusChart2m`, `FocusChart4m`, `FocusChart8m`, `FocusChart16m`: the same
chart of bar pairs (`postReference_focusBars`: four rows, 8 pairs across the
top row, doubling on each row below, 0.8 on 0.03, unlit) at 2, 4, 8 and 16
units, each scaled with its distance so all four subtend the same angle.
The 4-unit chart is in focus; the others are as far out of it as the lens
puts them.
The scene's `player` intent is `none`. A chart's sharpness is how many of its
rows still resolve: `postMetrics.profile` along a row reads the bar
contrast.
# bloomEnergy
The bloom reference: emitters of known size and light on black, and a
specular highlight smaller than a pixel that moves.
## Contents
- `ReferenceCamera`: orthographic, 25.6 world units tall, on black with no
ambient term. Captured at **256 x 256**, one pixel is 0.1 world units and
the frame's centre lies on a pixel corner; every size below is in pixels
of that frame.
- `Emitter1px`: a single-texel emitter, centred on the pixel 48 from the left
and 40 from the top (`postReference_emitter`: 16 times the display's
white).
- `Emitter4px` and `Emitter16px`: emitters 4 and 16 pixels square, their
edges on pixel boundaries, at 4.0 world units above the centre (pixel row
88 from the top), centred at x = 0 and x = 8.0.
- `MovingSpecular`: a polished metal sphere lit by `Sun` (directional,
intensity 6), its highlight a sub-pixel source; a `Mover` carries it round
a circle 0.03 units (0.3 pixel) across at 1.5 radians per second.
The scene's `player` intent is `none`. Capture it with `capture.fromCamera`
at 256 x 256, or put the viewport on `ReferenceCamera` and read
`renderer.presentedFrames`. `postMetrics.ringEnergy` reads the light a bloom
spreads around an emitter.
# sceneLighting
Scene setups that light a whole scene with the engine's real-time lighting in
one placement, and a scene that shows them.
- `dynamicLighting.sceneSetup`: a sky whose hour drives a sun and a moon, the
sky light, ray-traced probe global illumination, ambient occlusion, contact
shadows, height fog, exposure that adapts from day to night, temporal
anti-aliasing and screen-space reflections. Its sky, sun and moon are the
assets beside it: `dynamicSky.sky`, `dynamicSun.sceneLight` and
`dynamicMoon.sceneLight`.
- `dynamicLightingShowcase.scene`: a cottage in a garden lit by
`dynamicLighting`, with a room lit through its windows, lamps inside and
out, trees and bushes, a glossy terrace and a mirror ball.
Place the setup in any scene:
```lua
asset.resolve("@builtin::systems.sceneLighting.dynamicLighting", "sceneSetup")
:instantiate(nil, { name = "lighting" })
```
and set `sky/backdrop/timeOfDay` on the placement to move the scene between day
and night.
# modules.api.engine.dirty_hot_reload
Picks up dirty-overlay changes from disk while a scene is loaded in
edit mode, applies them to the live entities, and keeps the in-memory
representation in lockstep with `scene_dirty/` files. Pairs with
`scene_saver` (writes deltas) + `scene_loader` (composes canonical +
overlay at load time).
## Parents
A record's `parent` names the entity it stands under: the entity whose id is
that text, else the entity whose display name is exactly that text. A `*` or
`?` in it is a character of the name, never a pattern.
A record whose parent no entity provides waits. An entity that does not stand
yet is not built, one that already stands keeps its state, the layer logs the
record once, and `debugState(guid).waiting` maps its id to the parent it
names. While a record waits, the scene saver leaves it as it stands rather
than writing a standing entity's older state over it, until an author edits
that entity, which the saver then records as it stands. When a record builds
an entity, the records waiting on that entity's id or display name are built
under it, so a child record that arrives before its parent's record lands
where a load of both places it. Each waiting record is built as its overlay
file states it at that moment, so a record rewritten while it waited,
including by this session's own saver, builds from its current bytes. A load
gives the same account of a record whose parent stays missing: the loader
abandons it with `parentMissing`.
# 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.decode(str: string) -> any` — decode a JSON string. Returns the decoded value, or `nil` + error message on failure.
## 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.
# scene_starter
The files a new scene is started from, read out of a starter scene folder
(`@builtin::scenes.starter_*`). `scene.create { template = ... }` copies a
starter into a new scene of a world with it, and a new world's startup scene is
copied from a starter the same way.
A copy takes every file of the starter except its `.meta` sidecars, so the new
scene gets an identity of its own where it is written. It takes the baked
`scene.json` with the `.build.state` that records the build script it was baked
from, so the new scene opens as the starter does without running its build.
`README.md` and `entrypoint.luau` carry the new scene's name where the starter
leaves a `[scene_name]` slot, and the copied `scene.json` records the document it
holds as the scene's initial generated baseline (`authoring.initialGenerated`,
as a scene `asset.create` makes carries), so the first authoring save reads the
entities the starter's build placed as that build's own.
```luau
local Starter = require("@builtin::modules.scene_starter")
local source = "/zero/source/libs/@builtin/scenes/starter_clearing.scene"
for _, rel in Starter.paths(source) do
vfs.write("/source/scenes/camp.scene/" .. rel, Starter.bytes(source, rel, "camp"))
end
```
- `paths(sourcePath)`: the files a copy takes, relative to the starter folder,
sorted.
- `bytes(sourcePath, rel, sceneName)`: one file's bytes as the new scene holds
it, or nil when it cannot be read.
- `sceneName(destPath)`: the scene name a `<name>.scene` folder path holds.
# PlayerPrototype
Marks the root of a player-setup subtree — the entity and children that define what a joining user becomes (avatar slot, spawn behaviour, controller). On awake it flips the entity to PrototypeOnly participation, so the prototype lives in the editor and drives spawning without being saved as a world entity itself; `kind` and `label` describe it for authoring surfaces. In edit mode it draws a cyan silhouette outline so the prototype root is easy to pick out, and surfaces its own setup-validation messages (missing camera, avatar slot, or wrong participation) on the component's error channel.
Location: `src/lua/lib/components/PlayerPrototype.component`
# component_snapshot
Serialized snapshots of script-component public data.
A component's `public` table is a live proxy — its fields live behind
`__iter` / `__index` metamethods, so copying or JSON-encoding the proxy
directly yields an empty table. This module materializes the plain,
serializable form. It is the script-component parallel to `ecs.snapshot`
(native components).
```lua
local componentSnapshot = require("modules.component_snapshot")
-- one component: live proxy -> plain table
local data = componentSnapshot.snapshot(entity(id).component.get("Camera"))
-- whole entity: { [type] = data }, named/multi instances nested as
-- { [type] = { [instanceName or "__default"] = data } }
local all = componentSnapshot.snapshotEntity(entity(id))
```
`componentSnapshot.plainCopy(value)` materializes ONE live value the same
way — a table behind a proxy is walked into a plain table, every other
value passes through — for callers reading a single field rather than a
whole component.
Serialized form: entity refs become id strings, asset refs become
`{ __ref, name, type }` envelopes, vectors and colors their plain-table
forms; framework functions are omitted. `snapshot` returns nil for a proxy
with no serializable fields.
Persistence (scene serializer, bundle capture, prototype spawn) and
inspection tooling (`debug.inspect`) read component data through this
module. Live gameplay reads and writes stay on the proxy itself via
`entity(id).component.get` / `getAll`.
# Scene composition transactions
`capture(folder, inputs)` reads a scene and its authored records under a world-bound source transaction. Capture build inputs before evaluating the builder, and pass the resulting document to `rebuild`. `edit` accepts saved entity records before and after an authored change. Both compose and validate before preparing an atomic update of the accepted generated base, intent records, and `scene.json`.
`editChanges(snapshot, entities, settingsEdits, opts, retirePaths?, attribution?)` accepts compact observed field changes. Each entity row has `id`, `changes` from `FieldEdits.diff` over normalized records, and optional component `bookkeeping`. Settings use field edits over the scene fields. Changes retain their original observed values when retried against a newer snapshot. `retirePaths` names captured journal files removed atomically with the accepted composition; a newer journal revision makes the entire transaction stale. `editDocument` projects saved documents into this same field-change path.
Journal consumers pass a session/sequence receipt to `editChanges` with the corresponding captured operation path in `retirePaths`. The coordinator checks the consecutive sequence, records its checksum in accepted state and retires that source atomically. Rebuilds preserve these receipts. `assetTypes.scene.shared.journal` handles operation creation, persistence, recovery and retry checks.
`migrate` accepts a legacy visible document derived from the captured scene and overlay, together with a recovered generated base when available. It retains the canonical and visible documents as recovery history and records unresolved baseline identities.
`incorporate` prepares source replacements together with selected intent retirement. Each selection names an entity (or scene settings), the captured intent revision, and exact field paths. The candidate generated value must reproduce every selected value. Unselected intents remain. Candidate source fingerprints, the generated base, build digest and artifact advance together.
For a loaded scene’s `build.luau`, `scene:prepareSourceChange(sourcePlan, selections)` evaluates the candidate from `SourceEditing.prepareTarget`. It returns the coordinator plan together with the target’s scope and known outputs. Candidate evaluation uses isolated capture: persistent writes, external requests, deferred task work and foreign-entity changes are refused. Component lifecycle work on candidate-owned entities is captured and cleaned up.
`awaitApplied(folder, revision, scope)` waits for an accepted complete revision to arrive through the local subscription. A committed result acknowledges backend persistence; this wait establishes local visibility.
`commit` returns the durable source-operation result. Its operation identity supports inspection, retry and cancellation through `modules.sourceOperations`. Runtime scene activation observes the committed files. Structural conflicts return a plan with `ready=false` and preserve the last valid document.
# player_prototype_spawn
The deterministic spawn core for authored player prototypes. A PlayerSpawn entity names a PlayerPrototype subtree to instantiate; `spawnFor` clones that subtree from its captured authored template, prunes clone-subtree nodes whose networkScope excludes the caller's owner/authority role, marks the clone RuntimeOnly, and turns the clone root into the joining user's hidden UserIdentity, named `user` like every user identity (the prototype keeps its own name, so a lookup by that name reaches the prototype), plugging it into the players registry, join/leave, ownership, and sync. The body named by `PlayerPrototype.body` is adopted as the user's avatar and placed at the PlayerSpawn's world transform; the prototype's CameraRig follows it. `installJoinHook` wires `spawnFor` to a scene's user-join event so a joining user is placed automatically.
Location: `src/lua/lib/modules/api/engine/player_prototype_spawn.module`
# Camera
Manages viewport priority, render-to-texture, and capture. State is stored in the native `Camera` ECS component; the Rust camera system handles render scheduling and render targets.
Public fields: `fov`, `near`, `far`, `priority`, `textureHandle` (the guid of the texture the camera renders into; empty = main viewport), `renderLayers` (which render layers this camera draws — a space-separated spec of names, e.g. `"all"`, `"all !ui"`, or `"default sky"`; `ui`/`sky`/`debug`/`EditorUI` are built-in layers), `postProcessing` (whether this camera runs the post-process chain), `debugChannel`, plus the behavior slot below.
Methods: `:lookAt(target)` (entity id string OR `{x, y, z}` table), `:render()`, `:capture()`, `:setTargetTexture(tex?)` (a `renderer.texture.create` handle to render into, or nil for the viewport).
```luau
entity(id).component.add("Camera", { fov = 90, priority = 10 })
entity(id).component.get("Camera"):capture()
```
The scene's play-mode camera is reached as `layers.active.camera`, a handle that
reads and writes the fields above on whichever entity currently carries them.
`layers.active.camera.entity` is the entity ref for that camera and
`layers.active.camera.entityId` its id string, so a script that needs to attach
something to the camera — an `AudioListener`, a child entity — goes through the
ref:
```luau
local cam = layers.active.camera
cam.fov = 70 -- the camera's settings
cam.entity.component.add("AudioListener") -- the entity carrying them
```
## How the camera moves: `behavior` and `follow`
A `Camera` does not move itself. `behavior` names a component that does, and setting it attaches that component to this entity. Clearing it detaches whatever was attached.
```luau
local cam = entity(id).component.get("Camera")
cam.behavior = asset.ref("@builtin::controller.orbital_follow", "component")
cam.follow = playerBody
```
The attached behavior is an ordinary component on the camera's entity, so it is tuned the way any component is: read it with `component.get` and set its fields there. A `component.add` of the same type configures the instance the slot attached instead of adding a second one: the values it passes are written onto that instance and its proxy is returned. That add is the form a scene `build.luau` tunes the behavior with, because its values are saved with the scene and the loaded Camera's behavior takes them back. A key the component reads only as it is created (one of its `initKeys`, a private field) refuses the add and names the key.
```luau
cam.behavior = asset.ref("@builtin::controller.third_person_follow", "component")
local rig = entity(id).component.get("third_person_follow")
rig.cameraDistance = 6
-- the same, as an add of the type the slot attached
entity(id).component.add("third_person_follow", { cameraDistance = 6 })
```
`follow` is the standard slot every shipped behavior reads. Set the follow target on the **Camera**, not on the behavior, so swapping behaviors keeps it. A behavior that finds its own `follow` field empty falls back to this one, which is what lets a rig keep tracking the player across a behavior swap.
`followResolves` answers whether that slot names an entity that is live — `true` while it names a live one or names nothing at all, `false` once the target is despawned or the id names no entity. A rig whose target does not resolve holds its last pose, and this is the field that tells it from a rig posed correctly on a subject that has not moved. `camera.get` carries the same value beside `follow`, and a write naming an id with no entity behind it draws a warning where it lands.
```luau
cam.followResolves -- false once the followed entity is gone
tools.use("camera", "get", id).followResolves -- the same answer off the tool
```
The shipped behaviors live under `@builtin::controller.*`: `orbital_follow`, `third_person_follow`, `first_person`, `free`, `orbit`, `chase`, `isometric`, `rts`, `birds_eye`, `side_scroller`, `cinematic`, `menu`.
## Writing your own
Any component can be a camera behavior. Write one that moves its own entity and attach it the same way:
```luau
cam.behavior = asset.ref("MyChaseCam", "component")
```
`follow` lives on the Camera, so a behavior gets no property notification of its own when the target changes. Declare `onFollowChanged(newFollow, oldFollow)` to be told the moment it does — the Camera calls it on the component it attached, which is what lets a rig re-pose on the new subject at once. A behavior that reads `Camera.follow` on its own schedule declares nothing and is attached the same way.
```luau
typed function public:onFollowChanged(newFollow: any, oldFollow: any)
-- pose this entity against the new target
end
```
To make it appear in the discovery catalog alongside the shipped ones, declare the `cameraBehavior` tag in the component's `.metadata`:
```json
{ "tags": ["cameraBehavior"] }
```
The tag governs **discovery**, not attachment. A tagged component is listed by `layers.active.camera.behaviors` and is what tooling offers when something asks "which camera behaviors exist"; an untagged component attaches just as well and simply stays out of that list. Tag the ones you want other people (and agents) to find.
```luau
for name, ref in pairs(layers.active.camera.behaviors) do
print(name, ref.identity)
end
```
## Texture colour space
`textureColorSpace = "display"` applies the display transform when rendering into a texture. `"linear"` writes scene-linear values instead. `postProcessing` independently controls the effects chain in either mode. Floating-point targets retain values above one; normalized targets clamp to their representable range. The main viewport uses display encoding.
# `scene.shared.saver`
Luau-side scene saver. Writes `scene.json` v6 — **authored intent
only**. No captured runtime state.
## Public surface
```lua
local saver = require("@builtin::assetTypes.scene.shared.saver")
saver.save(name, opts?)
-- name: logical scene name ("main") OR full VFS path
-- opts.layer: layer name to read from (default layers.active.name or "main")
-- Returns: the absolute VFS path written.
```
## What is captured
| Field | Source | Notes |
|---|---|---|
| `format`, `version` | constants | Always `"scene"` + `6`. |
| `entities` | `entity.findAll()` walk | Excludes `temporary` entities + the spawner-managed Player + primary Camera. |
| `entities[].transform` | local position / rotation / scale | NOT world transform — local only. |
| `entities[].components` | component.list + component.get | Strips `_`-prefixed runtime fields. |
| `entities[].attributes` | `attribute.list` + `attribute.get` | The entity's key/value bag, written as a `{ [key] = value }` map; omitted for an entity that holds none. Holds the authored keys — a `_`-prefixed key is the engine's own session bookkeeping. |
| `lighting` | `lights.snapshot()`, filtered | Scene-level `clear_color` + `sky` only. Directional / ambient / point lights persist as `Light` entities in `entities[]`. |
| `player` | `sceneProxy.player_config` | Carried forward from load-time, authored only. |
| `camera` | `sceneProxy.camera_config` | Carried forward from load-time, authored only. |
## What is NOT captured
- Local player's position / rotation. Runtime drift; not authored intent.
- Primary camera's transform. Runtime; behavior-driven.
- Any entity flagged `temporary = true`. Debug helpers, runtime markers.
- Internal component fields prefixed with `_` (e.g. `_velocity` on CharacterController).
The spawner-managed entities (Player + primary Camera) are excluded
because they're created on load by player_spawner / camera_spawner
from the scene's declarative `player` + `camera` blocks. Saving them
would double them on the next load.
## Parts
The module is a folder of parts, each a module of its own that `init.luau` requires:
- `scene_saver.serialize`: one live entity as the record a scene file carries.
- `scene_saver.recordDiff`: the comparisons the record diffs are built from.
## When to use
`layers.active:save(name)` (Phase 6) routes through this module. Callers
that want a state snapshot (save-game systems, undo stacks) should use
`world.debugSaveToDisk(...)` instead — that captures runtime state by design.
# Scene record projection
Require `@builtin::assetTypes.scene.shared.records`.
`saved(record, componentGuid)` converts a persisted entity into `{value, bookkeeping}`. `captured(record, ids, componentGuid)` converts an entity-record capture and remaps captured entity references to persistent placement ids. The resolver receives a component type spelling and returns its stable identity; unresolved types must raise an error. Captured entities require an entry in `ids`.
`value` holds editable fields with normalized transform and lifecycle defaults. Components are grouped by stable type identity: `named[name]` addresses one named instance, while `anonymous` preserves an ordered group. Saved `instance_index` markers are reconstruction metadata, and restoration emits them alongside named `instance_name` markers. FieldEdits treats that anonymous array atomically. Asset references compare by guid and type. Component references retain their entity, instance information and stable component type.
`bookkeeping` holds build ownership attributes, component order, and captured reference paths and row-field declarations. These capture annotations describe reconstruction and stay outside field comparisons. Compose edits over `value`, then call `restore({value=composed, bookkeeping=current.bookkeeping}, componentName)` to produce the saved record. The reverse resolver supplies the current component type spelling. Surviving instances retain their order; added instances are appended in deterministic order.
The module validates structured input before copying it. Duplicate named instances and missing identities fail before any scene mutation.
# Asset
Promote the bundle's spawned children from temporary to permanent scene state and remove the Asset component, "baking" the bundle's contents directly into the owning scene. Subsequent saves persist the baked entities verbatim and stop replaying the bundle template.
Location: `src/lua/lib/components/Asset.component`
# PlayerSpawn
A world entity that spawns players from a prototype. It carries the fields describing how spawning happens: which `prototype` to instantiate, the `team` and `role` assigned to spawned players, a `maxPlayers` cap (0 = unbounded), the `spawnPolicy` (how many players spawn from this point), and the `placement` (where a spawned player is positioned). The entity's own transform is the spawn point when `placement` is `at_spawn_transform`. In edit mode it draws an orange silhouette outline at the spawn point and surfaces its own setup-validation messages (missing or mis-targeted prototype) on the component's error channel.
Location: `src/lua/lib/components/PlayerSpawn.component`
# opts
The contract an options table is held to. A call that reads a fixed set of
keys acts on those keys and no others, so a key it does not know names a
change the caller asked for and never got — a cube asked for `size = 3` that
comes back one unit wide, reporting success. `Opts.check` makes that a refusal
carrying what to write instead: the key, the accepted set, and the nearest
accepted spelling.
The same three parts answer for a name of any kind — `tools.use` names the
near-miss toolbox, `MaterialAuthor` names the near-miss shader property — so
the distance search lives here too, and every caller ranks candidates the same
way.
Pure Luau, no engine dependencies.
## Exports
- `Opts.check(where: string, value: any, accepted: { string }, inTable?: string)` — raise unless every key of `value` is named by `accepted`. `nil` accepts.
- `Opts.forward(where: string, own: { string }, fn, ...) -> ...` — call `fn(...)`, and when it refuses an option, append the vocabulary `where` itself takes.
- `Opts.unknown(value, accepted) -> { string }` — the keys `value` carries that `accepted` does not name, sorted.
- `Opts.nearest(key: string, candidates: { string }) -> string?` — the candidate `key` is most plausibly a misspelling of, or nil.
- `Opts.editDistance(a: string, b: string, limit: number) -> number` — single-character edits between two names, capped at `limit + 1`.
## Usage
```luau
local Opts = require("@builtin::modules.opts")
-- The keys this call reads, named once.
local CUBE_OPTS = { "animate", "scale" }
function M.cube(name, x, y, z, opts)
Opts.check("primitives.cube", opts, CUBE_OPTS)
-- primitives.cube: unknown option 'scail'. Accepted: animate, scale. Did you mean 'scale'?
-- The spawn target is handed to `entity.spawn`, so it is that call's
-- contract a key is checked against — `own` says what this one takes.
local e = Opts.forward("primitives.cube", { "opts.scale", "opts.animate" }, entity.spawn, name)
-- entity.spawn: unknown option 'size'. Valid options: name, hidden, …
-- (primitives.cube itself takes: opts.scale, opts.animate)
end
```
A call taking more than one table names which one the key was written in:
```luau
Opts.check("primitives.ground", color, { "r", "g", "b", "a" }, "color")
-- primitives.ground: unknown option 'red' in color. Accepted: r, g, b, a. Did you mean 'r'?
```
## Notes
- Refusals raise at level 0: the message is the whole error, so a caller reads
the contract rather than the line inside the library that checked it.
- A key of any type is reported by how it is written, so the positional form of
a named shape (`{ 200, 50, 50 }` for `{ r = , g = , b = }`) names its indices
rather than passing as a table with nothing the call reads.
- `nearest` is case-insensitive, and a candidate containing the key scores by
how much longer it is, so `roughnes` prefers `roughness` over
`clearcoat_roughness`. How far a plain misspelling may stray scales with the
key's own length — a four-letter key admits two edits, a longer one three —
so a short key is not answered with an unrelated short name.
- Equal scores go to the shorter candidate, then the alphabetically earlier
one, so the answer never depends on the order candidates were listed in.
- `forward` matches the phrase both this module and the engine's own option
checks use for the condition (`unknown option '<key>'`). Every other error
passes through as raised.
# luau_introspect (module)
Parses Luau/asset source TEXT into structured declarations. Pure
string/pattern parsing (`string.find` / `string.match` / `string.gmatch`)
over the literal source — no compiling, no VM spawn, no runtime state, no
engine FFI. Given source text, it extracts what is written in the file.
This is the shared parser every per-assetType `M.ref.inspect` hook uses to
turn a component/module/tool's own source into the structured record
`asset.inspect` returns.
## Exports
- `docstrings(src) -> DocMap` — scans `--!desc` / `--!arg` / `--!return` /
`--!example` comment runs and binds each run to the name of the
declaration on the next non-comment line (the identifier after
`function`, `public:`, `local function`, or `M.`).
- `publicFields(src) -> { FieldEntry }` — parses `public = { name =
Field.<kind>(default, mode), ... }` table-literal entries and
module-scope `public.<name> = Field.<kind>(...)` assignments.
- `events(src) -> { EventEntry }` — parses `events = { name =
Event(payloadSchema?, syncMode?), ... }` table-literal entries.
- `methods(src) -> { MethodEntry }` — parses `function public:<name>(...)`
/ `typed function public:<name>(...)` declarations (params + optional
return type).
- `lifecycleHooks(src, catalog) -> { string }` — top-level `function
<name>(` declarations whose name is in the caller-supplied `catalog`
array.
- `moduleExports(src) -> { ExportEntry }` — parses `M.<name> = function`
assignments, `function M.<name>(...)` declarations, and a trailing
`return { foo = foo, ... }` export table.
- `forSource(src, computeFn) -> any` — memoises `computeFn(src)` keyed on
`src` itself in a module-local table. The same source text returns the
cached result without re-running `computeFn`; different source text
recomputes. Keyed on the source content (not an asset checksum) because
composite/container assets (component folders, scene folders, etc.) all
hash to the empty-string checksum — a checksum-keyed cache collapses
every such asset's detail onto whichever one was inspected first.
## Usage
```luau
local Introspect = require("modules.luau_introspect")
local src = self:getInitScript()
local detail = Introspect.forSource(src, function(s)
return {
fields = Introspect.publicFields(s),
events = Introspect.events(s),
methods = Introspect.methods(s),
hooks = Introspect.lifecycleHooks(s, lifecycleCatalog),
}
end)
```
## Notes
- Every function is a pure string→table transform: same source text in,
same structured table out, every time. No reads of live component
state, no entity/world queries.
- Structural scanning runs over a comment- and string-aware **mask** of
the source (a same-length copy where comment bodies and string-literal
contents are blanked to spaces, delimiters and newlines preserved).
Pattern matches and brace/paren balancing run on the mask — so a brace,
`Field.`, `Event(`, or a whole entry that appears inside a comment or a
string literal never registers — while captured values are sliced from
the original source at the same (aligned) indices. This makes the
parser robust to apostrophes in comments, commented-out entries, string
defaults containing `}` / `Field.` / `Event(`, and `[[ ]]` long
strings.
- `default` / `category` are raw trimmed source-text slices (with any
trailing comment stripped), not evaluated values.
- For a **ref constructor** (`Field.assetRef` / `dataRef` / `resource`
/ `componentRef`) the FIRST positional argument is the category /
contract / componentType selector, captured under `category`; the
SECOND argument is captured under `default`.
- For every **other** Field kind the first argument is the `default`
and `category` is nil.
- A trailing `Sync` / `NoSync` identifier is captured as `sync`,
tolerating a trailing comma or a trailing comment after the last
argument.
- Field/Event entries whose key is a computed or indirect expression
(`[expr] = Field.number(...)`) are omitted — only literal identifier
keys are recognised.
- `methods` captures a `...` variadic parameter (as `name = "..."`), with
its `: <type>` annotation when present.
- A `--!desc` written above a field/event declaration (`<name> =
Field.<kind>(...)` / `<name> = Event(...)`) or a `public.<name> =`
assignment binds to that name in `docstrings`, and is folded into the
corresponding `publicFields` / `events` entry's `desc`.
- `lifecycleHooks` never hardcodes the lifecycle-callback catalog; the
caller passes the list of names to match against.
- `forSource`'s memo is bounded (oldest-key eviction) so a long session
touching many distinct asset versions can't grow it without limit.
# ik
Look at a rig's bones and at what an IK solve is actually doing.
Debugging IK means answering three questions, and none of them can be answered
from a screenshot: what are this rig's bones called, where are they right now,
and is the chain reaching its target or merely near it.
`bones` lists a body's bones with their world positions and parents — the names
you need before naming a chain, and the positions you measure against when
checking a solve from outside the component. Rigs rarely use the word you would
guess: the standard humanoid here calls its feet `Ankle_L` and `Ankle_R`, with no
bone containing "foot" anywhere.
`reach` reports how far a limb can extend and how far away a point is, both in
the same units. A target beyond a limb's reach has no solution — the chain
extends straight toward it and stops, which is correct and looks exactly like a
broken solver. This is the first thing to check when a solve looks inert.
`state` gathers every IK component on an entity and reports what each one is
doing, so "is anything solving at all" is one call rather than five.
# assetType runtime
The machinery that reads a `<typename>.assetType/behavior.luau` and turns its
declarations into live behaviour.
A `behavior.luau` is a table of declarations — `ref` methods, `modules` shared
code, an `events` schema, a `namePattern`, `refShapes`, and the `onCreate` /
`onRegister` / `onChange` / `onDelete` / `validate` / `settingsDefaults` /
`settingsCorrections` hooks. None of it runs itself. This is the code that
runs it, and it lives here because reading a type's declarations is the
**assetType type's own behaviour** — the same way `material.assetType` owns
what a `.material` does.
## Sub-modules
| Module | Reads | Responsibility |
|---|---|---|
| `ref.module` | `ref`, `modules` | Builds every `AssetRef` envelope, attaches the shared metatable, and dispatches per-type methods and shared modules onto it. Also owns edit-mode write-behind persistence. |
| `create.module` | `onCreate`, `namePattern`, `validate` | Backs `asset.create`: resolves the type, checks the name against its pattern, runs `onCreate` (or clones `template/`), and writes the instance. `validate.module` beside it checks a creation `opts` table against the type's `createSchema`. Before running `onCreate`, resolves the type's settings chain (below) and hands the result to the hook as `opts.settings`. |
| `settings.module` | `settings`, `settingsDefaults`, `settingsCorrections` | A type's declared settings schema and where its values live (`type.yaml`'s `settings:` block). `Settings.resolveForCreate` layers the schema's own defaults, the type's own `settingsDefaults(name, opts, asked)` hook (a DEFAULT the schema can't express — a name-derived convention, a fact read off a payload the caller handed it, a value following a field `asked` shows a higher layer naming; any later layer overrides it), the Preset Manager, an importer's settings, the caller's `settings` table, then the type's own `settingsCorrections(values, name, opts)` hook (a CROSS-FIELD CONSTRAINT the schema can't express, applied last over the fully merged values). A correction over a default/preset/importer value lands silently; a correction that would override what the caller's own `settings` table explicitly asked for refuses the creation instead, naming the field and why. Neither hook is ever handed a table to mutate; each returns what it wants changed (`settingsCorrections` may also return a `{ [field]: reason }` table for that refusal message). `Settings.cloneValues` deep-copies a values table — `create.module` hands `onCreate` a copy, never the table it stamps. `Settings.valuesOf` / `writeValues` read and write an asset's own values file. |
| `typeYaml.module` | `type.yaml` | The folder a type lives in and its parsed `type.yaml`, decoded once per content version of the file. `settings.module` and `inspector.module` read their blocks through it. `about` / `aboutAt` read a type's `about.yaml` (`intent`, `function`, `usage`), leaving out any key that is empty or still starts with `[[describe]]`; `aboutRows` and `aboutMarkdown` lay the texts out for the Inspector and the `types/<name>` guide. |
| `inspector.module` | `type.yaml`'s `inspector:` block | Which inspector a type declares for its assets (`inspector: { type: ... }` or `{ instance: ... }`), and the declaration that file returns — the sections it adds, the generic ones it replaces, and their order — or the problem that kept it from loading. |
| `onRegister.module` | `onRegister` | Fires an instance's once-only registration hook — on arrival, on world load, and for `@builtin` library instances. |
| `changeDispatch.module` | `onChange`, `onDelete`, `refShapes` | Routes a VFS source write or a folder delete to the enclosing typed asset's type hooks. |
| `refShapes.module` | `refShapes`, `ref` | Publishes what every `AssetRef<category>` answers to, so a member read on an asset-typed value is checked against that category's real surface. |
| `events.module` | `events` | The per-asset event runtime behind `ref.events`. |
| `instantiable.module` | `ref.instantiate` | The instantiation contract an asset type opts into: `root` stands the root entity, `place` applies the base placement opts to one the type adopted, and `result` shapes the `(root, idMap)` every `instantiate` returns. Also registers the `sceneInstantiable` field-constraint validator. |
| `declaration.module` | `type.yaml` | The type's decoded declaration, read once and held until a write inside an `.assetType` folder; what every question about a type as a whole reads. |
| `previewRecipe.module` | `type.yaml` `preview:` | How an instance's `preview.png` is produced: which of the four recipes (`instantiate`, `image`, `surface`, `custom`) the type declares, and what that recipe needs. |
## Reaching it
```luau
local rt = require("@builtin::assetTypes.assetType.shared")
rt.ref.loadTypeBehavior("material")
```
Fields resolve lazily. The prelude requires the sub-modules directly, in
dependency order (`ref`, then `changeDispatch`, `onRegister.install()`,
`refShapes.install()`) — a table that required all six on load would take that
ordering away from it.