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

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 2mo 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

  • Built-in engine suites: src/lua/lib/tests/suites/<name>.testSuite/ (VFS: /zero/source/libs/@builtin/tests/suites/<name>.testSuite/).
  • 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

Suites may also ship fixture files (helper .module folders, sample data) alongside init.luau — allow_unlisted: true permits them.

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 the shell / CI: ./scripts/run_luau_tests.sh (all) or ./scripts/run_luau_tests.sh <name> (one). --list prints every discovered suite.
  • 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.

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.

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? }?) → 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.

argtypedescription
self?
opts{ quiet: boolean? }?Optional `{ quiet }`.

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.

173+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() ``` ## 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) The `assetType` is the **type of types** — the meta-type that every `<typename>.assetType/` folder is an instance of, including itself. A `<typename>.assetType/` folder declares a new asset type called `<typename>`: its on-disk shape, its identity rule, and the structural contract instances of the type must satisfy. This type is self-hosting. `assetType.assetType/` conforms to its own schema — a `type.yaml` plus a `README.md` — so the type system is defined in terms of itself rather than a hidden engine special-case (the same way a C compiler is written in C). Every asset in the engine, including each `.assetType` definition, now resolves to a registered assetType: a `.material` resolves to `material.assetType`, and `material.assetType` resolves to `assetType.assetType`, which resolves to itself. ## Why it exists Assets used to be mapped to their type *implicitly*, by matching the folder suffix against a name-keyed registry. That match carried no stored link: nothing on a `Foo.material` recorded *which* `material.assetType` it was written against, so two worlds shipping a same-named type could silently disagree. Making `assetType` a real, resolvable asset closes that gap — the link from an asset to its type is now an explicit reference pinned in the asset's `.refs` sidecar (`via: "asset_type"`), exactly like every other dependency. ## Where it lives - Source: `/zero/source/.../<typename>.assetType/` - Identity: `<typename>` (the `.assetType` suffix strips from the identity; the folder retains the suffix on disk). - Folder shape: - `type.yaml` — the structural spec the validator reads. **Required.** - `README.md` — type-level documentation. **Required.** - `about.yaml` — three short plain-language texts saying what the type is for (see "Say what your type is for" below). Every built-in type ships one. - `behavior.luau` — optional behavior/scaffolding module. - `template/` — optional canonical placeholder body the templater copies into a new asset of the type. - `<name>.module/` — optional shared code the type ships to **every instance** of it, conventionally `shared.module/` (see below). ## Shared code its instances reach (`asset.containing` + `.modules`) A type ships code every instance of it uses by declaring the modules in its own `behavior.luau`, as a map of tracked `require`s: ```luau -- inside <typename>.assetType/behavior.luau M.modules = { shared = require(".shared") } -- the sibling shared.module/ ``` An instance reaches it with one location-independent line: ```luau -- inside any foo.<typename>/init.luau local api = asset.containing(__FILE__).modules.shared ``` `__FILE__` is the chunk's own VFS path; `asset.containing` resolves the calling asset, and `.modules.<name>` follows the instance's pinned `typeRef` (the type's **guid**, recorded in the instance's `.refs` as `via = "asset_type"`) to the module its type declares. Because resolution follows that link rather than a category name, the same line in an instance of a different type resolves to that type's module, and identically-named modules in two types never collide. `asset.typeRef(target)` reads that guid for any target; `asset.resolve(asset.typeRef(target))` gives the full `AssetRef<assetType>`. See `assetTypes/README.md` § "Shared code: type-owned modules" for the full mechanism. ## How to create one Authoring a new asset type is just creating a `<typename>.assetType/` folder under `/zero/source/`. The engine registers `<typename>` as a category **the moment the folder is written** — no engine restart, no Rust change, and it works for built-in (`@builtin/assetTypes/`) and user-defined types identically. Once `<typename>` is registered, `<name>.<typename>/` folders are recognised as assets of that type and resolve their `asset_type` link back to this definition. Creating a `<name>.<typename>/` folder *before* its `<typename>.assetType/` exists fails fast: the suffix has no registered type, so the folder can't be a valid asset. Author the type first. ## Say what your type is for (`about.yaml`) Every type carries a small `about.yaml` beside its `type.yaml`, and the README you write for the type documents how to author an asset of it. Both are required, and both are meant to be written as you make the type, while you know what it is for. `about.yaml` answers three questions in plain words, one key each: ```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. Name the whole range of things it covers, in the words a game maker would use for them. - **`function`** is how it works today: what an asset of the type is made of and what the engine does with it. - **`usage`** is what a person or an agent does with one: how they pick it, place it, call it, or hand it to something else. A few habits keep it useful. Write about the type as a whole, so the text holds for every asset of it, and leave out any one asset's name. Say what the type does right now. Stay with words a game maker would say, and mention a file name or a call only where a game maker would know it. The limits are in bytes: `intent` 800, `function` 1500, `usage` 1200. Each is generous, and a few sentences usually say it. Why bother: agents working in a world read these three texts to learn what your type is for, so they reach for it when it fits and use it the way you meant. People searching find the type by what they want to make, and the three texts let them tell at a glance whether it is the one they need. `asset.create("assetType", name)` scaffolds the file with all three keys, and a README whose first paragraph is a `[[describe]]` note. Each value starts with `[[describe]]` followed by a note on what to write; replace the whole value with your own words. A value or a README line that still starts with `[[describe]]` counts as not written yet, which the push's check of each asset it carries against its type reports, naming the file. A type you leave as it was is not asked, so older types stand. Many types at once, or one you would rather not write by hand: `services describe` lists the types that lack these texts and what filling them costs, and `{ mode = "all" }` writes them into the same files, where you edit them like anything else you wrote. Where the texts show up: `asset.inspect("<typename>", "assetType")` returns them as `detail.about`, `assetTypeRef:getAbout()` returns them as a table with the keys `intent`, `function` and `usage`, the type's `types/<typename>` guide page ends with an "About this type" section holding them, and the Inspector's Type section lists them at the top. The guide page is this README plus that section, so a README that explains the type well and an `about.yaml` that says what it is for read well together. ## Ask your assets to say what they are A type can ask each of its assets to carry a description: a file, written by the author or generated, that says what that asset is and what it is for. The people and agents who find an asset read it to decide whether it fits, and the author knows what it is for at the moment of making it. **1. Declare the file with a `described` check.** This is the whole requirement: ```yaml files: required: - path: "README.md" # any file name works kind: "file" content: - { check: "described", message: "Say what this widget is for and where it goes." } ``` With that in place: - An asset whose file is missing, empty, or still has a line starting with `[[describe]]` does not meet the type's requirements. `asset.validate` names it, `zm status` and `world.publishBlockers()` list it, and a push that carries it is refused with `message`. - `services describe` finds it (`mode = "find"` lists it and the price) and can write the description for it (`mode = "all"`). It writes only this file. For a YAML file that holds several texts, name the keys and their limits in bytes, the way this type does for `about.yaml`: ```yaml content: - check: "described" keys: - { key: "intent", max_bytes: 800 } - { key: "usage", max_bytes: 1200 } message: "Write intent and usage." ``` `headings` names sections a Markdown file must have. `assetTypes/README.md` has the full check. **2. Optionally, steer what gets generated with a `describe:` block:** ```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>" ``` `guidance` says what a description of your type covers, and `examples` names assets whose descriptions show the shape you want. Without the block, generation still works from the general describing guide and the check's `message`. An example is an asset of your type in the library whose description is a true, written one, never a scaffold's placeholder, and never the asset being described. When the library has none, leave `examples` empty rather than name one that is not. A type whose assets the model cannot perceive (a sound it cannot hear, a motion it cannot see) says so in `guidance`: the description comes only from what the asset's own files state, such as its name and the `.metadata` where a generation service records the prompt that made it, and when they state nothing the model answers `cannot` with that reason. `services describe` then fails that one asset with the reason and leaves its file as it was. **3. Start the file unwritten in your template.** Put a heading and one line that starts with `[[describe]]` and a short note on what to write, in `template/<file>`, so a new asset starts unwritten rather than with text that only looks written. Do not put example content in it: every new asset carries the template verbatim, and the same text on many assets makes them impossible to tell apart in search. Types whose assets say what they are through their own content (a mesh, a texture, a sound) leave this out: declare nothing and nothing is asked. ## The `behavior.luau` contract `behavior.luau` is the type's code. It returns ONE table, and the keys below are the ones the framework reads off it for EVERY type — the surface you get by declaring them. Anything else on the table is your own: reachable by name through `require("@builtin::assetTypes.assetType.shared.ref").loadTypeModule("<typename>")` for a system that knows your type (`computeShader` publishes `dispatchKey` that way), and never called by the framework. ```luau local M = {} M.ref = { ... } -- methods on every AssetRef of this type M.modules = { ... } -- shared code the instances reach M.global = {} -- reserved key; ship the empty table function M.onCreate(name, opts) ... end return M ``` ### The tables | Key | Shape | What the engine does with it | |-----|-------|------------------------------| | `M.ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every `AssetRef` of this type: `ref:name(...)`, with `self` the ref. This is how a type gives its instances an API. Two names in here are contracted — see below. | | `M.modules` | `{ [name] = require(".sibling") }` | Shared code the type's instances reach through `asset.containing(__FILE__).modules.<name>`, resolved by the instance's pinned `typeRef` guid. See the section above. | | `M.refShapes` | `{ [method] = "TypeName" }` | Declares the result type of a `M.ref` method so the LSP can check what a call site does with it. See the `M.refShapes` section below. | | `M.events` | an events schema | The events an ASSET of this type fires, declared the way a component declares its own. Readers subscribe through `ref.events.<name>:connect(...)`; firing authority stays with the type. Keyed by the asset's guid, so every resolver of the same asset shares the signals and a re-resolved ref re-attaches to subscriptions already there. | | `M.namePattern` | a Lua pattern string | The name shape `asset.create` enforces for instances of this type, replacing the default `^[A-Za-z][A-Za-z0-9_]*$`. | | `M.global` | `{}` | Reserved. Ship the empty table. | ### The lifecycle hooks Each is optional; a type that omits one costs nothing. The engine calls them: | Hook | Signature | When it fires | |------|-----------|---------------| | `M.onCreate` | `(name, opts) -> { [filename] = contents }` | On `asset.create("<type>", name, opts)`. Returns the files that scaffold the new instance, as a map of relative path to contents; the framework writes them. The `opts` type annotation is the schema `asset.create` validates the caller's arguments against, so annotate it. | | `M.onReplace` | `(dest, files) -> { [filename] = contents }` | On an `asset.create` that writes over an asset already at `dest`, after `onCreate`. Receives the files `onCreate` produced and returns the files to write, so a type that re-derives its content (a rig re-imported from its source file) can carry what an author added to the asset it replaces. Optional. | | `M.onRegister` | `(self)` | Once per instance, the first time it registers: on `engine.onWorldLoaded` for instances already in the world, immediately on a live `asset.create`, and when an instance arrives after that sweep (installed, pulled, or synced from a peer). Guarded by the instance's path, so a double trigger never double-registers. An instance that leaves the runtime releases the guard, so one arriving at the same path again registers. This is what makes "write an asset into the world and it takes effect live" work for content that registers into a runtime registry. The `@builtin` library is excluded from the sweep. | | `M.onChange` | `(ref, change)` | On every VFS write to a file INSIDE one of this type's instances. `change` is `{ path, asset, type, kind, origin }`: `kind` is `"edited"` or `"seeded"`, `origin` is `"local"` or `"remote"` (an importer runs on the originator only). **Filter on `change.path`**: the hook fires for any file under the folder, so act on the one you care about. It runs as its own task and may wait on what it reads: a `vfs.read` of bytes only the blob store holds (a binary file on the web build) fetches them. The writes to one asset reach the hook in the order they were made, each once the hook before it has finished. A re-entrancy guard suppresses writes back into the same asset routed inline from the hook, and a write the hook makes is routed on a later frame like any other, so the hook must be convergent on its own: diff the meaningful state and short-circuit while your own regeneration is in flight. | | `M.onDelete` | `(ref)` | When an instance of this type leaves the runtime: it is deleted, or the engine swaps away from the world binding that held it. Its files are gone from `/zero/source` by then. A removal routed while the instance's `onChange` is waiting reaches `onDelete` once that hook, and every write queued behind it, has finished. On a swap the instance still exists in the world it belongs to, and a VFS write the hook makes reaches the world now bound. | | `M.validate` | `(assetRef) -> { { code, message, severity? } }` | On `asset.validate`, after the structural `type.yaml` check, for the type's own SEMANTIC validation. `severity` defaults to `"error"`; error-severity problems flip `ok` to false, warnings do not. A hook that raises or returns a non-table is itself reported as a `validate.hook_failed` error. `world.push` runs this per user asset, so declaring it enforces your type's rules at publish time with no further wiring. | ### The two contracted `M.ref` names Most `M.ref` methods are your type's own surface: name them what you like, return what you like. Two are read by the engine and mean the same thing for every type, so their shape is fixed: - **`instantiate(self, target?, opts?) -> (root, idMap)`** — makes an instance part of the scene. Defining it is the whole opt-in: `ref:canInstantiate()` is true exactly when it exists. Its **return is a contract** — see the next section. - **`inspect(self) -> detail`** — the type-specific half of `asset.inspect`. See its section below. ### Names a type cannot shadow Some keys resolve on every `AssetRef` before per-type dispatch, so an `M.ref` entry of the same name is never reached: `canInstantiate`, `getSource` / `getBytes` / `getText`, `exists`, `deps`, `meta`, `runtime`, `events`, `modules`, `typeRef`, and the residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`, `gpu_resident`. These are the behaviours every asset must expose identically, which is why they win. ### Reloading A `behavior.luau` edit ripples to existing refs with no restart: dispatch reads `mod.ref` fresh each time and `require`'s cache is re-run in place. A type whose folder appears at runtime is picked up on the next dispatch — negative results are not cached either. ## The names your type's assets hold (`references:`) An asset that names another asset by a string depends on it: the named asset travels with it into a pack or a pull, and a name nothing answers to is an unresolved dependency `worldValidation` reports and the push gate refuses. The engine reads `require(...)` and the asset lookups on its own; a name your type's format or API carries anywhere else is one you declare, in `type.yaml`: ```yaml references: # A top-level key of this type's own files that holds a name (or a table of them). keys: - { key: "shader", type: "shader" } # A call's argument, counting from 1, wherever the call is written. args: - { call: "g:node", position: 2, type: "procNode" } # A field of the options table a call takes. fields: - { call: "fx.beam", field: "material", type: "material" } ``` `type` is the category the name resolves in, one of `asset.categories()`. An argument declared once per category, at the same `call` and `position`, takes the name from whichever category answers. A key or a field holds one category: declared again with another `type`, it takes the later one. The block is declared as the type registers, when the library or the world holding it is laid into the VFS, so every reference table reads it whatever script has or has not run. `asset.declareReferenceKey`, `asset.declareReferenceArg` and `asset.declareReferenceField` declare the same things from a script, for a surface that is no type's. ## What search does with your type (`indexing:`) A type declares what search embeds for its instances. **This is not optional and there is no useful default**: ZeroMind runs your declaration and adds nothing of its own, so anything you do not point at is absent from the index — silently, and for every instance of the type forever. Twenty types once shipped with no `indexing:` block and every instance of them was unfindable. A type whose instances are never searchable (a run record, a log) says so with `indexing: none`; every other type declares a recipe. A type without an `about.yaml` beside its `type.yaml` refuses every push that carries it, whether or not the push edited the type. Texts in it that are not written yet follow the rule every `described` file follows: they refuse the push that edits, stages or commits the type. Two words carry the whole thing, and they are the same two the search tool exposes: - **`identity`** — what an instance IS. For anything you can look at, that is the picture (`content:` + `modality: image`, matched directly by a text query). For everything else it is the authored text that says what it is. - **`capability`** — what it DOES and how it is made. Code, settings, the model-written summary of them. A type with no behaviour has no `capability` entry. A type with nothing to look at has no image. Leaving a slot empty is a statement; filling it with whatever happens to be lying around is not. The one you have to decide when authoring a type is: *for an instance of this, what is the thing a person would recognise it by, and what is the thing it does?* A texture answers "the image" and "its compression settings". A module answers "its README" and "its code". Write those two answers into `indexing:` and the rest follows. Three specifics worth knowing before you write one: - **`derive` is instructed by this type's own `README.md`.** A model reads an instance's source and writes a description; what it embeds is the description, not the source. It follows your README to know what it is looking at, so a type whose README says what its instances are gets good derivations for free. There is no prompt to name. - **`derive` loses detail.** It keeps the main technique and drops secondary ones. If the source is code you want searchable by its own vocabulary, declare the same files a second time as `capability` with `extractor: verbatim`. Two entries, same role, different failure modes. - **Never `source: { field: name }`.** A filename is one or two words with no usable embedding, and a corpus indexed that way answers "language runtime" with `say_runtime_2.soundClip`. `facets:` is the second stage: a `file:` embedded whole (`.metadata`, so keys nobody declared still get indexed) plus computed keys that state a value for every instance including `false` — the raw file can imply "not rigged" and can never say it. The full schema, every extractor and the facet sources are in [`assetTypes/README.md`](../README.md); the scaffolded block with inline guidance is in [`template/type.yaml`](template/type.yaml). ## A container whose contents work together (`system: true`) A type that is a container can say its contents are one working whole by declaring `system: true` at the top level of its `type.yaml`. `package` declares it: the components, modules, scenes and tools a package ships are parts of one system. The declaration is plain data, read from the decoded `type.yaml` (`require("@builtin::assetTypes.assetType.shared.declaration").of("package").system`), and a type that leaves it out is an ordinary type. ## What your type looks like (`preview:`) A type declares how its instances are pictured, and the engine makes the picture when something needs it: staging an instance whose `preview.png` is missing or pictures content it no longer holds queues a render, a view that shows the instance asks for one, and `ref:preview()` renders one on demand. An edit renders nothing on its own. Each `preview.png` records the content it pictured, which is how a stale one is told from a current one. The preview studio owns the light, the backdrop, the framing and the camera, and nothing in the world reaches it, so an instance pictures the same in every world. Declare one of four recipes: | `kind` | The picture is | Your type provides | |---|---|---| | `instantiate` | the asset stood in the studio through its own `instantiate` | `ref.instantiate` | | `image` | a file the instance holds, fitted to the frame, nothing rendered | `source.files`, the candidate files in order | | `surface` | the asset painted on a builtin mesh | `mesh`, and `ref.previewMaterial(self) -> { material }` | | `custom` | whatever `ref.preview(self, opts)` returns | `ref.preview` | ```yaml preview: kind: surface mesh: sphere ``` A scene-instantiable type that declares nothing still answers `ref:preview()` through its `instantiate`, but persists no picture: the declaration is what makes the engine keep one. List `preview.png` among the type's files so an instance may hold it. The picture is findable only when `indexing.content` names it. The two are separate statements, and neither is derived from the other: ```yaml indexing: content: - role: identity modality: image source: { file: "preview.png" } ``` `@builtin::assetTypes.assetType.shared.previewRecipe` reads the declaration; the scaffolded block with inline guidance is in [`template/type.yaml`](template/type.yaml). ## Typing a result from the instance (`M.refShapes`) Every method on `M.ref` is checked against the type its `--!return` names, and every asset of the type gets the same one. That is right for most methods and wrong for the ones whose result is shaped by the ASSET: a method answering one entry per child folder, per row of a config, per binding an input map declares. The widest true annotation for those is `{ [string]: Thing }`, and an indexer accepts every key — so a caller's typo reads as valid and nothing reports. `M.refShapes` lets the type state the result per instance. Each entry is `function(self) -> (typeExpression, source?)`: a Luau type expression for THIS asset, and the module whose type vocabulary the expression uses. Read the asset; never run it — stating a type must not take effect. ```lua -- inputMap.assetType/behavior.luau — the shipped example. -- `activate()` hands back one handle per control the map declares. 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)` resolves and `map.noexisting` is reported with the map's real controls. Without it, both pass silently. ### What the call site has to say A per-instance type is matched by the asset's IDENTITY, so it applies only where the reference the method is called on says WHICH asset. Two spellings do: ```lua -- a component field, whose declared default names the asset public = { map = Field.assetRef("inputMap", "@builtin::inputMaps.default", Sync) } local controls = public.map:activate() -- typed for THAT map -- an annotation, naming category and identity local m: AssetRef<"inputMap", "@builtin::inputMaps.default"> ``` `asset.resolve("<identity>", "<category>")` carries the CATEGORY, so the methods the category defines are checked on the result — but not which asset it found, so a per-instance result keeps the category's declared return. A reference that names no asset (`asset.resolve(someVariable)`, a value passed in as a parameter) carries neither, and calls on it are unchecked. That is the same rule everywhere: the checker states what the code states, and a name computed at runtime states nothing. ### The result is a value, not a binding The type belongs to the expression, so it travels the way any inferred type travels. Indexing the call's result is checked; stashing it in a module local and indexing it from another function is not, because the local's declared type is what carries across — and `any` (or no annotation) carries nothing: ```lua -- checked: `d.greting` is reported function awake() local d = public.dialogue:lines() d.greeting:say() end -- NOT checked: `lines` is a module local typed `any` local lines: any = nil function awake() lines = public.dialogue:lines() end function start() lines.greting:say() end ``` Bind what you need at the call site and the names stay checked in both places — the asset-derived type at the boundary, ordinary scoping after it: ```lua local lineGreeting = nil function awake() local d = public.dialogue:lines() lineGreeting = d.greeting -- `d.greting` is reported here end function start() lineGreeting:say() end ``` ### When nothing is reported and you expected something From a call site, a type that is correct and a type that was never published look the same: no diagnostic either way. `require("@builtin::assetTypes.assetType.shared.refShapes").published()` answers which it is. It returns two maps — the category surfaces, and the per-asset results keyed by identity and then by method: ```lua local shapes = require("@builtin::assetTypes.assetType.shared.refShapes").published() shapes.categories.dialogue --> "{ lines: () -> any, lineNames: () -> { string } }" shapes.returns.Shopkeeper.lines --> "{ browsing: Line, farewell: Line, greeting: Line, wares: Line }" ``` An identity absent from `returns` was never published for, which is a different thing from published-and-correct — and the reason to look here rather than at the call site. The answers are recomputed when an instance is written, so a control added to a map reaches the checker with no restart. Only types that declare `refShapes` are read per instance, and at most 64 assets of one type are — past that the type keeps its declared return and the engine log names what was dropped. ## The instantiate hook (`M.ref.instantiate`) — a contracted return A type opts into becoming part of the scene by defining `instantiate` on its `ref` table. That is the whole opt-in: `ref:canInstantiate()` is true exactly when the hook exists, so consumers offer a scene path — an `Asset.source` field, a viewport drop, a tool argument — by CAPABILITY rather than by a list of type names. Unlike `inspect`, this hook's **return is a contract**. A caller writes one piece of code against every instantiable type, so what comes back cannot vary by type: ```lua -- behavior.luau local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable") local M = {} M.ref = { instantiate = function(self, target, opts) local root = Instantiable.root(self, target, opts) -- IN: the base opts -- ... compose whatever this type is, under `root`, NOW ... return Instantiable.result(self, root, idMap) -- OUT: the contract end, } return M ``` **IN.** `target` is an owning entity ref: the instance lands under (or, for a hierarchy type, onto) that owner. With no target the type spawns a fresh root. `position`, `rotation`, `scale`, `name` and `temporary` mean the same for every type — `Instantiable.root` applies them to a root you mint, `Instantiable.place` to one you adopt, so you never re-read the spec. Honour more opts of your own if your type needs them, and document them in the hook's `--!arg` docs. **OUT.** Return `(root, idMap)` through `Instantiable.result`: - **`root`** — the composed root, as an `EntityRef`. Composition is **synchronous**: everything your type builds is live when you return, so the caller can parent to it and read its components in the same statement. Do not defer the work to a component's `awake` and return an empty shell — a root that is not live is refused. - **`idMap`** — the `originalId -> runtimeId` map naming what you spawned, or nil for a type with no addressable children (`result` normalises it to `{}`). **A caller never receives nil.** A component that re-composes your asset on every load keeps this map and passes it back in, which is how a cross-entity reference into the composition survives a reload. `AssetRef` runs every `instantiate` through `result` on the way out whether or not your type called it, so returning something else fails at your own call rather than handing a caller a nil root. Calling it yourself is still how you say what you return, and running it twice changes nothing. `@builtin::assetTypes.assetType.shared.instantiable`'s README is the full reference for both halves. ## The inspect hook (`M.ref.inspect`) `asset.inspect(ref)` resolves `ref`, builds a common envelope shared by every asset (`identity`, `name`, `guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`, `description`, `tags`), then calls the resolved type's own inspect hook — `M.ref.inspect(self)` on `behavior.luau` — for the type-specific `detail`. The hook returns *only* `detail`; the framework fills in everything else: ```lua -- behavior.luau local M = {} M.ref = { inspect = function(self) -- self.path is the asset's own folder. Parse the asset's OWN -- files — source text, a native payload header, its `.metadata` -- — never runtime state (a live component instance, a GPU -- upload, a compiled schema): inspect must work on an asset that -- hasn't been compiled, uploaded, or registered yet. return { -- type-specific fields, whatever this type wants to surface } end, } return M ``` A type that omits `M.ref.inspect` yields the generic record: the envelope alone, `detail = nil`. That's a valid, working state — not an error — but it means agents calling `asset.inspect` / `tools.use("assets","describe", ...)` on an instance of the type see only identity and scope, none of what makes an instance of it meaningful. Declaring the hook is what makes a type's instances inspectable for what they actually are. A hook that raises leaves `detail = nil` and sets `record.warning` to the error text — `asset.inspect` itself never raises for a resolved ref. ## Discovery - `asset.list("assetType")` — every registered asset type. - `asset.inspect("<typename>")` — the type's identity, source path, and this README, plus its `about.yaml` texts as `detail.about`. - `asset.resolve("<typename>", "assetType")` — the `<typename>.assetType` asset itself (used by the validator to find the type's `type.yaml`). ## Related - `assetTypes/README.md` — the full `type.yaml` schema and validator rules. - `@builtin::assetTypes.assetType.shared.instantiable` — the instantiation contract's shared implementation, both halves. - Every other `*.assetType/` here — the concrete types built on this meta-type. ## The Inspector a type ships Every type names the file its Inspector sections come from with `inspector: { type: "inspector.luau" }` in its type.yaml. `asset.create("assetType", name)` scaffolds the block and an `inspector.luau` whose Contents section lists an asset's files, built from `ctx.parts`. `asset.validate` on a type that names none reports `assetType.inspector_required` (an error for a `@builtin` type the engine's library authors; a warning for a world's own, and for one the library carries by reference, which the world that published it answers for), and one whose file does not load `assetType.inspector_invalid`. ## In the Inspector Type: what the type.yaml declares (suffix, container, primary files, the settings and inspector blocks), whether the type ships a behavior, how many instances it has, and **Open** for its files. Schema: the settings every instance carries, as read-only typed controls at their defaults (a type whose schema is per instance says where it is declared). Instances: a link to each of the first 20 assets of the type, and how many there are when there are more.
▲ 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. 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` — optional per-scene notes about THIS scene. Author one only when there is scene-specific detail worth recording; the general scene model lives here, in `guides { path: "types/scene" }`. `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. The write returns as soon as the file is on disk and the rebuild finishes behind it, so what it landed comes back as a notice: ``` [info] a write to build.luau rebuilt the scene { content="6", scene="scenes.main", editorOnly="1" } ``` 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. 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 scene saved before records were stated this way holds every field; those values load and save as they are, since a stored value cannot be told apart from one an author chose, 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 — update every `layers.load` callsite and the world's startup-scene field. ## Related types - `.bundle` — reusable entity hierarchies that scenes spawn into themselves. - `.service` — cross-scene background work that outlives a scene load. - `.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
·
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. 3. **Hot reload.** Editing the file re-runs the module body and folds what it returns into the table already loaded, so that table keeps its identity: a caller that captured it with `require` reads the new source's functions and values through the reference it already holds, and a later `require` returns that same table. A key the new source drops goes away; a key something set at runtime stays. The body's own `local`s start again from their initial values, so state that must outlive an edit lives in `modules.state()` (`guides { path: "core/scripting-and-tasks" }`). 4. **Identity resolution.** A module is reached by its `<identity>`, and where the caller lives decides which spelling of it resolves. For a module in a **world**, from a caller in that same world — another module, a component, a scene entrypoint, or an `execute` chunk: - `require("<identity>")` — the identity on its own, resolved against the caller's own root. It carries every folder segment, so a module created with `{ folder = "demo" }` is `require("demo.beats")`. - `require("@root::<identity>")` — the same root-relative resolution, written out. - `require(".sibling")` — a module in the same folder, by its bare name; `..name` steps up one folder, `...name` two. Logs, stack traces and hot-reload notices name that same module `@local.source.<identity>` — its key under the world source root. The `<identity>` tail of that key is the form above, so a trace reading `@local.source.demo.beats` is `require("demo.beats")`. For a module in a **library** — content under `/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's root from anywhere: `require("@builtin::modules.transform")`. Mounting a world as a library moves its files under such a root and flips the caller root to `@<lib>::`, which is what keeps the root-relative forms above resolving across the move. ## Discovery - `asset.list("module")` — every registered module. - `asset.inspect("<name>")` — public functions, source path, this type README. - `ls /zero/source/<name>.module` lists the files the folder holds. ## Authoring conventions - Return a single `M` table from `init.luau`. Top-level statements with side effects run on first require — useful for one-time initialization, dangerous if they touch the engine before it's ready. - Write exported functions as `typed function`, not `function`: the argument types are enforced at the call and the checker knows the signature, so a caller's mistake is reported where they made it. - Annotate exported functions with `--!desc` / `--!arg` / `--!return` / `--!example` so the LSP, `tools.list`, and `asset.inspect` surface them. A function with no `--!desc` is reachable only by someone already reading this file. - Declare a VALUE with `Field.<kind>(default, mode, description)`, and a table whose members are reached through a metatable with `--!members <TypeName>` — the latter gives the surface its accepted member set, its type, and its documentation from one table. See `guides { path: "core/authoring" }` for all four rules and `modules/api/engine/entity.module/members.module` for a worked member table. - Keep module state in module-local upvalues or in `modules.state()`. Globals leak across reloads. Module-locals start again from their initial values with each hot reload; the table `modules.state()` returns is the same table on both sides of every reload. - Prefer focused modules over kitchen-sink modules. If two halves of a module have no shared state, split them. ## Common pitfalls - **Cyclic requires.** A `require` chain that loops will return the partial table (the half built before the cycle was detected). Design for one-way dependencies. - **Engine-time side effects.** Don't `entity.spawn` at module top-level — the engine may not be ready. Expose an `M.init` and call it from a scene entrypoint. - **Hot-reload + module-local cache.** A module that caches expensive computation in upvalues loses that cache on reload — fine for dev, but be aware in performance work. - **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical. - **Writing one while play runs.** A `/source` write made while play is running lands on the play shadow, and a guarded play-exit discards it unless it is kept. One `.module` write shadows `init.luau`, the `README.md` and the `.metadata` together. `vfs.write(path, bytes, { durable = true })` skips the shadow, and `vfs.promotePlayShadow` keeps what is already on it — the `core/vfs` guide has the model and what each route costs. ## Related types - `.component` — for entity-bound state + lifecycle hooks. - `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider. - `.tool` — for a single agent-callable function with a YAML schema. - `.package` — to group several modules + components + scenes into one shippable folder. ## In the Inspector Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
▲ 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, and button legends. - `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 mutations. - `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
▲ 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
△
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
❒
bundle · 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
❒
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
# 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 } }`. ## 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
·
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
△
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
❒
bundle · born here
❒asset
▲ 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
❒
bundle · born here
❒asset
▲ 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 (point) or direction (directional). 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. 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`, `castsShadows`, `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)`, `:setKind(lightKind)`. `kind = "spot"` opens a cone along the entity's forward axis, at the engine's default 30° outer and 20° inner half-angles; the `SpotLight` component is the one that carries the cone angles and the `face` axis as fields. `"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} }) ```
▲ 0↑ born
❒
package · born here
❒asset
▲ 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
❒
package · born here
❒asset
# oceans A sea and the ground under it, as one package: the wave simulation, the surface that renders it, the seabed it is seen through, and the answer to "how high is the water here" that gameplay needs to float things on it. ```lua local Ocean = require("@builtin::systems.oceans.modules.ocean") Ocean.create({ preset = "gale" }) ``` That is a whole ocean — waves out to the horizon, foam on the breaking crests, a seabed below, and a surface that follows whoever is looking at it. To float something on it: ```lua local ocean = Ocean.forEntity(oceanEntityId) boat.position = { x, ocean:sampleHeight(x, z), z } ``` It is a building block. The sun the water glitters under, the ambient its foam sits in and the sky it reflects all come from the scene, through the same directional light and reflection probes every other material in the engine reads — so an ocean drops into a world that already has lighting instead of bringing a second set, and changing the scene's light changes the water with it. ## What it does The simulation is **spectral**: instead of animating individual waves, it builds the sea's energy across every wavelength and direction from an oceanographic spectrum, then inverse-transforms that into a height field. A real sea is what comes out — wind speed alone decides wave height, and it rises with wind the way a fully developed sea does, following the Pierson–Moskowitz law. It runs in **cascades** — independent wave fields over different patch sizes, each band-limited to its own range of wavelengths. A tile of roughly two kilometres carries the long waves and one of a few hundred metres the short ones; they sum into a surface with detail at every scale, and because the bands are disjoint no wavelength is synthesised twice. Above them a **Gerstner bank** adds the swell analytically, which no cascade can hold: a wave longer than its own patch has nowhere to live, and swell arrives from a distant storm on its own heading anyway. **Foam** is not painted on. It comes from the Jacobian of the wave displacement: where the surface folds over itself, the wave is breaking. Whitecaps appear where and when the geometry actually breaks, accumulate into a persistent world-space field, and streak behind the crest as they decay. **Colour and transparency are the same mechanism.** Per-channel Beer–Lambert extinction over the distance light travelled through water gives both — red dies within a metre, blue survives tens. That is why shallow water over sand reads turquoise and the open sea reads near-black blue without switching materials. **The seabed** is one noise field read twice: scaled it is the terrain's relief, unscaled it picks between sand and rock, so outcrops stand on the high ground and sand fills the hollows. The sun's caustic web moves over both, bent by the horizontal displacement of the water directly above it. Bodies land on it: the pass that raises the ground writes the same field out as a height patch that travels with the viewer, so what a body stands on is what the frame drew. Nothing here ships an image. Every map the surface and the seabed sample — the foam patterns, the sand, the rock, the caustics — is grown on the GPU at startup. ## The pieces | Asset | What it is | |---|---| | `components/Ocean` | Puts a sea on an entity. Its fields are the sea state; the simulation is rebuilt from them, so an ocean survives a scene reload. | | `modules/ocean` | The substrate: `attach`, `create`, `forEntity`, `sampleHeight`, `sampleDisplacement`. | | `components/Buoyancy` | Floats a rigid body on the sea. Its fields are the hull: how dense it is, how steady, and what box displaces water. | | `modules/buoyancy` | The forces: `attach`, `forEntity`, `columns`, `submergedFraction`, `restingY`. | | `modules/oceanPresets` | Nine named sea states, from `calmClear` through `gale`. | | `modules/oceanQuality` | The four tiers — how finely a sea is resolved, as distinct from what sea it is. | | `modules/oceanClipmap` | The camera-following ring geometry both the surface and the seabed are built on. | | `modules/oceanFloor` | The seabed: terrain, ground materials, caustics and the ground physics collides with. | | `modules/oceanScene` | The seam between the scene capture and the materials that sample it. | | `shaders/oceanSurface` | The water: cascade normals, absorption, exact dielectric Fresnel, subsurface scattering, sun glitter, foam, and the view from below. | | `shaders/oceanFloor` | The seabed: sand and rock blended by terrain noise, under a caustic web. | | `materials/oceanWater`, `materials/oceanSeabed` | The default looks. | | `renderFeatures/oceanScene` | Copies the frame's colour and depth so the surface can refract what is behind it and measure its own water column. | | `computeShaders/ocean_*` | The ten-stage GPU pipeline. | ## Wind is the control Significant wave height goes as the **square** of wind speed, so that one field does most of the work: | Wind | Sea | Wave height | |---|---|---| | 3 m/s | glassy, a mirror | ~0.2 m | | 11 m/s | working sea, occasional whitecap | ~2.5 m | | 24 m/s | gale, breaking and streaked | ~12 m | Everything else shapes character rather than size: `choppiness` pinches crests into peaks, `standingWaveRatio` runs waves both ways instead of only downwind, `jonswapGamma` sharpens a fetch-limited sea, and the foam layers decide how readily a breaking crest whitens and how long it streaks. Read `documentation/oceans.guide` for the full walkthrough, including the seabed, buoyancy, reflections and what each tier costs.
▲ 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
# Error Test Intentionally broken material used to exercise the renderer's error-handling and fallback paths. It targets `@builtin::shaders.error_shader` and carries a bright magenta base colour (`1.0, 0.0, 1.0`) — the classic "missing/failed" flag colour — with mid roughness (`0.5`), opaque render type, and back-face culling. ## Inputs - `colors.base_color` (`1.0, 0.0, 1.0, 1.0`) — magenta error flag tint. - `floats.roughness` (`0.5`) — neutral surface roughness. - `render.type` (`opaque`) / `render.queue` (`2000`) — drawn in the standard opaque pass.
▲ 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
▣
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.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` / `sunIntensity` follow the scene's sun unless the call pins them. 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. `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
△
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. 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
◐
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
▣
module · born here
❒asset
# edui.shell (module) The editor dock shell on the CSS-parity `ui.*` surface. One edui app owns a `ui.*` native `dockArea` whose children are a `dockPanel` per registered edui panel — real `egui_dock` tabs, splits and drag, with the arrangement persisting across rebuilds because the dockArea and each dockPanel carry a stable `id`. ## Why a separate registry The shell keeps its own panel registry (`addPanel` / `removePanel` / `panelsSorted`), distinct from the deprecated zui `editor.registry`. That keeps the zui editor completely untouched while panels migrate to edui one at a time: the zui dock renders the zui-framework panels it always has, and the edui shell renders the edui panels registered here. The two registries fold into one at cutover, when the zui dock is retired. ## One app, one reactive loop `App.rebuild` sets the shell as the building app before it calls `buildShell`, so a panel's `build()` — which uses `edui.current()` to register its closures — wires every callback onto the ONE shell app. All interaction for every panel flows through the shell's single callback env, and a click anywhere rebuilds the whole dockArea. That is why the shell needs no per-tab scheduler (unlike zui's `dockApp`): the edui App is the scheduler. ## Usage ```lua local edui = require("@builtin::modules.edui") edui.shell.addPanel{ id = "entities", title = "Entities", order = 10, build = function() return edui.panel{ title = "Entities", body = edui.tree{ ... } } end, } edui.shell.mount() -- registers the screen on the EditorUI layer -- each editor-update frame: edui.shell.update(dt) -- liveness rebuild every `refresh` seconds ``` `mount(opts?)` takes `{ refresh? }` (seconds between liveness rebuilds, default 0.5). `refresh()` forces an immediate rebuild; `unmount()` tears the screen down but keeps the panel registrations for a later `mount`.
▲ 0↑ born
△
mesh · born here
❒asset
▲ 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
# 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
△
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
❒
package · born here
❒asset
# deprecatedParticles (deprecated) > **Deprecated.** This belongs to the earlier particle substrate. It stays loadable by identity and guid for content that already uses it; nothing new should use it, and search does not offer it. Particles are procgen sim nodes (`sim.spawn`, `sim.particles`, `sim.shader`) played through an effect: use `@builtin::assetTypes.effect`. The package holds the GPU particle engine module (`engine`), the `deprecatedParticles` module over it, the `DeprecatedParticleEmitter` and `DeprecatedSimpleParticleEmitter` components, the shaders, compute shaders and materials they draw with, and a demo scene. The package's `.metadata` carries the deprecation marker, so every asset inside is deprecated.
▲ 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 — the bare indicators only. 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 `---`), block-scalar chomping/indentation indicators (`|-`, `|+`, `>-`, `|2`, ...), 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
# 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. Loose image files under a `textures/` directory classify as `texture`. > 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 `wgpu::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 (`TextureRefCounts` → `drop_texture`) and is **not** part of this assetType. Same texture identity, two separate residency states, two separate operation sets, two separate reference counts. See `docs/specs/runtime-asset-copying.md`. ## Internal layout A `.texture/` is permissive (`allow_unlisted: true`). `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. `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. (`data.tex` is the pre-rename legacy payload name — still resolved for existing assets; new content writes `data.ztex`.) That fallthrough takes the lowest-named raster image in the folder and never the generated `preview.png` thumbnail, which is rendered 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`. A texture whose settings were stored under an earlier schema reads with the same meaning, and its first local edit rewrites them into `settings.yaml` under the fields below. ```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 downsampled to fit, and a `uastc` texture's longest side is the largest power of two within it. 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 texture whose settings predate `textureType` reads as `color`, with `alpha = input` and no transparency fill, which is what its payload holds. A cook that drops texels — a `maxDimension` smaller than the source, or a `uastc` cook resampling a side to a power of two — 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. A texture whose payload predates wrap and anisotropy reads `repeat` / `repeat` / `world`, which is how it has always been sampled. `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 format is `zero_texture::blob` (`ZTEX` magic + 32-byte header + 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 with a side under four texels. | each side is resampled to the nearest power of two (halfway rounding up), nearest-neighbour for a `nearest` texture. | | `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. A payload of BC7 blocks, written before `uastc` existed, stays as it is: `Bc7RgbaUnorm[Srgb]` where the adapter samples BC textures, re-encoded as it loads into ASTC 4x4 or ETC2 where the adapter samples those instead, and decoded to RGBA8 where it samples none. Its settings read `compression = uastc`, what an encode of it now asks for, while `texRef:info()` reports the `bc7` payload it holds. #### 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 predate `compression` (stored before it was a setting) is healed by its first local edit: a `nearest`-filtered one becomes a `sprite` in `rgba8`, an `rgba16` or `rgba32f` one keeps its format, and every other one becomes `uastc` and is re-encoded; an older "no cap" becomes a `maxDimension` of 8192. Loading one changes nothing, and an edit arriving from another session or a texture installed from a library is never healed. 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 by `scripts/fonts/build_cjk_fallback.py`, 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
# 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). 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. | *(legacy)* An `@compute @workgroup_size(...)` entry over storage buffers — you write the `@group/@binding` lines yourself. **The canonical path is now the separate `.computeShader` assetType** (see below); `.shader` + `// @domain: compute` still compiles for back-compat. | `// @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 are now 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`. The `.shader` compute domain above remains only for back-compat. **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 legacy `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. `uniforms.*` (sun direction/colour, ambient, `camera_pos`, `time`) and the punctual lights (`zero_point_light(i)`) are always in scope; the shadow functions come from `#include "@builtin::shaderModules.shadows"`. 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 now `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 read | |---|---|---| | `fn fragment(input: FragmentData) -> vec4<f32>` | the finished pixel, and the `PbrSurface` too when the body hands one to `zero_pbr_shade` | the real channel where a surface was handed over; magenta, the "no data here" marker, where the body shades by its own math | | `fn surface(input: FragmentData) -> PbrSurface` | the surface (albedo, roughness, metallic, emissive, normal, occlusion), which the engine then lights | the real channel | 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. A body that lights itself by its own math draws those channels magenta. `pbr.shader` exposes `surface()`. `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()`. ### 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; } ``` #### 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 culled against its undisplaced bounds. ### 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 to the camera | | `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>` | ambient colour | | `ambient_intensity` | `f32` | ambient intensity | | `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`. `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). ### 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 The common lighting state — the sun (`input.light_direction` / `light_color` / `light_intensity`), the ambient (`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 one thing not on `FragmentData` is the punctual-light array (its length varies), which is always in scope: | Expression | Type | Meaning | |---|---|---| | `uniforms.point_light_count` | `u32` | number of active point/spot lights | | `zero_point_light(i)` | `PointLightData` | one point or spot light (fields below) | | `zero_punctual_shadow(i)` | `PunctualShadowEntry` | that light's shadow record (its projected map or cube) | `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 with no PBR: ```wgsl // @domain: surface #include "@builtin::shaderModules.shadows" // exposes compute_directional_shadow_factor 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 lit = input.light_color * input.light_intensity * max(dot(n, sun), 0.0) * sun_shadow; // Point + spot lights (the punctual-light array, varying length). for (var i = 0u; i < uniforms.point_light_count; i = i + 1u) { let pl = zero_point_light(i); 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); lit += pl.color * pl.intensity * max(dot(n, l), 0.0) * atten; } // Ambient fill. lit += input.ambient_color * input.ambient_intensity; return vec4<f32>(albedo * lit, material.base_color.a); } ``` - **Unlit:** skip the lights and return your colour directly. - **Toon / PS1 / custom:** start from the loop above and band, quantize, or warp it however you like. - **PBR:** build a `PbrSurface` and call `zero_pbr_shade` (see "Library includes") instead of writing the BRDF by hand. ## 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>` | sRGB colour, default is `[r,g,b,a]` | | `int` | `i32` | | | `bool` | `u32` | | | `texture` | `texture_2d<f32>` + `sampler` | `default:` is a built-in texture name (`white`, `black`, `flat_normal`) | 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. `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 | ```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. ## 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 `all`, the picture after `__display__` with the UI 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. `opts.layer` names one explicitly — `"all"` is what an effect that must grade the interface says. 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 now); 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(d, near, far)` | `f32` | that sample as a distance in metres — the one inversion of the reversed range | | `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 | 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. | 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.) 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) | | `@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(...)` | | `@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.depth` | `zero_linear_depth(depth, near, far)` — the one reading of a stored depth | | `@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: vec2<f32>)`, `zero_scene_world_normal(px: vec2<f32>)`, `zero_scene_depth_fade(px: vec2<f32>, world_position: vec3<f32>, fade_distance: f32)` — every `px` is a pixel coordinate in two components, so a surface fragment passes `input.frag_coord.xy`, not the `vec4<f32>` `FragmentData.frag_coord` holds. The depth already drawn UNDER a surface fragment, and the world position and geometric normal of the surface standing there. What a decal projector box, a soft particle, a forcefield or water intersection foam shades against. Surface domain; the depth belongs to the view being drawn | | `zero::scene_color` | `zero_scene_color(px: vec2<f32>)`, `zero_scene_color_uv(uv: vec2<f32>)`, `zero_scene_color_texel(px: vec2<i32>)`, `zero_scene_color_size()`, `zero_scene_color_refract(px: vec2<f32>, offset_px: vec2<f32>)`, `zero_scene_color_refract_uv(px: vec2<f32>, offset_fraction: vec2<f32>)` — every `px` is a pixel coordinate in two components, so a surface fragment passes `input.frag_coord.xy`, not the `vec4<f32>` `FragmentData.frag_coord` holds. The scene colour already composed BEHIND a surface fragment, and the displaced read that bends it. What heat haze, a refraction shockwave, a cloaking or shield warp, glass and ice shade with. Surface domain; the colour belongs to the view being drawn, and is the lit opaque scene as it stood immediately before the transparent pass — so a `blend`-queue surface reads this frame's, an opaque one reads the previous frame's, and two overlapping blended surfaces both read the same picture and do not bend each other | `asset.list("shaderModule")` enumerates the `.shaderModule` assets in this engine, builtin and world-authored alike, and each one's README says what it exposes. Those are the `@builtin::shaderModules.*` rows above; a module you write is included exactly the same way, by its own identity or by the package-relative `~.name` form. The `zero::`-named rows come from the renderer itself. Their WGSL is baked into the engine binary and registered under those names before any asset exists, so they answer an `#include` in every engine and appear in no asset index. A shader that includes one records no dependency on it: the engine reading the shader is the engine that already holds the module. Two spellings reach the same `.shaderModule`: an earlier name is kept working through the module's declared alias, so a shader written against `zero::pbr` still compiles and still pins the asset that name resolves to. Newly written shaders should use the identity — it says which asset travels with the content. Whichever punctuation an include is written with — `#include "name"`, `#include 'name'` or `#include <name>` — names the same module and records the same dependency. The engine's own scaffolding — `zero::surface`, `zero::sky`, `zero::post`, `zero::screen` — is injected by the compiler around the matching domain and is never written by hand. The surface framework puts `safe_normalize`, `mat3_from_mat4` and `apply_normal_map(FragmentData, tangent_normal)` in scope for every surface shader. ## Shader features — compile-time variants A **property** is runtime uniform data (a colour, a float, a texture): set per material, read as `material.<name>`, no recompile. A **feature** decides which code is in the program at all. Use a property when the value changes at runtime, a feature when it changes what the shader is. Declare features in `properties.yaml`, alongside the properties: ```yaml properties: - { name: base_color, type: color, default: [1, 1, 1, 1] } features: - { name: PARALLAX, default: false, description: silhouette parallax march } - { name: DETAIL, default: true, description: detail-normal overlay } ``` Guard the code each feature owns with `#ifdef`: ```wgsl fn surface(input: FragmentData) -> PbrSurface { var s = zero_pbr_default_surface(input); #ifdef PARALLAX s.normal = parallax_normal(input); // absent when PARALLAX is off #else s.normal = input.world_normal; #endif return s; } ``` `#ifdef` / `#ifndef` / `#else` / `#endif`, one per line, and they nest. The directives resolve before the WGSL reaches the compiler, so the program holds exactly the lines its feature set selected and every other line is an empty one, which keeps a compiler message on the line number the file shows. An unbalanced block is a compile error naming its line. A material is what chooses a feature set, so `features:` shapes the shaders a material draws with — the surface, sky and screen-space domains. A material names the features it wants in its `mat.yaml`: ```yaml name: worn_rock shader: "@builtin::shaders.pbr_layered" features: PARALLAX: true # on, over the shader's default DETAIL: false # off, against the shader's default ``` or through `asset.create`: ```lua asset.create("material", "worn_rock", { shader = "@builtin::shaders.pbr_layered", features = { PARALLAX = true, DETAIL = false }, }) ``` The engine compiles one program per feature set its materials ask for, named `<shader>#<features>`. Materials sharing a set share that program. A feature the shader does not declare selects nothing, so a stray name cannot make the engine compile anything, and the compile names both halves of a mismatch: a guard on a name `features:` does not declare, and a declared name no guard tests. **Permutations are the cost.** A shader with n features can express 2^n programs, each its own compile and pipeline. One shader holds at most 32 variants; a material asking for a set past that draws with the shader's default features and the engine logs which shader ran out. Read what a scene is spending: ```lua for _, s in renderer.shaderVariants() do print(s.shader, #s.variants, "of", s.budget) print(renderer.variantSource(s.base.program)) -- what it ships as for _, v in s.variants do print(v.program, renderer.variantSource(v.program)) -- what one asked for end end ``` A shader registers under every key it answers to — its identity, its guid, each alias — and each key is a row. A variant lands on the row for the key the material named, which for authored content is the guid, so take a program name from the report rather than composing one. ## Materials reference shaders A `.material` applies a shader to entities. Its `mat.yaml` references the shader by its identity string and supplies property values: ```yaml name: my_material shader: "@builtin::shaders.pbr" render: blend: alphaBlend cull: back depth_write: false floats: roughness: 0.5 colors: base_color: { r: 1.0, g: 1.0, b: 1.0, a: 1.0 } textures: base_color_texture: { ref: "default:white" } ``` `shader:` is a plain identity string, and each `colors:` entry is an `{ r, g, b, a }` map — the two forms `mat.yaml` accepts for those keys. A key's value is the rest of its line, so every value above stands alone on one. ### The render block Render behaviour that used to be material "flags" — the blend equation, alpha cutout, which faces are drawn — lives in the `render:` block and drives the pipeline, not the fragment. These are the keys that reach the pipeline from both authoring routes, and the values each one takes: | Key | Values | Sets | |-----|--------|------| | `blend` | `opaque` `transparent` `alpha` `alphaBlend` `additive` `add` `cutout` `alphaCutout` `premultiplied` `premultipliedAlpha` `multiply` | the equation the fragment composites with | | `cull` | `back` `front` `none` `off` `disabled` | which faces the rasterizer keeps | | `depth_write` | `true` `false` | whether the draw writes depth | | `depth_compare` | `less` `lessEqual` `lequal` `equal` `greater` `greaterEqual` `gequal` `always` `never` | the test a fragment's depth passes | | `topology` | `triangleList` `lineList` `lines` `line` | what consecutive vertices assemble into | `blend` is also spelled `type`, and the two name one key. Its equations, over the fragment the shader returned (`src`) and the value already in the target (`dst`): `opaque` is `src`; `transparent`, `alpha` and `alphaBlend` are `src * src.a + dst * (1 - src.a)`; `additive` and `add` are `src + dst`, the mode a glow, a light shaft or a spark card is written for; `premultiplied` and `premultipliedAlpha` are `src + dst * (1 - src.a)`, taking a source that already carries its own coverage; `multiply` is `src * dst`, which is how a soot, grime or shadow card darkens what stands behind it. `cutout` and `alphaCutout` keep the fragment or discard it on its alpha and go on writing depth. The same block is what `asset.create`'s `render` argument takes, key for key and value for value, so one material named in Luau and the same material standing on disk ask for their pipeline with the same words. `depth_write` is the one key whose value takes the shape of its route: the word `false` on a `mat.yaml` line, the boolean `false` in the Luau table. ```lua asset.create("material", "heat_plume", { shader = "@builtin::shaders.pbr", render = { blend = "alphaBlend", cull = "none", depth_write = false }, }) ``` Where a value outside a key's set is reported is what the two routes differ on. `asset.create` refuses the call on any of these keys and names the set it measured the value against. A `mat.yaml` standing on disk registers either way, each key falling back to a value of its own: `blend` to `opaque`, `cull` to `back`, `depth_write` to `true`, `depth_compare` to `less` and `topology` to `triangleList`. The engine log carries the blend fallback, naming the value and the set it was measured against, so a `mat.yaml` value is worth putting through `asset.create` once — that is where every key answers with its set. ## Registration & hot reload A `.shader` is compiled by the asset system, not by the renderer: writing `shader.wgsl` or `properties.yaml` fires the `.shader` assetType's `onChange`, which calls `shader.compile` — that reads the body + the property schema, generates the group(1) interface and (for surface) every render-mode entry point, expands `#include`s, **validates the result with naga**, and registers it. Validation happens at this compile step — the whole point of "compile". A shader with invalid WGSL (an unknown field, a type mismatch, an undefined function) **fails to compile** with the real reason — readable directly from Luau via `shaderRef:compileStatus()` (`{ status = "compiled" | "failed" | "pending", error?, pending? }`), and also in the author log and `asset.inspect`; it is **not** registered. This fires on create and on every edit, so saving a `.wgsl` recompiles with no world reload; the change is visible on the next frame. Compilation is async, so a `compileStatus()` of `"pending"` immediately after a write means check again next frame. A surface shader is also checked for the material resolve, the pass that shades each pixel of the visibility buffer through the shader's own code. That check reaches its verdict a few frames after the raster compile. Until it does, `compileStatus()` reads `"pending"` with `pending` saying so, and the shader already draws. A shader the check refuses reads `"failed"`, and `error` names the construct the resolve cannot evaluate and where it sits; its pixels resolve through the error shader until it changes. The stage the compile checks comes from one of two places: the hook the engine scaffolds entry points around (`fragment()`, or `surface()` for an engine-lit surface), or the `vs_main` / `fs_main` pair the body writes itself. The pair is a pair: a body that writes its own entry points owes both stages. A body carrying neither route — a hook whose name is a letter off, say, or half a pair — holds no stage the rasterizer can enter, so the compile **refuses it** and names both the entry point it looked for and what the body carries, in the same `compileStatus()` error every other compile failure reads back through. ### Reading a compile error against the text it is about What the compiler reads is not the file you wrote. The engine generates the group(1) material interface from `properties.yaml`, wraps the body in its domain's framework and every entry point that domain needs, expands every `#include`, and resolves every `#ifdef` — so a 100-line body reaches naga as tens of thousands of lines. **Every line number in a compile error, and every `[N]` handle index naga prints where it has no name to print, is a position in that composed module.** A fault at module scope (`no definition in scope for identifier: 'zero_scene_depth'`) reads fine without it; a fault inside a function body does not. `renderer.compiledSource(name)` returns that composed module, and `shaderRef:compiledWgsl()` returns it for a ref you already hold. Both answer for a shader that declares no features, needs no material, entity or draw, and — the case they exist for — **answer for a shader whose compile failed**, holding the text the compiler was refused over for as long as `compileStatus()` reports that failure. `renderer.compiledShaders()` lists every name they answer for. ```lua local ref = asset.resolve("myShader", "shader") local status = ref:compileStatus() if status.status == "failed" then print(status.error) -- the line, the caret, and the cause local wgsl = ref:compiledWgsl() -- the text those positions are in local line = tonumber(string.match(status.error, "wgsl:(%d+):")) print(string.split(wgsl, "\n")[line]) end ``` The composed text carries every `zero::*` module the shader included, so the signature a call was rejected against is in the same text as the rejection — which is the whole of what a "wrong argument type" error needs to be actionable. A material bound to a broken (or missing) shader renders with the **magenta error shader** — never invisibly — so a shader problem is impossible to miss on screen as well as in the log. **Fixing the shader and re-saving recovers it live**, with no engine restart: the recompile clears the failed-shader state and the object returns to normal on the next frame. ## Discovery - `asset.list("shader")` — every registered shader. - `asset.inspect("<name>")` — domain, status, source, parse errors, this README. - `shaderRef:compileStatus()` — did it compile? `{ status, error?, pending? }`, no log needed. `"pending"` with `pending` set means the material resolve check is still reaching its verdict; a resolve refusal reads as `"failed"`. - `shaderRef:compiledWgsl()` / `renderer.compiledSource("<name>")` — the WGSL the compiler received, which is what a compile error's positions index into. Answers for a failed compile too. - `renderer.compiledShaders()` — every name that call answers for. - `shaderRef:getProperties()` — the parsed `properties.yaml` schema. - `shaderRef:listMaterialsUsing()` — materials bound to this shader. ## Common pitfalls - **A compile error shows up in one of three ways at the draw.** A shader that never compiled has no pipeline, so the renderer binds the magenta placeholder. A shader that compiled once and was then edited into brokenness KEEPS the pipeline that build produced — the surface goes on drawing the last good program, pixel for pixel, and looks entirely intact while the source is broken. A geometry-pass-only shader has no magenta tell either, since it is not on a forward mesh. `shaderRef:compileStatus()` gives the status + error text (as does `asset.inspect("<name>")`), and `renderer.drawDiagnostics()` names which renderables are in which of the three states — a row carries `substituted` for the placeholder, `stale` for a program that no longer compiles, and the cause either way. - **A compile error's line numbers are lines of the composed module, not of your file.** `renderer.compiledSource("<name>")` / `shaderRef:compiledWgsl()` is that module; resolve the position against it rather than counting lines in `shader.wgsl`. The `[N]` a message prints in place of a name is a naga handle index — it moves with the size of the body and is the same value for two unrelated faults in one file, so it is neither a line number nor a way to tell two failures apart. - **Don't declare group(0) or group(1) in a surface shader.** The engine owns group(0) and generates group(1) from `properties.yaml`. Re-declaring them is the fastest way to a layout mismatch. - **`#include` does nothing by itself** — it only exposes functions; you must call them. - **Renaming a property** changes the generated uniform field; materials setting the old name silently fall back to its default. - **Compute shaders don't render** — verify output via a buffer readback or a debug pass. Author them as a `.computeShader` (its own assetType), not a `.shader` — see `man compute`. ## Related types - `.material` — the required wrapper that applies a shader to entities. - `.style` — UI cascade, not GPU shaders. ## In the Inspector Selecting a shader opens its **Shader** section: its domain and shading model (and, for a post-process shader, the space its `fragment()` reads and returns), whether it compiled (and the compiler's error when it did not), a table of its declared properties (type, default, range), its post-process passes when it has any, the bindings it declares, and openers for its source. The **Materials** section (collapsed at first) has a Find materials action that lists, as links, every material drawing with the shader; it scans every material, so it runs only when asked.
▲ 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`, `destroy`). - You want to expose configurable fields to designers / `entity.spawn` callers / scenes without code changes. If you need a global service that outlives any entity, use a `.service` instead. If you need a stateless pure-function library, use a `.module`. ## 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 beside it on the fixed timestep; `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`, `destroy`) 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 service, 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. Update every `component.add(<oldname>, ...)` call and the scene JSON entries that reference it. ## Related types - `.module` — pure-function library, no per-entity state. - `.service` — globally-scoped behavior, 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
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.

These counts cover only the parts this page shows. Problems on the parts it leaves out are not counted here.

3+problems

Inside

3 problems across 1 item
●
dep.unresolved · L76
could not resolve `.shared`
●
dep.unresolved · L284
could not resolve `.shared`
●
dep.unresolved · L359
could not resolve `.shared`
⌬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.