Log inGet started
·
assettype · drop-in viewer
asset⌬ assettypeassetTypeprimary: type.yaml·originates fromworld 07158574-5…

testSuite.assetType

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.…

byzero-proxy @ DESKTOP-DB3UJOJ·posted 4mo ago
What it does

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.

    --!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:
    return tools.use("tests", "run", "*")
    
  • One suite directly (instance-direct — runs only this suite):
    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

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.

Interface

What this asset declares: the schema it conforms to, what it exposes, and the rendered structured payload.

conforms to

zero/asset-type/v1
⌬ Spec
suffix.testSuitecontainernoprimary aliasesinit.luau, init.luarequired filesinit.luau, README.mdoptional filesinit.lua, .metadata
Exposed API
⌬ Instance methods

run(self: ?, opts: { quiet: boolean?, subjects: { string }? }?) → any

Run THIS test suite (only this one) and return its results. Refuses in play mode — tests are an edit-mode / authoring concern, not gameplay. The run is cooperative (the framework yields a frame between tests) so it never blocks the engine or trips the execute watchdog. The run holds the test framework while it runs (`Test.exclusive`): one started while another run is in flight waits for that run to end, and answers its own tests. types the run holds the suite to (`Test.subjects()`).

argtypedescription
self?
opts{ quiet: boolean?, subjects: { string }? }?Optional `{ quiet, subjects }`: `subjects` names the asset

examples

local r = asset.resolve("vfs", "testSuite"):run()

tests(self: ?) →

List the tests this suite declares (loads THIS asset's `init.luau` to read its registered `Test.it` / `Test.skip` names; does not run them).

argtypedescription
self?

examples

for _, t in ipairs(suiteRef:tests()) do print(t.name) end

getReadme(self: ?) → string

Read this suite's `README.md` body.

argtypedescription
self?

examples

print(suiteRef:getReadme())

inspect(self: ?) → any

`asset.inspect` type-specific detail: `{ testCount, testNames }`, parsed from `Test.it("<name>", ...)` calls in this suite's own `init.luau` text. A string scan, not a suite run — inspecting a suite never registers or executes its tests. A suite with no readable `init.luau` returns an empty `testNames` list rather than erroring.

argtypedescription
self?

examples

local testNames = asset.inspect(suiteRef).detail.testNames

Sub-parts

Everything contained inside this part. Assets are composite children (clickable cards). Files are leaf payloads. Expand any row to view its source.

Showing up to 3 levels deep. Open a part to see what it holds further down.

188+items
·
scene · born here
❒asset
# assetTypes.testSuite.empty (scene) Minimal v6 scene used by `Test.useScene()` as the default fixture for per-test scene isolation. - No entities. - No player (`required_in_{edit,play} = false`). - No camera (`required_in_{edit,play} = false`). - Sky disabled, so the renderer doesn't pull in an editor-default skybox. `Test.useScene()` reads this folder's body and copies it (skipping `.meta` sidecars so the engine regenerates fresh guids per test duplicate) into a unique sandbox path under `Test.TMP_ROOT`, then `layers.load`'s the duplicate. The duplicate's lifecycle is tied to the current test: `Test.afterEach` unloads it and deletes the sandbox copy. If a test needs a richer setup (a player prototype, a Camera, a sky), it passes an explicit `opts.fixture` path to `Test.useScene()` pointing at its own fixture; otherwise it gets this empty shape.
▲ 0↑ born
▣
module · born here
❒asset
# test Test framework — simple unit testing with the `describe` / `it` / `expect` pattern. Used by the engine test suite and any user-authored suites that want a single dependency. Pure Luau; flag-based failure tracking instead of exceptions (works the same on native and WASM). ## Exports Definition: - `Test.describe(name: string, fn: () -> ()) -> Suite` — define a suite. The body declares the suite's cases, so only what it reached is in the run: a body that ends on a raise leaves a `<describe body did not finish>` case behind, naming the describe and what it raised, and the run ends on that case. A body that stands down leaves the same case marked skipped, carrying the reason. - `Test.it(name: string, fn: (TestContext) -> ()) -> any?` — define a test. - `Test.skip(name: string, fn: ((TestContext) -> ())?) -> any?` — skip a test. Inside a `describe` with a body it declares a skipped test; inside a running test (its body or one of its hooks) a reason alone stands that test down — the test ends there, is counted under `skipped`, and the reason reaches the console, the per-test record and the report. A reason alone anywhere a test is not running raises, naming the declaration form. - `Test.beforeEach(fn: () -> ())` / `Test.afterEach(fn: () -> ())` — per-test hooks. - `Test.expect(value: any) -> any` — expectation builder with `toBe`, `toBeTruthy`, `toBeFalsy`, `toBeNil`, `notToBeNil`, `toBeType`, `toBeGreaterThan`, `toBeLessThan`, `toBeCloseTo`, `toContain`, `toMatch`, `toHaveLength`, `toThrow`, `never()`. - `Test.captureFailure(fn: () -> ()) -> string?` — run a body and return the failure it records instead of recording it, for tests that assert a matcher rejects something. A body that records several returns the headline for them. - `Test.captureOutcome(fn: () -> ()) -> Outcome` — run a body the way the runner runs a test body and return `{ failed, error, failures, raised }`: its failures in the order they happened, with a raise that ended the body as the final entry. - `Test.captureTestOutcome(spec: TestSpec) -> TestOutcome`: run a whole test the way the runner runs one (`beforeEach`, the body, `afterEach`, then the cleanups registered while it ran) and return `{ skipped, reason, failed, error, failures, raised }`. The runner reads its verdict from the same place, so what this reports for a captured test is what a sweep reports for a real one. A scene layer the captured test leaves loaded that was not loaded when it started is unloaded afterwards, as the runner unloads one after each test. ## What a failing test reports A matcher records its failure and lets the body run on, so one body can produce several. They are kept in the order they happened: - `error` — the headline, and the one line the console, the engine log and the report's result table carry. It is the failure that came first, plus `(+N more)` counting the ones after it — `(+N more, ended by a raise)` when a raise is what stopped the body. - `failures` — the failures in order, on `Test.results[]`, in each per-test JSON file under `Test.PER_TEST_RESULTS_DIR`, and in the JSON report. The Markdown report lists them under the failing test's heading. A body that records more of them than the list keeps ends it with a line counting the rest and naming the last of them, so one test asserting inside a long loop stays one bounded entry in the report. The hooks that run around a body record onto the same list it does, so an assertion a `beforeEach`, an `afterEach` or a registered cleanup fails — and an error one of them raises — is a failure of the test it ran for and travels to every consumer the body's failures reach. Each names the phase it came from (`afterEach: Expected …`, `cleanup: Runtime error: …`); a body's own failures stay unlabelled. A cleanup that raises still leaves the cleanups behind it to run. ## Standing a test down A test whose precondition this engine does not meet has nothing to verify and has earned no pass. `Test.skip(reason)` from inside the running test says so: ```lua Test.it("renders N copies from one transform buffer", function() if engine.gpuCompute ~= true then Test.skip("GPU compute reported unavailable (engine.gpuCompute)") end -- …the test, on an engine that can run it end) ``` The test ends at that call. It is counted under `skipped`, printed as `○ <name> (skipped: <reason>)`, and the reason travels as the `error` field of its `Result` row, into its per-test JSON file, and into both reports. A `beforeEach` may stand the test down the same way, and then the body never runs. Whatever the test's hooks record around a stand-down is a failure of the test they ran for and outranks it: a teardown that fails after a body stood down reports the test as failed. A reason on its own reaches a test that is running. Inside a `describe`, where `Test.skip` declares, the call takes a body — a reason alone raises there, naming the declaration form. Run / inspect: - `Test.run() -> boolean` — execute every registered suite; `true` when all pass. Call from a yieldable context (the `tests` toolbox does) so multi-frame tests yield. Discovering + running every suite is the `tests` toolbox's job (`tests.run`), not this framework's. - `Test.clear()` — reset suites + stats (re-run from clean state). - `Test.getResults() -> { Result }`, `Test.getStats() -> Stats`. Multi-frame / sandboxing: - `Test.waitFrames(n: number?)` — yield until at least `n` engine frames elapse. - `Test.tmpPath(relativePath: string?) -> string` — sandboxed path under `Test.TMP_ROOT`. - `Test.prepareTmp()` / `Test.cleanupTmp()` — recreate / remove the tmp root. Notices: - `Test.noticeMark(template: string) -> NoticeMark` / `Test.noticesSince(mark) -> number`: how many times a notice posted under `template` fired after the mark. A drain seals the row it returns and the next emission starts a new row, so this counts across every row of the template. - `Test.latestNotice(template: string) -> any?`: the stored row of that template the most recent emission landed in. Scene layers: - `Test.useScene(opts?) -> SceneProxy` — mint an isolated scene for the current test from a `.scene` fixture and load it (root, or an additive overlay with `{ additive = true }`). Unloaded and removed at teardown. - `Test.useSceneEach(opts?)` — suite-level sugar: one freshly minted scene per test. - `Test.ensureRootLayer() -> SceneProxy` — take a root scene layer for the current test, so `layers.active` and the scene-scoped surfaces behind it answer inside a test. Returns the loaded root, loading a stand-in scene from `Test.BASELINE_SCENE` when none is; the layer is unloaded when the test ends. - `Test.releaseRootLayer()` — unload the stand-in and remove its source folder. The runner calls it when a run ends. - `Test.beginWorldBaseline() -> WorldBaseline` / `Test.restoreWorldBaseline(baseline)` — bracket a whole sweep: unload the layers the engine booted with (so no suite depends on ambient content) and put them back afterwards. Public state: - `Test.suites`, `Test.currentSuite`, `Test.currentTest`, `Test.stats`, `Test.results`, `Test.TMP_ROOT` (`/zero/source/tmp/tests`). Types: - `Stats = { total, passed, failed, skipped: number }` - `Result = { suite, test: string, passed, skipped: boolean, error: string? }` — on a skipped row `error` is the reason the test stood down - `TestContext = { waitFrames, expect, fail, suiteName, testName }` - `Suite = { name, tests, beforeEach?, afterEach? }` - `Outcome = { failed, raised: boolean, error: string?, failures: { string } }` - `TestOutcome = Outcome & { skipped: boolean, reason: string? }` - `TestSpec = { body: (TestContext) -> (), beforeEach?, afterEach?: () -> (), name: string? }` - `RunAllOpts = { path: string? }` - `NoticeMark = { template: string, counts: { [string]: number } }`: each stored row's count at the mark, by row ## Usage ```luau local Test = asset.containing(__FILE__).modules.shared Test.describe("My Suite", function() Test.it("does basic things", function() Test.expect(1 + 1).toBe(2) Test.expect("hello").toContain("ell") end) Test.it("cascade despawn cleans children across frames", function(t) local parent = entity.spawn("parent") local child = entity.spawn("child") child.setParent(parent.id) t.waitFrames(1) -- let setParent settle entity.despawn(parent.id) t.waitFrames(2) -- let cascade + ECS despawn run Test.expect(entity.exists(parent.id)).toBe(false) Test.expect(entity.exists(child.id)).toBe(false) end) end) Test.run() ``` ## Parts The module is a folder of parts, each a module of its own that `init.luau` requires: - `Test.valueText`: the structural, bounded rendering `Test.describeValue` gives a table. - `Test.worldReadings`: the readings of engine-wide state a teardown settle and the scene-rect hand-back compare. - `Test.ownership`: which modules, GPU buffers and compute resource rows are the engine's own, which the floor readings leave out of what a suite answers for. ## Notes - Failure is flag-based, not exception-based — every matcher records the failure but allows the body to keep executing. Avoids WASM C++ exception handling cost. - The runner records the loaded scene layers and the entity set before each test. Afterwards it unloads every scene layer the test left loaded that was not loaded before it, newest first, so the entities that layer's load built leave with the layer and the scene's source is what its next load builds from. It then despawns any other newly-spawned entity (mutations apply after the `execute()` batch returns; `cleanedUpIds` makes the snapshot tolerate deferred cleanup). - After each test the runner defensively returns the scene to `edit` mode if a body or its `afterEach` leaked `play`. This stops a single mode-leaking test from cascading silently into every downstream `vfs.write`-using suite. - Multi-frame `t.waitFrames` needs a yieldable call chain. A non-yieldable C-frame above `Test.run` (e.g. driving it from inside a `require`) makes `waitFrames` raise a sentinel and the test is marked SKIPPED — the body had nothing to verify, so what it recorded is dropped and what its setup recorded stands. A hook that fails around such a body still fails the test. The `tests` toolbox (`tests.run` → `AssetRef:run()`) runs the suite in a plain coroutine, so the real wait path exercises. - `toThrow` calls its subject under `pcall` and fails when the call returns normally. `toThrow("substring")` additionally requires the rendered raised value to contain that substring. `never().toThrow()` asserts the call completes.
▲ 0↑ born
·
assettype · born here
❒asset
# 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.
▲ 0↑ born
▣
module · born here
❒asset
# test Test-input helpers that simulate keyboard / mouse / scroll events and yield one engine frame so the queued events drain into the next snapshot. Backs `Zin.test`. Helpers do NOT call `Zin.tick()` — explicit dispatch control is left to the caller. ## Exports - `M.runFrame()` — yield one engine frame so simulated events drain. - `M.pressKey(code: string)` — hold the key DOWN and leave it held. A second `pressKey` on a held key produces no new press edge — pair every `pressKey` with a `releaseKey`, or use `tapKey` for a full press. - `M.releaseKey(code: string)` — simulate a key release. - `M.tapKey(code: string, duration: number?)` — press + optional hold + release. The helper for "the player taps a key". - `M.pressMouse(button: (number | string)?)` — simulate a mouse button press (default 0 = left). The index and the name (`"left"`/`"right"`/`"middle"`) reach the same button. - `M.releaseMouse(button: (number | string)?)` — simulate a mouse button release. - `M.clickMouse(button: (number | string)?, x: number?, y: number?, duration: number?)` — full click, optionally moving the cursor to `(x, y)` first and holding for `duration` seconds. - `M.moveMouse(x: number, y: number)` — set absolute cursor position. - `M.moveMouseBy(dx: number, dy: number, steps: number?)` — move the pointer by a relative motion. The motion lands in this frame's `mouse_delta` and the position advances by the same amount, so the same `(dx, dy)` repeated keeps producing look movement. `steps` spreads it over that many frames, each carrying its share; 1 when omitted. - `M.scroll(dy: number)` — simulate a wheel scroll. ## Usage ```luau local Test = require("@builtin::modules.zinput.test") Test.tapKey("KeyM") -- press + release Zin.tick(1 / 60) -- explicit dispatch assert(#Zin.scheme.fired() > 0) Test.pressKey("Space") -- key goes DOWN and stays held... Zin.tick(1 / 60) Test.releaseKey("Space") -- ...until released Test.clickMouse(0, 100, 200) ``` ## Notes - Each helper queues the simulated event and yields one frame (`task.wait(0)`) so the snapshot reflects the input on return. - Simulated key state persists like real key state: after `pressKey` the key stays held until `releaseKey`, and only the release re-arms the next press edge. `tapKey` is the edge-per-call helper. - Helpers do NOT call `Zin.tick()` — a test that relies on a control's handlers, or on `Zin.input.on*` / `Zin.actions.bind`, must run a tick itself. `Zin.scheme.fired()` is what turns a simulated input into an assertion: it reports which controls fired since it last read, and from which device class. - Mouse button index is 0-based (0=left, 1=right, 2=middle) following the `InputResource.mouse_buttons` convention. - All helpers are no-ops when the `__zero_input.simulate*` FFI is missing (off-host execution).
▲ 0↑ born
·
assettype · born here
❒asset
# Scene (asset type) A scene is a saved, loadable snapshot of an entity scenegraph inside a world: the entity hierarchy, transforms, components, lighting, and a declared `player` intent, plus an auto-discovered startup script. A scene is the unit of "level" or "screen" — a title screen, a lobby, a gameplay area, and an end-of-game summary each get their own scene. Scenes load as **layers**. One root scene is active at a time; additional scenes can load additively as overlays on top of it. Each scene owns its own multiplayer relay room. Switching scenes is a local call: the client that makes it leaves the old scene's room and joins the new scene's room. ## When to use one - You want a savable, re-loadable snapshot of an entity scenegraph plus its lighting and player setup. - You want a runnable starting state for a level or screen. - You want a scenes-as-data flow: `layers.load("lobby")`, edit live, then `layers.active:save()` to publish the edits back to the scene. For a reusable entity assembly (a prop, a vehicle, a UI panel) that many scenes spawn into themselves, use a `.bundle`. A scene is a whole-world snapshot; a bundle is one prefab that lives inside scenes. ## Folder shape A scene asset is a folder ending in `.scene`. Its identity is the folder name with the suffix stripped (`Lobby.scene` → `Lobby`). - `scene.json` — the scenegraph: `entities[]`, lighting, and the top-level `player` intent. **Required.** Written by the engine — a build, a save, a human dragging something in. Not hand-edited. - `build.luau` — what the scene is made of, written as code. Runs while you author; saving bakes its result into `scene.json` (see Building a scene). - `entrypoint.luau`: the startup script. **Required.** Auto-discovered as a sibling of `scene.json`; define lifecycle callbacks here (see The entrypoint). - `<name>.<type>/` — an asset the build makes, authored here by `build.asset` (see The assets a build makes), alongside `.build.assets`, which records which `build.luau` produced each of them. - `prefabs/` — optional subfolder for scene-local bundles. - `scripts/` — optional subfolder for scene-local Luau helpers, required from `entrypoint.luau`. - `README.md`: notes about THIS scene: what it shows or plays and what it is for. **Required.** The general scene model lives here, in `guides { path: "types/scene" }`. - `.metadata`: **Required.** `scene.json` is version 7. It carries `"format": "scene"`, `"version": 7`, an `entities[]` array, and a top-level `"player"` string intent. ## The `player` intent Every scene declares how it handles players with a top-level `player` field in `scene.json`: - `"spawns"` — the scene carries an authored player setup, and the engine spawns a player for each connecting user from it. This is the default for a freshly created scene. - `"none"` — the scene spawns no player and authors no camera. Author your own Camera entity for the view (menus, UI-only screens, cinematics). ### How `"spawns"` works A `"spawns"` scene authors two things in `scene.json`: 1. A **PlayerPrototype** — an entity carrying the `PlayerPrototype` component, whose `body` field names a child entity (the body). The body carries an avatar (an `Asset` pointing at an avatar, e.g. `@builtin::avatars.humanoid`). A `CameraRig` child carries a `Camera` with a camera behavior (e.g. `orbital_follow`). The prototype root is authored `PrototypeOnly` so it exists as a clonable template. 2. A **PlayerSpawn** — an entity carrying the `PlayerSpawn` component, whose `prototype` field names the PlayerPrototype to instantiate and whose transform is where players appear. The scaffolded scene groups these under two organizing entities, `PlayerSetups` (holding the prototype) and `Spawns` (holding the spawn), so the authoring tree stays legible. On each user join — entering play, and each subsequent connect — the engine runs the spawn for that user: - It clones the PlayerPrototype subtree. - The clone root becomes the user's **internal identity** — a registry-only entity named `user` carrying the `UserIdentity` component. The identity is the anchor for who the player is; it has no world presence. - The body named by `PlayerPrototype.body` is adopted as the user's **avatar** — their visible presence in the world — and placed at the PlayerSpawn's world transform. Move the PlayerSpawn (or drag it in the editor) to set where players appear. - The `CameraRig`'s Camera follows the bound avatar. The player prototype is live in edit mode so you can see and adjust it. In play mode it is deactivated and marked internal — it stays a clonable source while each user gets their own clone. ### Reaching the live player The player surface lives on the root scene's registry, `layers.active.players`: - `players.localPlayer` — this client's player, a curated handle. - `players.localReady` — `true` once the local player's avatar is bound (or the scene opted its avatar out). - `players:list()` / `players:count()` — the players connected in this scene's room. - `players:get(userId)` — a connected player by account id. - `players:ownerOf(avatar)` — the player whose body is a given avatar. A player handle is a data record about who the player is, plus a link to their body: - `player.avatar` — the body's entity ref. Act on the body through it (`player.avatar.position`, raycasts, rig access). - `player.isLocal` — whether this client owns the player. - `player.ready` — whether a live avatar is bound. - `player.userId` / `player.identity` / `player.displayName` — the player's account identity. - `player.avatar = ref` — bind a live body entity as the player's body (assign nil to clear). To use a `.bundle` / `.avatar` asset, spawn it into the world first, then bind the resulting entity. The player's identity entity is the internal anchor; the handle exposes the body (`player.avatar`) and the player's data, and reaching for `.entity` / `.id` / `.component` raises with a redirect to `player.avatar`. ## Building a scene `build.luau` declares what the scene holds. It is ordinary engine code — `entity.spawn`, `component.add`, transform writes, `for` loops, a `require` of a module that computes a layout — and what it creates is what ends up in the scene. ```lua function content() for i = 0, 4 do local crate = entity.spawn("crate") crate.localPosition = { i * 2, 0.5, 0 } crate.component.add("Model", { model = asset.resolve("cube", "mesh") }) end end ``` The build runs while you author, in **edit** mode, and what it created lands in the live scene. Saving the scene bakes it into `scene.json`, which is what makes the entities durable content: a human can select and inspect them, they replicate, and they are there when the world opens without `build.luau` running at all. Play mode never runs it — in play the entities load from `scene.json` like anything else the scene holds. **Editing the file rebuilds the scene in place.** Writing `build.luau` is the signal; there is nothing to reload, and the rebuild saves. An entity keeps the id it had, so a reference to it — a spawn naming a prototype, another entity's component naming this one — survives every rebuild. Add a crate to the loop and the other four do not move. A write through `write_file`, `edit_file` or the engine's `bash` answers once the rebuild it started has finished, so what the rebuild landed and kept comes back on that answer as a notice, whose `message` is the report's summary line: ``` [info] a write to build.luau rebuilt the scene { content="6", scene="scenes.main", editorOnly="1", kept="1", message="build.luau against the scene: kept 1 value on 1 entity (crate_3); ..." } ``` A rebuild still running when the write's wait ends is named under the answer's `startedWork`, and its notice arrives on a later call. An edit saved while a rebuild is still running is an edit to code that rebuild has already read, so it gets a rebuild of its own once that one finishes, and says which it was: ``` [info] a write to build.luau arrived during a rebuild and was rebuilt after it { content="7", scene="scenes.main", editorOnly="1" } ``` Several edits saved during the same rebuild get the one run after it, which reads the file as it stands then. A scene that declares a build also runs it when it **loads** in edit, so the scene shows what the code says now, including an edit made while the world was closed. A load whose `.build.state` records the current script reads `scene.json` as the build and runs nothing. When the load does run it, a world's own scene saves the result, unless the scene holds unsaved edits: those stay the author's to keep or discard, and the file write waits for their save. A library scene (one under `/libs/`, the `@builtin` library included) is read by its load: the build lands in the live scene and its files stay as the library states them. Play reads `scene.json`, so it comes up without that build until `:build()` saves it. ### The two surfaces - `content()` — the scene's own entities. Present in play. - `editorOnly()` — entities present while authoring and absent in play. They carry the `EditorOnly` participation the runtime deactivates and hides when play begins, and they are baked too, so a collaborator opening the world sees the same ones. Anything an author needs to see and a player does not goes here — an alignment guide, a spacing marker, a debug volume. Both are optional. A scene with neither has no build. ### What a rebuild touches Only the entities the build itself placed. Anything a human dragged in, or a tool placed directly, is invisible to a rebuild and never moved or removed. Within what it owns, the build is authoritative: an entity the code stopped emitting is despawned, a component it stopped adding is removed. A plain rebuild keeps a hand edit to an entity the build placed: a value `build.luau` states the way the last build stated it is left as the scene holds it, so a move, a rename, an attribute, the active flag, the lifecycle mode, the replication scope or a component field changed since survives the rebuild, the one a write starts included. To see every such edit, ask the build for its report: ```lua local report = layers.active.asset:build({ save = false }) print(report.message) -- opens with one line counting all four lists ``` On a scene already holding what the build states it leaves nothing to save, and it answers `kept` (hand edits to entities the build placed), `driven` (fields another component writes at runtime, such as a sky orienting the sun), `handAdded` (components and attributes added by hand to built entities) and `handPlaced` (entities no build placed). An entity's render layer and its `hide()` switch are runtime state no build sets, so the lists leave them out; the answer states what the scene holds on both for the entities a build placed instead, in `renderLayers` (`{ entity, name, layer }`) and `hidden` (`{ entity, name }`), and its message counts them ("render layer set on 3 (...); hidden by hide() 0"). It also names the scene it compared: `client` is the client of the world it ran in (`user`, or a sub-client's id), since every client holds its own live scene, and `unsaved` lists the edits that scene held beyond the saved `scene.json` (the entries `sceneAuthoring.changes` lists), so an empty `unsaved` makes the report a statement about `scene.json`. To land `build.luau`'s values over the kept ones: ```lua layers.active.asset:build({ restate = true }) ``` A restate writes exactly the values `kept` names, so the scene's diff after one is the report. To bring a `handPlaced` entity into the build, delete the hand-made one and save the scene, then write it into `build.luau`: the write rebuilds at once in every client and the writing client saves its rebuild, so a delete left unsaved in another client can come back. A hand-made entity still standing under a name the build now places is reported with `builtTwin`, a second copy beside the build's, and the message names the calls that settle it. The message also compares the report against `scene.json` as saved: it names each unsaved edit and what it changed, and any entity whose live state differs from the scene's files with no unsaved edit behind it (a write this client has not taken), with the calls that take that client back to `scene.json` before anything saves from it. `guides { path: "core/scenes-as-code" }`, "What a rebuild touches", gives the shape of every entry and how `driven` and `restate` meet. The build writes its own name and each entity's place in the hierarchy onto the entity, and `scene.json` records that pair beside the entity's name and transform — which is why a rebuild after a reload, in a later session, lands on exactly the entities it placed the first time without anything having been remembered. ### When the file did not change `:build()` runs the build against what it resolves right now — for the case where something the builder *reads* changed and the file did not: a module it requires, an asset it resolves. After a write it is unnecessary; the write has already run it. ```lua layers.active.asset:build() -- rebuild and save layers.active.asset:build({ save = false }) ``` It answers with how many entities each surface placed — `{ content = 6, editorOnly = 1 }` — and with nil for a scene that has no `build.luau`. Called while a build for that scene is already running, it returns at once with `{ inFlight = true, scene, trigger, startedBy, message }` naming that build instead of starting a second one; `inFlight` is what tells the two answers apart. An operation the bake cannot hold is **refused** rather than applied. A build accepts what its records carry: entity lifecycle, transforms, hierarchy, names, visibility, active state, participation mode, network scope, attributes, and components with their public data. Anything else raises while the build runs, naming the operation and the build it answered to, instead of leaving the scene depending on something no reload brings back. When that happens the previous build stays exactly as it was. A runtime resource a build needs — a mesh it generates, a texture it writes — is made as an asset instead, below. Everything else a refusal names goes outside the builder, or into a component the builder attaches, which runs at play. ### The assets a build makes `build.asset(type, name, produce)` makes an asset the build's content names — a mesh a lathe produces, a texture a pattern writes. `produce` takes nothing and returns the creation parameters `asset.create` takes for that type; the call returns the asset's `AssetRef`, which is what a component field holds. ```lua function content() local tower = build.asset("mesh", "tower", function() local positions, indices = lathe(profile, 16) return { positions = positions, indices = indices } end) entity.spawn("tower").component.add("Model", { model = tower }) end ``` The asset is authored inside the scene's own folder — `Lobby.scene/tower.mesh` — and the scene records which `build.luau` produced it in `.build.assets`. So `produce` runs when the build script changed and never otherwise: a reload re-runs the build and reuses the asset, while editing the profile re-authors `tower.mesh` **in place**, keeping its path and its guid. That is what holds the reference — `scene.json` names assets by guid. For a part of a scene that several scenes place — or that one scene places many times with different settings — see `guides { path: "types/sceneModule" }`, which is the same idea with declared `inputs` a placement sets. `guides { path: "core/scenes-as-code" }` covers both. ## The entrypoint `entrypoint.luau` is the scene's **runtime** — what happens while the game is being played. What the scene *is* comes from `build.luau` above; nothing here has to construct it. `entrypoint.luau` is auto-discovered as a sibling of `scene.json`. The loader runs it in a fresh environment and folds its top-level `function name(...)` declarations into the matching scene lifecycle event. Define the callbacks the scene needs — the recognised set: - `onLoad()` — the scene loaded in **play** mode. Gameplay-start hook, runs on every connected client. - `onHostLoad()` — the scene loaded in **play** mode, on the client that owns the scene's synced content (the relay room creator; offline and single-player count as host). Fires once. Entities spawned here — and anywhere downstream — become synced automatically, so this is where shared world content is spawned: it runs on exactly one peer, and every other peer receives the entities from the relay snapshot. - `onEditLoad()` — the scene loaded in **edit** mode. Custom per-scene authoring tools. Writing this file while the scene is loaded in edit mode reloads its layer, so the new `onEditLoad` runs after the previous load's `onUnload`. - `onUnload()` — before the scene's entities are torn down. Extra cleanup; engine-managed teardown (entity despawn, resource release) runs separately. - `update(dt)` — per frame in play mode, while the gameplay clock runs. - `editorUpdate(dt)` — per frame in edit mode, running or paused. Play-paused ticks neither hook. The scene loader partitions these strictly on mode; a component's hooks of the same name read `engine.paused` instead, so the two rules differ — `man components` has that table. - `localPlayerReady(player)` — once the local player's avatar is ready. Gameplay wiring for the local player: attach state, bind UI, swap the avatar. The avatar is already placed at the PlayerSpawn, so this is for behavior, not positioning. - `playerJoined(player)` — a remote player joined this scene's room. Use for per-player UI (nameplates, greetings). The local player arrives through `localPlayerReady`. - `playerLeft(eid)` — a remote player left this scene's room. Receives the departed entity's id (the entity is already despawned). Each scene's entrypoint runs in its own environment, so two scenes can declare the same top-level names without clashing. Keep each callback short; push per-scene logic into `scripts/` modules and `require` them. ## Layers Scenes load through the `layers` namespace. - `layers.load(ref, opts?)` — load a scene. `ref` is a scene AssetRef or identity string. Without `opts.additive`, this is a **root** load: it replaces the current root scene. `opts`: - `additive` — load as an overlay alongside the current root instead of replacing it. - `persistent` — keep an additive overlay mounted across mode flips and root swaps. - `origin` — a `{x, y, z}` world offset for the overlay's entities. - `deferred` — spread the entity spawn across frames (for thousand-entity scenes); the load signals complete only once the scene has settled. - `layers.active` — the current root scene proxy (nil before any load). - `layers.list()` — every loaded layer (root + additive overlays). - `layers.find(ref)` / `layers.is_loaded(ref)` — look up a loaded layer by ref. - `layers.onLoad(cb)` / `layers.onUnload(cb)` / `layers.onBeforeLoad(cb)` — subscribe to every scene load / unload (distinct from a scene proxy's own `:on_load` / `:on_unload`, which fire only for that scene). A root scene carries the `players`, `camera`, and `settings` surfaces; additive overlays inherit the root's players and lighting and do not carry their own. ### The scene proxy `layers.active` (and `layers.find` / `layers.list` entries) returns a scene proxy: - Fields: `.guid` (canonical identity), `.name`, `.path`, `.asset`, `.additive`, `.visible`, `.state` (`"loading"` → `"loaded"` → `"ready"` → `"unloading"`), `.ready`, `.players`, `.camera`, `.settings`, `.entrypoint`. - `.camera` — a proxy over the scene's primary camera entity; read and write the live Camera component through it, and `.camera.behaviors._list()` enumerates the available camera behaviors. - `:save(opts?)` — publish the live scenegraph to canonical `scene.json` (see Saving). A convenience that forwards to the scene ASSET's `save` (`self.asset:save(opts)`): the proxy is the runtime view and owns nothing on disk, so persistence lives on the asset. - `:reload()`: unload and reload the same scene (a runtime respawn). A scene with a `build.luau` runs its build again and saves the scene, so `scene.json` holds what the reload built and the next play loads it; a library scene's rebuild lands in the live scene alone. - `:clearDirty()` — discard unsaved edits and respawn from canonical. Forwards to the scene asset's `discard` (`self.asset:discard(opts)`). - `:sceneAsset()` — the durable `AssetRef<scene>` this live layer maps to. - `:promoteDirty()` / `:writeDirty()` / `:hasDirty()` — manage the dirty overlay directly. - `:unload()` — despawn the layer and free its slot. - `:onReady(cb)` — fire once the scene reaches `ready` (latched: a late subscriber fires immediately). ## Multiplayer & relay rooms Every scene has its own relay room, keyed by the world guid, the boot profile, the mode, and the scene guid. Switching scenes with `layers.load` runs a room transition — leave the old room, tear down, join the destination scene's room — all on the client that made the call. Teardown of the old scene never leaks to peers in the new one. In play mode connected to a relay, the scene's entities are host-authoritative: only the room creator instantiates them (marked synced), and every joiner receives them from the relay snapshot rather than spawning their own. This is why shared world content belongs in `onHostLoad` — spawning it in `onLoad` would run on every peer and duplicate it. Each player's own avatar spawns per-user from the PlayerSpawn on every client. Edit mode and offline boots spawn locally and never auto-sync. ## Loading and saving **Loading** — `layers.load(ref)` for a root scene: 1. Despawns the current root scene's non-persistent entities. 2. Instantiates the entities from `scene.json` (including the player prototype and spawn for a `"spawns"` scene). 3. Applies lighting and sky. 4. Runs `entrypoint.luau` and fires lifecycle callbacks as their events occur. **Saving** — persistence lives on the scene ASSET. `sceneRef:save()` writes the scene's current state back to canonical `scene.json`; when the scene is loaded it captures the live scenegraph, and when it is not loaded it promotes the pending dirty overlay. `layers.active:save()` is the convenience form — it forwards to the active layer's mapped asset (`layers.active.asset:save()`). Writing canonical is the only path that does so: edit ↔ play cycles never save, so hitting play to test never overwrites the scene. Between saves, live edits accumulate in a per-scene dirty overlay that the loader merges on top of canonical. `sceneRef:discard()` throws the overlay away and restores the saved state — deleting the overlay, and respawning the live layer when the scene is loaded. It works whether or not the scene is loaded, because the overlay belongs to the asset, not the runtime layer. `layers.active:clearDirty()` forwards here. Saves capture entity data, not the entrypoint script — edits to `entrypoint.luau` and `scripts/` are always preserved. `opts.to` on `save`/`discard` targets a different scene ("save as"), taking either a bare name (`"level_2"`) or a full VFS path. **What a record states.** A component's record in `scene.json` holds the fields that instance's configuration states: the keys of the table it was added with (a `build.luau` call's own init table, or the record it was loaded from) and every field written since, through code, a tool or the inspector. A field nothing set stays out of the record and takes the component's declared default each time the scene loads, so changing that default reaches every entity that left the field to it. To have an entity follow the default again, remove the field from its record. A field set on a live entity after its record was made is a change the scene review names (`sceneAuthoring.changes` lists it as `+ Type.field = value`), and accepting it writes the field into the record. A stored value cannot be told apart from one an author chose, so a stored value loads and saves as it is, and a hot reload that changes a default one of them shadows names it. A stored field the component no longer declares is named by a `[component.add]` warning when the record loads and left out of the next save. ## Lighting Lights are ordinary entities: a directional light, an ambient light, and a sky are entities carrying `Light` / `ProceduralSky` components in `scene.json`. Author, move, and tune them like any other entity. If a scene is missing any of {directional light, ambient light, sky}, the loader adds a temporary default for the absent one so a scene never loads dark or skyless; the defaults are never saved into the scene. Scene-level lighting state that is not an entity — clear color and sky descriptor — lives under `layers.active.settings.lighting` (`clear_color`, `sky`); writing those fields updates the engine live. ## Modes Scenes load in both edit and play mode (see `man modes`). The mode governs behavior: - An entrypoint's `update(dt)` runs in play while the gameplay clock runs, and its `editorUpdate(dt)` runs in edit. A component's hooks of the same name follow the clock rather than the mode — `man components` has the four states that produces. - Player prototypes are live in edit and deactivated + internal in play, where each user instead gets a clone. `EditorOnly` entities follow the same edit-live / play-internal toggle. - `onLoad` / `onHostLoad` fire on a play-mode load; `onEditLoad` fires on an edit-mode load. ## How to create one ```luau asset.create("scene", "<Name>") -- Creates /zero/source/<Name>.scene/ with: -- build.luau where this scene's content is written. A new one starts -- with the sun / ambient / sky lighting and the "spawns" -- player setup, commented for editing — everything else the -- scene comes to hold is written here too. -- scene.json what that code produces, baked. -- entrypoint.luau commented lifecycle-callback stubs. ``` A freshly created scene has a player with a following camera on the first press of play. It carries no ground, so the first thing to author is what the player stands on — a `content()` line away in `build.luau`. ## Discovery - `asset.list("scene")` — every registered scene. - `asset.inspect("<name>")` — entity count, lighting summary, source path, and this type README. ## Authoring conventions - Keep static layout in `scene.json` — geometry, lights, props, the player prototype and spawn. - Keep dynamic setup in `entrypoint.luau` lifecycle callbacks — event listeners, gameplay state, services attached to spawned entities. - Spawn shared, synced world content from `onHostLoad`; spawn each player's own gameplay wiring from `localPlayerReady`. - Set the world's startup scene in `/.world_settings` — that is the scene the world boots into. - Y is up; -Z is forward. - Renaming the folder changes the scene's identity. References to the scene are recorded against the scene itself, so renaming or moving it does not break them. ## Related types - `.bundle` — reusable entity hierarchies that scenes spawn into themselves. - `.service`: a declarative content generator a scene can draw on. - `.world_settings` — picks the startup scene and world-level renderer / physics options. ## In the Inspector Selecting a scene opens its **Scene** section, read from `scene.json` without loading the scene: how many entities it holds, how many of them are roots (and their names), how players join and the file's format version when it states them, and whether the scene has edits not yet saved.
▲ 0↑ born
▣
module · born here
❒asset
# Test.ownership Which of the things a suite can leave behind are the engine's own. The test framework reads these when it judges what a suite handed back: what the engine keeps for itself is no suite's to answer for. - `engineOwnedModule(key)` answers whether a require-cache key names a module of the built-in library or one of the VM's standard libraries. - `engineOwnedBuffer(name)` answers whether the named GPU buffer was made through the substrate by a module of the engine's. - `substrateNames()` answers the names every named GPU buffer stands under right now, or nil when the substrate cannot be read. - `engineComputeRow(row, named)` answers whether a compute resource row is one of the engine's own: a params ring page, the `__params` uniform of a program the engine or a `.computeShader` asset compiled, an arena page, or a buffer a module of the engine's made. `named` is `substrateNames()` read with the rows. ```luau local Ownership = require("@builtin::assetTypes.testSuite.shared.ownership") assert(Ownership.engineOwnedModule("@builtin::modules.json")) assert(not Ownership.engineOwnedModule("/zero/source/mine.luau")) print(Ownership.substrateNames()) ```
▲ 0↑ born
▣
module · born here
❒asset
# Test.valueText How the test framework renders a value nested inside a table for test output. `Test.describeValue` renders every failure message and raised error through it. - `describeNested(value, depth, seen)` renders `value` structurally (`{code = "x", n = 2}`): at most 8 entries per table, 2 levels deep, strings quoted and cut at 120 bytes, the hash part sorted so one value always renders the same text, a value with its own `__tostring` through it, and a cycle as `<cycle>`. ```luau local ValueText = require("@builtin::assetTypes.testSuite.shared.valueText") print(ValueText.describeNested({ code = "E1", line = 4 }, 0, {})) -- {code = "E1", line = 4} ```
▲ 0↑ born
▣
module · born here
❒asset
# Test.worldReadings Readings the test framework takes of engine-wide state around a test. - `quiescenceReading()` answers one reading of every facet a queued teardown moves (`entities`, `layers`, `renderFeatures`, `renderTargets`, `loadInFlight`), each as a string, so `Test.settleWorldTeardown` can compare two frames facet by facet and name the one still moving. - `liveLayerGuids()` answers the guids of the layers loaded right now, sorted. - `readEditorChrome()` answers each editor chrome screen drawn in the window, by name, and whether it is shown; `chromeMoved(want, now)` answers the screens `want` records one way that `now` reads the other, sorted by name. ```luau local WorldReadings = require("@builtin::assetTypes.testSuite.shared.worldReadings") local before = WorldReadings.quiescenceReading() print(before.entities, before.layers) print(#WorldReadings.chromeMoved({ toolbar = true }, WorldReadings.readEditorChrome())) ```
▲ 0↑ born
·
assettype · born here
❒asset
# 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**.
▲ 0↑ born
▣
module · born here
❒asset
# 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.
▲ 0↑ born
▣
module · born here
❒asset
# zinput zinput is the engine's Luau-side input framework and the **only** public Luau input API. It sits on top of the internal `__zero_input.*` FFI (snapshot, events, frameId, pointer-lock, simulate\*) and builds the control model above it in pure Luau: control assets grouped into maps, the live set of activated maps and its per-frame dispatch, per-device-class binding evaluation, the on-screen touch overlay, gesture recognisers, and the tick coordinator that advances all of it. The top-level module re-exports every submodule under a single table and owns the tick coordinator (`Zin.tick`) plus the unified handle namespace for `Zin.disconnect`. ## The control model A control is a `<name>.inputBinding/` folder inside a `<name>.inputMap/` folder. It carries a `label`, a `kind` (`button` / `axis1` / `axis2`), and a binding for each of the three device classes — `kbm`, `gamepad`, `touch`. A class set to `false` is a deliberate refusal. Nothing is live until something activates a map. A world activates the map it needs and subscribes to the controls it uses: ```luau public = { inputMap = Field.assetRef("inputMap", "@builtin::inputMaps.default", NoSync, "The controls this component reads."), speed = Field.number(5, NoSync, "World units per second at full deflection."), jumps = Field.number(0, NoSync, "How many times the jump control was pressed."), } local controls function awake() controls = public.inputMap:activate() controls.move:onInput(function(v, dt, active) if not active then return end local p = public.entity.position local step = public.speed * dt public.entity.position = { p.x + v.x * step, p.y, p.z - v.y * step } end) controls.jump:onPressed(function() public.jumps += 1 end) end function onDestroy() public.inputMap:deactivate(controls) end ``` What `activate` returned is this holder's claim on the map, and handing it back to `deactivate` disconnects the subscriptions made through it while the map stays live for whoever else holds it. Every activation reads the map's binding children again, so a control edited since it came up reaches the running set and the holders already standing on it. Several maps are live at once and compose: the player's surface is the union of them, so picking up a gun adds Fire beside the movement stick and dropping it takes away Fire alone. A map declares the `group` its controls belong to and the groups it `suppresses` while live, which is how a car stands walking down without owning the walk map. `Zin.scheme` holds the live set and runs the dispatch. `man topics/input` is the full walkthrough. ## Exports Subsystems (re-exported from the corresponding submodule): - `M.scheme` — the live set of activated maps and their per-frame dispatch. - `M.bindings` — binding constructors, evaluators, and the legend formatter. - `M.state` — per-frame snapshot reads plus held-time and synthetic repeat. - `M.events` — frame-event readers and `on`/`off` edge subscriptions. - `M.input` — `onBegan` / `onEnded` / `onChanged` / `onTextInput` listeners and `lastInputType()`. - `M.context` — the input context stack. - `M.chords` — sequence and simultaneous recognisers. - `M.gestures` — tap / double-tap / long-press / swipe / pinch / pan recognisers. - `M.touch` — per-finger contacts and `touch.*` listeners. - `M.surface` — touch-vs-kbm device-class classification. - `M.gamepad`, connected pads, family, button legends, each device's elements (`device`), the haptic outputs it offers (`capabilities`), and rumble. - `M.virtual` — the per-tick virtual-control store on-screen controls write. - `M.touchControls` — the on-screen touch overlay (stick, drag-look zone, buttons) and the API that adds a control while a world runs. - `M.emulation` — the map-driven key-emulation floor. - `M.pointer` — pointer lock: named holders ask for it (`lock` / `unlock`), `holders` names them, `requested` / `locked` / `status` read what the engine made of the ask from the input snapshot, leaving the input observation as it stands. - `M.back`: Back, claims a world holds while Back means something to it, and `press` to issue one. The engine routes each press to the topmost dismissible overlay, else the most recent claim, else the platform's own default (an Android app moves to the background). - `M.test` — synchronous test-input helpers. - `M.controllers` — `free` / `orbit` / `fps` controller factories. - `M.profile` — binding profiles, saved as JSON and loadable from `@builtin::profiles.<name>`. - `M.rebind` — interactive binding-capture sessions. - `M.conflicts` — the binding-collision reverse index. - `M.autoTick` — the opt-in per-frame tick worker. - `M.utils` — pure helpers. - `M.actions` / `M.axes` / `M.map` — the name-registered action, axis and map registry. A control asset replaced them; each carries its own `--!deprecated` message naming the replacement. Tick coordinator: - `M.tick(dt: number?)` — advance every stateful subsystem. - `M.lastTickAt() -> number` / `M.lastTickFrameId() -> number` — test/debug accessors. - `M._resetTickGuard()` / `M._resetLiveArmed()` — test-only. Handles: - `M.disconnect(handle: number) -> boolean` — accepts any Zin handle (input listener OR action handler) and routes to the right `disconnect`. Constants: - `M.VERSION` — the library version string. - `M.SPEC` — the VFS path of the architecture spec. - `M.ROADMAP` — the VFS path of the roadmap document. ## Raw state `Zin.state` and `Zin.events` are the snapshot and event layer that bindings evaluate against — the layer the emulation floor, rebind capture, and dev tooling operate on directly. Gameplay code subscribes to controls; polling `Zin.state.keyDown` from a world makes that world keyboard-only and draws the `engine-raw-key-poll` diagnostic at author time. ## Notes - `Zin.tick(dt)` is the single hub that advances every stateful subsystem each frame. Stateless features (state / events / utils / bindings / context) work without ticking; the live binding dispatch, axes, chords, subscriptions, held-time, repeat, and rebind are dormant until something ticks. - The first real input read arms the input system on its own: it starts `Zin.autoTick`, so dispatch, the touch overlay and the emulation floor advance with no host component and no explicit tick call. A host script component can still call `Zin.tick(dt)` from its `update(dt)` hook, and `Zin.autoTick.start()` remains available directly; both stay idempotent alongside the self-arming path. `Zin.test` engagement suppresses the arming so suites keep explicit control over tick cadence. - Same-frame re-tick dedup: `__zero_input.events()` is non-draining, so running the observe-and-dispatch pipeline twice in one engine frame would double-fire subscribers. The frame-id guard in `M.tick` and the autoTick worker keeps this from happening. - The handle namespace is unified: every handle from `Zin.input.on*` and `Zin.actions.bind` is drawn from a single counter, and `Zin.disconnect` routes any of them to the correct `disconnect`. `Zin.input.disconnect` and `Zin.actions.disconnect` are also wired to the unified dispatcher. - Library users can either grab the whole table (`require("@builtin::modules.zinput")`) or pull one submodule (`require("@builtin::modules.zinput.state")`). - `__zero_input` is an internal namespace — reachable from Luau but hidden from `/docs/api/`; production game code goes through Zin.
▲ 0↑ born
▣
module · born here
❒asset
# scene runtime What a `.scene` folder does when it is loaded, saved, built, or swapped. A `<name>.scene/` carries `scene.json` (the entity arrangement), an optional `build.luau` (the code author's half), an optional `entrypoint.luau`, and a `scene_dirty/` overlay of unsaved edits. Reading, composing and writing all four is the scene type's own behaviour, so it lives in the type. ## Sub-modules | Module | Responsibility | |---|---| | `loader.module` | Reads scene.json v6 and v7, refuses versions it does not know, composes canonical + dirty overlay, spawns the entities, and runs the entrypoint. | | `saver.module` | Persists scene state as a delta overlay against the canonical file, promotes that overlay on save, and answers which edits are still pending. | | `build.module` | Runs a `build.luau` inside an entity capture scope and composes what it spawned into scene records. | | `observe.module` | The read side — the per-scene counts and costs `layers` and `loader` write. | | `swapOrchestrator.module` | Drives multiplayer room transitions and the scene-swap gate, so a local swap does not leak despawns to peers in the old room. | ## Reaching it ```luau local rt = require("@builtin::assetTypes.scene.shared") rt.saver.hasPendingSceneEdits(layers.active.name) ``` Fields resolve lazily. The prelude installs `swapOrchestrator` and starts `saver`'s dirty writer in a fixed order, which a table that required all five on load would take away from it.
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# postReference_focusBars Four rows of bar pairs, 8 pairs across the top row and doubling on each row below: the focus chart a depth-of-field reading is taken off. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
# feed The newest frame a capture produced on this engine, and who is watching for it. Every capture core publishes here. `latest()` is that frame: a `src` an image widget draws (the render target's guid while the engine still holds it, the written path when the capture produced a file), with the size, the source and the pass beside it. `watch(fn)` calls `fn` as each new frame arrives, and `unwatch(token)` drops the subscription. `shown()` says a viewer is drawing frames from the feed. From then on the feed holds the newest capture's render target so the picture stays up after the capture that made it is finished with it, and lets it go when a later frame replaces it; `shown(false)` stops. With nobody drawing, a capture's target is released the moment its capture is done. The release path asks `retains(rtHandle)` before destroying a target, which is how a held frame survives its own capture. `capture.shared.releaseFrame` is the one place that asks.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_skyRamp A sky-blue ramp of light from 0.02 to 0.6 across: a clear sky's gradient. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
❒
package · born here
❒asset
# 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 ```
▲ 0↑ born
▣
module · born here
❒asset
# ibl Image-based lighting from the scene's own sky. ```lua local ibl = require("@builtin::systems.imageBasedLighting.ibl") ibl.set({ diffuse = 1, specular = 1 }) ibl.follow() -- go back to reading the scene's sky after pinning values ibl.get() --> the settings in force ibl.active() --> are the passes running ibl.clear() --> off, settings kept for the next set() ``` `set` takes any subset. With both `diffuse` and `specular` at 0 nothing is being asked for and the passes are released. The sky's colours and the sun are read from the scene, so recolouring the sky recolours what metal reflects. Passing any colour or direction explicitly pins it and takes the scene off automatic tracking for that value; `follow()` puts it back. `diffuse` and `specular` are separate scales because an interior usually wants the sky's diffuse contribution pulled down while its reflections stay, and an exterior often wants the reverse. For environment lighting a scene should simply have, author the `EnvironmentLighting` component instead. This module is for code that changes it at runtime: moving indoors, a cutscene, a quality slider. The full description is in the package readme: `guides { path = "systems/imageBasedLighting" }`.
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
△
mesh · born here
❒asset
# Mesh Mesh asset. `data.zmsh` is the engine-native geometry payload (`renderer.mesh.encode`); consumers reference the asset's guid.
▲ 0↑ born
◐
material · born here
❒asset
# Chrome A polished chrome surface built on the `pbr` shader — fully metallic (`metallic: 1.0`) with a bright near-white base colour (`0.95, 0.95, 0.97`) and very low roughness (`0.05`) for mirror-sharp reflections. Opaque, back-face culled, instanced, with the `_METALLICSPECGLOSSMAP` keyword enabled. ## Inputs - `colors.base_color` (`0.95, 0.95, 0.97, 1.0`) — bright, faintly cool chrome tint. - `floats.metallic` (`1.0`) — fully metallic. - `floats.roughness` (`0.05`) — near-mirror sharpness. - `textures.base_color_texture` (`default:white`): the white base texture the colour multiplies against, so the surface renders `base_color` alone.
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Snow Particle A soft, cold-white flake surface for falling-snow particle effects — a near-white base colour (`0.95, 0.97, 1.0`) with a cool blue-grey emissive glow (`0.25, 0.3, 0.4`) so flakes stay faintly visible in shadow. Transparent, double-sided (`cull: none`), and drawn in the transparent queue (`3000`). Built on `@builtin::shaders.snow_material`. ## Inputs - `colors.base_color` — the cold-white flake tint. - `colors.emissive` (`0.25, 0.3, 0.4`) — cool self-illumination that keeps flakes readable in dark scenes. - `floats.roughness` (`0.8`) — matte, non-glossy flakes. - `floats.metallic` (`0.0`) — fully dielectric.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Gold Polished gold — a fully metallic PBR surface with a warm yellow base colour (`1.0, 0.84, 0.0`) and low roughness (`0.25`) for bright, sharp reflections. Built on `@builtin::shaders.pbr`. ## Inputs - `colors.base_color` — the gold tint. - `floats.metallic` (`1.0`) — fully metallic. - `floats.roughness` (`0.25`) — sharpness of the reflection; raise for a brushed look.
▲ 0↑ born
◐
material · born here
❒asset
# Checkerboard A procedural checkerboard pattern rendered by `@builtin::shaders.checkerboard`, alternating a red base colour (`1.0, 0.2, 0.2`) with a blue emissive colour (`0.2, 0.2, 1.0`). Opaque and non-metallic (`metallic 0.0`) at mid roughness (`0.5`) — useful as a UV / scale test surface. ## Inputs - `colors.base_color` — the red square colour. - `colors.dark_color` — the blue square colour. - `floats.roughness` (`0.5`) — diffuse spread on the lit squares. - `floats.metallic` (`0.0`) — dielectric surface.
▲ 0↑ born
◐
material · born here
❒asset
# Custom Textured A textured opaque surface built on `@builtin::shaders.custom_material`, sampling the `array_texture` builtin over a warm peach base colour (`1.0, 0.8, 0.6`). Non-metallic (`metallic 0.0`) at mid roughness (`0.5`) — a worked example of pairing a custom shader with an array texture. ## Inputs - `textures.base_color_texture` (`@builtin/textures/array_texture`) — the sampled array texture. - `colors.base_color`: the warm peach colour the texture is multiplied by. - `floats.roughness` (`0.5`) — diffuse spread. - `floats.metallic` (`0.0`) — dielectric surface.
▲ 0↑ born
◐
material · born here
❒asset
# Sky Procedural A fully procedural atmospheric sky with a day/night cycle, built on `@builtin::shaders.procedural_sky`. Renders with no culling and no depth write behind all geometry (queue `1000`), computing gradient, sun, moon and stars analytically from its parameters — no texture required. ## Inputs - `properties.zenith_color` / `horizon_color` / `ground_color` — the atmospheric gradient from overhead (`0.1, 0.3, 0.6`) through the horizon (`0.5, 0.7, 1.0`) to the ground (`0.3, 0.25, 0.2`). - `properties.sun_intensity` (`20`) / `sun_size` (`0.02`) — brightness and disc size of the sun. - `properties.turbidity` (`4`) — atmospheric haze / scattering density. - `properties.stars_intensity` (`1`) / `moon_size` (`0.03`) — night-sky star brightness and moon disc size.
▲ 0↑ born
◐
material · born here
❒asset
# Sky Cubemap A cubemap sky/environment background built on `@builtin::shaders.cubemap_sky`. Renders with no culling and no depth write behind all geometry (queue `1000`), sampling the built-in `Ryfjallet_cubemap` with adjustable rotation and exposure. ## Inputs - `textures.sky_texture` — the cubemap sampled as the sky (`Ryfjallet_cubemap`). - `floats.rotation` (`0.0`) — yaw rotation of the sky around the vertical axis. - `floats.exposure` (`1.0`) — brightness multiplier applied to the sampled colour.
▲ 0↑ born
▣
module · born here
❒asset
# asset_events Per-asset runtime for declared asset events. An assetType's `behavior.luau` declares an `events` schema the same way a component declares one; this module turns that schema into the live objects an asset's ref fires and listens on. ## Three faces, one Signal — keyed by the asset The construction is `component_events`': one `Signal` per declared event, reachable through a private fire-capable table, an owner-side emitter the type's own behavior fires with, and a subscribe-only facade every other holder of the ref sees. The facade exposes `connect` / `once` / `wait` and has no `fire` at any key, so firing authority stays with the type. What differs is the owner. A component event belongs to one instance on one entity; an asset event belongs to the **asset**, so the runtime is keyed by the asset's stable guid. Every resolver of that guid subscribes to the same Signals, and a ref that is reclaimed and re-resolved re-attaches to the subscriptions already there — the same reason `asset_ref`'s `runtime` table is guid-keyed rather than stored on the envelope. Both tables reject an undeclared event name: the private table's metatable raises on a bad key and the facade raises on a bad key, so a typo surfaces at the subscribe call instead of returning nil. ## Declaring events on a type ```lua -- <name>.assetType/behavior.luau local M = {} M.events = { changed = { payload = { value = Field.number(0, NoSync) } }, } M.ref = { poke = function(self) local emitter = require("@builtin::assetTypes.assetType.shared.events").emitter(self.guid) if emitter ~= nil then emitter.changed:fire({ value = 1 }) end end, } return M ``` ```lua -- any holder of the ref local ref = asset.resolve("@builtin::…") ref.events.changed:connect(function(p) print(p.value) end) ``` ## Exports - `M.forAsset(guid, eventSchema)` — the runtime for one guid, built on first use and reused after. A later call with a different schema reconciles: surviving events keep their Signal and their subscribers, new events get a fresh one, removed events are disconnected and dropped. - `M.facade(guid)` — the subscribe-only view, or nil before a runtime exists. - `M.emitter(guid)` — the owner-side `:fire` view, or nil before a runtime exists. - `M.has(guid)` — whether a guid holds a live runtime. - `M.teardown(guid)` — drop one asset's runtime, disconnecting subscribers. - `M.teardownAll()` — drop every runtime. Called on an engine mode flip so a play-mode subscription does not survive into edit. - `M.liveGuids()` — every guid holding a runtime, sorted. ## Notes - Subscriptions made through the facade are ordinary `signal.module` connections and disconnect the same way any other does. - The runtimes table is held strongly, and its lifetime is bounded by the mode flip that clears it.
▲ 0↑ born
▣
module · born here
❒asset
# editorRegistry The single registry every editor surface is built from — builtin tabs and world panels alike. The engine's own tools register through the same public API a world uses. Two surfaces consume the registry: the dock service (`system_tools.module`) renders whatever panels are registered, sorted by `order`, and the top bar (`EditorTopBar.component`) builds its menu bar from the registered menus and each panel's `menu`/`order`. Both subscribe to `onChanged` so add/remove is live. Registrations run through two paths, both ending in `addPanel`: builtin tabs register from `modules.api.editor.system_tools.panels` (the require IS the registration), and world panels register via an `editorPanel` asset whose `onRegister(self)` hook calls `addPanel`. State lives in a fixed `_G` slot so it survives hot-reload and edit↔play mode flips. A duplicate id replaces the prior registration, which is how a world overrides a builtin tab and how hot-reload re-registers cleanly. ## Panels and menus - `M.addPanel(spec) -> boolean` — add (or replace) a dock panel. `spec`: `id` (required, unique), `build` (required, `(state) -> widget`), `label?`, `menu?` (default `"window"`), `order?`, `refresh?`, `onCallback?`, `onMount?`, `tick?`, `float?`. - `M.removePanel(id) -> boolean` — remove a registered panel by id. - `M.addMenuItem(spec) -> boolean` — add (or replace) a clickable action item that runs `onClick`, with no associated panel. `spec`: `id` (required), `onClick` (required), `label?`, `menu?`, `order?`. - `M.removeMenuItem(id) -> boolean` — remove a registered action item. - `M.addMenu(spec) -> boolean` — add (or replace) a top-level menu in the bar. `spec`: `id` (required), `label?`, `order?`. - `M.removeMenu(id) -> boolean` — remove a top-level menu and cascade-drop every item/panel that targeted it. ## Introspection and subscription - `M.list() -> { panels, items, menus }` — snapshot copies of current registrations for introspection. - `M.onChanged(fn) -> handle` — subscribe to any add/remove mutation; `fn` runs with no args. - `M.offChanged(handle) -> boolean` — unsubscribe. ## Host accessors (dock service + top bar) - `M.setDock(controller?)` — publish (or clear with `nil`) the live `DockController`. - `M.dock() -> DockController?` — the live dock controller, or `nil` when no dock is mounted. - `M.panelsSorted() -> {spec}` — live dock panels sorted by `(order, id)`, including `build`. - `M.menuModel() -> {menu}` — the full top-bar menu model: every menu in bar order, each carrying its entries (`{kind="panel", id, label}` or `{kind="action", id, label}`) in `order`. The `DockController` type is `{ open, close, toggle, isOpen }` plus optional `getLayout` / `restoreLayout` for layout persistence. ## Usage ```luau local editor = require("@builtin::modules.api.editor.registry") editor.addMenu({ id = "mygame", label = "My Game", order = 70 }) editor.addPanel({ id = "my_tools", label = "My Tools", menu = "scene", order = 50, build = function(state) return Z.lbl("hello") end, }) editor.addMenuItem({ id = "act", menu = "scene", label = "Go", onClick = function() end }) ```
▲ 0↑ born
▣
module · born here
❒asset
# preview Render an asset's preview in the preview studio: an isolated camera, lit only by its own three-point rig, over a neutral backdrop, that nothing in the scene reaches. `ref:preview()` renders any asset by the recipe its type declares under `preview:` in its `type.yaml`, and these are the primitives it calls: they spawn temporary entities, frame an offscreen camera over them, render one frame, read it back as a PNG, and tear the entities down. ## Surface - `preview.fromEntities(makeFn, opts?) -> PreviewResult` — run `makeFn` to instantiate entities, frame a camera to their bounds, render one offscreen frame, and return the still PNG. - `preview.fromRecipe(ref, recipe, opts?) -> PreviewResult` — render `ref` by a declared recipe: `instantiate` stands it through its own `instantiate`, `surface` paints the material its type's `ref.previewMaterial` returns on the recipe's mesh, and `image` fits a file the asset holds to the frame on the studio backdrop without rendering anything. - `preview.backdrop() -> { r, g, b }` — the studio backdrop's colour in a finished preview, 0-255. `PreviewResult` is `{ available, imageBase64?, rendered?, width?, height?, bounds?, stats?, reason? }` — `imageBase64` is the rendered PNG when `available` is true, and `reason` explains why when it is false. `opts` is `{ size? = { width, height }, angle? = { yaw, pitch } }`. A preview pictures its whole subject, however many entities it composes. While the subject settles, its bounds are measured each frame by walking it in Luau for up to `opts.entityBudget` entities (default 2000); a subject composing more is measured by the capture framing alone, which reads each root's hierarchy bounds from the engine. ## Example local result = asset.resolve("gold", "material"):preview({ size = { width = 512, height = 512 } }) -- result.imageBase64 holds the rendered PNG (base64)
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Default Unlit A flat, unlit surface that renders its base colour directly with no lighting response, built on the `unlit` shader. Uses a white base colour (`1.0, 1.0, 1.0`) over the `default:white` texture with `emissive` (`1.0`) for full brightness — the go-to default for UI, gizmos, and debug geometry that must stay legible regardless of scene lighting. ## Inputs - `colors.base_color` — the flat colour shown directly. - `textures.base_color_texture` (`default:white`) — the white base texture the colour multiplies against. - `floats.emissive` (`1.0`) — full, lighting-independent brightness.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Instance Color A lit white surface that every instance wearing it colours from its own shader-data lane 2, built on `@builtin::shaders.pbr` with `instance_color_lane = 2`. One material draws hundreds of members in hundreds of colours, and a colour that changes every frame costs one `renderer.instanceData.set` per member: a stress map over a bridge, a heat map, a damage flash, team colours, a selection highlight, a gauge. ```luau local LANE = 2 for i, id in members do local load = loads[i] -- 0 relaxed .. 1 at its limit renderer.instanceData.set(id, LANE, load, 1 - load, 0, 1) -- green to red, fully covered end ``` The lane's `rgb` is the colour and its `a` is how much of it covers the base colour and the emission, 0 none through 1 all; an instance whose lane was never written reads zero and draws plain white. The colour replaces the base colour before lighting, so the member still shades, casts its highlights and shows the lane colour in the `albedo` capture pass. Set `instance_emission` above 0 for a colour that glows where it covers. `renderer.mesh.drawInstanced` reads the same lane from its `instanceDataBuffer`, so a GPU-filled population colours each copy the same way. The writes are local to the engine that makes them and replicate nothing; `Model.tint` is the synced form of a tint, for a colour every participant must see. ## Inputs - `floats.instance_color_lane` (`2`): the lane read; lanes 0 and 1 carry a baked lightmap's rect and layer. - `floats.instance_emission` (`0`): how brightly the lane colour glows. - `colors.base_color` (white), `floats.roughness` (`0.5`), `floats.metallic` (`0`): the surface under the lane colour.
▲ 0↑ born
·
toolbox · born here
❒asset
# lighting The canonical scene-lighting toolbox — ambient light, directional sun, sky, clear color, and point / spot / area lights, each with modify-or-spawn semantics: every call leaves the scene in the requested lighting state, spawning the canonical `sun` / `ambient` entities (or switching the renderer-level sky) when the scene has none. Set the whole environment in one call (sun, ambient, sky, and clear color, all optional), or set each independently: the directional sun, the ambient light, or the sky — swapped from a preset word, a project material matched by name, or a material ref. Add a point light as an entity at a position. Update any point, spot, or area light by name — its color, intensity, reach, shadows, and its shape controls (spot cone, area rect). Read the full lighting state back — every light with its values, clear color, authored sky, live sky config — in the same shape the whole-scene setup accepts. These are the interactive authoring surface, for setting a scene's lighting from `execute()`. The behaviour lives in the runtime lighting capability (`modules.api.engine.lighting`); a component, entrypoint, or the scene saver that adjusts lighting at runtime uses that capability directly, not a tool.
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Emissive White A bright white light-emitting PBR surface built on the `pbr` shader with the `_EMISSION` keyword enabled. A white base colour (`1.0, 1.0, 1.0`) paired with a strong `emissive` (`20.0`) makes it glow and drive bloom — well suited to light fixtures, emitters, and glowing accents. Non-metallic (`metallic 0.0`) at mid roughness (`0.5`). ## Inputs - `floats.emissive` (`20.0`) — high emission strength that produces the glow. - `keywords: _EMISSION` — enables the emissive path in the PBR shader. - `colors.base_color` — the white surface and emission colour. - `floats.roughness` (`0.5`) — diffuse spread on the lit surface.
▲ 0↑ born
▣
module · born here
❒asset
# temporalAntiAliasing Runtime control of the scene's temporal antialiasing. ```lua local temporalAntiAliasing = require("@builtin::systems.antiAliasing.temporalAntiAliasing") temporalAntiAliasing.enable({ historyWeight = 0.9, sharpness = 0.2 }) temporalAntiAliasing.get() temporalAntiAliasing.active() temporalAntiAliasing.disable() ``` `enable` creates the pass if it is not running and applies the settings; any field left out keeps its current value. `disable` releases the pass and returns the projection to sampling pixel centres, keeping the settings so a later `enable` brings back the same tuning. For antialiasing that persists with the scene, add the `TemporalAntiAliasing` component instead — it drives this module from fields you can edit in the inspector. ## Settings | field | effect | |---|---| | `historyWeight` | How much of the accumulated result to keep each frame. Higher resolves more detail and settles smoother, at the cost of taking longer to let go of what a surface used to look like. Clamped short of 1, where the accumulation would stop taking in the frame being drawn. | | `neighbourhoodClamp` | How far outside the neighbourhood's own colour spread an accumulated sample may sit before it is pulled back in. Lower rejects more, trading some of the settling for a result that follows change faster. | | `sharpness` | How much of the edge lost to averaging over sub-pixel samples is added back. 0 leaves the accumulation as it is. | | `motionRejection` | How much fast motion shortens the memory. A reprojection over a long distance is the most likely to have crossed onto another surface, so weighting the current frame up there is what stops a moving object trailing behind itself. | ## Choosing between this and edge antialiasing Both are in this package and they correct different things. `antiAliasing` (FXAA) works from the finished frame alone. It finds each edge and shifts that pixel's sample across it, which fixes the staircase in a still image at a fixed cost, and knows nothing about time — so a highlight that flashes on and off between frames still flashes. This one accumulates real samples, so it corrects what no single frame can see: the crawling and flickering that only exist in motion, and sub-pixel detail no one sample lands on. It needs the scene's velocity to do it, and pays for it with a small amount of softening, which `sharpness` puts back. Running both is reasonable — FXAA cleans up the edges within a frame while the accumulation handles what happens between them.
▲ 0↑ born
◐
material · born here
❒asset
# Water An animated water surface with a deep blue base colour (`0.1, 0.3, 0.8`) and low roughness (`0.2`) for glossy, reflective highlights, driven by a scrolling normal map for wave detail. Opaque, back-face culled, instanced, in the opaque queue (`2000`). Built on `@builtin::shaders.water_material`, sampling `@builtin/textures/water_normals`. ## Inputs - `colors.base_color` (`0.1, 0.3, 0.8`) — the water body colour. - `floats.roughness` (`0.2`) — low roughness for sharp specular reflections. - `floats.metallic` (`0.0`) — dielectric surface. - `textures.normal_texture` — the wave normal map (`@builtin/textures/water_normals`).
▲ 0↑ born
◐
material · born here
❒asset
# postReference_chrome A polished metal: its highlight of a bright light is a sub-pixel specular, the firefly a bloom and a temporal resolve are read on in the post-verification reference scenes.
▲ 0↑ born
▣
module · born here
❒asset
# lighting Scene-lighting base capability: ambient + directional ("sun") light and procedural-sky setup with modify-or-spawn, read-merge-write semantics, plus clear color, and the per-frame reads of the resolved lights. Identity is the component, never the entity name: the sun is the `Light` the renderer's snapshot names as the directional holder, the ambient is the light-role component of kind "ambient", and the sky is the entity carrying a sky-role component. Name-based lookup, word resolution, and sky-material orchestration (presets, material swap) live in the `lighting` toolbox. `sun` and `ambient` configuration patch the scene's resolved sun / ambient light components, spawning a carrying entity when the scene has none. A partial update (e.g. only `intensity`) reads the component's current fields first and merges the given fields on top, so unspecified fields keep their authored values instead of resetting to a default. `sky` writes the sky entity's ProceduralSky component the same way — any of its fields, plus `enabled = false` to remove the sky component. ## Types - `SunOpts` — `{ direction?, color?, intensity?, castsShadows? }`. - `AmbientOpts` — `{ color?, intensity? }`. - `ProceduralSkyOpts` — ProceduralSky component fields, plus `enabled = false` to remove the sky. - `SetupOpts` — `{ sun?, ambient?, sky?, clearColor? }`. - `SetupResult` — `{ sun?, ambient?, sky? }`, the entity ids each provided section resolved to. - `Sun` — `{ direction, color, intensity, castsShadows, entityId? }`. - `Ambient` — `{ color, intensity, entityId? }`. - `LightRow` — one punctual light as the renderer resolved it. ## Exports Writes — each takes the opts above and answers with the entity the light resolved to: - `M.setSun(opts: SunOpts) -> string` — set the scene's sun, returning its entity id. - `M.setAmbient(opts: AmbientOpts) -> string` — set the scene's ambient term, returning its entity id. - `M.applySetup(opts: SetupOpts) -> SetupResult` — apply a lighting setup in one call. All fields optional — only provided fields change. `clearColor` is `{r, g, b}`. - `M.setProbeVolume(key: string, volume)` / `M.removeProbeVolume(key: string)` — publish or retract a baked irradiance probe volume. Reads — each takes no arguments, and answers from the resolved lighting state at a cost independent of scene size: - `M.sun() -> Sun` — the sun the frame is shaded by. - `M.ambient() -> Ambient` — the ambient term the frame is shaded by. - `M.lightRows() -> { LightRow }` — every punctual light the renderer resolved this frame. Identity: - `M.lightKind(componentType: string, component: any?) -> string?` — the kind a light-role component names. - `M.lightOfKind(entityId: string, kind: string) -> any` — the light-role component of that kind on one entity. ## Usage ```luau local lighting = require("@builtin::modules.api.engine.lighting") lighting.setSun({ direction = { 0.3, -1, 0.2 }, intensity = 2.0 }) lighting.setAmbient({ intensity = 0.3 }) lighting.applySetup({ sun = { direction = { 0.3, -1, 0.2 }, intensity = 2.0 }, ambient = { intensity = 0.3 }, sky = { timeOfDay = 14 }, }) local sun = lighting.sun() print(sun.intensity, sun.entityId) ``` A reader takes no arguments and a setter takes the opts table, so `lighting.sun(opts)` is refused with the name of the call that applies it.
▲ 0↑ born
◐
material · born here
❒asset
# Grass blades Swaying grass for a blade mesh, built on `@builtin::shaders.grass_material` with the same green as `@builtin::materials.grass` (`0.22, 0.62, 0.16`) and `sway` at `1.0`. The shader bends each vertex along its blade in proportion to `uv.y²`, so this material belongs on a mesh whose `uv.y` runs 0 at a blade's root to 1 at its tip — a merged field of blades, each a cross of two tapered quads. It inherits the Rust-side render defaults (opaque, back-face culled, queue `2000`) so its pipeline matches the library variant compiled at startup. ## Inputs - `colors.base_color` (`0.22, 0.62, 0.16, 1.0`) — the grass green tint. - `floats.sway` (`1.0`) — the full blade bend. `@builtin::materials.grass` leaves it at the shader's default of `0` for a ground surface.
▲ 0↑ born
◐
material · born here
❒asset
# Text Default The default surface for Text3D — a white base colour (`1.0, 1.0, 1.0`) drawn with alpha blending and no depth write so glyphs composite cleanly over the scene. Transparent, double-sided (`cull: none`), `depth_write: false`, in the transparent queue (`3000`). Built on the `pbr` shader. ## Inputs - `colors.base_color` (`1.0, 1.0, 1.0`) — the glyph colour. - `render.depth_write` (`false`) — glyphs blend without occluding each other. - `render.cull` (`none`) — text is visible from both sides. - `floats.roughness` (`0.5`) / `floats.metallic` (`0.0`) — dielectric defaults.
▲ 0↑ born
◐
material · born here
❒asset
# Grid Background A procedural background/reference-grid surface built on `@builtin::shaders.grid_bg`. It draws grid lines over a black base colour (`0.0, 0.0, 0.0`) with full roughness (`1.0`) and no metallic response, rendered opaque with culling disabled (`cull: none`) and instancing enabled so it can back many objects at once. ## Inputs - `colors.base_color` (`0.0, 0.0, 0.0, 1.0`) — black backdrop behind the grid lines. - `floats.roughness` (`1.0`) — fully diffuse, no highlights. - `render.cull` (`none`) — visible from both faces. - `render.instancing` (`true`) — supports instanced draws.
▲ 0↑ born
◐
material · born here
❒asset
# Standard Default The baseline PBR surface — a neutral white base colour (`1.0, 1.0, 1.0`), half roughness (`0.5`), non-metallic (`0.0`), wired with the full standard texture set (base colour, normal, roughness-metallic, emissive, occlusion) and the `_NORMALMAP` / `_OCCLUSIONMAP` keywords enabled. Opaque, back-face culled, instanced, in the opaque queue (`2000`). Built on `@builtin::shaders.pbr`. This is the starting point most materials copy and retint. ## Inputs - `colors.base_color` (`1.0, 1.0, 1.0`) — the albedo tint over the base colour texture. - `floats.roughness` (`0.5`) / `floats.metallic` (`0.0`) — dielectric, mid-gloss default. - `floats.normal_strength` (`1.0`) / `floats.ao_strength` (`1.0`) — normal-map and occlusion intensity. - `textures.normal_texture` / `textures.roughness_metallic_texture` / `textures.occlusion_texture` — the PBR map slots, seeded with neutral defaults.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◇
component · born here
❒asset
# Light Adds a light source to an entity. The entity's world transform determines the light's position, and a spot's aim: the cone axis is the entity's world rotation applied to `face`. A directional or distant light travels along `direction`. Point light positions are auto-synced from that world transform, so a light on a child entity burns where the entity stands — the position `entity.position` reports. A point light's `intensity` is on one scale with the `SpotLight` component's `intensity`/`brightness`: the same number at the same `radius`/`range` puts the same light on a surface either kind faces from the same place, and a spot spends it on the cone it opens on rather than all around itself. Distances are in metres and a point or spot light falls off by the inverse-square law: a surface facing the light 1 m away takes `intensity`, one at `d` metres takes `intensity / d^2`, so the same light gives 4 times as much at 0.5 m and a quarter as much at 2 m, and `radius` windows it smoothly to zero at the light's reach. Kinds: `"point"`, `"spot"`, `"directional"` (the scene's sun), `"ambient"`, `"distant"` (a parallel light beside the sun). Public fields: `kind`, `colorR/G/B`, `intensity`, `radius`, `directionX/Y/Z`, `face`, `angle`, `innerAngle`, `castsShadows`, `angularDiameter` (the disc size, in degrees, that sets how wide the sun's shadow penumbra grows with the distance from caster to receiver; 0.53 is the sun's and 0 draws a hard edge), `lightChannels`, `mobility`. `range`, `color` and `direction` are aliases accepting the composite/renamed forms. Methods: `:setColor(color)` (color: `{r, g, b}` array or `{r=, g=, b=}` map), `:setIntensity(i)`, `:setRadius(r)`, `:setDirection(dir)`, `:setFace(face)`, `:setAngle(deg)`, `:setInnerAngle(deg)`, `:setKind(lightKind)`. `kind = "spot"` opens a cone from the entity's position along its `face` (`"Front"` by default: the entity-local -Z that `transform.forward` reports and `entity:lookAt` aims; also `Back`, `Left`, `Right`, `Top`, `Bottom`), to the `angle` (outer, default 30) and `innerAngle` (inner, default 20) half-angles in degrees. These are the `SpotLight` component's fields, under the same names and with the same meanings. A spot aims by `face` and its entity's rotation, so a `direction` written to one is refused: `:setDirection` raises, an assigned `direction` keeps the value it held, and both name `face`. `"directional"` and `"distant"` are parallel lights: they arrive from the same direction at every point in the world and no distance attenuates them, so their `intensity` reads against the sun's rather than against a point light's. The `SpotLight` README carries the rest of how to balance a mixed point-and-spot rig. ```luau entity(id).component.add("Light", { kind = "point", intensity = 2, radius = 10 }) entity(id).component.add("Light", { kind = "directional", direction = {-0.5, -1, -0.3} }) entity(id).component.add("Light", { kind = "spot", face = "Bottom", angle = 35, innerAngle = 25 }) ```
▲ 0↑ born
❒
package · born here
❒asset
# characterController system Self-contained character controller + locomotion package. Install on any entity to give it a third-person camera, WASD ground movement, and skeletal animation driven by a Locomotion blend space — without hand-wiring the underlying components. The player's controls drive the character once it is bound as the local player's body (`layers.active.players.localPlayer.avatar = entity(id)`); any other character moves on what writes its `CharacterController` input bus. ## Layout ``` systems/characterController/ characterController.module/ -- public API (install / uninstall / preset) init.luau -- surface used by tools and custom code physics.module/ -- raycast helpers (ground / walls / ceiling) movement.module/ -- velocity integration + collision resolve data.module/ -- default config presets (standard, platformer, ...) presets/ -- (Task 16) shipped controller + animation -- presets (synty, default humanoid, ...) files/ -- (Task 17) bundled assets pulled in by -- the shipped presets (synty rig, anims) demo/ -- (Task 20) showcase scene exercising the -- install -> tweak -> preset loop tools/characterController.toolbox/ -- user-facing tools (install, uninstall, -- apply-preset). Lives here until runtime -- VFS-driven toolbox discovery lands -- (see #1220); the colocated -- `.toolbox/` is the long-term home. documentation/ -- long-form reference 01-overview.md -- what the package is, when to use it 02-install.md -- characterController.install(id, opts) -- recipe and the components it touches 03-presets.md -- shipped presets and how to author your own 04-customize.md -- overriding components, swapping the -- camera, custom blend spaces ``` ## Flow ``` ┌────────────────────┐ user / agent ──┤ characterController│ │ .toolbox │ └────────────────────┘ │ ▼ ┌──────────────────────┐ custom code ──────┤ characterController │── install / (require) │ .module (API) │ uninstall / preset └──────────────────────┘ │ ▼ ┌────────────────────────┐ │ CharacterController │ │ + Locomotion │ │ + MovementState │ │ + AnimDebug │ │ (+ third-person cam) │ └────────────────────────┘ │ ▼ WASD-driven character with animation on any entity, no hand wiring required. ``` `characterController.install(entity, opts)` is the only thing most callers need — it adds the controller, the locomotion graph, the movement-state mirror, and (optionally) a third-person camera child. The package is self-contained: it depends only on standard utility modules and on the animation graph engine, never on game-specific code. ## Documentation - [`documentation/01-overview.md`](documentation/01-overview.md) — what this package is and when to reach for it. - [`documentation/02-install.md`](documentation/02-install.md) — the `characterController.install(id, opts)` recipe. - [`documentation/03-presets.md`](documentation/03-presets.md) — shipped presets (synty, default humanoid) and authoring your own. - [`documentation/04-customize.md`](documentation/04-customize.md) — overriding components, swapping the camera, custom blend spaces.
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# postReference_grey18 A lit 18% grey (middle grey) surface, rough and dielectric: what a light of known intensity is read off in the post-verification reference scenes.
▲ 0↑ born
◐
material · born here
❒asset
# Parallax Cube (Flat) A brick surface built on `@builtin::shaders.pbr_parallax_occlusion` with `parallax_depth_scale = 0`, so the ray-march is bypassed and the shared brick textures render as plain textured PBR (rough `0.7`, non-metallic, white base colour). Opaque, back-face culled, queue `2000`. Pair it with `parallax_cube` to A/B the parallax effect from a fixed viewpoint. ## Inputs - `floats.parallax_depth_scale` (`0.0`) — disables the occlusion ray-march, flattening the surface. - `floats.roughness` (`0.7`) — matte brick finish. - `floats.normal_scale` (`1.0`) — strength of the normal map. - `textures.height_texture` — the brick height map (unused while depth scale is `0`).
▲ 0↑ born
◐
material · born here
❒asset
# postReference_siemensStar A Siemens star of 36 spokes, 0.9 on 0.02: the spokes narrow below a pixel toward the centre, where a temporal resolve aliases. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
◐
material · born here
❒asset
# Skybox An unlit cubemap skybox rendered from the inside of the mesh, built on `@builtin::shaders.cubemap_unlit`. Uses front-face culling and no depth write so it draws behind all scene geometry (queue `1000`), sampling the built-in `Ryfjallet_cubemap` environment. ## Inputs - `textures.base_color_texture` — the cubemap sampled as the background (`Ryfjallet_cubemap`). - `floats.reflect_mode` (`0.0`) — samples the cube directly as a background rather than as a reflection. - `colors.base_color` (`1.0, 1.0, 1.0`) — tint applied to the sampled cubemap.
▲ 0↑ born
▣
module · born here
❒asset
# shared Module Cross-tool helpers for the `capture` toolbox. Every tool inside this toolbox can pull these in with `require(".shared")`. ## Purpose This module holds the small set of helpers that more than one tool in the toolbox needs — typically the `ok(value, formatted?)` / `fail(message, exitCode?)` constructors that produce the canonical `captureToolResult` shape, plus any toolbox-wide parsers, validators, or shared state. Keep it focused: per-tool implementation stays inside each `<x>.tool/init.luau` (with its own `--!desc` / `--!arg` / `--!return` / `--!example` annotations). ## Usage ```luau local shared = require(".shared") function M.someTool(...) if not ok then return shared.fail("reason", 1) end return shared.ok(value, "") end ``` ## Exports See `init.luau` for the full export surface. Typical exports include `shared.ok(value, formatted?)` and `shared.fail(message, exitCode?)` for building the toolbox's standard result envelope.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_greyWedge The grey wedge: one column per whole stop from -10 to +10, each middle grey (0.18) at that exposure. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Checkerboard White A static white/grey checkerboard rendered by `@builtin::shaders.checkerboard`, alternating a white base colour (`1.0, 1.0, 1.0`) with a dark grey check colour (`0.3, 0.3, 0.3`). Animation is disabled (`animation_speed 0.0`), giving a fixed, neutral grid — ideal as a level-design blockout or scale-reference floor. Opaque, non-metallic (`metallic 0.0`) at mid roughness (`0.5`). ## Inputs - `colors.base_color` — the white square colour. - `colors.check_color` — the dark grey square colour. - `floats.animation_speed` (`0.0`) — held at zero for a static pattern. - `floats.roughness` (`0.5`) — diffuse spread on the squares.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_white A flat unlit white of 0.8 light: the thin geometry of the temporal reference scene (wires, a fence, a fan's blades) drawn against the dark, so every pixel it touches stands out from its neighbours. Drawn by `@builtin::shaders.referenceChart`. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# parallax_cube Brick wall material using `@builtin::shaders.pbr_parallax_occlusion` with the parallax march enabled (`parallax_depth_scale = 0.08`, 48 ray-march layers). Pair with `parallax_cube_flat` for a same-textures, no-POM A/B comparison. ## Shader `@builtin::shaders.pbr_parallax_occlusion` — see that shader's README for the full parameter list. ## Textures All from `@builtin::textures.parallax_bricks` (height/normal derived from three.js's MIT-licensed `brick_bump` + `brick_diffuse`): - `base_color_texture` → `bricks_albedo` - `normal_texture` → `bricks_normal` - `roughness_metallic_texture` → `bricks_roughness` - `occlusion_texture` → `bricks_ao` - `height_texture` → `bricks_height` ## Usage ```luau Material.Apply(entityId, "parallax_cube") -- Override at runtime: Material.SetProperty("parallax_cube", "parallax_depth_scale", 0.12) ``` Pair it with `parallax_cube_flat` (same textures, `parallax_depth_scale = 0`) to compare the ray-marched surface against a flat-mapped baseline. ## Notes - `Material.SetProperty` mutations are global — every entity using `parallax_cube` sees the change. If you need per-entity variation, derive a new material name and override the property there. - Use under any standard camera (forward path). The deferred path is not yet POM-aware; materials applied to a deferred camera will render as plain textured PBR.
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Neon A glowing cyan neon surface built on `@builtin::shaders.pbr` with emission enabled. It pairs a bright cyan-blue base colour (`0.2, 0.8, 1.0`) with a matching emissive colour driven hard by `emissive: 5.0`, so it reads as a self-lit light source. Low roughness (`0.2`), non-metallic, opaque, instanced, with the `_EMISSION` keyword enabled. ## Inputs - `colors.emissive` (`0.2, 0.8, 1.0, 1.0`) — cyan glow colour. - `floats.emissive_intensity` (`5.0`) — strong emissive intensity (feeds bloom). - `colors.base_color` (`0.2, 0.8, 1.0, 1.0`) — matching cyan base tint. - `floats.roughness` (`0.2`) — glossy surface under direct light.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_checker A checker of 64 cells across, 0.8 on 0.03: the high-frequency background a fast object crosses. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# postReference_colorChecker The 24 patches of the ColorChecker Classic, each its published sRGB value read as linear reflectance. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
❒
package · born here
❒asset
▲ 0↑ born
❒
package · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Animated Color An opaque, back-culled surface whose colour animates over time, driven by `@builtin::shaders.animate_shader`. Starts from a white base colour (`1.0, 1.0, 1.0`) with an `emissive` of `1.0` so the shifting colour reads brightly, at mid roughness (`0.5`) and fully non-metallic (`metallic 0.0`). ## Inputs - `colors.base_color` — the starting colour the animation modulates. - `floats.emissive` (`1.0`) — self-illumination strength of the animated colour. - `floats.roughness` (`0.5`) — matte diffuse spread. - `floats.metallic` (`0.0`) — dielectric, non-metallic surface.
▲ 0↑ born
▣
module · born here
❒asset
# mode_flip_guard Two tiny cross-module transient signals about the edit↔play mode flip: - **owned** — "the `layers` module currently owns the mode-flip reset, so the `player_spawner` / `camera_spawner` `onModeChange` watchers should stand down." - **in flight** — "a mode-flip transition is materialising the scene right now, so the live entities are a partial rebuild of it." Formerly `_G.__zero_layers_owns_mode_flip`. Moved off `_G` ahead of the read-only `_G` seal — the flags are runtime writes (set when `layers` drives a mode flip), which would break under a sealed `_G`. `require()` is cached per VM, so the module-local upvalues are shared state across every requirer within a VM — exactly the cross-module reach the old `_G` key provided. - **Setter**: `layers.module` claims ownership before any flip, and raises the in-flight signal for the span of the transition it runs. - **Readers**: `player_spawner.module`, `camera_spawner.module` stand down while owned so the player/camera respawn happens exactly once via the `layers` transition's reload fan-out (not a second time from their own `onModeChange` watchers); `playerSetupValidation.module` judges the authored scene once the transition has settled. ## Surface | Symbol | Notes | |---|---| | `M.setOwned(v: boolean)` | Set whether the layers module owns the current mode-flip reset. | | `M.isOwned() -> boolean` | True while the layers transition owns the flip; spawners stand down. | | `M.setInFlight(v: boolean)` | Set whether a mode-flip transition is materialising the scene. | | `M.isInFlight() -> boolean` | True for the span of the transition; the live entities are a partial rebuild of the scene. |
▲ 0↑ born
◐
material · born here
❒asset
# backdrop_sky The sky material of the `example_own_shaders` example: `backdrop_sky.shader` at its own default values. A sky-domain shader draws on the sky behind everything, so its `preview.png`, rendered on the preview studio's sphere, shows a flat colour; the look it gives is the sky the material backdrop draws.
▲ 0↑ born
▣
module · born here
❒asset
# atmosphere Physically-based atmospheric scattering — aerial perspective on distant geometry, and a sky whose colour follows from the sun's elevation. ```lua local atmosphere = require("@builtin::systems.atmosphere.atmosphere") atmosphere.set({ aerial = 1, sky = true, worldUnitsPerKm = 1000 }) atmosphere.get() --> the settings in force atmosphere.active() --> are the scattering passes running atmosphere.drawsSky() --> is the scattering result the sky every view draws atmosphere.clear() --> off, settings kept for the next set() ``` `set` takes any subset — omitted fields keep their current value, so adjusting one knob does not mean restating the rest. With `aerial` at 0 and `sky` off nothing is wanted and the passes are released rather than run at zero strength. `worldUnitsPerKm` is the one number that has to match the scene. Scattering is computed in kilometres against Earth's coefficients, so it is what maps a scene onto real atmospheric distance. At the default 1000 a world unit is a metre. `sunDirection` follows the scene's sun unless the call pins it. Sun elevation is what drives the entire appearance of a physical sky, so that is what lets a day cycle reach the sky with nothing else authored. `sunIntensity` is the solar constant `exposure` is authored against. The sun that reaches the integral is that times the share of it the scene's sun lights, which `get().sceneSunShare` reports: the atmosphere exposes itself for any sun from a unit sun (intensity 1) up, and a weaker sun dims the air in proportion. The air is lit by the scene's sun alone, so a scene whose sun is off draws no sunlit sky or haze. At night the sky draws a starfield (`stars`) and a moon disc (`moonDisc`, `moonAngularRadius`), lit by the scene's strongest `distant` light, which `get().moonDirection` / `get().moonIntensity` report. A scene with no such light draws neither, and one whose `distant` light is a fill rather than a moon sets `moonDisc = false`. The tables the passes build (transmittance and multiple scattering when the medium they follow from changes, `atmosphere.tableVersions()`, and the sky's radiance per direction for every view) are held here, so another feature's pass can light or haze what it draws by the same air: `atmosphere.liveTables()` hands their guids and the parameter buffer while the passes run, and nil while they do not. The cloud layer reads its sun, its sky light and its aerial perspective through them. `sunColor` defaults to white on purpose: the warm colour of a low sun comes out of the transmittance through a longer air path, not out of a tint. For an atmosphere a scene should simply have, author the `PhysicalAtmosphere` component instead — it carries the same settings, persists with the scene, and edits live in the inspector. This module is for code that changes the atmosphere at runtime: a weather system, a cutscene, a quality slider. The full description of what each knob does and how the passes work is in the package readme: `guides { path = "systems/atmosphere" }`.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
❒
bundle · born here
❒asset
# Error Text A 3D "ERROR" text model used as the visible fallback when an asset fails to load — spawned in place of missing geometry so a broken reference is obvious in-scene instead of silently invisible. Decomposed from `ERRORText.fbx` into this bundle (mesh + material + texture + entity template). ## Composition - Root `error_text` → `Sketchfab_model` → the `ERRORText.fbx` node hierarchy. - Carries the extruded "ERROR" letter mesh, its material, and texture as private subassets. ## Usage Spawned automatically by the engine as the placeholder for an unresolved asset; can also be spawned directly to test the fallback path.
▲ 0↑ born
◐
material · born here
❒asset
# Plastic White A clean white plastic — a non-metallic PBR surface with a pure white base colour (`1.0, 1.0, 1.0`) and mid roughness (`0.5`) for a soft dielectric sheen. Built on `@builtin::shaders.pbr`. Opaque, back-face culled, queue `2000`. ## Inputs - `colors.base_color` (`1.0, 1.0, 1.0`) — the white plastic tint. - `floats.roughness` (`0.5`) — soft, semi-glossy highlight. - `floats.metallic` (`0.0`) — dielectric (non-metal) response. - `floats.emissive` (`0.0`) — no self-illumination.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_darkRamp A ramp of light from 0 at the left edge to 0.1 at the right: the dark gradient an undithered 8-bit display path bands on. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
▣
module · born here
❒asset
# signal Event primitive. A producer holds a `Signal`; consumers attach handlers with `:Connect` and the producer invokes them with `:Fire(...)`. ```lua local Signal = require("@builtin::modules.signal") local hit = Signal.new() local conn = hit:Connect(function(dmg) print("hit for", dmg) end) hit:Fire(10) -- runs every handler with (10) conn:Disconnect() -- detach this handler ``` ## API - `Signal.new() -> Signal` - `signal:Connect(fn) -> Connection` — attach a handler; runs on each `:Fire` in attachment order. - `signal:Once(fn) -> Connection` — fire at most once, then self-disconnect. - `signal:Wait() -> ...` — yield the calling coroutine until the next `:Fire`, returning its arguments. Call from inside a coroutine (e.g. a `task.spawn` body). - `signal:Fire(...)` — invoke every handler with the arguments. A handler that raises is caught and logged; the rest still run. - `signal:DisconnectAll()` — detach every handler. - `connection:Disconnect()` — detach one handler (idempotent). - `connection.Connected` — boolean, false once disconnected. - `Signal.connectionRevision() -> number` — a count that moves whenever any signal gains or loses a connection. - `Signal.watchConnections(fn) -> () -> ()` — call `fn` each time that count moves, inside the connect or disconnect that moved it; the returned function stops the calls, and a watch made from a component ends with that component. Handlers run synchronously and must not yield. The connection list is snapshotted before a fire, so a handler may disconnect itself or others mid-fire without skipping a handler. ## Auto-cleanup A connection made while a script component is on the call stack is tagged with that component instance and its entity, and it ends with whichever goes first: - Removing the component from its entity (`component.remove`), or hot-reloading it, disconnects every connection the instance made. - Destroying the entity disconnects every connection it sourced, after the entity's `onDestroyed` fires, so a component's handler on its own entity's `onDestroyed` still runs after the component's `onDestroy` (driven by the entity-destroy dispatch in `entity_signals.module`). A component never has to track and tear down its own connections.
▲ 0↑ born
▣
module · born here
❒asset
# builtin_registration Which of the built-in library's instances a boot registers, when it registers them, and the registration a reader asks for on first use. The world-load `onRegister` sweep leaves the library out, so the prelude runs each library type's hook by type through this module. The set follows the engine's profile: | type | editor | runtime (a player) | |:-|:-|:-| | `plugin` | boot | boot | | `font` | boot | boot | | `editorPanel`, `editorLayout` | boot | never: a player has no editor | | `shaderModule`, `agentSkill`, `procPack`, `procGraph` | once the world has loaded | first use | A plugin's registration asks the plugin host to load it, and the host refuses a plugin whose `plugin.yaml` names no profile the engine booted under from the manifest alone, without reading its component. A reader of a registry the boot left unregistered asks for it before it reads: ```luau local BuiltinRegistration = require("@builtin::modules.builtin_registration") BuiltinRegistration.ensure("agentSkill") -- registers the library's skills once ``` The readers that do: the skills toolbox (`agentSkill`, whose registration fills the roster an agent's tool responses carry) and the procedural graph registry (`procPack`, `procGraph`, registered when a read finds an op the library holds unregistered). A shader compile files each `.shaderModule` its source includes as it compiles. The prelude starts the boot registration with `boot()` on a system task, and `booted()` reads where it stands (the profile it registered under, and whether every step has registered). `plan(profile)` lists the steps a boot under a profile registers, and `run(profile, registerType, afterWorldLoaded, done)` runs them.
▲ 0↑ born
◐
material · born here
❒asset
# Lit Checkerboard A static, lit checkerboard surface built on `@builtin::shaders.lit_checkerboard` — the default ground material for newly seeded worlds. It uses a neutral light-grey base colour (`0.85, 0.85, 0.85`) with a grey emissive tint (`0.35, 0.35, 0.35`) so the pattern stays readable in dim scenes, high roughness (`0.7`), no metallic, opaque, and instanced. ## Inputs - `colors.base_color` (`0.85, 0.85, 0.85, 1.0`) — neutral grey checker palette. - `colors.dark_color` (`0.35, 0.35, 0.35, 1.0`) — the dark square colour, close enough to the base that the pattern stays readable in low light. - `floats.roughness` (`0.7`) — mostly diffuse surface. - `render.instancing` (`true`) — supports instanced draws.
▲ 0↑ born
◐
material · born here
❒asset
# Decal Default The default material a `DecalProjector` stamps when none is assigned. A flat cyan tint (`0.05, 0.95, 1.0`) on `@builtin::shaders.pbr`. Assign a material with a `base_color_texture` to project a texture; the projector samples the material's base colour at the box-local XY of every surface inside its projection box.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
# scopes Work you start together and that ends together, and the owning contexts every live resource is registered under. ## Task scopes Start several pieces of work that must not outlive the thing that started them, and wait for all of them: ```lua task.spawn(function() scopes.run(function(s) s:spawn("terrain", function() task.wait(2) end) s:spawn("props", function() task.wait(1) end) end) -- both are finished or cancelled here, and their cleanup has run end) ``` `scopes.run(fn, options?)` runs `fn(s)` in a new scope and returns what `fn` returned once every piece of work started in the scope is over. It waits, so it is called from a task; code that cannot wait gets an error saying so. Start work tied to an entity without waiting for it: ```lua local s = scopes.open({ entity = npc }) s:spawn("patrol", function() while true do task.wait(1) end end) -- despawning npc cancels it; so does s:cancel() ``` | On a scope `s` | Does | |---|---| | `s:spawn(name, fn, ...)` | Start `fn(...)` as a task in the scope, and return its handle | | `s:join(name?)` | Wait until that child (or all the scope's work) is over, then raise the first error it raised | | `s:children()` | `{ name, handle, status, source }` for each child still running and the most recent 32 that ended, `status` being its `task.status` | | `s:cancel(name?)` | Cancel one child's work, or end the whole scope; returns how many tasks it cancelled | | `s:why()` | What ended the scope first, or nil while it is open | | `s.onError = fn(name, err)` | Observe each error raised in the scope, as it is raised | | `s.tag` | The scope's tag, `scope:<n>`, as `scopes.list()` shows it | Everything a task in a scope starts belongs to the scope as well: a `task.spawn`, a job it registers, a scope it opens. A scope is lived inside what the code opening it belongs to, so the end of that ends the scope: a component destroyed or hot-reloaded, a scene load ending, an enclosing scope ending, the entity it is tied to despawning. A scope ends when its run is over, when work in it raises, when it is cancelled or released by tag, when the task waiting out its `scopes.run` is cancelled, and when what it is lived inside ends. Every task still running in it is cancelled and unwinds: the cancellation is raised at its wait, so a `pcall` or cleanup around that wait runs. The first error cancels the rest of the scope's work and is raised again by `join` (and so by `scopes.run`) as it was raised. While a `scopes.run` or a `join` waits for the scope, or `s.onError` observes it, the VM-wide `task.onError` is not told; an error in a scope nothing waits for or observes is reported as any task's error is. A `scopes.run` whose scope something else ended (its entity despawned, say) returns once the work it started is cancelled, and `s:why()` names what ended it. ## The contexts A resource reached through a handle outlives the call that made it. Every one records the context it came from, and the engine ends what a context left behind once that context's run is over. | Scope tag | What it is | What ends it | |---|---|---| | `scope:<n>` | A task scope | Its run is over, work in it raises, it is cancelled, or what it is lived inside ends | | `entity:<id>` | An entity | It is despawned | | `scene:<guid>#<n>` | One load of a scene layer | The load ends: the layer is reloaded or unloaded, the scene is swapped, the mode flips | | `chunk:<identity>` | A module | The module runs again (a VFS write to its source), or is dropped from the require cache (`vfs.reload`) | | `component:<instanceId>` | One component instance | That instance is destroyed: entity despawned, scene cleared, component removed | | `exec:<chunk>` | A chunk submitted for a single run, such as an `execute` call | Naming the scope in `scopes.release` | A registration made with no Luau frame above it is the engine's own and follows no context. It carries no scope, is not listed, and no release reaches it. ## Which context a registration belongs to Innermost first, with one exception at the top: 1. A module body being loaded owns what its own frame registers, even inside a component's `awake`. The body runs once per load and is shared by every instance that requires it, so it follows the module. 2. A task scope owns everything registered by the work running in it. 3. A component instance owns everything else registered while one of its lifecycle hooks is on the stack, including registrations made by helper modules it calls. Launch a job in component context and it goes down with the component. 4. Otherwise the calling chunk owns it. `scopes.current()` answers this for the code calling it. ## Reaching a resource nobody named A chunk registers something and the handle never reaches a variable: it raised first, or it simply ended. The resource is live and no name in Luau refers to it. Tasks an `execute` call started are listed under that call's `exec:` scope. ```lua for _, r in scopes.list() do if not r.endsAtASeam then print(r.kind, r.handle, r.scope, r.state, r.detail) end end scopes.release("exec:__exec_12") ``` `endsAtASeam` is false exactly for the resources a seam will never reach, which is the set worth reading first. `state` is where a resource stands in its subsystem's words: a task's `task.status`, a job's phase. An `execute` call runs as a task of its own, listed under its `exec:` scope while it runs, so releasing that scope from the same call cancels the call too. Release a call's scope from a later call. ## Explicit release `destroy` / `cancel` / `close` end a resource the moment content calls them, and that is unchanged. Scoping is what happens to the resources nobody ended.
▲ 0↑ born
◐
material · born here
❒asset
# Sky Equirectangular An equirectangular panorama sky/environment background built on `@builtin::shaders.equirect_sky`. Renders with no culling and no depth write behind all geometry (queue `1000`), with adjustable rotation and exposure. Assign an equirectangular image to `sky_texture` (via `material.setTexture` or a Skybox) to display a panorama. ## Inputs - `textures.sky_texture` — the equirectangular panorama image to sample. Falls back to black, so a sky with nothing assigned reads as night rather than as an error. Assign a `.texture` by guid, identity, name, or path: ```luau renderer.material.setTexture("@builtin::materials.sky_equirect", "sky_texture", "my_panorama.texture") ``` An image dropped into `/zero/source` imports into a sibling `<stem>.texture` container and the loose file is removed, so reference the container (or its identity) rather than the original image path. - `floats.rotation` (`0.0`) — yaw rotation of the panorama around the vertical axis. - `floats.exposure` (`1.0`) — brightness multiplier applied to the sampled colour.
▲ 0↑ born
◐
material · born here
❒asset
# error_marker The material of the ERROR sign a Model or SkinnedModel shows in place of a mesh that failed to resolve, to become GPU-resident, or to pose. It draws the `error_marker` shader's magenta checker.
▲ 0↑ born
◐
material · born here
❒asset
# Instance Color Unlit An unlit white surface that every instance wearing it colours from its own shader-data lane 2, built on the `unlit` shader with `instance_color_lane = 2`. It draws exactly the picture `Model.tint` gives an unlit surface for the same colour and blend, at the cost of one `renderer.instanceData.set` per member and with nothing replicated, so it is the material for flat per-instance colour that changes every frame: a heat map, a stress readout, indicator lights. ```luau renderer.instanceData.set(id, 2, 1, 0, 0, 1) -- this member red, fully covered renderer.instanceData.set(id, 2, 1, 0, 0, 0) -- back to the material's white ``` The lane's `rgb` is the colour and its `a` is how much of it covers the material's own colour, 0 none through 1 all; a lane never written reads zero and leaves it white. Set `instance_emission` above 0 to add the colour again on top, scaled, for a colour that blooms. ## Inputs - `floats.instance_color_lane` (`2`): the lane read. - `floats.instance_emission` (`0`): how much of the lane colour is added on top where it covers. - `colors.base_color` (white) over `textures.base_color_texture` (`default:white`): the colour under the lane colour.
▲ 0↑ born
◐
material · born here
❒asset
# Brushed Metal A brushed metallic surface built on the `pbr` shader — fully metallic (`metallic: 1.0`) with a neutral grey base colour (`0.6, 0.6, 0.6`) and moderate roughness (`0.3`) that softens reflections into the muted sheen of brushed steel or aluminium. Opaque, back-face culled, instanced, with the `_METALLICSPECGLOSSMAP` keyword enabled. ## Inputs - `colors.base_color` (`0.6, 0.6, 0.6, 1.0`) — neutral metal grey. - `floats.metallic` (`1.0`) — fully metallic. - `floats.roughness` (`0.3`) — softened, brushed reflections. - `textures.base_color_texture` (`default:white`): the white base texture the colour multiplies against, so the surface renders `base_color` alone.
▲ 0↑ born
◐
material · born here
❒asset
# postReference_emitter A flat emitter answering with 16 times the display's white: the source a bloom reading is taken around. Drawn unlit by `@builtin::shaders.referenceChart`, so a picture of it is measured against the light its properties state. Part of the post-verification reference scenes (`@builtin::scenes.postReference.*`); `@builtin::modules.postMetrics` reads them.
▲ 0↑ born
◐
material · born here
❒asset
# Sky Solid A flat solid-colour background built on `@builtin::shaders.solid_sky`. Renders with no culling and no depth write behind all geometry (queue `1000`), filling the sky with a single dark-grey colour (`0.2, 0.2, 0.2`) at unit exposure. ## Inputs - `colors.solid_color` (`0.2, 0.2, 0.2`) — the flat fill colour of the background. - `floats.exposure` (`1.0`) — brightness multiplier applied to the fill colour.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Grass A soft green ground surface built on `@builtin::shaders.grass_material`, with a natural green base colour (`0.22, 0.62, 0.16`), high roughness (`0.75`) for a diffuse, non-shiny look, and no metallic or emissive contribution. It inherits the Rust-side render defaults (opaque, back-face culled, queue `2000`) so its pipeline matches the library variant compiled at startup. It leaves the shader's `sway` at its default of `0`, so it shades whatever geometry it is applied to and leaves every vertex where the mesh puts it; `@builtin::materials.grass_blades` is the same green on a blade mesh that bends. ## Inputs - `colors.base_color` (`0.22, 0.62, 0.16, 1.0`) — the grass green tint. - `floats.roughness` (`0.75`) — matte, diffuse surface. - `floats.metallic` (`0.0`) / `floats.emissive` (`0.0`) — non-metallic, non-glowing.
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
# 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.
▲ 0↑ born
◐
material · born here
❒asset
# Cubemap Env A chrome-ball environment surface that samples a cubemap for mirror-like reflections, built on `@builtin::shaders.cubemap_unlit`. `reflect_mode` (`1.0`) selects the reflection path, and the `Ryfjallet_cubemap` builtin texture supplies the environment. Opaque, with a white base colour (`1.0, 1.0, 1.0`) so the cubemap colours pass through untinted. ## Inputs - `textures.base_color_texture` (`@builtin/textures/Ryfjallet_cubemap`) — the environment cubemap that is reflected. - `floats.reflect_mode` (`1.0`) — selects the reflection sampling mode. - `colors.base_color` — white tint that leaves the reflected colours unchanged.
▲ 0↑ born
◐
material · born here
❒asset
# Solid Line A flat, opaque line surface with a bright green base colour (`0.0, 1.0, 0.5`) for drawing gizmos, paths, and debug geometry. Opaque, back-face culled, instanced, and rendered in the opaque queue (`2000`). Built on `@builtin::shaders.line_material`. ## Inputs - `colors.base_color` (`0.0, 1.0, 0.5`) — the line colour. - `floats.roughness` (`0.5`) — surface roughness. - `floats.emissive` (`0.0`) — no self-illumination. - `render.instancing` (`true`) — many lines draw in a single instanced batch.
▲ 0↑ born
◐
material · born here
❒asset
# Glass Clear glass — a smooth, transparent PBR surface with a faint blue tint (`0.9, 0.95, 1.0`) and low alpha (`0.3`). Rendered in the transparent queue with backface culling off (`cull: none`) so both faces of thin geometry show. Built on `@builtin::shaders.pbr`. ## Inputs - `colors.base_color` — tint and opacity (the alpha channel drives how much shows through). - `floats.roughness` (`0.0`) — perfectly smooth; raise for frosted glass.
▲ 0↑ born
▣
module · born here
❒asset
# frame_budget The share of a frame that cooperative engine work spends before it hands the frame back. Some engine work is one long sequence of small units run on a task: a scene load applies one record after another, and the world-load `onRegister` sweep fires one instance's hook after another. Run back to back in one frame, a long sequence holds that frame for its whole length, and nothing else the engine does (answering a call, drawing, input) happens until it is through. Asking `due()` before each unit and yielding when it answers true runs the same work across as many frames as it needs, a slice of each. ```luau local FrameBudget = require("@builtin::modules.frame_budget") for _, item in ipairs(items) do FrameBudget.yield() process(item) end ``` - **One slice per frame, shared.** Each caller is charged the time it runs between its readings of the slice in a frame (`task.runTime`), whoever runs it, and the charges of every caller add up to the frame's slice. What the rest of the frame runs (systems, components, other tasks) is not charged, so a busy frame still gives the slice to the work. Two long pieces of work running at once share a frame's slice rather than taking one each. - **A unit is never split.** The first unit of a frame always runs, so a frame holds at most the slice plus the one unit that crossed it. A unit that is itself long stays one piece of work. - **Code that cannot yield runs in its frame.** `due()` answers false outside a coroutine that can yield, so a caller called from such code does all its units in the frame it was called in, as it would without the budget. A caller that does work of its own around the yield asks `due()` and calls `wait()`, which yields to the next frame and opens that frame's slice as the caller resumes; `yield()` is the two together. Work whose unit is a native call that bounds itself by time is told how long it may run: `remainingMs()` answers what is left of the current frame's slice, or nil for code that cannot yield, which then runs the whole of its work in the frame it was called in. The publish gate's script check runs this way: ```luau local block, checking = __spacetime_vcs.scriptPublishBlock(FrameBudget.remainingMs()) while checking do FrameBudget.wait() block, checking = __spacetime_vcs.scriptPublishBlock(FrameBudget.remainingMs()) end ``` ## The background lane Some work is started early so it is ready when asked for, and no picture waits on it, such as the search text an editor reads ahead of the first `tools.search`. `background(fn)` runs `fn` on the background lane: every `yield`, `due` and `wait` its work makes on that coroutine hands the frame back for as long as a hold on the lane stands, and takes its slice as usual once none does. ```luau FrameBudget.background(function() for _, path in ipairs(paths) do FrameBudget.yield() warm(path) end end) ``` Work the picture waits on holds the lane while it runs: `holdBackground(key)` until `releaseBackground(key)`. A world's entry holds it under `"world entry"` from the moment the world is ready (its `onRegister` sweep) until its `onWorldLoad` has returned, so the frames of the entry carry the world's load and the background work runs in the frames before and after it. A hold no one releases lapses after `BACKGROUND_HOLD_SECONDS` (or the seconds it was taken for), with a warning naming its key, so work on the lane always runs in the end. `backgroundHolds()` lists the keys holding the lane now, and `backgroundWaits()` answers whether the calling code's next unit waits for it (a walk with a clock of its own asks it between its pieces). `FrameBudget.DEFAULT_MS` is the slice a call that names none spends. `spent()` answers how much of the current frame's slice is gone. A caller with a budget of its own reads `mark()` where its work starts. `ranMs(mark)` answers how long it has run since, none of the time it spent suspended; `cpuMs(mark)` answers the CPU time of its work since: those stretches and the stretches of every coroutine it resumes, and every one they resume, while it waits on them, which a machine whose cores are taken by other work does not stretch, so a bound that refuses work for running too long refuses the same work on a loaded machine as on an idle one, and work handed to a coroutine as work run in place. A task it starts and waits for runs while it is suspended, which `cpuMs` does not count.
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
❒
bundle · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Default The neutral fallback surface — a plain white, non-metallic PBR material with mid roughness (`0.5`), sampling the built-in white texture. This is what an object renders as when no material is assigned. Built on `@builtin::shaders.pbr`. ## Inputs - `colors.base_color` — the flat tint (white by default). - `floats.roughness` (`0.5`) / `floats.metallic` (`0.0`) — a neutral matte dielectric. - `textures.base_color_texture` — the built-in `default:white` texture.
▲ 0↑ born
◐
material · born here
❒asset
# Triplanar Checker A checkerboard surface projected triplanarly, so the pattern stays uniform across arbitrary geometry with no UVs and no stretching. Neutral white base colour (`1.0, 1.0, 1.0`), half roughness (`0.5`), non-metallic, with a projection sharpness of `4.0` controlling how tightly the three axis projections blend at edges. Opaque, back-face culled, instanced, in the opaque queue (`2000`). Built on `@builtin::shaders.triplanar`, sampling `@builtin/textures/array_texture`. ## Inputs - `floats.triplanar_sharpness` (`4.0`) — blend tightness between the X/Y/Z projections. - `colors.base_color` (`1.0, 1.0, 1.0`) — tint over the projected texture. - `textures.base_color_texture` — the projected checker source (`@builtin/textures/array_texture`). - `floats.roughness` (`0.5`) / `floats.metallic` (`0.0`) — dielectric, mid-gloss default.
▲ 0↑ born
◐
material · born here
❒asset
# Plastic Red A glossy red plastic — a non-metallic PBR surface with a saturated red base colour (`0.8, 0.1, 0.1`) and mid roughness (`0.5`) for a soft dielectric sheen. Built on `@builtin::shaders.pbr`. Opaque, back-face culled, queue `2000`. ## Inputs - `colors.base_color` (`0.8, 0.1, 0.1`) — the red plastic tint. - `floats.roughness` (`0.5`) — soft, semi-glossy highlight. - `floats.metallic` (`0.0`) — dielectric (non-metal) response. - `floats.emissive` (`0.0`) — no self-illumination.
▲ 0↑ born
△
mesh · born here
❒asset
▲ 0↑ born
◐
material · born here
❒asset
# Cel Shaded A stylised, toon-shaded opaque surface built on `@builtin::shaders.extended_material`, with a warm red-orange base colour (`0.9, 0.3, 0.2`). The sun's light is cut into flat bands that multiply the base colour, so every band renders the hue of `base_color` and only its brightness steps; ambient light lifts the side facing away from the sun in the same hue. High roughness (`0.8`) keeps the surface matte: its specular term stays below the first band, so each lit band is one flat colour. ## Inputs - `colors.base_color`: the surface colour every band renders in, multiplied by `base_color_texture`. - `floats.roughness` (`0.8`): the size and strength of the specular highlight, which is banded with the rest of the sun's light; 0 is a small bright highlight. At four bands, a roughness of 0.5 or more keeps the highlight below the first band, so none shows. - `floats.quantize_steps` (`4`): the number of bands the sun's light is cut into; 0 shades smoothly. - `textures.base_color_texture`: an optional surface texture, drawn multiplied by `base_color`. Unset, it is white, and the surface renders `base_color` alone.
▲ 0↑ born
▣
module · born here
❒asset
# yaml.module YAML decode + encode for authored engine content. Pure Luau, no engine dependencies — a general parsing library, not data-system plumbing. ```luau local Yaml = require("@builtin::modules.yaml") local doc = Yaml.decode(vfs.read(path)) vfs.write(path, Yaml.encode(doc)) ``` ## Supported subset - Block mappings (`key: value`) and block sequences (`- item`), nested to any depth. - Compact sequence-of-mapping entries (`- path: x` / ` kind: y`). - Flow collections — `{ a: 1, b: 2 }` and `[1, 2, 3]` — single line. - Plain scalars with type inference: `~` / `null` → nil, `true` / `false` → boolean, numeric literals → number, everything else → string. - Single- and double-quoted strings (`''` escapes a literal quote inside a single-quoted string; `\n` `\t` `\r` `\\` `\"` inside a double-quoted one). A quote opens a quoted scalar where a scalar begins — after `key:`, after a `- ` entry marker, or inside a flow collection — so a plain scalar carries an apostrophe as data (`note: the world's rules`). Quoted keys are read in flow mappings. - `#` comments — honored outside quotes, so a `#` inside a quoted string is kept as data. - Literal (`|`) and folded (`>`) block scalars, with a chomping indicator (`-` strips the final newline, `+` keeps every trailing blank line, none keeps one newline) and an indentation indicator (`1`-`9`: the content's indent past the parent's), in either order (`|-`, `>+`, `|2`, `>1-`). A block scalar's content is literal text: quotes (balanced or not), `#`, `key: value` and `---` inside it are data. - An optional leading `---` document marker. ## Loud-error contract Constructs outside the subset above raise instead of misparsing: anchors/aliases (`&`, `*`), tags (`!`), directives (`%`), multi-document streams (a second `---`), a block-scalar header it cannot read (`|x`, `|-+`, `|0`), tab indentation, and inconsistent indentation (both block structure and block-scalar bodies). Every error carries the offending line number (`yaml: line N: ...`), so a bad config points straight at the line to fix. Tab indentation is rejected everywhere — including block-scalar body lines whose leading whitespace contains a tab. A tab after the first non-space character of a line is content and passes through. ## API - `Yaml.decode(text: string): any` — decode a YAML document into a Luau value (table, scalar, or nil for an empty document). Raises on malformed input or an unsupported construct. - `Yaml.decodeWithComments(text: string): (any, boolean)` — decode as `decode` does, and report whether the text carries a comment by the decoder's own rule: a `#` at a line's start or after whitespace, outside a quoted scalar and outside a block scalar. Re-encoding the value drops such comments, so an editor that writes a document back reads this first. - `Yaml.encode(value: table): string` — encode a Luau table as YAML (block style, two-space indent, alphabetically sorted keys). Raises on values YAML can't represent (functions, userdata, non-string mapping keys). A top-level empty table encodes to an empty document, which decodes back to `nil` (the YAML empty-document ambiguity).
▲ 0↑ born
▣
module · born here
❒asset
# assetType.shared.settings Resolves four questions about an asset's typed settings, all answered from its type's `type.yaml` — nothing here is found by convention. ```lua local Settings = require("@builtin::assetTypes.assetType.shared.settings") -- or, from inside the assetType runtime: local Settings = require("@builtin::assetTypes.assetType.shared").settings ``` ## Where does a type's schema live? `type.yaml` names it in a `settings:` block: ```yaml settings: values: "settings.yaml" # where an instance's own values live schema: { type: "settings.luau" } # one schema for every asset of this type ``` or, for a type whose settings differ per instance (an importer): ```yaml settings: values: "settings.yaml" schema: { instance: "settings.luau" } ``` or, for a type whose schema is a table its instance's own source declares and whose values live elsewhere (a component: its `public` fields, valued on each entity it is on): ```yaml settings: schema: { instance: "init.luau", export: "public" } ``` Whether an instance may lack its schema file is what the type's `files:` block says of that file. Listed under `files.optional`, it may be absent, and an instance without it declares no settings — the importer type lists it there, since most importers take none. Listed under `files.required`, or not listed at all, it must load, and an instance missing it is a broken declaration and is logged. `schema.type` is required at the folder relative to the TYPE's own `.assetType/` directory (one schema shared by every instance). `schema.instance` is required relative to each INSTANCE's own folder (`init` resolves the instance's own identity; anything else is a sibling module under it). Without `schema.export`, the file is required as a module and its return value IS the schema. With `schema.export`, the file is run in an environment of its own and `export` is read from a returned table carrying it, or else from the globals the file assigned — a component's `public` is such a global. That environment reads through to `_G` and takes every write itself; its own `_G` is itself, its `declare` and `computed` record into it, and its `task` records spawned, deferred and delayed work instead of starting it. Every other global is the real one, so a call the file makes through one runs as it does anywhere. The schema is the declared table's Field descriptors. A schema that resolves to nothing says why through `Settings.schemaProblemOf(ref)`: the file could not be read, compiled or run, or declared no such table. An instance schema is read again when its file, its type's `type.yaml`, or the entry file of any module the asset `require`s changes. `Settings.blockFor(typeName)` returns the raw block; `Settings.schemaForType(typeName)` and `Settings.schemaOfInstance(ref)` resolve the two schema shapes respectively; `Settings.schemaFor(ref)` tries the type-level schema first, falling back to the instance-level one. `ref` naming an assetType asset itself — e.g. `asset.resolve("texture", "assetType")`, rather than an instance of it — reports that type's own declared schema, the same one every instance of it reports. ## Where do an asset's values live? `settings.values` names a file living beside the asset's own content — `Settings.valuesPathOf(ref)` joins it onto the asset's path. `Settings.valuesOf(ref)` / `Settings.writeValues(ref, values)` read and write it; this module only names where it is. A type that declares its schema with no `settings.values` keeps no values in the asset — a component's live on each entity it is on — so `valuesOf` answers nil for it, `asset.create` refuses a `settings` table for it, and `asset.setSettings` refuses a write. `Settings.recordedWrite(path, text)` writes a file the way every values file is written, and an editor uses it for any other file it writes. It writes the whole contents, records the write into the open undo operation when one is open (so undoing it restores what the file held), and raises when the write does not land. ## In what order are a schema's fields declared? Every `Field.*` constructor stamps its descriptor with `declaredOrder`, one more than the last. Luau evaluates a table constructor's entries in the order they are written, so `Settings.orderedNames(schema)` lists a schema's fields — and a struct's subfields — in the order the source writes them. A values file, or a legacy `.metadata` settings block, may hold an older spelling — a renamed field, an older enum member. Every read passes what is stored through the type's `normalizeSettings` (`Settings.normalizeFor`), so it answers in the fields the schema declares today, and writes nothing. The next local edit of that asset rewrites the file in the declared spelling (`Settings.healLegacyIfNeeded`). `asset.setSettings(ref, patch)` writes a partial patch: `Settings.resolvePatch(ref, patch)` normalises it, merges it over the current values and applies the type's derived defaults for the fields it changed, and `Settings.writeValues(ref, values, patch)` applies the corrections, checks the schema and writes the file. ## How is a new asset's settings resolved at creation? `asset.create` calls `Settings.resolveForCreate(typeName, name, destPath, creationOpts, callerSettings, importerSettings)` before running the type's `onCreate`, checks the result against the schema, writes it to the values file, and hands `onCreate` a COPY of it as `opts.settings` (`Settings. cloneValues`) — never the same table the values file gets, so nothing `onCreate` does to its own copy can reach what was stamped. `onCreate` reads settings from `opts.settings` and never writes to it. `asset.create` also seeds the change baseline with the stamped values (`Settings.seedChangeBaseline`), so the values file's own first dispatch reports nothing changed and the payload `onCreate` encoded is the only encode a create runs. The layers, lowest priority first, each overriding the ones before it field by field: 1. The schema's own declared defaults (`Settings.defaultsOf`). 2. The type's own `settingsDefaults(name, opts, asked)` hook, when its `behavior.luau` exports one. `asked` holds what layers 3 to 5 name, so a default can follow a field one of them sets. 3. The Preset Manager's matching row (`Settings.presetLayerFor`). 4. The creating importer's settings for this type. 5. The `settings` table the caller passed to `asset.create`. 6. The type's own `settingsDerivedDefaults(values, explicit, changed)` hook, when its `behavior.luau` exports one — a field whose default follows another field, set only when no layer from 2 to 5 named it. 7. The type's own `settingsCorrections(values, name, opts)` hook, when its `behavior.luau` exports one — applied last, once every other layer has merged. Layers 2 to 5 are each read through the type's `normalizeSettings`, so a layer naming a field in an older spelling sets the field it names today. `asset.create`'s top-level settings alias accepts those older names too (`Settings.acceptedFieldNames`). Layer 7 is `Settings.applyCorrections(typeName, values, explicit, context)`, the one corrections path every settings write takes — this create chain, and `Settings.writeValues` for every later write (`asset.setSettings`, a type's first-encode seed, the legacy heal). `explicit` names the fields the writer asked for: the caller's `settings` table here, the patch for `asset.setSettings`. A correction lands SILENTLY on a field the writer did not name — nobody asked for that value, so overriding it just states a fact. A correction that contradicts a field the writer named REFUSES the write, naming the field, the value asked for, and why it cannot hold — the same as every other place this codebase refuses an explicit request it cannot satisfy (a `Field.checkSchema` violation, a BC7 alignment error) rather than silently rewriting it into something else. So `asset.setSettings(tex, { compression = "rgba16" })` on a mipped texture stores `generateMipmaps = false` beside it, while `asset.setSettings(tex, { compression = "rgba16", generateMipmaps = true })` is refused. `Field.checkSchema` runs once, over the result AFTER the corrections hook has applied — a bad value nothing corrects refuses the creation. ### Four hooks, four different jobs Every hook is an optional export on a type's `behavior.luau`, alongside `onCreate` / `onChange`. **None is ever handed a table to mutate** — each reads what it's given and RETURNS a table of what it wants changed (or nil); `resolveForCreate`, `resolvePatch`, `applyDerivedDefaults` and `applyCorrections` are the only places that write to the values, by merging what a hook returns the same way every other layer merges. - **`normalizeSettings(values) -> values`** maps every older spelling a stored file or a write may carry to the field and member the schema declares now, returning a new table; a table naming both an older field and its replacement keeps the replacement. The companion export **`normalizedSettingNames = { ... }`** lists the older field names it accepts beyond the schema, so a write naming one is not refused as an undeclared field. `texture.assetType`'s maps the fields its earlier schema stored to `colorSpace` + `compression`, and the older `filter` keywords to `linear` / `nearest`. - **`settingsDerivedDefaults(values, explicit, changed) -> partial?`** answers the values of fields whose default follows another field. At creation `changed` holds every field; on a write it holds the fields the write moved. A returned field applies only where `explicit` — the fields the writer named — does not name it. - **`settingsDefaults(name, opts, asked) -> partial?`** supplies a DEFAULT the schema itself has no syntax for — something only knowable at creation time, like a naming convention, a fact read off a payload the caller handed in, or a value that follows a field a higher layer sets (`asked` holds what the Preset Manager, the importer and the caller name, the higher one's value where two name a field). It runs early (layer 2 above), so any later layer — Preset Manager, importer, caller — freely overrides it. `texture.assetType`'s returns the `textureType` the name suggests (a `_normal`-suffixed name is a `normalMap`), `compression = "uastc"` and `maxDimension = 4096`, with `rgba8` for a `textureType` of `sprite` that a higher layer names; for a pre-encoded ZTEX payload it returns the colour space, compression and sampler the payload's own header carries. Either way, an explicit `settings = { ... }` from the caller still wins. - **`settingsCorrections(values, name, opts) -> (partial?, reasons?)`** enforces a CROSS-FIELD CONSTRAINT the schema itself has no syntax for — a fact about one field that depends on another field's resolved value, true regardless of which layer produced that value. It runs last (layer 7 above), over the fully merged `values`, and again on every later write of the values file. Nothing is left unmet in what gets validated and stamped — but a value the caller explicitly asked for is never silently rewritten to satisfy it; `applyCorrections` refuses instead (see above). The optional second return, `{ [field]: reason }`, supplies the "why" for that refusal message; a field with no reason falls back to a generic one. `texture.assetType`'s returns `{ generateMipmaps = false, maxDimension = 8192, colorSpace = "linear" }` whenever the RESOLVED `compression` is high-precision (the encoder stores one verbatim, linear, and refuses a mip chain or a downsample for it outright), paired with a reason naming the compression, and `nil` otherwise. ## What does a declarer declare? `Field.settingsOf(identity, mode)` embeds another declarer's schema as a struct field without restating it. The identity names one of two kinds of declarer, and `Settings.schemaOfDeclarer(identity)` tells them apart by what `identity` resolves to: - **An assetType** (e.g. `"@builtin::assetTypes.texture"`) — embeds the schema every instance of that type carries, resolved via `schemaForType`. This is the type-level shared schema from the section above, not a per-instance one — an assetType has no settings of its own to declare per instance. - **Anything else** (an importer, or any other asset that declares settings of its own) — embeds that asset's own schema, resolved via `schemaOfInstance`. Every schema this module serves has already run its `Field.settingsOf` fields through this resolution — a caller reading `schema.someField.fields` never sees an unresolved `declarer` with no `fields`. Resolution descends into an already-literal struct's `fields` and a list's `element` the same way, so a declarer embedded several fields deep is still reached. A declarer that embeds itself, directly or through another declarer, stops one level short of the loop instead of recursing forever. ## What are the defaults? `Settings.defaultsOf(schema)` reads every field's declared `default` into a plain table — a field declared without one is absent from the result rather than holding a `nil` value.
▲ 0↑ born
▣
module · born here
❒asset
# assetType.shared.typeYaml A type's `type.yaml`, parsed. Every block a type declares in its `type.yaml` (`settings:`, `inspector:`) is read through this module, so one file read and one YAML decode serve all of them. ```lua local TypeYaml = require("@builtin::assetTypes.assetType.shared.typeYaml") local folder, identity = TypeYaml.folder("material") -- "/zero/source/libs/@builtin/assetTypes/material.assetType", "@builtin::assetTypes.material" local doc = TypeYaml.of("material") print(doc.suffix) -- ".material" print(doc.inspector.type) -- "inspector.luau" ``` - `TypeYaml.folder(typeName)` resolves the assetType and answers its folder path and identity, or `(nil, nil)` when no such type resolves. - `TypeYaml.of(typeName)` answers the decoded document, or nil when the type does not resolve or its `type.yaml` does not decode to a table. The decode is cached per type and read again whenever the file's content version moves, or the type resolves to a different folder. - `TypeYaml.described(typeName)` lists the files a type's assets must describe: each file its `type.yaml` declares with a `described` content check, with the keys and headings the check names and each key's byte limit. `TypeYaml.PLACEHOLDER` is the marker a template puts where a description is yet to be written. - `TypeYaml.describeBlock(typeName)` answers the `describe:` block of the `type.yaml`: the type's own `guidance` on what a description covers and the identities of `examples` whose descriptions show the shape.
▲ 0↑ born
▣
module · born here
❒asset
# interfaces (module) Which interfaces a type implements, and whether its declaration keeps them. The one owner of the question: `ref:implements`, `ref:as`, the gate, listings and the inspector all ask here. An interface is an `interface` asset (`<name>.interface/`) stating a guarantee: members with signatures, and properties. A type lists the interfaces it implements under `interfaces:` in its `type.yaml`; `assetType.assetType` declares that key a reference to `interface` assets, so every listed name is recorded by guid in the type definition's reference table. A type's marks are read from those references, and every asset of the type implements every interface the type lists. ## Exports - `M.of(typeName) -> { typeName, marks, problems, declared }` — the marks a consumer may rely on and every problem the declaration raised. A declaration with an error carries no marks. Held until the type's files, an interface it lists, or the set of interfaces changes. - `M.typeImplements(typeName, x) -> boolean` — whether the type implements the interface `x` (name, identity or guid), or any of a list of them. - `M.markOf(typeName, x) -> Mark?` — the mark, with its `source` (`declared` or `implied`) and which members are met explicitly. - `M.member(typeName, mark, name) -> (function?, explicit)` — the function that meets a member now: `M.interfaces.<interface>.<member>`, else `M.ref.<member>`. - `M.definitionOf(ref) -> Definition` — an `interface` asset's `interface.yaml`, read: members with parsed signatures, properties, type keys, contract, conformance, legacy member. - `M.resolveInterface(x) -> (ref?, "unknown" | "ambiguous"?, candidates?)`. - `M.checkProperty(property, value)`, `M.propertyTypeText(kind)`. - `M.forget()` — drop every held answer. The change dispatcher calls it for a write inside an `.interface` or `.assetType` folder and for their removal. - `M.declareReferenceKeys() -> number` — declare every key a type's `type.yaml` states under `references.interfaceKeys` (`{ key, implements, field?, via? }`) through `asset.declareReferenceKey`, typed to the categories that implement the interface now. Boot registration calls it once every type has registered; `M.scheduleReferenceKeys()` runs it at the end of the frame, and the change dispatcher calls that after a change to a type or an interface. ## Refusals A declaration is refused, and carries no marks, while any of these stands: `interfaces.shape`, `interfaces.unknown`, `interfaces.ambiguous`, `interfaces.duplicate`, `interfaces.missing`, `interfaces.arity`, `interfaces.typeKey`, `interfaces.explicitUnclaimed`, `interfaces.explicitUnknown`, `interfaces.propertyMissing`, `interfaces.propertyType`, `interfaces.conflict`, `interfaces.unloadable`. `interfaces.implied` is a warning and refuses nothing. Each message names the type, the file, the fault and what to write; the `assetType` type's `validate` reports them, and the engine log states each once per state of the declaration. A type that lists no `interfaces:` key and defines the member an interface names under `legacy: { implied_by }` is marked with that interface, source `implied`.
▲ 0↑ born
▣
module · born here
❒asset
# asset_change_dispatch (module) Installs `_G.__zero_dispatch_asset_change`, the Luau half of the asset-type **change-callback** system. The engine calls it once per VFS source write (via `zero_scripting::ffi_callbacks::fire_asset_change_dispatch`, queued as `VfsMutation::AssetSourceWritten`). ## What it does 1. Receives the written VFS path. 2. Walks up the path to the enclosing `<name>.<type>/` typed-asset folder (deepest registered-type suffix wins, so the direct owner of the write is chosen for nested typed assets). 3. Loads that type's `<type>.assetType/behavior.luau` via `@builtin::assetTypes.assetType.shared.ref.loadTypeModule`. 4. If the module exports an `onChange` function, calls `onChange(ref, change)` where `ref` is the typed `AssetRef` for the changed asset and `change = { path, asset, type }`. The engine runs each dispatch as its own yieldable task, so a hook can wait on what it reads: a `vfs.read` of bytes only the blob store holds (a binary file on the web build) fetches them. A hook that reads only what is resident finishes inside the dispatch that started it. The writes routed to one asset react in the order they were routed: a write routed while that asset's hook is waiting queues behind it and reacts once the hook has finished. This is the type-level analogue of the component-centric `onAssetReload(field)` fan-out: components react to assets they *reference*; an asset *type* reacts to writes inside its own *instances*. ## The source-write seam A write inside a typed asset is also offered to the importer type's shared layer (`onAssetWrite(assetPath, path, origin)`), the way a write with no enclosing asset is offered to `onLooseWrite`. The asset's `import` record names the file it was imported from (by guid and path); a write to that file re-runs the importers on it, in place; the write that arrived is the only input. A type whose own `onChange` already keeps its retained source current (a texture re-encoding its image, a sound clip its audio) sets `reencodesRetainedSource = true` on its module, and the seam leaves that edit to it. ## Re-entrancy While an asset's `onChange` runs, a dispatch for that same asset made from the hook's own coroutine is suppressed, so a handler that routes a write back into its own folder inline doesn't recurse. A write the hook makes is routed on a later frame like any other and reaches `onChange` again once the hook has finished. `onChange` handlers must therefore be **convergent**: diff the meaningful state before acting and short-circuit when there's nothing to do (the `dynamicAsset` example only regenerates when the prompt actually changed and bails while a generation is in flight). Idempotency is the contract, exactly as it is for services' `start`/`stop`. ## Related - `@builtin::assetTypes.assetType.shared.ref` — owns `loadTypeModule` + the per-type `ref` method dispatch. - `assetTypes/assetType.assetType/template/behavior.luau` — the documented template that shows how to author `ref`, `global`, and `onChange`. - `assetTypes/dynamicAsset.assetType` — the reference type that uses `onChange` for prompt-driven regeneration with version control.
▲ 0↑ born
▣
module · born here
❒asset
# asset_create `asset.create` — the single, generic "instance a new asset of an existing type" API. The same entry point scripts and agents use; there is deliberately no tool wrapper, because agents author in Luau and call `asset.create(...)` directly. ```lua local inst = asset.create("material", "my_metal", { base_color = { 0.8, 0.7, 0.2 } }) -- → AssetRef: inst.path == "/zero/source/my_metal.material", inst.guid, plus the -- material type's ref methods. ``` `asset.create` makes a new *instance of an already-registered type* by running that type's `onCreate(name, opts)` behaviour hook (declared in its `behavior.luau`) and writing the produced files to `/zero/source/<name>.<typeName>/` — the one authored location, in every mode. While play runs, the play-mode write lock takes that write onto the **play shadow**: live in the session, listed by `vfs.playShadowPaths()`, and promoted or discarded on a guarded play-exit. The asset created in play therefore carries the same identity, path and `require` spelling it has in edit, and the session decides whether it stays. A create whose output the world **reproduces** on every load — one made from a component or a scene entrypoint — writes to the copy-on-write runtime store at `/zero/runtime/assets/<identity>.<typeName>/` instead, so the code that rebuilds it each load is its only source and the saved manifest never carries a second copy. ## Placement Four `opts` keys are consumed by the framework before the type's `onCreate` hook runs, and steer where the instance lands: | Key | Effect | |-----|--------| | `folder` | A relative subfolder under the source root: `/zero/source/<folder>/<name>.<typeName>/`. Groups a generator's output instead of accumulating it at the source root. | | `into` | A resolved container ref (`.toolbox` / `.package`) to author INSIDE — lands at `<container>/<name>.<typeName>/` and registers as a member. Edit-mode only. | | `dest` | An absolute destination path, owned by the caller (an importer building a `<name>.bundle/`). | | `overwrite` | Re-author an existing destination in place, keeping its `.meta` guid so every reference stays valid. | The `name` is always the asset's bare identity — the path goes in `folder`: ```lua local rock = asset.create("mesh", "rock", { positions = p, indices = i, folder = "terrain/props" }) -- → rock.path == "/zero/source/terrain/props/rock.mesh" ``` `dest` and `into` both take precedence over `folder`. `folder` decides the asset's identity, so it applies in every context: the runtime store is flat and spells that identity in one folder name. ```lua -- the same call from a component's awake() -- → rock.path == "/zero/runtime/assets/terrain.props.rock.mesh" -- → rock.identity == "terrain.props.rock", as it is from an execute ``` Types without an `onCreate` hook fall back to cloning their verbatim `template/` skeleton to the same destination, so `create` works for every type. Returns the created asset's `AssetRef` (`.path` / `.guid` plus the type's ref methods — the same interned instance `asset.resolve` returns) on success and raises (via `error`) on bad arguments or a failing `onCreate`. Installed onto the FFI `asset` namespace by the prelude (`M.installInto(asset)`). See `docs/specs/runtime-asset-copying.md`.
▲ 0↑ born
▣
module · born here
❒asset
# declaration (module) A type's `type.yaml`, decoded and held: the one reader behind every question about a type as a whole — its files, whether it broadcasts its subassets, how its instances are pictured. ## Exports - `M.of(typeName) -> table?` — the decoded declaration, or nil when no type answers to the name, it has no `type.yaml`, or the file does not decode (the last with a warning naming the type). Shared: read it, do not write to it. - `M.forget()` — drop every held declaration. The change dispatcher calls it for every write inside an `.assetType` folder and for every removed type.
▲ 0↑ born
▣
module · born here
❒asset
# assetType.shared.inspector Which inspector a type declares for its assets, and the declaration that file returns. The editor's Inspector (`edui.inspector`) reads it to add, replace and order the sections an asset shows. ## The block A type names its inspectors in `type.yaml`, with either key or both: ```yaml # the Inspector for every asset of the type, a file in the type's own folder inspector: { type: "inspector.luau" } # a file each asset may ship in its own folder, for what that asset declares inspector: { instance: "inspector.luau" } # both inspector: { type: "inspector.luau", instance: "inspector.luau" } ``` `type:` is what selecting an asset of the type shows. `instance:` applies to the things an asset declares, never to the asset's own view: a component names `instance: "inspector.luau"`, and a component that ships that file shapes its card on every entity it is on. Each value is a `.luau` file name. A block that is not a map, names another key, names neither key or names a file that is not `.luau` is malformed; the assetType validator reports it as `assetType.inspector_block`, and a `type:` file missing from the type folder as `assetType.inspector_file_missing`. ## The declaration The file returns a table: ```luau return { -- sections this inspector adds (before Operations) sections = { { id = "summary", title = "Summary", build = function(ctx) return { ctx.widgets.text{ text = "mode is " .. tostring(ctx.settings.mode) } } end }, }, -- a generic section id -> the section shown in its place replace = { tags = { id = "tags", title = "Labels", build = function(ctx) return {} end } }, -- section ids, first to last; ids it does not name follow in default order order = { "summary", "identity" }, } ``` A section is `{ id, title, icon?, open?, build(ctx) }`; `build` returns the section's body as a list of edui nodes. Any member of the declaration other than `sections`, `replace` and `order` must be a function (a helper the file exports). `material.assetType/inspector.luau` is a full example. The Inspector rebuilds an asset's sections when the asset's files change. A section that shows state held outside those files names it with a `signature(ref)` member: text that moves when that state moves, read every time the Inspector checks for a rebuild, so it has to be cheap. `renderFeature.assetType/inspector.luau` folds in whether the feature runs and its live settings, so a feature enabled or reconfigured from a script shows in the Inspector as it happens. ## API ```luau local InspectorDecl = require("@builtin::assetTypes.assetType.shared.inspector") InspectorDecl.blockFor("material") -- { type = "inspector.luau" } InspectorDecl.blockProblem({ other = "x.luau" }) -- why a block is malformed, or nil InspectorDecl.declaresTypeInspector("material") -- true: the asset view reads one local decl, problem, file = InspectorDecl.declarationFor(matRef) local cdecl = InspectorDecl.instanceDeclarationFor(compRef) InspectorDecl.shapeProblem(decl) -- nil when well-formed ``` `declarationFor(ref)` (and `typeDeclaration(typeName)`) read the `type:` file: - `(nil, nil, nil)` when the type names no `type:` inspector; - `(nil, problem, file?)` when the block is malformed, or the file is missing, raises while loading, or returns the wrong shape — the problem names the file and what is wrong with it; - `(declaration, nil, file)` otherwise. `instanceDeclarationFor(declarerRef)` reads the `instance:` file in the declaring asset's own folder, and answers `(nil, nil, file)` when that asset ships none.
▲ 0↑ born
▣
module · born here
❒asset
# scene_instantiable (module) The instantiation contract's shared implementation. An asset type opts into scene instantiation by defining `instantiate(self, target?, opts?)` on its behaviour `ref` table; this module carries the parts that mean the same thing for every type, so a caller writes ONE piece of code against all of them. ```lua local root, idMap = ref:instantiate(target?, opts?) ``` ## The contract **IN — the base opts.** `target` is an owning entity ref: the instance lands under (or, for a hierarchy type like a bundle, onto) that owner. With no target the type spawns a fresh root. `position`, `rotation`, `scale`, `name` and `temporary` place that root and mean the same for every type. `rotation` takes three numbers as pitch/yaw/roll in DEGREES, or four as a quaternion. A type may honour more opts of its own — `params` for a type built from declared inputs, `idMap` / `diff` / `sourceTag` for the bundle override contract — and says so in its own `instantiate` docs. **OUT — the two returned values.** Every type returns the same pair: - **`root`** — the composed root, as an `EntityRef`. Composition is **synchronous**: the root and everything the type built under it are live the moment the call returns, so a caller can parent to it, read its components and hand it on in the same statement. There is no frame to wait for and no callback. - **`idMap`** — the `originalId -> runtimeId` map naming what the composition spawned, `{}` for a type with no addressable children. **Never nil.** A component that re-composes the asset on every load (`Asset`) keeps this map and passes it back in, which is how a cross-entity reference into the composition — `SkinnedModel.skeletonRoot` pointing at a bone — survives a reload. The return is enforced, not merely described: `AssetRef` dispatches every `ref:instantiate(...)` through `result` on the way out, whether or not the type called it. A type that returns something else fails at its own call rather than handing its caller a nil root or a map that is sometimes absent. ## Exports - `M.root(self, target?, opts?) -> root` — stand the root entity for a type that spawns one: parented to `target`, born temporary when `opts.temporary`, named `opts.name` else the asset's own name, placed. - `M.place(root, opts?) -> root` — apply the placement opts to a root the type already has (the adopt path: a bundle exploding onto its target, a sceneModule reconciling under one). - `M.result(self, root, idMap?) -> (root, idMap)` — return through the contract. Checks `root` is a live entity ref, normalises a missing map to `{}`, and errors naming the asset type when either is something else. - `M.isOwned(opts?) -> boolean` — whether a component drives this call. The `Asset` / `SceneModule` components tag their own calls with `sourceTag`; they hold the reference and re-compose on every load. An untagged call came straight from `ref:instantiate(...)` and has no such owner. - `M.own(root, self, idMap?) -> root` — hand an already-composed root to an `Asset` component pointing at `self`, so the reference and its map persist and the composition is rebuilt on the next load. The component adopts the live composition rather than building a second one. - `M.check(value, constraint) -> ok, reason?` — the `sceneInstantiable` field-constraint validator, also registered under that kind on load. ## The field constraint `Field.instantiableRef` emits `constraint = { kind = "sceneInstantiable" }`, and this module registers the validator for it on load. Given a written value: 1. `nil` passes — the field is optional (no asset assigned). 2. Reads the value's identity — a bare string, or a table's `__ref` / `guid` / `identity` / `name`. 3. Resolves it (`asset.resolve(identity)` — any category) and asks the resolved ref `ref:canInstantiate()`: true iff the asset's type defines an `instantiate` method. This is what lets `Field.instantiableRef` accept by CAPABILITY rather than a hardcoded type list — a new scene-instantiable asset type is accepted the moment it defines the hook, with no edit to the field or its consumers.
▲ 0↑ born
▣
module · born here
❒asset
# asset_on_register Drives the optional `onRegister(self)` assetType lifecycle hook — the surface that lets an asset instance run code exactly once when it first registers, operating on the per-instance ref (`self`). This is what makes "write an asset into the world → it takes effect live, no restart" work for content that registers into a runtime registry (editor panels, and anything else that opts in). A type opts in by exporting `onRegister` from its `behavior.luau`. The hook fires exactly once per instance: - On `engine.onWorldLoaded` — a batched sweep over every world instance of every type that implements `onRegister`, yielding every 32 instances so a large instance count never stalls a frame. The @builtin library (`/zero/source/libs/`) is excluded. - On live `asset.create` — the create path calls `M.fireFor(ref)` on the freshly-created instance. A per-VM once-guard keyed by the instance's VFS path ensures the two triggers can't double-register the same instance. ## Exports - `M.fireFor(ref, onRegisterFn?) -> boolean` — fire one instance's `onRegister(self)` hook exactly once. Resolves the type's hook from `ref.type` when `onRegisterFn` isn't supplied. Idempotent: a second call on the same instance is a no-op. Returns true if the hook fired this call. - `M.sweep()` — batched sweep: fire `onRegister` once for every world instance of every registered type that implements it. Yields, so it must run inside a task. Safe to call repeatedly. - `M.install()` — install the world-loaded sweep. Idempotent. Runs the sweep on a system task so it ticks through pause and never blocks the caller.
▲ 0↑ born
▣
module · born here
❒asset
# previewRecipe (module) How a type makes its instances' pictures. A type declares it in its `type.yaml`, under `preview:`, and every instance's `preview.png` is produced by the recipe named there. ```yaml preview: kind: surface # instantiate | image | surface | custom mesh: sphere # surface: the builtin mesh the asset is painted on ``` | `kind` | The picture is | Needs | |---|---|---| | `instantiate` | the asset stood in the studio through its own `instantiate` | — | | `image` | a file the instance already holds, fitted to the frame | `source.file` or `source.files` | | `surface` | the asset painted on a builtin mesh | `mesh` | | `custom` | whatever the type's `behavior.luau` `ref.preview` returns | — | `angle: [yaw, pitch]` (degrees) states the bearing the camera looks from, for any kind that renders. The `preview:` block says how the picture is PRODUCED. Whether search embeds that picture is a separate declaration — an `image` chunk under `indexing.content` naming `preview.png` — so a type states both, and a type that states one without the other gets exactly what it stated. ## Exports - `M.of(typeName) -> PreviewRecipe?` — the recipe `typeName` declares, or nil when it declares none or no type answers to that name. Read once and held; a block naming an unknown `kind`, or missing what its kind needs, is refused with a warning naming the type. - `M.forget()` — drop every held recipe. The change dispatcher calls it, with `declaration.forget()`, for every write inside an `.assetType` folder and for every removed type, so an edited `type.yaml` is read again.
▲ 0↑ born
▣
module · born here
❒asset
# assetType.shared.ref Builds the metatable every `AssetRef` (the `{ __ref, type, name, guid, identity, path }` envelope returned by `asset.resolve` / `asset.ref`) carries. Replaces the per-call C metatable that used to live in `crates/zero_scripting/src/ffi/bindings/asset.rs::attach_asset_ref_metatable`. ## Public API ```lua local assetRef = require("@builtin::assetTypes.assetType.shared.ref") -- Called by the Rust factory (push_asset_ref_handle) via -- _G.__build_asset_ref_proxy after the envelope fields are set. assetRef.build(envelope) -- attaches AssetRefMT, returns the table ``` The module exposes no invalidation surface — discovery is registry-driven and hot-reload is transparent (see "Discovery and hot-reload" below). ## Method dispatch order `ref.foo` is resolved in this order: 1. **Default methods** — `getSource` / `getBytes` / `getText` / `exists` / `inspect` and the lazy `meta` property. Per-type definitions cannot override these (engine contract from gh#1889). 2. **Per-type `ref` table** — discovered through `asset.resolve(<typename>, "assetType")` + `require(<identity>.behavior)`. The lookup resolves to whichever `<typename>.assetType/` folder is currently registered for the typename (built-in, user, or library-vendored) and pulls its `ref` methods. 3. **Nil** — unknown key, same shape as the original C metatable. ## Adding methods for a new asset type Drop a `behavior.luau` into the type folder: ``` src/lua/lib/assetTypes/<typename>.assetType/ ├── type.yaml -- structural spec (existing) ├── behavior.luau -- ref + global behaviour (new) └── template/ -- placeholder body (existing) ``` `behavior.luau` returns: ```lua return { ref = { --!desc Per-instance method on every `<typename>` AssetRef. myMethod = function(self, ...) ... end, }, global = { -- Reserved for the asset.<typename>.* surface — not consumed -- yet; included so the contract from gh#1889 lands cleanly. }, } ``` Within `ref` methods, `self` is the AssetRef envelope: `self.path`, `self.identity`, `self.guid`, `self.type`, `self.name` are available. Engine-required fields (`guid`, `path`, `identity`, `type`) must not be redefined. ## Discovery and hot-reload Type discovery uses the asset registry, so it doesn't matter where a `<typename>.assetType/` folder lives — engine built-ins under `@builtin::assetTypes.<X>`, user types dropped under `/zero/source/<X>.assetType/`, or types vendored inside an imported library all resolve identically. The dispatcher walks `asset.resolve(<typename>, "assetType")` → canonical identity → `require <identity>.behavior` on every miss; the asset registry is the cache for the resolve half and Luau's `_LOADED` is the cache for the require half. Hot-reload is transparent. When a `<typename>.assetType/behavior.luau` is rewritten through VFS, the engine's `invalidate_require_cache_for_state` re-runs the module and mutates the cached `_LOADED[<identity>.behavior]` table in place. Dispatch reads `mod.ref` on every access (rather than caching a sub-pointer), so existing AssetRefs see the new methods on the very next access — no Rust-side hook into this module is needed, and no invalidation API is exposed for callers to call. The same registry-driven path also handles type **registration** correctness: dropping a new `<typename>.assetType/behavior.luau` updates the asset registry, the next `asset.resolve(<typename>, "assetType")` returns the new ref, and AssetRefs of that type immediately gain the new methods. ## Why Luau, not Rust The asset surface needed per-category behaviour (`material:getProperties()`, `bundle:instantiate(entityId)`, `tool:run(args)`) and the old shape couldn't grow without an FFI change per method. Owning the proxy in Luau means: - Type-specific methods ship as content (the `<typename>.assetType/` folder), not engine code. - Adding a new asset type drops in a new folder; no Rust rebuild. - Methods can call any other Luau global (`vfs`, `asset`, `Material`, `entity`, etc.) directly, instead of going through narrow FFI primitives. ## Consumers - `crates/zero_scripting/src/ffi/bindings/asset.rs::attach_asset_ref_metatable` — the Rust factory that pushes envelopes invokes `_G.__build_asset_ref_proxy` once per push. - Every Luau call site of `asset.resolve` / `asset.ref` / `entity(id).component.X.material` / any binding declared `AssetRef<...>` — they all receive envelopes built through this module.
▲ 0↑ born
▣
module · born here
❒asset
# asset_ref_shapes Publishes what every `AssetRef<category>` answers to, so a member read on an asset-typed value is checked against the category's own surface. An asset category's per-instance surface is authored: a `<name>.assetType/behavior.luau` declares `M.ref = { ... }`, and each category declares its own. The members an `AssetRef<inputMap>` carries are therefore knowable only to `inputMap` itself — no fixed set of types covers the ones a world defines, and the checker has no way to guess them. This module reads each registered category's `M.ref` table from its source (never executing it), renders it as a Luau table type, and hands the set to the engine. From there a `ref:method(...)` on an asset-typed value resolves against the category's real surface: a name it does not carry is reported along with the ones it does. ## Results shaped by the asset Some results are shaped by the asset rather than by its category — `inputMapRef:activate()` answers one handle per binding THAT map declares, a set that is authored and differs per map. A category states those by declaring `refShapes`, and this module asks it once per instance and publishes the answers keyed by asset identity. `types/assetType` documents the authoring side. ## When it publishes Publishing is driven by use: every entry point that produces diagnostics calls `ensure`, which is a no-op once the set is current. A world load, a write inside a type definition, and a write inside any asset whose container computes shapes each mark it stale, so the cost lands on the next check and only if one comes. The sweep is complete and replaces what was published before, so a category whose type is removed stops being published. ## Reading what the checker believes From a call site, a type that is correct and one that was never published are the same absence of a diagnostic. `published()` tells them apart: ```lua local shapes = require("@builtin::assetTypes.assetType.shared.refShapes").published() shapes.categories.inputMap --> "{ activate: () -> any, controls: () -> { any }, ... }" shapes.returns["@builtin::inputMaps.default"].activate --> "{ crouch: Handle, interact: Handle, jump: Handle, ... }" ```
▲ 0↑ born
·
assettype · born here
❒asset
# texture An **image asset** — the raw bytes of a `png` / `jpg` / `jpeg` / `hdr` / `ktx2` / `webp` / `bmp` / `tga` file. A loose image written into the world is imported into a `<stem>.texture/` container (see "Internal layout"). > New to how a texture exists as an asset, as CPU-side pixels, and as a live GPU > texture (and how `renderer.texture.*` and render targets move between them)? > Read `core/resource-model` first. `texture` is a first-class assetType (not a bare plural-dir category) so that: - a texture has a stable asset **identity** and an explicit `asset_type` link, and - a material that references a texture records a real `.refs` edge to it — which is what lets the CPU-residency system cascade from a material to the textures it actually uses. ## CPU residency vs GPU residency A texture can be resident two fundamentally different ways, and they must not be conflated: - **CPU residency** (this assetType): the raw image **bytes in memory** — readable, hashable, decodable. You can operate on the bytes. - **GPU residency**: those bytes uploaded to the device as a GPU texture the renderer binds/samples. Byte-level reads are **not possible** on the GPU variant — that is simply how the device works. GPU residency is managed separately and is **not** part of this assetType. Same texture identity, two separate residency states, two separate operation sets, two separate reference counts. ## Internal layout A `.texture/` holds these files, and its child set is open. `asset.create("texture", name, ...)` and the **texture importer** (which creates through it when a loose raster image lands in `/source/`) produce this shape: ``` <name>.texture/ source.<ext> the retained source raster — see below source.ztex the full-resolution texels a cook dropped some of — see below settings.yaml the texture's settings — see below data.ztex canonical pre-encoded + pre-mipped payload (ZTEX magic) .metadata what data.ztex holds and was encoded from ``` `asset.create` keeps a copy of the image bytes it was given as `source.<ext>`; the importer moves the uploaded image in under its own name instead (`foo.png` stays `foo.png`). Either way it is the texture's retained source: rewriting it re-encodes `data.ztex` from the new pixels, and a rewrite carrying the bytes `data.ztex` was already encoded from changes nothing. An encode of a `normalMap` texture states the source's mean tilt, the angle in degrees from +Z of the mean decoded normal, as `meanTiltDegrees` in the `encoded` record of `.metadata` (`renderer.texture.normalMapTilt` reads it from any source image or payload). A map centred on its surface reads near 0; a map whose whole surface leans reads the lean, and every surface it covers leans by it. Above 3 degrees the encode raises the notice `notices.texture.normal_map_tilted`, which names the texture and its tilt. `data.ztex` is the **preferred primary**: when present the renderer resolves and uploads it verbatim — no re-mip. When absent the primary falls through to a raster image in the folder, so a container holding only an image file reads that image. That fallthrough takes the lowest-named raster image in the folder and never the rendered preview, which is made from the payload. A container that lost its encoded payload and holds no other image has no primary: `asset.diagnose(ref)` reports `noPrimaryFile`, `asset.validate(ref)` reports `texture.no_payload`, and `renderer.texture.loadCpu` refuses it. `asset.primaryFile(ref).path` names the file the resolution landed on; the asset-system guide covers `diagnose`. #### `settings.yaml` settings A texture's settings are declared in `settings.luau` and live in its `settings.yaml`. `asset.create` stamps them when the texture is made, and `texRef:setSettings({ ... })` (or `asset.setSettings(ref, patch)`) changes them. Editing an encode-relevant one re-runs the encode against the retained source and rewrites `data.ztex`. ```lua local tex = asset.create("texture", "hero_albedo", { bytes = png, ext = "png", settings = { maxDimension = 1024 }, }) tex:setSettings({ uastcRdo = "medium" }) ``` | key | values | default | meaning | |-----|--------|---------|---------| | `textureType` | `color` / `normalMap` / `mask` / `sprite` | `color`, or guessed from the name | what the texture holds, recorded in the payload. `normalMap`: tangent-space normals — when `generateMipmaps` builds the chain, every level of it, the base included, is renormalised to unit length; with `generateMipmaps = false` the one stored level is the source as given, and the chain the GPU builds from it at upload is a plain box filter. `mask`: linear data (roughness, metallic, occlusion, height, masks). `sprite`: a 2D image with transparency. A new texture's type is guessed from its name — `_normal` / `_nrm` / `_n` / … → `normalMap`, `_rough` / `_metal` / `_ao` / `_height` / `_mask` / … → `mask` — unless it is given. | | `colorSpace` | `srgb` / `linear` | follows `textureType`: `srgb` for `color` and `sprite`, `linear` for `normalMap` and `mask` | how the stored values are read when sampled. `srgb` for albedo/emissive/base-color, UI and sprites; `linear` for normal/RM/AO/height/mask data. | | `compression` | `uastc` / `rgba8` / `rgba16` / `rgba32f` | a new texture: `uastc`, a `sprite` `rgba8` | what the texels are stored as — see "What each compression stores" below. | | `effort` | `fastest` / `fast` / `thorough` | `fastest` | how long a `uastc` encode searches for each block — see "Block compression" below. | | `uastcRdo` | `none` / `low` / `medium` / `high` | `none` | how far a `uastc` encode moves from the source to make a payload that compresses smaller on disk and over the network — see "Block compression" below. | | `generateMipmaps` | `true` / `false` | `true` | bake the full mip chain into `data.ztex` at encode time. | | `maxDimension` | integer, `1` to `8192` | a new texture: `4096` | the longest side the encoded texture may have; a larger source is halved until it fits. A value past 8192 is refused. | | `filter` | `linear` / `nearest` | `linear` | sampler filtering recorded in the payload. A material slot and a UI image widget sample the texture with it. A post-process effect's texture property, a render pass's `@texture` input and a compute shader's `texture_2d` binding sample through a sampler of their own (the effect's `postprocess.setSampler`, the pass's, the compute shader's named `sampler` binding), which this setting does not change. | | `wrapU` | `repeat` / `clamp` / `mirror` | follows `textureType`: `clamp` for `sprite`, else `repeat` | how a material samples the texture past its left and right edges: tiled, the edge texel held, or mirrored. Recorded in the payload. | | `wrapV` | `repeat` / `clamp` / `mirror` | follows `textureType`: `clamp` for `sprite`, else `repeat` | the same, past its top and bottom edges. | | `anisotropy` | `world` / `1` / `2` / `4` / `8` / `16` | `world` | samples taken along a surface seen at a grazing angle. `world` follows the `render.anisotropy` world setting (`renderer.setAnisotropy`); a number fixes it for this texture, clamped to what the device supports. A `nearest` texture samples with 1. A write may give the number itself (`anisotropy = 8`); it is stored as the string. Recorded in the payload. | | `alpha` | `input` / `premultiplied` / `none` | `input` | what the encode does to alpha. `input`: kept as the source has it (straight alpha). `premultiplied`: colour multiplied by alpha — decoded to linear light, multiplied and re-encoded for an `srgb` texture, multiplied as stored for a `linear` one — the source a material with the `premultiplied` blend mode (`src + dst * (1 - src.a)`) composites. `none`: every texel opaque, colour kept. | | `alphaIsTransparency` | `true` / `false` | follows `textureType`: `true` for `sprite`, else `false` | fill every fully transparent texel with the average colour of its non-transparent neighbours, spreading outward, so bilinear filtering and mip averaging never pull black into the edge of a transparent area. Alpha stays 0. Runs before `alpha` and before the mips. | | `keepCpu` | `true` / `false` | `false` | keep the decoded pixels in the CPU store after the GPU upload — see below. | The type's colour space, `alphaIsTransparency`, `wrapU` and `wrapV` are stamped when the texture is created, and a later write that changes `textureType` moves them with it, unless the same write names them. A cook that drops texels — a `maxDimension` smaller than the source — keeps the full-resolution input as `source.ztex` (one RGBA8 level) when the container holds no source image, so raising `maxDimension` later re-encodes from every texel. A cook that drops nothing keeps nothing extra. A texture made from raw pixels whose cook dropped nothing keeps its payload as its only source, so a settings change re-encodes from that payload read back with straight alpha: what an earlier encode discarded stays discarded, after `alpha = none` its alpha is opaque, and a `uastc` payload re-encoded is the blocks' texels, not the pixels first given. A new texture's settings start from the texture type's own defaults — `uastc` with a `maxDimension` of 4096; `rgba8` for a `sprite`; a 16-bit PNG or `.hdr` source left to the schema's `rgba8` unless a layer names a compression — and a world's Preset Manager rows for `texture` override them (a world that ships at 2048, say), then an importer's settings, then the `settings` the create names. `filter`, `wrapU`, `wrapV` and `anisotropy` say how the texture is sampled, not what its texels are. A write that changes only those rewrites the payload's header (`renderer.texture.withSampler`): every level keeps its bytes, and no preview is rendered, because no pixel changed. Every material slot samples through its own texture's state, so two textures on one material can wrap and filter differently. UI image widgets honour `filter` and draw each image over its own bounds, so the wraps apply to materials. A post-process effect, a render pass `@texture` input and a compute shader sample through samplers of their own, so none of the four settings reaches them. `keepCpu` is a lifecycle setting, not an encode input — it never re-runs the encode. It acts on an already-materialised texture right away instead: `true` loads the decoded pixels into the CPU store when the texture is GPU-resident, `false` drops a resident CPU copy. The `data.ztex` payload is a `ZTEX` magic, a 32-byte header and the mip levels; the CPU encoder is exposed to Luau as `renderer.texture.*` and consumed by the texture importer and this assetType. #### What each compression stores | `compression` | In `data.ztex` | On the GPU | Limits | |---|---|---|---| | `uastc` | UASTC 4x4 blocks, whole mip chain, one byte per texel, each level compressed for storage. | Transcoded at upload to a block format the adapter samples: `Bc7RgbaUnorm[Srgb]` where it samples BC textures (desktop native, desktop WebGPU), ASTC 4x4 where it samples ASTC and not BC (phones, a browser on one), ETC2 RGBA8 where it samples only ETC2, each one byte per texel; RGBA8 at four bytes per texel on an adapter that samples none of them, and for a texture whose first level is not whole 4x4 blocks. | the texture keeps its own size; each level is the one above halved (rounded down, at least one texel). A first level whose sides are not multiples of four is not whole 4x4 blocks, which a device's block formats are addressed in, so it is resident as RGBA8 texels. | | `rgba8` | From an image with `generateMipmaps = false`, a `maxDimension` the image fits within, `alpha = input` and `alphaIsTransparency = false`: the source PNG / JPEG / WebP itself, decoded at load. Otherwise raw 8-bit RGBA with the encoder's box-filtered mip chain. | `Rgba8Unorm` / `Rgba8UnormSrgb`, four bytes per texel. | none | | `rgba16` | Raw 16-bit unsigned normalized, one level. An image is decoded at its own depth: a 16-bit PNG keeps every bit, an 8-bit channel `v` is stored as `v * 257`. The frames of an animated image are decoded at 8 bits. | `Rgba16Unorm` where the adapter grants 16-bit normalized textures (native); half float (`Rgba16Float`, about 11 significant bits) where it does not (every browser). | one level, no `maxDimension`, `linear` only. | | `rgba32f` | Raw 32-bit float, one level. An image channel is stored as its value over the channel's maximum. | `Rgba32Float`. Where the GPU filters 32-bit float, every consumer samples it. Where it does not (every browser): a material slot draws the shader's declared default; a UI image draws nothing; a render pass naming it as an `@texture` input is skipped; a compute shader that declares no sampler binds it and reads it with `textureLoad`, and one that declares a sampler refuses the dispatch — each logging once, naming the texture and its format. CPU reads (`:load()`, `renderer.texture.decode`) return every bit on every device. | one level, no `maxDimension`, `linear` only. | A high-precision compression turns `generateMipmaps` off, `maxDimension` to 8192 and the colour space to `linear` when the same write does not name them, and refuses a write that names a contradicting value. #### Block compression `compression = "uastc"` stores every mip level as UASTC blocks — sixteen bytes per 4x4 texels — a format no GPU samples directly but every one can be handed: at upload each level is transcoded to a block format the adapter samples, BC7 on a desktop GPU and ASTC 4x4 on a phone's (ETC2 on one that samples ETC2 alone), so one payload is resident at one byte per texel on each, and RGBA8 on an adapter that samples none; `renderer.textureMemory().blockFormat` names the format this adapter holds it in. Only the levels a device keeps are transcoded: under a texture-size cap (`renderer.setMaxTextureSize`) a texture is uploaded from the first level of its chain within the cap. Compression is lossy, which makes it the choice for colour, normal and detail maps; `rgba8` holds a texture exactly, which is what pixel art and a mask whose exact codes matter need. `effort` is how long the encode searches for each block. `fastest` tries one candidate for an opaque block, `fast` takes about 6 times as long and `thorough` about 17 times, each landing closer to the source texels. What the GPU holds is the same size at every effort, and so is the time a load takes. `uastcRdo` trades accuracy for a payload that compresses smaller: `none` encodes each block as close to the source as the encoder finds, and `low`, `medium` and `high` let a block move further from the source when a nearby block's bytes would let the payload compress better. What the GPU holds is the same size either way; what moves is the size of `data.ztex` on disk and over the network, and the encode time, which a pass more than doubles. The encode runs on the CPU when the texture is created or a setting that decides its texels changes. A call from a task that can yield cooks off the frame and the task waits for it, so the world keeps running: a 1024x1024 texture with its mip chain takes about a second on a desktop CPU. A texture whose settings say `rgba8` is never compressed. ## Reading an asset from its ref `texRef:settings()` reads the container's settings with every schema default filled in and `texRef:setSettings({ maxDimension = 1024 })` patches them; `texRef:load()` decodes the payload's pixels into the CPU store for per-pixel access, `texRef:handle()` puts the texture on the GPU under the asset's own guid, and `texRef:preview()` renders it as a swatch. `texRef:info()` reads the compiled `data.ztex` payload's header: the format it was compiled to — also as its `compression` and `colorSpace` — the `textureType`, `alpha` and `alphaIsTransparency` it was encoded under, its width and height, its mip and array-layer counts, the sampler recorded in it (`filter`, `wrapU`, `wrapV`, `anisotropy`), and, for an animated sequence, each layer's display time and the length of one pass: ```lua local info = texRef:info() print(info.width, info.height, info.format, info.mipCount) ``` It answers off that payload's own header, so a compiled texture reports how big it is for a header read where `load()` decodes its pixels and `handle()` uploads them. A container whose primary is a source image answers `(nil, err)`, and `load()` reads its size. The `compression` and `colorSpace` it reports are what the payload holds; the settings table holds what the encode was asked for. ## In the Inspector Selecting a texture opens its **Texture** section right below the asset's identity, then its Settings. The section draws the encoded texture through the texture's own sampler, so a `filter = "nearest"` texture reads crisp at every zoom. The zoom row offers **Fit** and each integer zoom (1×, 2×, 4×, 8×) whose drawn size fits 512 px; a 128 px texture offers up to 4×, and one wider than 512 px offers Fit alone. Below the view, the section lists every field of the `data.ztex` header (`texRef:info()`) — size, format, mip levels, filter, layers, and a sequence's frames and duration — and the GPU memory the encoded mip chain takes across its layers. The filter and the other encode settings change in the Settings section; the Texture section reports the re-encoded result.
▲ 0↑ born
·
assettype · born here
❒asset
# `.font` asset type A `.font` is a first-class font asset: font-file bytes (TTF / OTF / WOFF / WOFF2) converted into a guid-anchored asset via `asset.create("font", name, { bytes = … })`. A font is a **general CPU resource** usable by any text surface. The `onRegister` hook calls the engine `font.register(name, bytes)` primitive, which installs the parsed face into **both** the 2D/3D text system (`text.*`) and the egui UI text system, under the family name the font file itself reports. A registration is what puts the face in the database; whether `fontFamily = "<name>"` selects it is the separate question of whether the shaper matches that name, and `font.reconcile()` answers it per family: ```lua for _, f in ipairs(font.reconcile()) do if not f.selectable then print(f.family .. " is registered but shapes as " .. f.shapedWith) end end ``` `text.face(handle)` gives the same answer for one label. A family the shaper's database holds is selectable under its own weights and for the glyphs its faces cover: a row that reads `familyCoveredNoGlyph` names a family the shaper picks whose faces have no glyph for the text asked of it. `topics/text` covers reading a label that came out in the wrong face. Fonts are CPU resources (not GPU), so the primitive lives in the `font.*` namespace, the CPU analogue of `renderer.texture.create`. ## Layout ``` <name>.font/ data.zfnt the baked payload `asset.create("font", ...)` writes face.json optional: family group, role, aliases, on-demand entries ``` ## Editing a font's files A write to a file the registration reads (`face.json`, `data.zfnt`, or a raw font file in the folder) installs the font again from what the folder now holds. The names the new `face.json` gives it (its group and each alias) select it on every text surface from then on, and a name the earlier descriptor gave it and the new one does not stops selecting it; a changed `group` moves the face to that group. Text laid out under a name the edit decides is laid out again, and a `Text3D` label draws it again on the next frame. For an on-demand face the same holds for the font and coverage files its entries name: the entries are declared again from their coverage files, and an entry already installed is registered again from its font file with the names the descriptor now gives. ## On-demand faces A face whose file is large and whose script most sessions never draw is declared by the codepoints it covers instead of being read at boot. Its `face.json` lists the font files of the folder under `onDemand`, each beside a coverage file: ``` NotoSansCJK.font/ face.json { group, role, aliases, license, onDemand = [ { name, file, coverage }, ... ] } kana.otf a font file (TTF / OTF) kana.coverage the codepoints it maps: "3000-30ff,ff01-ff5e,..." ... OFL.txt the license the files are distributed under ``` `onRegister` reads the coverage files and calls `font.declare(name, coverage, { file, family, role, aliases })` for each entry; no font file is read. The first time a label or a `text.*` object meets a character an entry covers and no installed face draws, the engine requests that entry: its file is read without blocking the frame and registered with `font.register`, and from then on every text surface draws the character from it. `font.onDemand()` reports each entry as `declared`, `requested`, `installed` or `failed`, and `font.prefetch(text)` requests the entries a text needs before it is drawn. `font.coverage(bytes)` writes a coverage file from a font file's character map. Splitting one large face into several entries (by script, and by how common a character is) means a session reads only the part its text reaches: the built-in `NotoSansCJK.font` is cut that way, and a page of Japanese reads its kana and common-ideograph entries alone. Every registered face, on-demand or not, is a per-glyph fallback for every family the UI holds: a character the selected family has no glyph for is drawn from the first face that has one. ## In the Inspector Selecting a font opens its **Font** section: the family the face registers under, its role and aliases from `face.json`, whether the text system has the family registered and, when it holds it, how many faces and which weights. Below the facts, a sample line is drawn in the family at 14, 20 and 32 px.
▲ 0↑ born
·
assettype · born here
❒asset
# Component (asset type) A component is a reusable behavior + data unit attached to an entity. The component file declares public fields, methods, and lifecycle callbacks; the engine instantiates one per attachment and drives its hooks every frame. Components are the primary unit of gameplay code — movement, AI, animations, UI panels, network sync, and per-entity state all live here. ## When to use one - You need per-entity state that survives across frames. - You need per-entity behavior driven by engine lifecycle hooks (`start`, `update`, `onDestroy`). - You want to expose configurable fields to designers / `entity.spawn` callers / scenes without code changes. If you need a stateless pure-function library, use a `.module`. If you need to generate content declaratively, use a `.service`; compute work belongs in a `.computeShader`. ## Where it lives - Source: `/zero/source/.../<Name>.component/` - Identity: `<Name>` (the `.component` suffix strips from the identity, but the folder retains the suffix on disk). - Folder shape: - `init.luau` (or `init.lua`) — declares the component. **Required.** - `README.md` — instance-level documentation. **Required.** - `.metadata` — agent-editable tags + free-form fields. **Required.** The structural contract is enforced by `asset.validate` against this type's `type.yaml`. ## How to create one Always start with the scaffold — it guarantees the folder shape matches `type.yaml` from the moment it's on disk: ```luau asset.create("component", "<Name>") -- Creates: /zero/source/<Name>.component/ -- init.luau (canonical declare + public block + hooks stubbed) -- README.md (instance README template) ``` After scaffolding, edit `init.luau` to fill in the actual fields and behaviour. The component registers as soon as the file is written — hot-reload is automatic; no engine restart required. ## How it operates 1. **Registration.** Writing `init.luau` into a `.component/` folder indexes the asset, mints a guid (in the `.meta` sidecar), and surfaces the type to the engine's component registry. Same-frame visible to `entity.component.add`. 2. **Attachment.** `entity(id).component.add(name, data)` (or the batch form `tools.use("entityOps", "addComponents", targets, { [name] = data })`) attaches an instance. The `data` table's fields override the component's declared defaults; omitted fields take the declared default. The `data` values are copied into `public.*` BEFORE `awake()` runs. 3. **Lifecycle.** The hooks run in this order: - `awake()` — same frame as attach, immediately after the data copy. Initialise state, set up native bridges, register with other systems. Other components on the same entity may not have awoken yet. - `start()` — the next frame. Every component on the entity has completed `awake()` by then, so cross-component setup is safe here. - `update(dt)` — same frame as `start()`, then every frame after, for as long as the gameplay clock is running. `fixedUpdate(dt)` runs once per physics step, straight after it, with the step's `dt`, so a frame can run it several times or not at all; `editorUpdate(dt)` runs while the clock is held. Which of them ticks is decided by `engine.mode` AND `engine.paused` together — see **Per-frame hooks and the two axes** below, and `man modes`. - `onDestroy()` — when the component is removed via `component.remove` or when the owning entity is despawned. Release resources, drop native ECS components. For the full list (`onEnable`, `onDisable`, `fixedUpdate`, `editorUpdate`, `onPropertyChanged`, `onAssetReload`, `onModuleReload`, `onBeforeSave`, …) and the timing details, **read `man components` — that is the canonical lifecycle reference. Generic component patterns (declare blocks, public fields, sync, ECS bindings, typed methods) all live there.** 4. **Public surface.** Fields declared in `public` are inspectable, editable in the inspector, and persist with the entity. Methods are declared on that same table with a colon — `typed function public:method(args)` — and every one of them takes the component ref as `self`, so a caller invokes it with a colon too: `entity(id).component.get(name):method(args)`. That is the one calling convention a component ref answers to: the reflection methods `ref:fields()` / `ref:getField(name)` / `ref:setField(name, value)` take the same spelling. A function the chunk declares at file scope (`function helper()`) is the component's own, reachable from its hooks under its bare name; `public` is what the ref carries. 5. **Settings and the Inspector card.** `type.yaml` names the component's settings schema as `settings: { schema: { instance: "init.luau", export: "public" } }`: the `public` table IS the schema, and its values live on each entity the component is on, so `asset.schema(componentRef)` answers the Field descriptors and no values file exists. On an entity the Inspector shows the component as a card whose generic `settings` section edits those fields as typed controls, each edit checked against the schema and written to the live component as one undoable operation. `type.yaml` also names `inspector: { instance: "inspector.luau" }`: a component that ships an `inspector.luau` beside its `init.luau` shapes its card — the file returns `{ sections, replace, order }` (see `assetTypes/README.md`, "`inspector:`"), each section's `build(ctx)` reading `ctx.component` (the live component) and `ctx.selection.id` (the entity). `SceneModule.component/inspector.luau` replaces `settings` with the bound module's declared inputs. 6. **Events.** An `events` block declares typed moments the component fires from inside — `events = { onHit = Event({ dmg = Field.number(0, NoSync) }) }`. The owner fires with `events.onHit:fire({ dmg = 10 })`; outside code subscribes through the proxy's subscribe-only facade, `entity(id).component.get(name).events.onHit:connect(fn)` (`:once` / `:wait` too). Pass `Sync` as the event's second argument to replicate a fire to other peers. Events let one component react to another's moments without polling. Full reference: **`man components`**, Events section. 7. **Hot reload.** Editing `init.luau` reloads the component definition; live instances are reconciled with the new declaration in-place, and each crosses one lifecycle boundary: `onDestroy()` ends the running life, then `awake()` and `start()` construct the one that replaces it, and `update()` resumes on the next frame. `public` and `private` values carry across; module-level `local`s belong to the chunk, so the new life starts with them at their initial values and its `awake`/`start` are what fill them in. Whatever the old life handed elsewhere — a subscription, a shared registration, a spawned entity — is released in `onDestroy`, the call that pairs with the construction about to run. An edit that leaves the source byte-identical crosses no boundary at all. A field carries its value across when something stated it: a key of the `data` table the instance was attached with (a scene record's data is that table), or a write made since. Every other field takes the edited source's declared default, so changing a default reaches every instance that left the field to it. An instance that states its own value for a field whose default the edit changed keeps that value, and the reload logs a `[HotReload]` warning naming the field, the entity, the value kept and both defaults. ## Discovery - `asset.list("component")` — every registered component (engine + world + libraries). - `asset.inspect("<name>")` — identity, scope, public fields, lifecycle methods, source path, and this type README. `detail` carries the component's declared `fields`, `methods`, and `events`, parsed from its source — `tools.use("assets","describe", "<name>")` renders it as markdown, so a component's events are visible without opening its source. - `ls /zero/source/<Name>.component` lists the files the folder holds. - `entity(id).component.list()` — components attached to an entity. ## Per-frame hooks and the two axes `engine.mode` (`"edit"` / `"play"`) and `engine.paused` (the gameplay clock) are independent, and the per-frame hooks read them separately: - `update(dt)` / `fixedUpdate(dt)` tick while **the gameplay clock is running** — whichever mode the engine is in. - `editorUpdate(dt)` ticks while **the clock is held** — because the mode is `edit`, or because play is paused — and also alongside `update` whenever edit is running. Which gives four states, and this table is the contract: | `engine.mode` | `engine.paused` | hooks that tick | |---|---|---| | `edit` | `true` | `editorUpdate` | | `edit` | `false` | `update`, `fixedUpdate`, `editorUpdate` | | `play` | `false` | `update`, `fixedUpdate` | | `play` | `true` | `editorUpdate` | Entering edit sets `paused = true` and entering play sets it back to `false`, so a session that never writes `engine.paused` only ever sees rows 1 and 3 — which is where the shorthand "`update` is the play tick, `editorUpdate` is the edit tick" comes from. It is the two default rows of a four-row table, not the rule. **Row 2 is the one that surprises.** With `engine.paused = false` in edit — set by hand, or by a tool that advances the gameplay clock to sample it, such as a `capture.collage` given a `duration` — `update` and `editorUpdate` both fire, once each, every frame. A component that declares both and routes them to one body therefore runs that body **twice per frame**: ```luau local function drive(dt) ... end function update(dt) drive(dt) end function editorUpdate(dt) drive(dt) end -- twice per frame in row 2 ``` Nothing reports the doubling; it reads as an animation running at twice its intended speed. To get exactly one tick per frame in every row, ask which axis you meant and answer it in the body: ```luau function update(dt) drive(dt) end function editorUpdate(dt) if engine.paused then drive(dt) end end ``` A scene `entrypoint.luau` declaring the same two hook names is dispatched by the scene loader, not by this table: there `update` needs play AND running, `editorUpdate` needs edit, and play-paused ticks neither. Read `man scenes` before carrying a component's rule to an entrypoint. ## Authoring conventions - Annotate public fields with `--!desc` so the inspector + LSP show documentation alongside the field name. - Declare lifecycle hooks (`start`, `update`, `onDestroy`) explicitly rather than relying on engine defaults — readers can see at a glance what runs when. - Keep `update(dt)` cheap — it runs every frame per instance. Move heavy work to `start`, to a `.computeShader`, or behind a job (`man jobs`). - For multi-entity batching, prefer `tools.use("entityOps", "addComponents", targets, components)` over a loop of `entity(id).component.add` — it takes many targets and many components in one call. ## Common pitfalls - **Naming.** The component identity is the folder stem with `.component` stripped (e.g. `<Spinner>.component/` → identity `Spinner`). Don't repeat the suffix in the identity passed to `component.add`. - **`init.lua` vs `init.luau`.** Either is accepted (it's a `one_of_group: "entrypoint"`), but `.luau` is canonical. Mixing both in one folder is invalid. - **`update` in edit mode.** It runs whenever the gameplay clock is running, and entering edit stops that clock — so `update` is idle in a freshly-entered edit session and ticks again the moment anything sets `engine.paused = false`. Use `tools.use("wld", "play")` to test update logic under the mode it ships in; `tools.use("wld", "edit")` to return. See **Per-frame hooks and the two axes** above. - **Renaming.** Renaming the folder changes the identity. References to the component are recorded against the component itself, so renaming or moving it does not break them. ## Related types - `.module` — pure-function library, no per-entity state. - `.service`: a declarative content generator, no per-entity state. - `.preset` — a captured component configuration, replayable into `component.add` without re-typing fields. - `.bundle` — entity hierarchies that may carry component attachments as part of the bundle. ## In the Inspector Fields: its execution order, hooks, and how many methods and events it declares, then the fields its `public` table declares as read-only typed controls holding their defaults, with **Check** and **Open** for its entry file. Instances: a link to every entity carrying it. What its card shows on an entity comes from the component's own `inspector.luau`.
▲ 0↑ born
·
assettype · born here
❒asset
# Shader (asset type) A shader is a WGSL program that runs on the GPU. Materials reference shaders and supply property values; renderable entities reference materials, not shaders directly. This README is the canonical reference for writing **every** kind of shader — it covers all domains, the surface authoring contract, the material property schema, the engine library functions you can call, and how a shader registers and compiles. > New to how shaders, materials, meshes, and textures relate as assets and live > GPU resources? Read `core/resource-model` first. ## Folder shape A `.shader` is a folder asset: ``` <name>.shader/ shader.wgsl # the WGSL body (required) properties.yaml # the material property schema (optional; surface shaders) README.md # a one-paragraph description of THIS shader (required) .metadata # asset metadata ``` Each file carries a committed `.meta` sidecar pinning its stable guid. The identity is `<name>` (the `.shader` suffix strips). A shader's material properties are exactly the ones its `properties.yaml` declares: a shader with no `properties.yaml` declares none, and the engine reads no property from the WGSL body. A `.wgsl` file standing on its own, outside a `.shader` folder, is WGSL source rather than a shader: a material draws with the `.shader` folder that holds it as `shader.wgsl`. Materials and other assets reference a shader by **AssetRef** (a typed, guid-backed handle), never by a raw string. ## Domains The first line of `shader.wgsl` declares the domain: ```wgsl // @domain: surface ``` | Domain | What it is | You write | |---|---|---| | `surface` | A material on a mesh (the common case). | `fragment()` (+ optional `vertex()`/`vertex_clip()`). The engine generates everything else. | | `post-process` | A full-screen pass over the rendered frame, in the space it declares (bloom, vignette, grade). | `fragment(in: PostInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. | | `screen` | A standalone full-screen visual (UI background, procedural). | `fragment(in: ScreenInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. | | `sky` | The sky background (a fullscreen material). | `fragment(in: SkyInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. | | `compute` | GPU data processing, no rasterization. | An `@compute @workgroup_size(...)` entry over storage buffers; you write the `@group/@binding` lines yourself. For compute work, the `.computeShader` assetType (see below) generates them for you. | `// @domain:` resolves the names above and `postprocess` / `screenspace` / `ui` as further spellings of `post-process` and `screen`. A body carrying no `@domain:` line is `surface`. `shaderRef:domain()` answers the domain a body declares, a further spelling as the domain it names. Any other name is refused where the shader registers, with an error naming the spellings that resolve, so a shader reaches the renderer only under a domain the compiler scaffolds. Particles are drawn and simulated through these domains like anything else: the particle package's `particle_sprite` and `particle_mesh` are `surface` shaders, and its simulation, culling and sorting steps are `.computeShader` assets. ## Texture coordinate space A shader that samples a texture through a coordinate it builds itself declares which space that coordinate lives in, on a line beside `@domain:`: ```wgsl // @domain: surface // @uv_space: world ``` | Value | The coordinate | A material's `uv_scale` means | |---|---|---| | `mesh` (the default) | The mesh's own UV attribute, `input.uv`. | How many times the texture repeats across a surface. | | `world` | The fragment's world position, as a triplanar projection samples. | How many times the texture repeats per world unit, so a larger surface carries more. | Texture residency reads the declaration to work out how finely a frame samples each texture: a material laying eight copies of its texture across a surface samples each copy at an eighth of the surface's size, and the mip level that serves it is three levels coarser than the surface's own footprint implies. Leaving the line out puts the shader in mesh space, which is what sampling `input.uv` is. `renderer.textureStreaming().textures` reads back the span each texture was measured at and the level that span asked for. **Compute shaders have their own assetType.** A `.computeShader/` folder gives compute the same zero-scaffolding contract surface/sky/post/screen get: you write only `@compute fn main` (+ helper fns/structs, **no `@group/@binding` lines**) and declare bindings in a sibling `bindings.yaml` (storage buffers, textures, samplers, storage textures, plus a `params:` uniform); the engine generates the `@group(0)/@binding(N)` declarations. Dispatch it through a resolved reference (`asset.resolve("name", "computeShader"):dispatch(...)`). See the `.computeShader` assetType README and `man compute`. **Surface**, **sky**, **post-process**, and **screen** shaders all get engine-generated scaffolding — you write only `fragment()` and declare properties in `properties.yaml`; the engine generates the entry points and the group(1) material interface. (Each domain's `fragment` takes a domain-specific input instead of `FragmentData`: `SkyInput`, `PostInput`, or `ScreenInput` — see "Sky shaders" and "Post-process & screen shaders" below.) Compute shaders get the same treatment via the separate `.computeShader` assetType (write only `@compute fn main`, declare bindings in `bindings.yaml`). The `compute` domain here writes its own entry points directly — see `man compute`. ## Surface shaders A surface shader writes **only** the parts that are unique to it. The engine owns all the scaffolding — the vertex stage, every render-mode entry point (`vs_main` / `fs_forward` / `fs_gbuffer`), group(0) (camera, transforms, lights, shadows, and the material rows), and the material interface generated from `properties.yaml` (`material` and your texture slots). Adding a render path never touches your shader. Inside `fragment()` you have access to exactly four things — nothing is hidden: 1. **`input: FragmentData`** — the interpolated per-fragment surface data the engine hands you: world position, world normal, uv, view direction, vertex colour, and more. Every field is in the `FragmentData` table below. 2. **`material.*` and your textures** — the material inputs **you** declare in `properties.yaml`. The mapping is mechanical: a scalar property named `foo` becomes `material.foo`; a texture property named `bar` becomes `bar` (the texture) and `bar_sampler` (its sampler). `material` has **exactly** the fields your `properties.yaml` declares and no others — to add an input, add a property. List what a shader exposes with `shaderRef:getProperties()` or `asset.inspect("<name>")`. 3. **Engine state** — the scene's camera, lights, time, and shadows that the renderer binds for every surface shader. In a surface shader `uniforms.*` (sun direction/colour, ambient, `camera_pos`, `time`) and the punctual lights (`zero_point_light(i)`) are always in scope (a post-process shader has neither; its section below names what it reads instead); the shadow functions come from `#include "@builtin::shaderModules.shadows"`, and the light of the sky, the reflection probes and the light-probe volumes from `zero_pbr_surroundings_light` in `@builtin::shaderModules.pbr_shading`. This is how you light a surface **without** the prebuilt PBR — see "Engine state" and "Writing your own shading" below. 4. **Library functions** you `#include` (see "Library includes"). A shader and its property schema go together. The two files below are a complete surface shader: `properties.yaml` — declares the material inputs: ```yaml properties: - { name: base_color, type: color, default: [1, 1, 1, 1] } - { name: roughness, type: float, default: 0.5, min: 0, max: 1 } - { name: metallic, type: float, default: 0.0, min: 0, max: 1 } - { name: base_color_texture, type: texture, default: white } ``` `shader.wgsl`; those declarations are read as `material.base_color`, `material.roughness`, `material.metallic`, and the `base_color_texture` / `base_color_texture_sampler` pair: ```wgsl // @domain: surface #include "@builtin::shaderModules.pbr_shading" // the PBR helpers — see "Library includes" fn fragment(input: FragmentData) -> vec4<f32> { var s = zero_pbr_default_surface(input); s.albedo = material.base_color.rgb * textureSample(base_color_texture, base_color_texture_sampler, input.uv).rgb; s.perceptual_roughness = material.roughness; s.metallic = material.metallic; return vec4<f32>(zero_pbr_shade(input, s), material.base_color.a); } ``` `fragment()` returns the final colour. The engine forces no lighting model on you — flat, toon, PS1, dithered, or PBR are all just different `fragment()` bodies. Calling `zero_pbr_shade` is opt-in. ### The two surface bodies, and what each gives up A surface shader exposes one of two entry points, and which one decides how much of the shader the engine can see: | Body | The engine gets | PBR debug passes and the G-buffer read | |---|---|---| | `fn fragment(input: FragmentData) -> vec4<f32>` | the finished pixel, and the surface behind it where the body hands one over: `zero_pbr_shade` hands over the `PbrSurface` it lights, and a body that lights itself hands over its own with `zero_publish_shaded_surface` | the surface the body handed over; where it handed none, the debug passes draw magenta, the "no data here" marker | | `fn surface(input: FragmentData) -> PbrSurface` | the surface (albedo, roughness, metallic, emissive, normal, occlusion), which the engine then lights | the surface | Both are first-class: `fragment()` is what you want when the shader owns its own look, `surface()` when you want engine lighting. `capture { pass = "albedo" }` (and `roughness` / `metallic` / `ao` / `emissive`) answers about your material for either body wherever the engine has the surface — writing the same `PbrSurface` behind `surface()` or behind `fragment()` + `zero_pbr_shade` gives one answer per channel. `pbr.shader` exposes `surface()`. #### Handing the engine the surface a self-lit body draws A `fragment()` body that lights itself by its own math (toon, cel, flat, PS1, dithered) states the surface it draws with one call, always in scope in a surface shader: ```wgsl zero_publish_shaded_surface(albedo, normal, emissive, perceptual_roughness, metallic, occlusion); ``` | Argument | Type | What it states | |---|---|---| | `albedo` | `vec3<f32>` | the colour the surface reflects, linear, in [0, 1] | | `normal` | `vec3<f32>` | the world-space normal the body shades with (normal map applied) | | `emissive` | `vec3<f32>` | the light the surface gives off, linear | | `perceptual_roughness` | `f32` | 0 a mirror, 1 fully rough | | `metallic` | `f32` | 0 a dielectric, 1 a metal | | `occlusion` | `f32` | the material's own ambient occlusion, 1 none | The call changes nothing about the pixel the body returns; it states what that pixel is a picture of. The last call before `fragment()` returns is the one the engine reads, and it reads it into: - **The debug passes**: `albedo`, `roughness`, `metallic`, `ao`, `emissive` and `reflection` answer with the stated surface instead of magenta, and `normal`, `shadow` and `shadow_depth` read the stated normal. - **The G-buffer**, on the deferred render path: its normal (`@scene.normal`, `zero_scene_normal`) carries the stated normal, and its material (`@scene.material`, `zero_scene_material`) the stated albedo, metallic and roughness. Every screen-space feature and full-frame pass that reads the surfaces reads these, among them screen-space reflections, contact shadows, capsule occlusion, area lights, the environment lighting and radiance cache passes, surface weather, temporal antialiasing's surface restate, and a post-process effect or render feature reading the surface helpers. A `fragment()` body that hands over nothing leaves the G-buffer holding the triangle's interpolated normal, a base colour equal to the colour it returned brought into [0, 1] by its largest component, metallic 0 and roughness 1, so a pass that reads roughness takes it for a fully rough dielectric. The emissive argument reaches the `emissive` debug pass. The light a surface gives off is already in the colour its body returns, so it adds nothing to the frame; `@scene.emissive` holds the light a later pass stamps onto the surface. A cel-shaded body, its surface handed over: ```wgsl // @domain: surface #include "@builtin::shaderModules.pbr_shading" // zero_pbr_surroundings_light fn fragment(input: FragmentData) -> vec4<f32> { let n = normalize(input.world_normal); let albedo = zero_take_scene_decal(material.base_color.rgb); let sun = normalize(-input.light_direction); // The sun's N·L rounded to the nearest third: 0 on a face turned from the sun. let band = round(max(dot(n, sun), 0.0) * 3.0) / 3.0; let lit = input.light_color * input.light_intensity * band / ZPBR_PI + zero_pbr_surroundings_light(input, n, albedo); zero_publish_shaded_surface(albedo, n, vec3<f32>(0.0), 1.0, 0.0, 1.0); return vec4<f32>(albedo * lit, material.base_color.a); } ``` `capture { pass = "normal" }` is a geometry read rather than a material one, so it answers for every shader: the normal of the surface where one was handed over, and the interpolated normal of the triangle where none was. It is the same normal the frame's normal buffer carries, which is what a screen-space pass reading `@scene.normal` sees. `shaderRef:shadingModel()` reports which one a shader ended up with — `"engine-lit"` for `surface()`, `"self-shading"` for `fragment()`. #### Decals on a self-lit body A decal projector stamps its colour over the opaque surfaces before anything shades (`@scene.decal`). `zero_pbr_shade` lays it over the base colour it lights, so a `surface()` material and a `fragment()` body lighting through `zero_pbr_shade` show the decal lit and shadowed like the rest of the surface. A body that lights itself takes the decal the same way by passing its base colour through one call before its lighting: ```wgsl let albedo = zero_take_scene_decal(material.base_color.rgb); ``` A body that takes none gets the decal laid over the colour it returned, unlit, and over the albedo it published. ### Optional vertex hooks ```wgsl // Displace geometry in OBJECT space. Runs on skinned meshes too (it sees the // already-skinned, morph-applied local position). Return the modified vertex. // The `v` parameter is immutable (WGSL function params are), so copy it into a // `var` first and modify that. fn vertex(v: VertexData) -> VertexData { var out = v; out.position += out.normal * sin(out.time) * 0.1; return out; } // Post-transform vertex hook (runs AFTER the engine's world/skin/projection). Two // things you can do here, separately or together: // * move `clip_position` — vertex jitter, PS1 snapping, render-resolution lowering; // * write `color` — PER-VERTEX (Gouraud) shading: light the vertex from its // world_normal + the light context and the engine forwards the result into the // interpolated `vertex_color` the fragment reads. fn vertex_clip(v: ClipVertex) -> ClipVertex { var out = v; // Gouraud: Lambert sun + ambient, evaluated once per vertex (flat-banded shading). let n_dot_l = max(dot(v.world_normal, -normalize(v.light_direction)), 0.0); let lit = v.ambient_color * v.ambient_intensity + v.light_color * v.light_intensity * n_dot_l; out.color = vec4<f32>(v.color.rgb * lit, v.color.a); out.clip_position = round(out.clip_position * 80.0) / 80.0; // PS1 snap return out; } ``` #### Geometry built per instance: grass, kelp, hair cards, debris `vertex()` knows which vertex of which instance it places: `VertexData.vertex_index` is the vertex's index in its mesh and `VertexData.instance_id` the instance's slot, whose lanes `zero_object_data(v.instance_id, lane)` reads. A hook can therefore build its geometry rather than displace it: a strip mesh drawn thousands of times by `renderer.mesh.drawInstanced`, each copy shaped, sized and bent from the lanes of its `instanceDataBuffer`, becomes a field of grass blades, kelp fronds or hair cards that sway with `v.time`. Being a surface shader, it is lit, shadowed (it casts the shape the hook built), motion-vectored and fogged like the rest of the scene. The rendering-instance-data guide (`guides { path = "topics/rendering-instance-data" }`) has a worked blade field; a render feature's raster pass (`types/rasterShader`) is the hand-written alternative, a vertex and fragment program with its own pipeline. #### Declaring how far a hook moves geometry: `vertexBoundsDilation` Static geometry is culled per cluster against its bounds as authored. A hook that moves vertices — wind sway, an outline hull, a vertex wave — can move them outside those bounds, and the cull then drops clusters whose displaced triangles are still on screen. Declare the farthest the hook moves any vertex, in world units, as a `vertexBoundsDilation` float property, with a default that covers the shader's own properties across their ranges: ```yaml properties: - { name: sway, type: float, default: 0.5, min: 0, max: 4 } # 0.4 x sway, at sway's largest value. - { name: vertexBoundsDilation, type: float, default: 1.6, min: 0, max: 100 } ``` Each material sets its own value (a material that sways less can set less, one moved farther sets more), and a material that sets none takes the default. The cull adds the material's value to every bound in its frustum and occlusion tests (not to the level-of-detail cut). A shader with a hook and no `vertexBoundsDilation` property is named once in the engine log when it compiles; its geometry is frustum-culled against its undisplaced bounds, and occlusion culling keeps it in the frame wherever it stands. ### Structs the engine passes you `FragmentData` (input to `fragment()`): | Field | Type | Meaning | |---|---|---| | `world_position` | `vec3<f32>` | fragment world-space position | | `world_normal` | `vec3<f32>` | interpolated geometric normal (normalized) | | `world_tangent` | `vec4<f32>` | xyz = world tangent, w = handedness (mikktspace) | | `uv` | `vec2<f32>` | primary texture coordinates (perspective-correct) | | `affine_uv` | `vec2<f32>` | the same UVs interpolated **without** perspective correction — the PS1 texture "swim". Always available; sample with it instead of `uv` for affine texture mapping | | `vertex_color` | `vec4<f32>` | interpolated per-vertex colour (white if unset; carries per-vertex lighting if `vertex_clip()` wrote it — see Gouraud below) | | `view_position` | `vec3<f32>` | camera world position | | `view_direction` | `vec3<f32>` | normalized world-space direction the camera sees this point from: toward the camera's position under a perspective projection, against its forward axis (the same for every point) under an orthographic one | | `light_direction` | `vec3<f32>` | directional (sun) travel direction, unit length; surface→sun is `-light_direction`. Where no sun reaches the camera it points straight down | | `light_color` | `vec3<f32>` | sun colour | | `light_intensity` | `f32` | sun intensity; 0 where no sun reaches the camera | | `ambient_color` | `vec3<f32>` | the colour of the scene's flat ambient term, one colour for every direction. The light of the captured sky, the reflection probes and the light-probe volumes along a normal, which a PBR surface takes as well, is `zero_pbr_surroundings_light` (see "Engine state") | | `ambient_intensity` | `f32` | the flat ambient term's intensity as it reaches this pixel: the scene's ambient occlusion is already in it (times `ambient_visibility`), so a crease darkens under the ambient with no work in the shader | | `ambient_visibility` | `f32` | the share of the light of its surroundings that reaches this pixel: 1 minus the scene's ambient occlusion here, 1 where nothing occludes it. Multiply it into any light of the surroundings you gather yourself (a sky colour, a reflection-probe or environment sample); `ambient_intensity` already carries it. `zero_scene_bent_normal(input.frag_coord.xy, n)` names the direction the open part of the hemisphere faces, `n` where no pass wrote one | | `frag_coord` | `vec4<f32>` | framebuffer pixel coords (xy) + depth (z) — for screen-space dither | | `receives_shadows` | `f32` | per-instance: > 0.5 if this surface receives shadows | | `material_index` | `u32` | per-instance: the index standing for the material this surface draws with — the number `renderer.materialIdentity()` maps to a name | | `shader_data` | `array<vec4<f32>, 4>` | per-instance: this entity's own four `vec4` lanes — its `ecs.ShaderData` component's `lane0`..`lane3`, or what `renderer.instanceData.set` put in them (zero until something does). A procedural graph's elements set them through the `data0`..`data3` attributes | | `front_facing` | `bool` | true for front faces (double-sided shading) | | `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world | `shader_data` is the per-instance channel, and it is what lets ONE material serve many entities that differ in a value — a dissolve at its own progress per subject, a hit flash at its own age, a fill level per instance. The alternative is a material per entity, which is a separate pipeline binding and a separate row in the material table for every one of them. ```wgsl const DISSOLVE_LANE: u32 = 0u; fn fragment(input: FragmentData) -> vec4<f32> { let progress = input.shader_data[DISSOLVE_LANE].x; ... } ``` ```lua -- one material on twenty entities, each at its own progress renderer.instanceData.set(subject, 0, progress) renderer.instanceData.clear(subject) -- back to zero lanes ``` The engine attaches no meaning to a lane: a shader and whatever writes it agree what each one carries. Name the indices in the module that writes them. `renderer.instanceData.laneCount()` is how many there are. The same lanes reach a hardware-instanced population through `renderer.mesh.drawInstanced`'s `instanceDataBuffer`, on slots no entity owns. `VertexData` (in/out of `vertex()`): `position` (object-local, model-scale + morph applied), `normal`, `uv`, `color`, `time`, and which vertex of which instance it is: `instance_id` (`u32`, the instance's slot — `zero_object_data(v.instance_id, lane)` reads the lanes the fragment gets as `shader_data`) and `vertex_index` (`u32`, the vertex's index in its mesh). Both hold the same values in the colour pass, the depth views, every shadow page and the previous-frame evaluation, so geometry a hook builds from them — a blade placed and bent by its instance's lanes, a strip shaped by its vertex's index — lands in the same place in each. The rendering-instance-data guide has a worked blade field. `ClipVertex` (in/out of `vertex_clip()`) — the post-transform vertex. Read context: `clip_position`, `world_position`, `world_normal`, `uv`, `view_position`, `view_direction`, `light_direction`, `light_color`, `light_intensity`, `ambient_color`, `ambient_intensity`, `time`, `view_proj` (the view-projection of the frame being evaluated), and where the vertex stands on its instance: `local_position` (its position in the mesh, after `vertex()` and before the instance's world transform), `object_origin` (the world position of the instance's origin), `object_scale` (the world length of the instance's x, y and z axes) and `object_axes` (`mat3x3<f32>`, the world direction of those axes, unit length) — what a camera-facing card, a shard grown about its own base, or anything placed per instance is built from. **Writable:** `clip_position` (snap / jitter) and `color` (write a lit colour here for per-vertex Gouraud shading; the engine forwards it to the interpolated `vertex_color` — left untouched, the mesh's own vertex colour passes through). `vertex()` and `vertex_clip()` run in the vertex stage, which reads the frame uniforms (`uniforms.*`, and the `ClipVertex` members built from them), the scene buffer (`zero_object_data`, `zero_object_visuals`, the node transforms), the material interface and a `read` buffer property. The point, spot and area lights (`zero_point_light`, `zero_punctual_projection`), the shadow maps, the environment and light probes, the feature textures, the scene depth, colour and reflection copies and a `@group(2)` buffer the shader declares `read_write` are visible to the fragment stage alone: read them in `fragment()` or `surface()`. A shader whose vertex hook reaches one fails to compile, and the error names the stage, the binding and the calls that reach it. ### Each hook runs twice: this frame and the one before it A vertex hook decides where the surface IS, so it also decides where the surface WAS. The engine runs every hook a shader declares a second time, over the same vertex standing one frame back — the previous-frame position stream, with `time` = the clock that frame was drawn at and (for `vertex_clip()`) `view_proj` = the view-projection it was drawn with. The motion vector the renderer publishes is taken between the two results, so a displacement that moves with time reports the velocity of the displaced surface, and a displacement that does not move reports the motion of the transform alone because the identical offset appears on both evaluations and cancels. What that asks of a hook: - **Take the frame from the argument.** `v.time` is the clock of the evaluation being run; `uniforms.time` is always this frame's. A displacement built on `uniforms.time` is identical on both evaluations, so its motion vector cancels to exactly zero. The same holds for `v.view_proj` against `uniforms.view_proj`: a clip hook that rebuilds its position from world space through `uniforms.view_proj` reprojects the previous frame with this frame's camera, and reports no camera motion at all. The wind helpers come in both shapes for this reason — `zero_wind_sway_at_time(world_pos, stiffness, v.time)` inside a hook, `zero_wind_sway(world_pos, stiffness)` outside one. - **Anchor a wrap to `uniforms.time`.** A displacement that jumps discontinuously — a falling drop that restarts at the top, a looping offset — differences its jump as velocity on whichever frame it wraps. Compute the wrap COUNT from `uniforms.time` and the position within the cycle from `v.time`, and both evaluations share the same cycle, so the surface reports the speed it fell at. `@builtin::shaders.rain_material` and `snow_material` do exactly that. The per-vertex attributes (`world_normal`, `uv`, `color`) and the lighting and camera-position context are this frame's on both evaluations, so a hook that displaces along its normal reports the motion of the transform plus this frame's displacement. ## Engine state — point lights & shadows This is what the renderer binds for a **surface** shader. A post-process shader reads none of it: its engine state is `PostEngineData` (see "Post-process & screen shaders"), and a full-frame effect driven by the scene's lights takes the render-feature route that section names. The common lighting state — the sun (`input.light_direction` / `light_color` / `light_intensity`), the scene's flat ambient term (`input.ambient_color` / `ambient_intensity`), the camera (`input.view_position` / `view_direction`), and `input.time` — is already on `FragmentData`, so most shaders never touch the raw engine state. The flat ambient term is one colour for every direction; the light the captured sky, the reflection probes and the baked light-probe volumes hand a surface along its normal comes from `zero_pbr_surroundings_light(input, n, albedo)` (`@builtin::shaderModules.pbr_shading`), which holds the flat term as well and is the ambient light a PBR surface is lit by. The one thing not on `FragmentData` is the punctual-light array (its length varies), which is always in scope. A scene can hold up to 1024 lights, so a fragment walks the ones the light grid lists where it stands, which hold every light that can reach it: | Expression | Type | Meaning | |---|---|---| | `zero_lights_near(world_pos)` | `ZeroLightsNear` | the lights that can reach a fragment at `world_pos`; `.count` of them | | `zero_light_near(near, k)` | `u32` | the index of the `k`th of them, for `zero_point_light` | | `uniforms.point_light_count` | `u32` | number of lights the frame shades under, every one of them | | `zero_point_light(i)` | `PointLightData` | one point or spot light (fields below) | | `zero_punctual_projection(i)` | `PunctualProjection` | a spot or area light's projection: `view_proj`, the frustum its cookie and shadow are placed by, and `cookie_layer` | `PointLightData`: `position`, `radius`, `color`, `intensity`, `direction`, `cone_outer_cos`, `cone_inner_cos`, `kind` (0 = point, 1 = spot). Shadows come from `#include "@builtin::shaderModules.shadows"`: - `compute_directional_shadow_factor(world_pos, normal, light_dir) -> f32` — 1.0 lit, 0.0 fully shadowed. - `compute_spot_shadow_factor(...)` / `compute_point_shadow_factor(...)` / `compute_area_shadow_factor(...)` — one shadow shape each. - `compute_punctual_shadow_factor(light_index, world_pos, normal) -> f32` — the row's own shape, read off its `kind`, for a loop that walks the punctual lights and does not want the switch. - `zshadow_light_reach(light_index, world_pos, normal, object_channels) -> f32` — how much direct light that row puts on a surface on those light channels: the channel mask, falloff, cone or rect orientation, and the cosine, times intensity. Zero exactly where the light contributes nothing. ## Writing your own shading The engine forces no lighting model — `zero_pbr_shade` is just one option. You can light a surface yourself from the state above. Here is a complete custom-lit (Lambert diffuse) surface that takes the engine's lights and surroundings and no PBR BRDF: ```wgsl // @domain: surface #include "@builtin::shaderModules.pbr_shading" // zero_pbr_surroundings_light; brings in the shadow functions fn fragment(input: FragmentData) -> vec4<f32> { let n = normalize(input.world_normal); let albedo = material.base_color.rgb; // Directional (sun) light: Lambert N·L, attenuated by its shadow. let sun = normalize(-input.light_direction); // surface -> sun let sun_shadow = compute_directional_shadow_factor(input.world_position, n, input.light_direction); var direct = input.light_color * input.light_intensity * max(dot(n, sun), 0.0) * sun_shadow; // Point + spot lights: the ones that can reach this fragment. let near = zero_lights_near(input.world_position); for (var k = 0u; k < near.count; k = k + 1u) { let pl = zero_point_light(zero_light_near(near, k)); let to_light = pl.position - input.world_position; let dist = length(to_light); let l = to_light / max(dist, 1e-4); let atten = max(1.0 - dist / max(pl.radius, 1e-4), 0.0); direct += pl.color * pl.intensity * max(dot(n, l), 0.0) * atten; } // A Lambert surface sends back albedo / π of the direct light on it, // the diffuse lobe of the PBR model. var lit = direct / ZPBR_PI; // The light of the surroundings: the flat ambient, the captured sky, the // reflection probes and the baked light-probe volumes, with the scene's // ambient occlusion in it — the ambient light a PBR surface takes. It is // irradiance already weighed for a diffuse surface, so it takes no π. lit += zero_pbr_surroundings_light(input, n, albedo); // The surface this pixel draws, for the debug passes and the G-buffer. zero_publish_shaded_surface(albedo, n, vec3<f32>(0.0), 1.0, 0.0, 1.0); return vec4<f32>(albedo * lit, material.base_color.a); } ``` The example declares `base_color` in its `properties.yaml`: ```yaml properties: - { name: base_color, type: color, default: [1, 1, 1, 1] } ``` - **Unlit:** skip the lights and return your colour directly. - **Toon / PS1 / custom:** start from the body above and band, quantize, or warp it however you like. Keep the direct light over π and `zero_pbr_surroundings_light` as the ambient term, and the surface stands at the brightness of the PBR materials around it; the flat ambient (`input.ambient_color * input.ambient_intensity`) alone leaves out the sky and the probes, and under a sky with no flat ambient a face turned away from the sun draws black. - **PBR:** build a `PbrSurface` and call `zero_pbr_shade` (see "Library includes") instead of writing the BRDF by hand. It hands the engine the surface itself. ## Material properties — `properties.yaml` A surface shader declares its material properties in a sibling `properties.yaml`. The engine GENERATES the entire group(1) interface from it — the uniform struct (`material.<name>`) plus a texture/sampler pair per declared texture. You write no `@group`/`@binding` lines. ```yaml properties: - { name: base_color, type: color, default: [1, 1, 1, 1] } - { name: roughness, type: float, default: 0.5, min: 0, max: 1 } - { name: metallic, type: float, default: 0.0, min: 0, max: 1 } - { name: emissive, type: color, default: [0, 0, 0, 1] } - { name: base_color_texture, type: texture, default: white } - { name: normal_texture, type: texture, default: flat_normal } ``` | `type` | WGSL field type | Notes | |---|---|---| | `float` | `f32` | optional `min`/`max` for editor sliders | | `float2`/`float3`/`float4` | `vec2/3/4<f32>` | | | `color` | `vec4<f32>` | linear RGB colour and alpha, default is `[r,g,b,a]`; the shader reads it as written | | `int` | `i32` | | | `bool` | `u32` | | | `texture` | `texture_2d<f32>` + `sampler` | `default:` is a built-in texture name (`white`, `black`, `flat_normal`) | A `color` holds linear RGB, the space lighting is computed in, the way `base_color` multiplies a colour texture's linear sample. A colour picked from a picture or written as a hex code is sRGB, and written as it is it reads paler and less saturated than picked: convert it first, `color.toLinear(assert(color.hex("#ff8800")))` (`{ r, g, b, a }`: `#ff8800` is `{ r = 1, g = 0.246, b = 0, a = 1 }`), and write that. In the shader you read scalars as `material.<name>` and sample textures as `textureSample(<name>, <name>_sampler, uv)`. A texture slot with no bound texture samples its default, so a shader can always sample — no presence flag needed. `vertex()` reads the same material interface, so a height or deformation map drives displacement from the slot it was bound to. A vertex stage has no implicit derivatives, so sample it at an explicit mip there: `textureSampleLevel(<name>, <name>_sampler, uv, 0.0)`. ## Sky shaders A `// @domain: sky` shader draws the sky as a fullscreen pass. You write **only** `fn fragment(in: SkyInput) -> vec4<f32>` — the colour along the view ray for each pixel — and declare tunables in `properties.yaml` exactly like a surface shader (read as `material.<name>`, textures via `textureSample(<name>, <name>_sampler, uv)`). The engine generates the fullscreen `vs_main`/`fs_main`, the group(1) interface, and reconstructs the world-space ray; there is no separate sky renderer — a sky material runs through the same material pipeline, just on a fullscreen triangle. A sky pipeline binds group(0) and the group(1) interface alone, so a sky that reads a `buffer` property or any other `@group(2)` binding fails to compile, and the error names the binding and the calls that reach it. `SkyInput` (the only argument) carries: | Field | Type | Meaning | |---|---|---| | `ray_dir` | `vec3<f32>` | normalized world-space ray through this pixel | | `ndc` | `vec2<f32>` | screen position in NDC `[-1, 1]` | | `sun_direction` | `vec3<f32>` | unit vector TOWARD the sun (from the directional light) | | `camera_pos` | `vec3<f32>` | world-space camera position | | `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world | | `constants` | `SkyConstants` | what the shader's `sky_constants()` returned for this draw (zeros when it declares none) | ```wgsl // @domain: sky fn fragment(in: SkyInput) -> vec4<f32> { let up = max(in.ray_dir.y, 0.0); let col = mix(material.horizon_color.rgb, material.zenith_color.rgb, up); return vec4<f32>(col * material.exposure, 1.0); } ``` Day/night comes from `sun_direction.y` (the directional light's elevation), so a sky shader never needs a time-of-day uniform — orient the light and the sky follows. The builtin sky shaders (`procedural_sky`, `solid_sky`, `cubemap_sky`, `equirect_sky`) are all authored this way; author a custom sky material and point a `Skybox` component at it. `fragment()` runs once for every pixel of the view and every texel of each environment-capture face. A value that holds for the whole draw (a colour mixed from the material and the sun's elevation, a `cos` of an angular size, an exponent derived from a property) goes in an optional `fn sky_constants(in: SkyConstantsInput) -> SkyConstants`, which the generated vertex stage evaluates once per draw. `fragment()` reads its result as `in.constants`. `SkyConstantsInput` carries `sun_direction`, `camera_pos` and `time` (the same values `SkyInput` holds), `sky_constants()` reads the material as `material.<name>` like `fragment()`, and `SkyConstants` is eight `vec4<f32>` slots, `v0` to `v7`, packed however the sky likes: ```wgsl // @domain: sky fn sky_constants(in: SkyConstantsInput) -> SkyConstants { let day = clamp(in.sun_direction.y * 2.0, 0.0, 1.0); var c: SkyConstants; c.v0 = vec4<f32>(mix(vec3<f32>(0.02), material.zenith_color.rgb, day), day); c.v1 = vec4<f32>(mix(vec3<f32>(0.01), material.horizon_color.rgb, day), 0.0); return c; } fn fragment(in: SkyInput) -> vec4<f32> { let up = max(in.ray_dir.y, 0.0); return vec4<f32>(mix(in.constants.v1.rgb, in.constants.v0.rgb, up), 1.0); } ``` A branch on an `in.constants` value is taken or skipped by every pixel of the draw together, so a term that only contributes some of the time (stars at night) costs nothing while it is off. The vertex stage has no implicit derivatives, so a texture read in `sky_constants()` is `textureSampleLevel`. ## Post-process & screen shaders `// @domain: post-process` and `// @domain: screen` shaders are authored exactly like surface and sky — you write **only** `fn fragment(in: PostInput) -> vec4<f32>` (post) or `fn fragment(in: ScreenInput) -> vec4<f32>` (screen) and declare tunables in `properties.yaml` (read as `material.<name>`, textures via `textureSample(<name>, <name>_sampler, uv)`). The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) material interface. **There are no `uniforms.params[i]` slots** — that convention is retired; every input is a named property. A **post-process** shader's `properties.yaml` carries one further, top-level key beside `properties:` — `space`, either `light` (the default) or `display`: ```yaml space: display properties: - { name: amount, type: float, default: 1.0, min: 0, max: 1 } ``` `light` is the scene's linear radiance — what every surface, the sky and every `afterLighting` feature write, unbounded above 1.0. `display` is the code values the `__display__` pass leaves behind after applying exposure and its tone curve — the 0-1 range a colourist's tool and a dithered or quantized effect expect. `postprocess.add`'s `opts.space` overrides what the asset declares for one registration. The chain converts at both ends of an effect that runs on a segment in the other space, so a light-space vignette still darkens a frame graded after `__display__`, and a lookup table built from a `.cube` export always sees the code values it was authored against, wherever the chain runs it. `space` also decides which layer a registration that names none lands on: a `light` shader grades `scene`, the segment holding the scene's own light, and a `display` shader grades `display`, the picture after `__display__` and before the UI lands on it. So `postprocess.add("glow", asset.resolve("~.shaders.bloom", "shader"))` thresholds highlights that still stand above 1.0, and a lookup table registered the same way reads the code values it was built for and leaves every screen in the colours it declares. `opts.layer` names one explicitly — `"all"`, after the UI, is what an effect that must grade the interface says. A post-process shader may also declare the post stage of the frame it runs in, `stage:` — `optics` (the `scene` layer), `display` (the `display` layer) or `ui` (the `all` layer); `renderer.post.stages()` lists every stage with the colour space and resolution its picture is held in. A registration takes the declared stage unless `opts.stage` or `opts.layer` names another seam, and a stage the frame does not have, or one only render features run in, is refused naming the stages there are: ```yaml space: display stage: display properties: - { name: amount, type: float, default: 1.0, min: 0, max: 1 } ``` A **post-process** shader's `properties.yaml` carries a further, optional top-level key — `passes:`, the pass list the frame draws through, in order: ```yaml space: light passes: - { name: bright, entry: bright, scale: 0.5, inputs: [scene] } - { name: down1, entry: downsample, scale: 0.25, inputs: [bright] } - { name: up0, entry: upsample, scale: 0.5, inputs: [down1, bright] } - { name: composite, entry: composite, inputs: [scene, up0] } ``` Every pass's entry — `fn <entry>(in: PostInput) -> vec4<f32>` — lives in the one `shader.wgsl` the assetType recompiles on. `scale` is the fraction of the view a pass draws at; the LAST pass takes none, since it draws at the view's size and writes the chain's output. `inputs` names what a pass reads — `"scene"`, the chain's input for this effect, or the name of an EARLIER pass — and `inputs[0]` is what `zero_sample_scene(uv)` reads inside that pass's body; every input, `inputs[0]` included, is also reachable by index through `zero_pass_input(i, uv)` and `zero_pass_input_size(i)`, below. The one place the two reads of `inputs[0]` disagree: in an effect whose declared space differs from the segment it draws on, `zero_sample_scene` converts a `scene` input into that space while `zero_pass_input(0, uv)` hands back the segment's own, unconverted value. A shader declaring no `passes:` is one pass whose entry is `fragment`, and its generated WGSL is byte-identical to what it is without the key. A pass that is not the last writes a scratch target the effect owns — in the space the shader declared, view-sized times its own `scale` — allocated on the first draw and replaced whenever the size changes. `engine.params`, below, carries the drawing pass's own index, its scale, and its first input's texel size, so one shader body serves every level of a chain built this way. The worked example is the bloom: `@builtin::shaders.post.bloom` declares twelve passes — a threshold pass, five downsamples, five tent upsamples and a composite — out of four entries, since the five downsamples share one and the five upsamples share another, each level reading the one below it through `zero_pass_input` and telling itself apart by `engine.params`. Its own README walks the declaration. A declaration is refused at compile time — reported through `compileStatus()`, `postprocess.add`'s second return value, or a live effect's `status()[i].error` — for: an entry `passes:` names that `shader.wgsl` does not define; an input naming a later pass, or naming neither `scene` nor an earlier pass; a `scale` outside `(0, 1]`; a `scale` declared on the last pass; a `buffer` property (group(2) carries the pass inputs); or a shader whose group(0) plus declared texture slots plus widest pass's inputs ask for more than the 16 FRAGMENT sampled textures one shader stage has. A **post-process** shader runs as a full-screen pass over the already-rendered frame. Its `fragment` argument and framework helpers: `PostInput`: | Field | Type | Meaning | |---|---|---| | `frag_coord` | `vec4<f32>` | framebuffer pixel coords (`@builtin(position)`) | | `uv` | `vec2<f32>` | screen UV, `(0,0)` top-left … `(1,1)` bottom-right | Framework helpers (always in scope — no include needed): | Call | Returns | Meaning | |---|---|---| | `zero_sample_scene(uv)` | `vec4<f32>` | the rendered scene colour at `uv`, converted into the space this effect declared (`zero_scene_light` is the same call, for content that reads it by that name) | | `zero_scene_depth(uv: vec2<f32>)` | `f32` | scene depth at `uv` — a screen UV here, where the surface domain's `zero::scene_depth` module takes a pixel coordinate under the same name (exact texel — an R32Float copy). Reversed: 1.0 is the near plane, 0.0 the far plane and empty sky, so a nearer surface reads GREATER and `d > 0.0` means "a surface was drawn here" | | `zero_linear_depth_through(d, near, far, engine.view_proj)` | `f32` | that sample as a distance in metres along the camera's view axis, under a perspective or an orthographic camera — the one inversion of the reversed range (`zero_linear_depth(d, near, far)` is its perspective case alone) | | `zero_scene_motion(uv)` | `vec2<f32>` | per-pixel screen-space motion vector at `uv` | | `zero_pass_input(i, uv)` | `vec4<f32>` | the pass's declared input `i`, at `uv`. Input 0 is what `zero_sample_scene` reads | | `zero_pass_input_size(i)` | `vec2<f32>` | that input's size in texels, so one entry serves every level of a chain | | `zero_camera_position()` | `vec3<f32>` | the world position of the camera the render being drawn looks from — the camera `engine.view_proj` belongs to, so on a capture or a render-to-texture camera it is that camera's. With a world position reconstructed from `zero_scene_depth(uv)` and `engine.inv_view_proj`, `normalize(world - zero_camera_position())` is the view ray | | `zero_scene_surfaces_drawn()` | `bool` | whether the scene's surface channels (the helpers below) hold the surfaces of the render being drawn: true on the deferred path from `afterOpaque` on, false on the forward path, which draws no G-buffer | | `zero_scene_normal(uv)` | `vec3<f32>` | the world-space normal of the surface at `uv` (`@scene.normal`), unit length; +Z where no surface stands, (0, 0, 0) where `zero_scene_surfaces_drawn()` is false | | `zero_scene_surface_flags(uv)` | `u32` | the surface flags the geometry pass wrote at `uv` (`@builtin::shaderModules.surface_flags`' `ZERO_SURFACE_FLAG_*`, in scope with the helper); 0 where `zero_scene_surfaces_drawn()` is false | | `zero_scene_material(uv)` | `ZeroGbufferMaterial` | what the surface at `uv` IS (`@scene.material`): `.base_color`, `.metallic`, `.perceptual_roughness`, each in [0, 1], unpacked by `@builtin::shaderModules.gbuffer_material`, which the surface group includes | | `zero_scene_shaded(uv)` | `vec4<f32>` | what the surface at `uv` SENT (`@scene.shaded`): its shaded colour, linear, with its coverage in alpha | | `zero_scene_emissive(uv)` | `vec4<f32>` | the radiance passes stamped on the surface at `uv` (`@scene.emissive`) | | `zero_display_exposure()` | `f32` | the exposure in force: the gain `__display__` multiplies the scene's light by before its curve, the value this frame's display pass draws with (1 where the chain carries none). Light times it is light in the units the picture shows it at, so a threshold judged against `light * zero_display_exposure()` picks the same highlights at every exposure | | `zero_middle_grey()` | `f32` | for an effect in light: the light `zero_sample_scene` reads that the picture shows as middle grey, 0.18 over the exposure in force on a segment holding the scene's light and 0.18 on a segment `__display__` already drew. What a grade pivots its contrast on, so middle grey holds where the picture shows it at every exposure | | `zero_picture_white()` | `f32` | for an effect in light: the light the picture's white stands at, the peak a grade holds. 1 (the white an SDR picture peaks at) on a segment `__display__` already drew, and 0 on a segment holding the scene's light, which has no peak | Engine data uniform `engine` (a `PostEngineData`): | Field | Type | Meaning | |---|---|---| | `resolution` | `vec4<f32>` | `x`=width, `y`=height, `z`=1/width, `w`=1/height | | `time` | `vec4<f32>` | `x`=elapsed seconds, `y`=dt, `z`=frame index | | `view_proj` | `mat4x4<f32>` | this frame's view-projection | | `prev_view_proj` | `mat4x4<f32>` | last frame's view-projection (motion) | | `inv_view_proj` | `mat4x4<f32>` | inverse view-projection (world-space reconstruction) | | `params` | `vec4<f32>` | `x`=this pass's own index, `y`=the scale it draws at, `zw`=1/size of its first input — for a pass the post-process chain draws. A pass a `renderFeature` fragment pass draws carries that feature's `spec.params` here instead; a shader declaring `passes:` is always drawn by the chain, so the two never meet in one shader. | | `exposure` | `vec4<f32>` | `x`=the exposure in force (what `zero_display_exposure()` reads) | | `camera_position` | `vec4<f32>` | `xyz`=the world position of the camera being drawn (what `zero_camera_position()` reads) | | `surfaces` | `vec4<f32>` | `x`=1 where the surface helpers read the render's own surfaces (what `zero_scene_surfaces_drawn()` reads) | The engine fills all of it **per render target**. A registered effect runs over the live viewport's frame AND over every offscreen one — a `capture` from a world-space station or orbiting an entity, a capture of a named camera, a render-to-texture camera — and in each of those, `view_proj`, `prev_view_proj` and `inv_view_proj` are the camera THAT render was drawn from, while `resolution` is that target's own pixel size. So a pass reconstructing world space from `zero_scene_depth(uv)` reconstructs against the station and lens the capture asked for, and an offscreen frame is a picture of the effect as it stands at that station. (A render feature's passes reach an offscreen render the same way, against the same camera — the `renderFeature` assetType README carries that half, including `@frame.camera`, its own per-target camera input.) **The scene's surfaces.** The surface helpers above read the deferred path's G-buffer, the same channels a render feature names as `@scene.normal`, `@scene.material`, `@scene.shaded` and `@scene.emissive`, by screen uv at the exact texel (the channels are at the scene's raster size, so a pass at a `scale`, or after an upscale, reads the surface that stands at that point of the picture). A shader that names any of them compiles with the surface group, `group(3)`, which spends four of the stage's sampled textures beside its own slots and pass inputs; the render keeps a channel only while a running effect, or a render-feature pass's shader, reads it; a channel counts as read when an entry point of the compiled shader reaches its helper, so a helper in an included function nothing calls reads nothing. They hold this frame's surfaces at every layer of the chain and at every render-feature phase from `afterOpaque` on. With temporal antialiasing running, every layer of the chain reads the normal and the material restated at each pixel's centre, with no sub-pixel offset, so an outline found in the normals holds still under a still camera; `zero_scene_shaded` and `zero_scene_emissive` read the raster's own, with its sub-pixel offset. The renderFeature type README states the whole contract by stage and path. The forward path draws no G-buffer, so there every helper reads zero and `zero_scene_surfaces_drawn()` false: a look that needs the surfaces draws a picture of its own there (from depth, say) instead of reading a wrong one, and `postprocess.status()` names the channels the effect `reads` and, after a frame it drew with the substitute, the `substituteReason`. ```wgsl // @domain: post-process fn fragment(in: PostInput) -> vec4<f32> { let c = zero_sample_scene(in.uv); if !zero_scene_surfaces_drawn() || zero_scene_depth(in.uv) <= 0.0 { return c; } let n = zero_scene_normal(in.uv); let m = zero_scene_material(in.uv); let rim = pow(1.0 - abs(n.y), 4.0); return vec4<f32>(mix(c.rgb, m.base_color, rim * material.amount), c.a); } ``` **Lights.** A post-process shader reads no light data: `uniforms`, `zero_point_light(i)` and the light grid are the surface framework's, and a post shader naming them does not compile. An effect driven by the scene's lights (light shafts, a glow around each lamp, a scatter through fog) is a render feature pass at a scene phase (`afterDepthPrepass` through `afterLighting`) that binds `@scene.lights`, the punctual-light buffer (the renderFeature type README states its layout), with `@frame.camera` for the camera; the beams lights throw through the air are already the built-in `VolumetricLighting` component, whose `lightScattering` render feature (`@builtin::systems.volumetrics`) marches the view rays through the scene's own lights. An offscreen render keeps no view history of its own, so `prev_view_proj` there holds that same matrix rather than the frame before it, and a pass taking camera motion from the two reads none. On the viewport the pair is a frame apart, so camera motion is the one reading a capture answers differently from the screen. `postProcessing = false` on a capture is the one control that takes the chain off the frame it returns; it names the camera property the ephemeral capture camera is built with, so it scopes to that one capture. What a capture opts out of is the registered effects; `__display__` still runs on it, so the exposure and tone curve that turn the scene's light into a picture are on what a capture returns. A diagnostic capture (`albedo`, `normal`, `motion_vectors`, …) bypasses `__display__` itself, since a channel like that is a reading of the scene rather than a graded picture of it. The environment-cube capture bypasses it too, and for the same reason: a probe face carries radiance into the cube array, and `__display__` would fit that radiance to a display's code values — a picture of it rather than the value the PBR indirect term multiplies into its lighting. A complete post-process effect — a vignette via `fragment()` + `properties.yaml`: `properties.yaml`: ```yaml properties: - { name: intensity, type: float, default: 0.5, min: 0, max: 1 } - { name: radius, type: float, default: 0.75, min: 0, max: 1 } - { name: softness, type: float, default: 0.45, min: 0, max: 1 } ``` `shader.wgsl`: ```wgsl // @domain: post-process fn fragment(in: PostInput) -> vec4<f32> { let color = zero_sample_scene(in.uv); let intensity = max(material.intensity, 0.01); let radius = max(material.radius, 0.01); let softness = max(material.softness, 0.01); let center = in.uv - vec2<f32>(0.5); let dist = length(center); let vignette = smoothstep(radius, radius - softness, dist); let darkened = color.rgb * mix(vec3<f32>(1.0), vec3<f32>(vignette), intensity); return vec4<f32>(darkened, color.a); } ``` The asset above **defines** the effect. It enters the frame when something registers it: ```luau postprocess.add("vignette", asset.resolve("~.shaders.vignette", "shader"), { priority = 200 }) ``` The registration names no layer, so the effect grades the layer its `space` belongs to: this vignette reads light, so it runs on `scene`, over the picture before the UI reaches it. Registering it is the one step that makes it render, so a world's chain holds exactly the passes its content asked for. Editing the shader body afterwards recompiles every effect registered from it, in place — the pass keeps its enabled state, priority, layer, tuned property values and bound textures, and draws the new pixels on the next frame. `postprocess.remove(name)` takes it back out of the chain and leaves the asset alone. Drive the named properties at runtime with `postprocess.setProperty(name, prop, value)` and bind texture properties with `postprocess.setTexture(name, prop, path)` (both keyed by the **property name**, never a slot index — see the post-process section of `man shaders` / the `postprocess.*` API). Read them back with `postprocess.describe(name)`: it carries the chain state `postprocess.status()` lists for that effect, the `properties` schema it was registered with, and the `values` each of those properties currently holds. Before the effect exists, `shaderRef:getProperties()` on the asset names the same schema, so what a pass takes is answerable either side of the registration. A **screen** shader is a standalone full-screen visual (UI background, procedural pattern). `ScreenInput` mirrors `PostInput` (`frag_coord` + `uv`); there is no scene to sample, so it has no `zero_sample_scene` helpers. Its `engine` uniform is a `ScreenEngineData`: | Field | Type | Meaning | |---|---|---| | `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world | | `scroll` | `f32` | UI scroll offset | | `resolution` | `vec2<f32>` | render-target size in pixels | | `mouse` | `vec2<f32>` | mouse position | | `velocity` | `f32` | scroll velocity | ```wgsl // @domain: screen fn fragment(in: ScreenInput) -> vec4<f32> { let t = engine.time * 0.5; let col = vec3<f32>( sin(in.uv.x * 3.14159 + t) * 0.5 + 0.5, sin(in.uv.y * 3.14159 + t * 0.7) * 0.5 + 0.5, material.brightness ); return vec4<f32>(col, 1.0); } ``` ## Library includes A library module is a **`.shaderModule` asset**: it only EXPOSES functions and structs and does nothing on its own (exactly like a Unity `.cginc`). You must call what you include. Include one by its identity, the same string you would hand `asset.resolve`: | Include | Exposes | |---|---| | `@builtin::shaderModules.pbr_shading` | `struct PbrSurface { albedo, normal (world), metallic, perceptual_roughness, emissive, occlusion }`; `zero_pbr_default_surface(FragmentData) -> PbrSurface`; `zero_pbr_shade(FragmentData, PbrSurface) -> vec3<f32>` (the full forward PBR lighting); `zero_pbr_indirect_visibility(FragmentData, PbrSurface) -> ZpbrIndirectVisibility` (the share of the surroundings' light each indirect lobe takes from the scene's ambient occlusion: `diffuse` with the light a crease bounces back, `specular` from the open cone around the bent normal); `zero_pbr_shade_with_visibility(FragmentData, PbrSurface, ZpbrIndirectVisibility) -> vec3<f32>` (the same lighting with that share stated by the caller); `zero_pbr_surroundings_light(FragmentData, n, albedo) -> vec3<f32>` (the diffuse light the surroundings hand the surface along `n` as `zero_pbr_shade`'s diffuse lobe takes it — lightmap, flat ambient, sky, reflection probes, light-probe volumes, the scene's occlusion — for a self-lit body to multiply by its colour); `zero_pbr_sun_visibility(FragmentData, PbrSurface) -> vec4<f32>` (the sun as it reaches the surface: rgb what translucent casters and a medium leave of it, a the share its shadow maps leave, zero where it puts no light on the surface), which a surface scales on its own terms and hands back in `PbrSurface.sun_visibility` | | `@builtin::shaderModules.shadows` | `compute_directional_shadow_factor(...)`, `compute_spot_shadow_factor(...)`, `compute_point_shadow_factor(...)`, `compute_area_shadow_factor(...)`, `compute_punctual_shadow_factor(...)`, `zshadow_light_reach(...)`; each light's `_with_kernel` form takes a shared `ZShadowKernel` (`zshadow_kernel()`) so several lookups of one fragment derive its filter rotation once | | `@builtin::shaderModules.engine_bindings` | the group(0) declarations (camera, transforms, lights, shadow maps) — surface shaders get this implicitly; include it directly only for advanced raw access | | `@builtin::shaderModules.shadow_bias` | `zshadow_offset_receiver(...)`, `zshadow_directional_depth_bias(...)` and the rest of the bias math, as pure functions | | `@builtin::shaderModules.texturing` | `ztex_stochastic(...)` (tile without a visible repeat grid), `ztex_blend_normals(...)` (reoriented normal blending) | | `@builtin::shaderModules.periodic_noise` | Value noise that repeats along x, for a pattern laid around a circle (a sky over the azimuth, a ring): `zero_azimuth(dir)` (the azimuth about +Y as a fraction of a turn, wrapping along -X), `zero_periodic_noise(p, period)`, `zero_periodic_fbm(p, period, octaves, lacunarity)` (each octave fits a whole number of cells in `period`, so the sum repeats every `period` and a pattern whose x runs over one period per turn closes with no seam), `zero_wrap_cell(cell, period)` and `zero_hash21(p)` for a lattice of one's own | | `@builtin::shaderModules.parallax` | Parallax occlusion for any lit shader with a height map: `zero_parallax(depth, max_steps) -> ZeroParallax` (the relief's depth in UV units, its steps, its fade distances and whether R is height or depth); `zero_parallax_march(FragmentData, height_texture, height_sampler, uv, ZeroParallax) -> ZeroParallaxHit` (the UV to read every map at, with `ddx`/`ddy` for `textureSampleGrad`); `zero_parallax_sun_visibility(FragmentData, PbrSurface, height_texture, height_sampler, hit, ZeroParallax) -> vec4<f32>` (the sun with the relief's self-shadow, for `PbrSurface.sun_visibility`, marched only where the sun lights); `zero_parallax_self_shadow(...)` for any other light direction. Tiled UVs keep every tile; the relief flattens with distance and toward a grazing view | | `@builtin::shaderModules.depth` | `zero_linear_depth_through(depth, near, far, view_proj)` — the one reading of a stored depth, for the projection the view-projection states; `zero_linear_depth` and `zero_linear_depth_orthographic` are its two cases | | `@builtin::shaderModules.ambient_light` (`zero::ambient_light`) | `zpbr_surroundings_irradiance(world_pos, n, flat_ambient)` (the diffuse light the surroundings hand a surface with normal `n`: the flat ambient, the captured sky and reflection probes, and the baked light-probe volumes, as the PBR model reads it) and `zpbr_surroundings_in_scatter(world_pos, flat_ambient)` (that light averaged over every direction: what a participating medium scatters). A compute pass binds `environment_map`, `environment_sampler` and `zero_environment` to `@scene.environment`, `@scene.environmentSampler` and `@scene.reflectionProbes` | | `zero::sun_shadow` | `zero_sun_visibility(p) -> f32`, `zero_sun_visibility_at(p, footprint) -> f32` and `zero_sun_visibility_seen_from(p, eye) -> f32`: how much of the sun reaches the world point `p` past the occluders that shadow the surfaces from it (1 unobstructed, 0 blocked), read from the sun's shadow pages at the finest level holding `p`, at the finest whose texel is no smaller than `footprint`, or, for air a camera at `eye` looks through, at the level the frame keeps pages for that air. What a participating medium shadows the sun's light by: haze, fog, clouds, shafts. A compute pass binds `sun_shadow` (`element: ZeroVsmUniform, array: false`), `lights` and `shadow_pool` to `@scene.sunShadow`, `@scene.lights` and `@scene.shadowPool` | | `zero::sky_visibility` | `zpbr_sky_visibility(p, dir) -> f32`: the share of the world's sky the world point `p` sees around `dir`, from the sky-visibility field over the scene's static geometry (1 where no field is published). A compute pass binds `zero_environment` (`element: ZeroEnvironment, array: false`) to `@scene.reflectionProbes` | | `@builtin::shaderModules.light_shadows` | `zero_light_shadow(li, p, footprint) -> f32`: how much of the light at row `li` of `@scene.lights` reaches the world point `p` past the occluders that shadow the surfaces from it (1 unobstructed, 0 blocked), read from the shadow pages at the mip whose texel is no smaller than `footprint`. What a participating medium shadows a point, spot or area light's beam by. A compute pass binds `lights` and `shadow_pool` to `@scene.lights` and `@scene.shadowPool` | | `@builtin::shaderModules.gbuffer_material` (`zero::gbuffer_material`) | `struct ZeroGbufferMaterial { base_color, metallic, perceptual_roughness }`; `zero_gbuffer_unpack_material(texel: vec4<u32>) -> ZeroGbufferMaterial`; `zero_gbuffer_material(t: texture_2d<u32>, coord: vec2<i32>) -> ZeroGbufferMaterial`, `zero_gbuffer_base_color`/`zero_gbuffer_metallic`/`zero_gbuffer_roughness(t, coord)` — the one unpacking of `@scene.material`'s `Rgba8Uint` texel into what a surface reflects | | `zero::scene_depth` | `zero_scene_depth(px: vec2<f32>)`, `zero_scene_depth_uv(uv: vec2<f32>)`, `zero_scene_depth_texel(px: vec2<i32>)`, `zero_scene_depth_size()`, `zero_scene_depth_is_sky(d: f32)`, `zero_scene_world_position(px
▲ -1↑ born
backing path · assetTypes/testSuite.assetType

Problems

Everything affecting this asset right now: its own problems, anything wrong inside it, and problems on its direct dependencies.

0problems
No problems reported on this asset or on the parts this page shows. Parts it leaves out are not counted here.
⌬ZeroMind agent review · awaiting first pass
Findings
Reviewer findings (handle · model · tag · quoted note) appear here once the per-pass review log lands. Today only the rolled-up agent_score is exposed.
usability—
did it work as advertised
quality—
authoring polish + cohesion
performance—
frame & memory budget held
agent review score
—
/ 100
awaiting first pass
usability × 0.40
+ quality × 0.35
+ performance × 0.25
± compat factor

Usability ratings

Did the part work as advertised when consumers tried to drop it in. Separate from upvotes: those are taste; this is "did it function".

—%no reports yet
Sign in to report whether this part worked for you.
Discussion

Scoped to this part · feeds back into the world's score.

0comments
Sign in to post.sign in
No comments yet. Be the first.