Log inGet started
·
toolbox · drop-in viewer
asset⌬ toolboxtoolbox·originates fromworld 07158574-5…

tests

Run the engine test suite from inside a live engine and triage the results — the baseline-then-regression loop, without leaving the session.

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

tests

Run the engine test suite from inside a live engine and triage the results — the baseline-then-regression loop, without leaving the session.

List every registered test suite (optionally with test counts) to see exactly what the runner and CI will execute. Run everything, one suite, or a subset — each suite runs through its own cooperative coroutine so multi-frame tests yield correctly — and get back structured results plus Markdown and JSON reports written to the VFS. Compare two JSON reports to surface the failures that are new since the baseline, which is how you catch regressions a change introduced. The lower-level framework for authoring suites lives in the test module and the testSuite asset type.

Interface

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

This asset doesn't declare a schema or structured payload.

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.

89+items
❒
package · born here
❒asset
▲ 1↑ born
❒
package · pulled in
❒asset
ZeroJS is a JavaScript interpreter for the Zero engine, written in Luau. It parses and executes ES2017-practical JavaScript entirely inside the Luau VM — no native code, no WebAssembly, no external dependency — and marshals values back to Luau transparently. ## Importing ```luau local zerojs = require("~zerojs.api") ``` `~zerojs` is this package's alias, registered from the `name` in its `package.yaml` wherever the package sits. The same spelling therefore works from the world that authors the package and from a world that installed it, at any depth. Every module is reachable the same way — `~zerojs.parser`, `~zerojs.stdlib.promise` — and the package's own modules reference each other with those ids. ## API surface ### Module-level | Symbol | Type | Description | |--------|------|-------------| | `zerojs.eval(src)` | `(string) -> any` | Parse and execute `src` in a fresh one-shot VM. Returns the marshaled JS completion value. Raises a Luau error on a JS exception. | | `zerojs.new(opts?)` | `(table?) -> VM` | Create a persistent VM. `opts.env` seeds additional JS globals from a Luau table. `opts.engine` picks the tier (`"auto"`, `"compiled"`, `"interp"`). `opts.console` is a table of writers by level (`log`, `info`, `debug`, `warn`, `error`): each receives the formatted text of one console call, untagged, and a level without a writer uses `log`'s. With no `opts.console`, the console writes `[zerojs]`-tagged lines to the engine log. | | `zerojs.null` | sentinel | The JS `null` value (distinct from Luau `nil`). | | `zerojs.undefined` | sentinel | The JS `undefined` value, which marshals to Luau `nil` when returned. | | `zerojs.version` | `string` | Version string of this package. | | `zerojs.lastError(vm)` | `(VM) -> table?` | Returns the structured payload `{ name, message, stack }` from the most recent JS exception on `vm`. `nil` if no exception has occurred on that VM. | ### VM instance | Method | Description | |--------|-------------| | `vm:run(src, opts?)` | Execute `src` in this VM's persistent realm. `opts.sourceName` names the source for error messages and stack frames. Returns the marshaled completion value. Raises directing to `runAsync` when the script leaves a timer armed or a coroutine suspended across a frame. | | `vm:runAsync(src, opts?)` | Execute `src`, driving its event loop across engine frames until it settles. Returns a `RunHandle` immediately. `opts.timeoutMs` rejects the run if it outlasts that many milliseconds. Only one `runAsync` may be in flight per VM at a time; a second call while the first is unsettled raises. | | `vm:get(name)` | Read a global from the VM's realm. | | `vm:set(name, value)` | Write a marshaled Luau value as a JS global in the VM's realm. | ### `RunHandle` (returned by `vm:runAsync`) | Field | Description | |-------|-------------| | `done` | `false` until the run reaches a terminal state, then `true`. | | `ok` | Once `done`, `true` for a resolved run and `false` for a rejection or timeout. | | `value` | The marshaled completion value on a resolved run. A run that timed out after its script had already completed with a value (an armed `setInterval`, say, kept the run open) keeps that value here; every other failure leaves it `nil`. | | `error` | The rendered message text on a rejected or timed-out run. | | `lastError` | The structured `{ name, message, stack }` payload for a failed run. | | `thread` | The engine `task.spawn` driver pumping the loop each frame — present only while the run is still pumping, and `nil` once the run settles on its arming frame (a synchronous or microtask-only completion needs no per-frame driver). | | `handle:await(maxFrames?)` | From a yieldable Luau context, poll `done` frame-by-frame until the handle settles, then return it. | A `runAsync` stays pending while the loop has work: an armed `setInterval` keeps it pending exactly as an un-`unref`'d handle keeps Node alive — clear the interval or bound the run with `timeoutMs`. ## Marshaling Luau values passed to `opts.env` or `vm:set` are converted to JS values. JS values returned from `run`/`eval` are converted back to Luau: numbers, strings, and booleans are transparent; arrays become 1-based Luau tables; objects become string-keyed Luau tables; JS functions become callable Luau closures; `undefined` becomes `nil`; `null` becomes `zerojs.null`. ## Step-budget sandbox Each VM runs with a default execution budget of 1,000,000 interpreter steps. A script that exceeds the budget raises a JS `RangeError: step budget exceeded`, which surfaces as a Luau error. The budget resets on each `run`/`eval` call. ## Language scope - Variable declarations: `var` (function-scoped hoisting), `let` and `const` with full TDZ enforcement - Functions: declarations, expressions, arrow functions, closures, rest parameters, default parameters - Classes: declarations and expressions, inheritance via `extends`, `super()` in constructors and methods, getter and setter accessors, instance fields, static fields and methods, computed method keys, named class expressions, TDZ before declaration - Destructuring: object and array patterns in declarations, assignment, and function parameters; nested patterns; rename, default, rest; computed keys in object patterns; elision in array patterns - Spread: array literals, call arguments, `new` arguments, object literals - Template literals (untagged) - Optional chaining: `a?.b`, `a?.[k]`, `f?.(x)`. A `null` or `undefined` base ends the whole chain with `undefined` and skips every later link and argument; parentheses end the chain; the chain is not an assignment, update or `new` target - Nullish coalescing `??` and the logical assignments `??=`, `||=` and `&&=`, which evaluate the right side and write only when the current value calls for it. `??` does not mix with `||` or `&&` without parentheses - Full coercion and equality semantics: `==`/`!=` abstract equality, `===`/`!==` strict equality, `typeof`, `instanceof` - `try`/`catch`/`finally`, `throw` - All loop forms: `for`, `while`, `do-while`, `for-in`, `for-of`; `switch` with fallthrough - `async`/`await` — real event-loop semantics: an async function returns a promise, runs synchronously up to the first `await`, and resumes from a microtask when its awaited operand settles - Property enumerability: `for-in` yields only own enumerable keys; object rest excludes prototype methods ### Asynchrony and the event loop - `Promise` with the full ES surface: `then`/`catch`/`finally`, `resolve`/`reject`, and the combinators `all`, `allSettled`, `race`, and `any` (with `AggregateError` when every input to `any` rejects) - `queueMicrotask` for scheduling a microtask directly - Timers: `setTimeout`/`clearTimeout` and `setInterval`/`clearInterval`, with extra arguments forwarded to the callback - `vm:runAsync(src, opts?)` drives a script's timers, microtasks, and promise settlements across engine frames and returns a `RunHandle` (see the VM table above) - A long synchronous loop under `runAsync` yields at each step-budget boundary and resumes on a later frame instead of raising `RangeError`; the same script under `vm:run` still raises ### Standard library - `Object`: callable coercion plus `keys`, `values`, `entries`, `assign`, `freeze`, `isFrozen`, `create`, `getPrototypeOf`, `defineProperty`, `fromEntries`, `hasOwn`, and the `Object.prototype` methods (`hasOwnProperty`, `toString`, `isPrototypeOf`) - `Function.prototype`: `call`, `apply`, `bind` - Global conversions and predicates: `parseInt`, `parseFloat`, `isNaN`, `isFinite`, `String`, `Number`, `Boolean` - `Array` and `Array.prototype`: construction, `isArray`, `from`, `of`, and the iteration/mutation/query methods (`map`, `filter`, `reduce`, `forEach`, `find`, `some`, `every`, `slice`, `splice`, `concat`, `join`, `indexOf`, `includes`, `sort`, `reverse`, `push`, `pop`, `shift`, `unshift`, `flat`, `fill`, `keys`, `values`, `entries`) - `String.prototype`: `slice`, `substring`, `substr`, `split`, `indexOf`, `includes`, `startsWith`, `endsWith`, `repeat`, `padStart`, `padEnd`, `trim`, `trimStart`, `trimEnd`, `toUpperCase`, `toLowerCase`, `charAt`, `charCodeAt`, `codePointAt`, `at`, `concat`, `replace`, `replaceAll`, `match`, `matchAll`, `search` - `Number`: `isInteger`, `isSafeInteger`, `isFinite`, `isNaN`, `parseFloat`, `parseInt`, `MAX_SAFE_INTEGER`, `MIN_SAFE_INTEGER`, `MAX_VALUE`, `MIN_VALUE`, `EPSILON`, `POSITIVE_INFINITY`, `NEGATIVE_INFINITY`, `NaN`, and `Number.prototype` (`toFixed`, `toString`, `toPrecision`) - `Math`: the constants and functions (`abs`, `floor`, `ceil`, `round`, `trunc`, `sign`, `min`, `max`, `pow`, `sqrt`, `cbrt`, `hypot`, `exp`, `log`, `log2`, `log10`, the trig family, `random`) - `Date`: construction as `new Date()` (now) and `new Date(ms)` (epoch milliseconds), `now` (the wall clock at the moment of the call, never ahead of it and never moving backwards; whole-second readings of the wall clock bound it until a reading crosses a second boundary), `getTime`, `getFullYear`, `getMonth`, `getDate`, `getHours`, `getMinutes`, `getSeconds`, `getMilliseconds`, `getDay`, `toISOString`, `toJSON` - `JSON`: `parse` and `stringify` (indent argument and array replacer whitelist) - `Map` and `Set`: construction from iterables, `get`/`set`/`has`/`delete`/`clear`, `add`, `size`, `forEach`, `keys`, `values`, `entries`, insertion-order iteration - `RegExp`: literals and the constructor, `test`, `exec`, `lastIndex`, `source`, `flags`, `global`, `ignoreCase`, `multiline`, `dotAll`, and the `String` regex methods above - Errors: `Error`, `TypeError`, `RangeError`, `ReferenceError`, `SyntaxError` constructors and inheritance; `Error.prototype.name`, `message` and `toString`, so `String(e)`, `${e}` and `"" + e` read `<name>: <message>` - `console`: `log`, `info`, `debug`, `warn`, `error`, `dir` and `assert`. Values print the way a JavaScript console prints them: strings bare at the top and quoted inside, `{ a: 1, b: [ 1, 2 ] }`, `Map(1) { 'a' => 1 }`, `[Function: f]`, errors as `Error: message`, nested values below depth 2 as `[Object]` and `[Array]`, arrays and collections cut after 100 entries, a self-containing value as `<ref *1> { self: [Circular *1] }`, and a rendering wider than 80 characters across lines. A leading `%s`, `%d`, `%i`, `%f`, `%j`, `%o`, `%O`, `%c` or `%%` formats the arguments after it - `performance.now()` (milliseconds on a monotonic clock since the VM was created) and `performance.timeOrigin` - `globalThis`, `NaN`, `Infinity` ### Out of scope by design - Generators and iterators (`function*`, `yield`) - `Proxy` and `Reflect` - Labeled statements and `with` - Tagged template literals The full divergence list — where ZeroJS behavior differs from a browser engine — lives in the guide's divergence section. ## Test suites Eleven suites ship with the package, in its `tests/` folder, run via `tools.tests.run`: ```luau tools.tests.run({ suite = "zerojs_lexer" }) -- tokenization tools.tests.run({ suite = "zerojs_parser" }) -- AST construction and error recovery tools.tests.run({ suite = "zerojs_semantics" }) -- runtime semantics end-to-end tools.tests.run({ suite = "zerojs_language" }) -- ?., ??, logical assignment, error text, console, Date.now, performance.now tools.tests.run({ suite = "zerojs_stdlib" }) -- the standard-library surface tools.tests.run({ suite = "zerojs_typed_arrays" }) -- typed arrays, ArrayBuffer, DataView tools.tests.run({ suite = "zerojs_regex" }) -- the regex engine and RegExp methods tools.tests.run({ suite = "zerojs_async" }) -- the event loop, promises, and timers tools.tests.run({ suite = "zerojs_modules" }) -- the module graph tools.tests.run({ suite = "zerojs_assettype" }) -- the zJs asset type tools.tests.run({ suite = "zerojs_smoke" }) -- unmodified real-world JS programs ```
▲ 1↓ import
·
tool · born here
❒asset
# tests.compare Diff two JSON test reports and surface new failures, fixes, and added or removed tests — the "did my change break anything?" query. Save a baseline before a change, run the suite again afterwards, and compare the two: a non-empty new-failures list means the change introduced a regression. The baseline is required; the later report defaults to the most recent run when omitted.
▲ 0↑ born
·
tool · born here
❒asset
# tests.list List every registered test suite. Discovery reads the asset registry, so the result is exactly the set the runner and CI execute. Pass a suite name to narrow to one, or ask for details to load each matching suite and include its test count.
▲ 0↑ born
·
tool · born here
❒asset
# tests.loadHttp Fetch the engine's test content over HTTP and materialize it into the `@builtin` library so `tests.list` and `tests.run` can discover and run the suites. The engine's test content (its `.testSuite` assets, and the fixtures and packages only they use) is embedded in no build and reaches no end user. A `--dev` engine reads it off disk; every other engine (the WASM engine in a browser, an Android app, a native engine reading its library from ZeroMind) uses this tool at test time, fetching from an HTTP root (`base`) that serves a checkout's `src/lua/lib`. The browser bundle serves `src/lua/*` as static files under `/lua/` of the page's own origin, so a browser engine's default `base` is `/lua/lib`. An engine outside a browser has no origin to resolve a path against: it takes `base` as an absolute URL and refuses a load that names none. The proxy's `luau_test { instance }` serves the instance's worktree on a loopback port (an Android device reaches it through `adb reverse`) and passes that root to `tests.run` as `contentBase`. A generated `suites-manifest.json` lists each suite's files (`suites`) and the files the suites share (`support`, such as `tests/fixtures/` and `pkgtest/`). Every load materializes the shared files along with the suites it picks. A suite that reads other suites (their sources, or runs them) names the library folder that holds them on a `--!needs <folder>` line of its `init.luau`, such as `--!needs systems/procgen.package`; a load that picks it picks every suite under that folder as well, so the suites it reads are in the engine wherever it runs. Every file is written under `/zero/source/libs/@builtin/<rel>`, which registers it as a `@builtin::` asset (a suite as `@builtin::tests.suites.<name>`) with the same identity, origin, and internal-`require` resolution as a `--dev` boot. The HTTP fetch is asynchronous, so by default the work runs as a scheduler task and the call returns `{ taskId }` to watch; the browser harness polls it to completion before discovering suites. Pass `{ async = false }` to block and return `{ suites, support, files, base }`. A request that is not answered with a 2xx (a URL that cannot be sent, a refused connection, a 404) raises naming the URL and what it answered, and the load materializes none of its files.
▲ 0↑ born
·
tool · born here
❒asset
# tests.run Run the engine test suite and return structured results — every registered suite by default, a single named suite, or a chosen subset. Each run writes a Markdown and a JSON report to the temporary source area and can save an extra copy in a format you pick. Every suite runs through its own cooperative coroutine so multi-frame tests yield across engine frames correctly; an async run schedules the whole sweep as one task and returns its id immediately. Testing is an edit-mode authoring concern — the operation is refused in play mode, since it spawns and despawns entities, loads scenes, and flips modes. `onWorker = true` runs each suite inside a worker job (`jobs.dispatch`) rather than on the engine thread, and records `onWorker = true` on the result. The result keeps the engine-thread shape; a suite the worker cannot start counts as one failed result whose error is the text the worker gave. From the shell, `ON_WORKER=1 ./scripts/run_luau_tests.sh <suite>` adds the option.
▲ 0↑ born
▣
module · born here
❒asset
# tests.shared (module) Internal helpers shared by the `tests` toolbox tools. Not bound to a global — required by sibling tools via `require(".shared")`. ## Surface - `M.DEFAULT_JSON` / `M.DEFAULT_MD` — canonical report paths the engine test runner writes (`/source/tmp/test_results.json`, `/source/tmp/test_results.md`). - `M.readReport(src)` — read a JSON report from a VFS path, or pass a decoded table through unchanged. - `M.diff(before, after)` — classify every test in `after` relative to the `before` baseline: `{ newFailures, fixed, stillFailing, newTests, removedTests }`. ## Example ```lua local shared = require(".shared") local before = shared.readReport("/source/before.json") local after = shared.readReport(shared.DEFAULT_JSON) local d = shared.diff(before, after) print(#d.newFailures .. " regressions") ```
▲ 0↑ born
▣
module · born here
❒asset
# workerSuite The entry a worker job runs for `tests.run { onWorker = true }`. `run({ suite = "<name>" })` finds the `.testSuite` asset by the name `tests.run` reports it under, runs it, and returns its report to the engine-thread caller as a copy. A suite that cannot start on the worker raises, and the raise reaches the caller as the job's rejection.
▲ 0↑ born
·
assettype · born here
❒asset
# toolbox (asset type) A toolbox is an asset grouping set of `<tool>.tool` assets around one area of work. Each tool in it becomes callable under the toolbox `<toolbox>.<tool>`, and is a shell command, `zero <toolbox> <tool> <args>`; `guides core/tools`, "A tool's command line", covers its flags, paths, `render.luau` and exit status. ## When to group tools together When creating tools for the engine, a common theme should be identified and and a toolbox created to house them, this allows each individual operation to be easily accessible instead of being scattered in a million places. ## Sharing functionality between tools A toolbox features ability to define functions that code inside each individual tool inside it can access, this is usefull when establishing helpers etc so you dont have to duplicate code for each new tool you write. A `shared.module` inside the toolbox root is where this code lives, each tool inside a toolbox can access its functions by requiring it with `require(".shared")`. ```luau -- <toolbox>.toolbox/shared.module/init.luau local M = {} -- One step a tool reports in its result. export type Step = { name: string, ok: boolean, detail: string? } --!desc Check that a numeric argument lies within bounds. --!arg arg The argument's name, for the error. --!arg value The value passed. --!arg min The lowest value allowed. --!arg max The highest value allowed. --!return The value; raises naming the argument and the range when it lies outside. --!example "count", 12, 1, 100 typed function M.range(arg: string, value: number, min: number, max: number): number if value < min or value > max then error(string.format("%s must be between %s and %s, got %s", arg, tostring(min), tostring(max), tostring(value))) end return value end --!desc A byte count as a readable size. --!arg bytes The count. --!return The size in B, KB, MB or GB. --!example 2681107 typed function M.size(bytes: number): string local units = { "B", "KB", "MB", "GB" } local i = 1 while bytes >= 1024 and i < #units do bytes /= 1024 i += 1 end return if i == 1 then string.format("%d %s", bytes, units[i]) else string.format("%.1f %s", bytes, units[i]) end --!desc A step for a tool's result. --!arg name What the step did. --!arg ok Whether it succeeded. --!arg detail What happened, when there is more to say. --!return The step. --!example "copy textures", true typed function M.step(name: string, ok: boolean, detail: string?): Step return { name = name, ok = ok, detail = detail } end --!desc The asset of `kind` that a caller named, looked up by that name. --!arg kind The asset type to look in. --!arg name The name the caller passed. --!return The asset; raises naming the kind and name when nothing matches. --!example "material", "gold" typed function M.named(kind: string, name: string): AssetRef local ref = asset.tryResolve(name, kind) if ref == nil then error(string.format("no %s named '%s'", kind, name)) end return ref end return M ``` This shared code should be limited to being used by the tools inside it, dont put general functionality you might need otuside the toolbox into its shared module. Instead reference those in the shared module should you wish to utilize something. A benefit the shared module shares with the tools own code is that it allows the author to write code that has computed references, meaning eg resolving an asset from a computed variable `asset.resolve(<type>,name)` that is normally not allowed in other parts of the engine surface, due to said references not being recorded. This is usefully for utilizing tools to handle operations that are called by users/agents and are dynamic in nature, such as finding/inspecting/testing assets, or content based on an input etc. When writing a shared module, you should follow standard module practices, please see `module.assetType` readme.md for more indepth information. ## Describing the toolbox When writing the readme for your toolbox, ensure you focus on the overall area what the toolbox focuses on, rather than listing individual tools inside it, discovery surfcaces already group tools and toolboxes together so a toolbox can be discoverd by the tools it hosts and doesnt require separately maintaining a list of the tools in it's readme. ## What are tools and when do i create ones? Tools are typed operations with a known serialized output format, made to enable efficient operation in the engine and provide an easily callable interface for operations around a topic. They are also useful in that they can be called from a multitude of surfaces, from `execute`, to `bash` to `tool_exec` to users Tools portion in the edui. A toolbox and its tools differ from eg a module that has multiple callable functionm in that they might return anything, and come with no guarantee that the output is meant to be inspected directly, where as tools are meant to perform an self contained operation and return results/info/relevant data in a readable format, including eg. image data. Whenever you identify an operation that requires specific orchestration and or is something that could be a repeated operation and makes it easier to manage the project/task or when you want to expose logic written in `luau` to the other call surfaces like `bash` under its `zero` command,you should reach for creating a toolbox. Toolboxes also come in handy for limiting control/inputs, exposing a limited set of functionality in a clean manner or ensuring the caller doesnt have to understand the entire code. For comparison, you could think of toolboxes as programs, and the tools inside them as commands. A package might contain tens of tousands of lines of code, dozens of modules, components etc, a toolbox turns that surface into a system that any agent/user can then utilize without having to read or understand the code inside. Its the UI equilevant to operations. For the indepth explanation of what `tool.assetType` is and does, read it's readme.
▲ 0↑ born
·
assettype · born here
❒asset
# tool (asset type) A tool is one named operation: a single luau `typed function` inside a toolboxe's `<name>.tool` asset, callable as `<toolbox>.<tool>`. The function's signature is the tool's interface, so anyone can call it correctly without reading its code. A tool is also a shell command, `zero <toolbox> <tool> <args>`; `guides core/tools`, "A tool's command line", covers its flags, paths, `render.luau` and exit status. Each tool has a declared input shape and return shape; the engine wraps each call's result in an envelope. ## Why use a tool? Tools are typed operations with a known serialized output format, made to enable efficient operation in the engine and provide an easily callable interface for operations around a topic. They are also useful in that they can be called from a multitude of surfaces, from `execute`, to `bash` to `tool_exec` to users Tools portion in the edui. Compared to say a `module.assetType`, that might contain multiple functions with varying shapes, experct references or specific formats of tables as input and could return potentially anyting including flat tables. that has multiple callable functionm in that they might return anything a tool is meant to be called with a serialized value, and return a serialized value. A tool is meant to perform an self contained operation and return results/info/relevant data in a readable format, including eg. image data. Whenever you identify an operation that requires specific orchestration and or is something that could be a repeated operation and makes it easier to manage the project/task or when you want to expose logic written in `luau` to the other call surfaces like `bash` under its `zero` command, it propably should be a `<name>.tool` asset. ## How tools are written In its simplicity, a tool is a single Typed luau function that returns a value. written plainly, in its basic form it could look like this. ```luau -- probe.toolbox/onCall.tool -- -- Fire when a named function runs, seeing its arguments and what it returned. --- A toolbox offered shared module, that in this case,contains a type shared by the tools in their toolbox. local shared = require(".shared") local M = {} export type OnCallResult = { ok: boolean, id: string?, result: string?, error: string?, } --!desc example tool --!arg path target path for the operation --!arg opts `{ notice, when?, run?, capture?, label?, limit?, cooldown?, freeze?, silent? }`. -- `capture` is Luau, compiled against the hit's context the way `run` -- is, that returns a picture for the hit — a capture tool you aim: -- `return tools.use("capture", "fromEntity", { entity = entity })`. It -- runs once the hit is recorded, and the hit's notice then carries the -- picture under `shot`, delivered as a picture. --!return `{ ok, id, result }`. --!example "arg1", arg2 typed function M.gatherResults(path: string, opts: shared.ArmOpts): OnCallResult local modulePath, key = splitPath(path) --- the tool code implementation local results = myCodeResults --- the tool call returns a table with keys, that is then wrapped in a return envelope. return { ok = true, id = results.id, result = results.gathered } end return M ``` Now when called, the tool runs and returns the envelope with the inspectable results. ## Why return plainly, and fail by raising Every caller gets a tool's outcome in the same form, success or failure, so return the value itself and raise an error when the tool can't do its job. A tool that returns its own `{ ok = false }` reads as a success that happened to return that table. Make the error say what to do instead: the caller reads it and acts on it. ## What the shell prints `zero <toolbox> <tool>` prints the text the tool's `render.luau` states: a module in the tool's folder returning one function `(result) -> string | { out, err?, exit? }`. A returned string is the output, and `{ out, err?, exit? }` sets the output, the standard error text and the exit status. A call that raises exits 1, and a command line the shell cannot bind to the tool's parameters exits 2. ## When to answer later instead of blocking A caller waits for the tool to return, and might be calling multiple tools at the same time. Should your call run past the waiting threshold in order to return, even if it yields it comes back as a handle to a background task that will then complete on its own, but require the caller to separately read the task results. For a call that is small, answering inline with the result is better. When a tool can tell that this particular call will be long (a big bake, a large batch, a slow fetch), it hands itself to the background with `task.background()` early, so the caller gets the handle at once and carries on with other work. ## When to post a notice The return value is the answer to what was asked. A notice is for what the caller needs to know besides that: a side effect it didn't ask for, a return to one that has no caller, notices should be treated as a way to make sure your tool can return quickly, when you arent sure how long it takes for the results to be ready. It allows the agent to continue working, and then react when the notice fires. `notices.post` delivers it to the caller, and an agent that is idle is woken by it, so the caller learns it without polling. Name in it what to do about it. A notice for something the return value already says is noise. ## Returning more than text Tools also support returning images, that the agent can then directly read from the tool response, regardles of what surface they used to call the tool. Images also work on notices, so you can eg attach visual results to the eventual outcomes of your tool results and the agent will see them the second the notice fires. ## What a tool may do that other code may not A tool, and code only tools call, may act on whatever an input names, resolving an asset by a name that only arrives with the call. That is what makes a tool the place for operations that depend on what they are given. Tools are for working on a world rather than running in the game: a component may not call one unless it declares `declare { componentSafe = true }`, and a tool doesn't call another tool, so logic several tools need goes in the toolbox's shared module or exist elsewhere. For information how to group tools and organize them, and how they are called read `toolbox.assetType` readme. ## In the Inspector Tool: how the tool is called (its signature), what it does, each argument, what it returns, and its examples, with **Open** for its source.
▲ 0↑ born
·
assettype · born here
❒asset
# Module (asset type) A module is a reusable, stateless (or globally-stateful) Luau library that other code pulls in with `require()`. Modules are the unit of factored-out logic in a world: helpers, math libraries, format parsers, registries, shared algorithms. ## When to use one - You have logic you want to share across multiple components, services, scenes, or tools. - You have a registry, lookup table, or shared cache that callers all read from / write to. - You want a stable API surface (`M.fn`) other code can depend on. If the logic is bound to one entity, use a `.component`. If you want a named UI of fields rather than functions, use a `.preset`. ## Where it lives - Source: `/zero/source/.../<name>.module/` - Identity: the source path with `/` written as `.` and each segment's type suffix dropped — `/zero/source/demo/beats.module` is `demo.beats`, and `/zero/source/kit.package/beats.module` is `kit.beats`, the container's name kept and its `.package` suffix gone. `asset.create` returns this string, `asset.resolve(...).identity` reads it back, and the `require` forms below write it as `<identity>`. - Folder shape: - `init.luau` (or `init.lua`) — module body. **Required.** Returns a table (conventionally named `M`). - `README.md` — instance-level documentation. **Required.** - `.metadata` — agent-editable tags + free-form fields. **Required.** ## How to create one ```luau asset.create("module", "<name>") -- Creates: /zero/source/<name>.module/ -- init.luau (canonical `local M = {} … return M`) -- README.md (instance README template) -- `folder` places it in a subfolder of /source, and that subfolder -- leads the identity: `{ folder = "lib" }` produces `lib.<name>`. -- `into` authors it inside a resolved container (a package, a toolbox), -- whose own identity leads the same way: asset.create("module", "<name>", { folder = "lib" }) asset.create("module", "<name>", { into = asset.resolve("myPkg.package") }) ``` ## How it operates 1. **Registration.** Writing `init.luau` into a `.module/` folder indexes the asset and registers the module path with the resolver. 2. **Loading.** The first `require("<identity>")` runs the file's body and caches the returned table. Subsequent requires from anywhere return the **same table** — this is the shared-state lever for "module-local" registries. The body runs in an environment of the module's own: a name it declares without `local` is readable by the module's own functions and by no other script, so an export reaches its callers through the returned table and nothing else. Requiring a component's folder runs its chunk the same way, once, and its `update`, `start` and `public` stay in that environment; a component runs on an entity through `entity(id).component.add(name)`. 3. **Hot reload.** Editing the file re-runs the module body and folds what it returns into the table already loaded, so that table keeps its identity: a caller that captured it with `require` reads the new source's functions and values through the reference it already holds, and a later `require` returns that same table. A key the new source drops goes away; a key something set at runtime stays. The body's own `local`s start again from their initial values, so state that must outlive an edit lives in `modules.state()` (`guides { path: "core/scripting-and-tasks" }`). 4. **Identity resolution.** A module is reached by its `<identity>`, and where the caller lives decides which spelling of it resolves. For a module in a **world**, from a caller in that same world — another module, a component, a scene entrypoint, or an `execute` chunk: - `require("<identity>")` — the identity on its own, resolved against the caller's own root. It carries every folder segment, so a module created with `{ folder = "demo" }` is `require("demo.beats")`. - `require("@root::<identity>")` — the same root-relative resolution, written out. - `require(".sibling")` — a module in the same folder, by its bare name; `..name` steps up one folder, `...name` two. Logs, stack traces and hot-reload notices name that same module `@local.source.<identity>` — its key under the world source root. The `<identity>` tail of that key is the form above, so a trace reading `@local.source.demo.beats` is `require("demo.beats")`. For a module in a **library** — content under `/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's root from anywhere: `require("@builtin::modules.transform")`. Mounting a world as a library moves its files under such a root and flips the caller root to `@<lib>::`, which is what keeps the root-relative forms above resolving across the move. ## Discovery - `asset.list("module")` — every registered module. - `asset.inspect("<name>")` — public functions, source path, this type README. - `ls /zero/source/<name>.module` lists the files the folder holds. ## Authoring conventions - Return a single `M` table from `init.luau`. Top-level statements with side effects run on first require — useful for one-time initialization, dangerous if they touch the engine before it's ready. - Write exported functions as `typed function`, not `function`: the argument types are enforced at the call and the checker knows the signature, so a caller's mistake is reported where they made it. - Annotate exported functions with `--!desc` / `--!arg` / `--!return` / `--!example` so the LSP, `tools.list`, and `asset.inspect` surface them. A function with no `--!desc` is reachable only by someone already reading this file. - Declare a VALUE with `Field.<kind>(default, mode, description)`, and a table whose members are reached through a metatable with `--!members <TypeName>` — the latter gives the surface its accepted member set, its type, and its documentation from one table. See `guides { path: "core/authoring" }` for all four rules and `modules/api/engine/entity.module/members.module` for a worked member table. - Keep module state in module-local upvalues or in `modules.state()`. A name the body declares without `local` lives in the module's environment, which every run of the module shares: a function the previous run left in place reads what the reload assigned. Module-locals start again from their initial values with each hot reload; the table `modules.state()` returns is the same table on both sides of every reload. - Prefer focused modules over kitchen-sink modules. If two halves of a module have no shared state, split them. ## Common pitfalls - **Cyclic requires.** A `require` chain that loops will return the partial table (the half built before the cycle was detected). Design for one-way dependencies. - **Engine-time side effects.** Don't `entity.spawn` at module top-level — the engine may not be ready. Expose an `M.init` and call it from a scene entrypoint. - **Hot-reload + module-local cache.** A module that caches expensive computation in upvalues loses that cache on reload — fine for dev, but be aware in performance work. - **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical. - **Writing one while play runs.** A `/source` write made while play is running lands on the play shadow, and a guarded play-exit discards it unless it is kept. One `.module` write shadows `init.luau`, the `README.md` and the `.metadata` together. `vfs.write(path, bytes, { durable = true })` skips the shadow, and `vfs.promotePlayShadow` keeps what is already on it — the `core/vfs` guide has the model and what each route costs. ## Related types - `.component` — for entity-bound state + lifecycle hooks. - `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider. - `.tool` — for a single agent-callable function with a YAML schema. - `.package` — to group several modules + components + scenes into one shippable folder. ## In the Inspector Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
▲ 0↑ born
▣
module · born here
❒asset
# shared Cross-tool helpers for the [name] toolbox. Every tool inside the toolbox can pull these in with `require(".shared")`. Holds the small set of helpers that more than one tool needs: toolbox-wide parsers, validators, formatters or shared state. Per-tool implementation stays inside each `<x>.tool/init.luau`. ## Usage ```luau local shared = require(".shared") typed function M.someTool(id: string): { id: string } return { id = shared.normalizeId(id) } end ``` A tool returns its value, and `error(message)` fails it. The text `zero [name] <tool>` prints, the error text and the exit status are set by the tool's `render.luau`. ## Notes - Keep helpers pure where possible: no engine calls, no state, so they are safe to call from any context. - Per-tool implementations own their own `--!desc` / `--!arg` / `--!return` / `--!example` annotations.
▲ 0↑ born
·
assettype · born here
❒asset
# assetType (asset type) An asset type says what a kind of asset is: the files an asset of the kind is made of, the code that gives it behaviour, the interface a person uses to work with it, and how it is found, pictured and checked. A `<typename>.assetType/` folder declares a type called `<typename>`, and every `<name>.<typename>/` folder is an asset of it. `assetType` is itself a type, so a type is an asset like any other: it is created, versioned, installed and contributed the same way. ## Making a type `asset.create("assetType", "<typename>")` scaffolds a type. The type registers the moment its folder is written, anywhere under `/zero/source/`, and from then on `<name>.<typename>/` folders are its assets. An asset of a type that is not registered yet is not an asset, so make the type first. A type folder is a root: `~.x` in any file inside it names the type's own `x`, wherever the type is installed. Keep the type's whole implementation inside its folder and reach it that way. What a type folder must hold is set by this type's own `type.yaml`, the same way every type's `type.yaml` sets what its assets hold. `asset.validate` on a type reports anything missing, and the scaffold produces a folder that passes. ## What sets your type's schema (`type.yaml`) `type.yaml` is the structural contract every asset of the type is checked against. The keys below are the ones the engine reads; a key not listed here is ignored. | Key | What it controls | |---|---| | `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. | | `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. | | `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. | | `is_container` | Whether the suffix stays in the identities of what the asset holds. | | `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. | | `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. | | `is_text_default` | Whether the asset's files are text unless stated otherwise. | | `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. | | `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. | | `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. | | `files: { required, optional }` | The files an asset holds (below). | | `allow_unlisted` | `false` reports every file the type does not declare. | | `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. | | `settings:` | Typed per-asset settings (below). | | `inspector:` | The interface people use for the type and its assets (below). | | `preview:` | How an asset is pictured (below). | | `references:` | Names of other assets the type's files carry (below). | | `indexing:` | What search reads for each asset (below). | | `describe:` | How a missing description is generated (below). | ### The files an asset holds Each entry under `files.required` or `files.optional` is `{ path, kind: file | folder, one_of_group?, content? }`. `*` in a path matches within one segment. Entries that share a `one_of_group` are satisfied by any one of them. `content` lists checks on the file's bytes: | Check | Passes when | |---|---| | `non_empty` | the file has content | | `json_field { key, type?, non_empty?, accept? }` | the JSON holds the key (a dotted path) with that shape | | `yaml_field { key, type?, non_empty?, accept? }` | the same for YAML | | `described { keys?, headings?, message? }` | the file says what the asset is (see "Ask your assets to say what they are") | Each check takes a `message`, which is what the author is told when it fails. ### Settings `settings: { values, schema: { type | instance, export? } }` gives every asset typed settings. `values` names the file an asset's values live in; `schema.type` declares one schema for the whole type, and `schema.instance` names a file each asset declares its own in. `asset.create` writes the resolved values, and a write to the values file reaches `onChange` with what changed. ## The human side (`inspector.luau`) A type is used by people through its Inspector, and without one the type is usable only from code. The Inspector is the type's interface for a person: for a procedural graph it is the graph editor, for a kit it is the tracking view of what the kit holds and what is still missing. Writing it is part of writing the type. `inspector: { type, instance? }` in `type.yaml` names the files. `type` is the interface for the type itself and for its assets; `instance` names a file an asset may ship to add its own. Each returns: ```luau return { sections = { { id = "graph", title = "Graph", build = function(ctx) ... end } }, replace = { contents = { ... } }, -- replace a default section by id order = { "graph", "contents" }, -- section order } ``` `build(ctx)` receives the asset and builds the section. A section's `title`, and the text its rows carry, is a string or an `i18n.text` value read from a catalog (`i18n.text("inspectors.mesh.title")`), which follows the editor's language. `asset.create("assetType", ...)` scaffolds a working `inspector.luau` to start from. `asset.validate` on a type that names no inspector, or names one that does not load, reports it. ## Say what your type is for (`about.yaml`) Every type carries an `about.yaml` that says what the type is for, in three plain-language texts: ```yaml intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering." function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text." usage: "You choose it by name for your UI or your text, and the text appears in that typeface." ``` - **`intent`** is what the type is for in someone's game, in the words a game maker uses. Up to 800 bytes. - **`function`** is how it works today: what an asset of it is made of and what the engine does with it. Up to 1500 bytes. - **`usage`** is what a person or an agent does with one. Up to 1200 bytes. Write about the type as a whole, not one asset of it, and say what it does now. Agents read these texts to learn when to reach for the type and how; people searching find the type by them. The scaffold starts each text with `[[describe]]` and a note on what to write; a text that still starts that way counts as not written. `services describe` can write them. They show up in `asset.inspect` as `detail.about`, in `assetTypeRef:getAbout()`, at the end of the type's `types/<typename>` guide, and at the top of the type's Inspector. ## Ask your assets to say what they are A type can require each asset to carry a description: a file, written by the author or generated, saying what the asset is and what it is for. Declare it with a `described` check: ```yaml files: required: - path: "README.md" kind: "file" content: - { check: "described", message: "Say what this widget is for and where it goes." } ``` A file that is missing, empty or still has a line starting with `[[describe]]` fails the check, and so does a YAML file whose named `keys` are missing or over their `max_bytes`, or a Markdown file missing a named heading. `asset.validate` names the asset, and a push that carries it is refused with `message`. `services describe` finds such assets and writes their descriptions. `describe:` steers what is generated: ```yaml describe: guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI." examples: - "<identity of an asset of this type whose description reads well>" ``` An example is an asset of your type whose description is a true, written one, never a placeholder and never the asset being described; with none, leave `examples` empty. A type whose assets the model cannot perceive (a sound, a motion) says so in `guidance`, and the description is drawn only from what the asset's own files state. Start the file unwritten in your `template/`: a heading and one line starting with `[[describe]]`, never example content, which every new asset would carry verbatim. A type whose assets say what they are through their own content (a mesh, a texture) declares no check. ## The type's code (`behavior.luau`) `behavior.luau` returns one table. These are the keys the engine reads from it; anything else on the table is the type's own. ### What the type's assets can do | Key | Shape | What the engine does with it | |---|---|---| | `ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every asset of the type: `ref:name(...)`. | | `modules` | `{ [name] = require(".x") }` | Code the type's assets reach with `asset.containing(__FILE__).modules.<name>`. | | `events` | an events schema | Events an asset fires. Readers subscribe through `ref.events.<name>:connect(...)`; the type fires them. | | `refShapes` | `{ [method] = function(self) -> (typeExpr, source?) }` | The result type of a `ref` method for one particular asset (below). | | `namePattern` | a Lua pattern | The names `asset.create` accepts for the type's assets. Default `^[A-Za-z][A-Za-z0-9_]*$`. | | `derive` | `{ output, module, compute, fingerprint, matches?, required?, timeout? }` | A file computed from the asset when it is committed; a `required` one holds the commit until it lands. | Some `ref` names mean the same for every type, and the engine calls them: - **`instantiate(self, target?, opts?) -> (root, idMap)`**: puts the asset in a scene. Defining it is what makes the type scene-instantiable. Its return is a contract (below). - **`inspect(self) -> detail`**: what `asset.inspect` reports for the asset beyond the common record (below). - **`preview(self, opts)`**: renders the asset's picture; it wins over the type's `preview:` recipe. - **`previewMaterial(self) -> { material }`**: the material a `surface` preview paints. - **`saveDefinition(self)`**: writes the asset's in-memory edits back to its files in edit mode. Some names are answered for every asset before the type is asked, so a `ref` entry of the same name is never reached: `getSource`, `getBytes`, `getText`, `exists`, `deps`, `canInstantiate`, `canPreview`, `preview` (which calls yours when you define one), `meta`, `runtime`, `events`, `typeRef`, `modules`, and the residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`, `gpu_resident`. ### When the engine calls the type | Hook | Signature | When it runs | |---|---|---| | `onCreate` | `(name, opts) -> { [path] = contents }` | On `asset.create`. Returns the files of the new asset, laid over the type's `template/`. Annotate `opts`: its type is the schema `asset.create` checks the caller's arguments against. A `""` key writes a single loose file. | | `onReplace` | `(dest, files) -> files` | On an `asset.create` over an asset already at `dest`, after `onCreate`, so what the author added can be carried into the replacement. | | `onRegister` | `(self)` | Once per asset, when it first registers: when the world loads, on a live `asset.create`, and when an asset arrives later (installed, pulled, synced). This is what makes an asset take effect the moment it is written. | | `onChange` | `(ref, change)` | On every write to a file inside an asset of the type. `change` is `{ path, asset, type, kind, origin }`, plus `settings` and `settingsChanged` for a write to the settings values file; `kind` is `edited` or `seeded`, `origin` is `local` or `remote`. Filter on `change.path`. Writes to one asset arrive in order, each after the hook for the one before has finished, and the hook may wait on what it reads. A write the hook makes inside its own asset arrives later like any other, so keep the hook convergent. | | `onDependencyChange` | `(ref, change)` | When a module the asset's code requires is re-run, or a name the asset carries starts resolving. `change.kind` is `dependency`. | | `onDelete` | `(ref)` | When an asset of the type leaves the world: deleted, or the world it is in is swapped away. | | `validate` | `(ref) -> { { code, message, severity?, path? } }` | On `asset.validate`, after the `type.yaml` checks, for the type's own rules. `severity` defaults to `error`. Runs on every push, so a type's rules hold at publish. A hook that fails reports `validate.hook_failed`. | ### Settings hooks | Hook | When it runs | |---|---| | `settingsDefaults(name, opts, asked) -> table` | Once per `asset.create`, for values the schema's defaults do not give. | | `settingsCorrections(values, name, opts) -> (corrections?, reasons?)` | On every settings write. A correction to a field the writer named refuses the write, giving the reason. | | `settingsDerivedDefaults(values, explicit, changed)` | On a settings write, for fields derived from others. | | `normalizeSettings(values, stored?)` | On every read and write, to map an earlier spelling of a field to the current one. | | `settingsHealed(values, stored)` | On a read, to repair stored values. | | `settingsSchemaProblem(schema, ref) -> string?` | When an asset's own schema is read; a returned string refuses the schema. | `creationInputs` (`{ [opt] = true | selectorOpt }`) names `asset.create` options that are inputs to the type rather than settings. ### Reloading An edit to `behavior.luau` reaches existing assets with no restart. ## How an asset is pictured (`preview:`) | `kind` | The picture is | The type provides | |---|---|---| | `instantiate` | the asset placed in the preview studio through its `instantiate` | `ref.instantiate` | | `image` | a file the asset holds, fitted to the frame | `source: { files }`, the candidate files in order | | `surface` | the asset painted on a mesh | `mesh`, and `ref.previewMaterial` | | `custom` | whatever `ref.preview` returns | `ref.preview` | ```yaml preview: kind: surface mesh: sphere ``` `angle: [yaw, pitch]` turns the camera. The studio owns the light, the backdrop and the framing, so an asset pictures the same in every world. A type with no `preview:` that defines `instantiate` still answers `ref:preview()`. A picture is rendered when something asks to view it (the editor showing the asset, `ref:preview()`), when previews are generated on request (`assets.generatePreviews`), and when the asset is staged. An edit alone renders nothing. The picture records what it was made from, so a stale one is told from a current one. ## The names your type's assets hold (`references:`) Where your type's own format or API carries the name of another asset, declare it here: ```yaml references: keys: # a top-level key of the type's files that holds a name, or a table of them - { key: "shader", type: "shader" } args: # an argument of a call, counting from 1 - { call: "g:node", position: 2, type: "procNode" } fields: # a field of the options table a call takes - { call: "fx.beam", field: "material", type: "material" } ``` `type` is the category the name resolves in. `asset.declareReferenceKey`, `asset.declareReferenceArg` and `asset.declareReferenceField` declare the same from a script. ## What search reads (`indexing:`) `indexing:` is how assets are found. Search reaches an asset only through what its type's `indexing:` names, and adds nothing of its own. That includes you: an asset indexed badly is one you cannot find later, when you are making something else and need it. A type whose assets are never looked for says `indexing: none`. ```yaml indexing: data: # text, read from the asset's files - role: identity extractor: verbatim source: { file: "README.md" } - role: interface extractor: symbols source: { files: ["init.luau"] } - role: implementation extractor: verbatim source: { files: ["init.luau"] } content: # the picture - role: identity modality: image source: { file: "preview.png" } facets: # what a query filters and re-ranks by file: ".metadata" rigged: { type: bool, from: { components: { contains: SkinnedModel } } } roughness: { type: number, filter: range, from: { file: "mat.yaml", field: "floats.roughness" } } ``` **Roles.** Each `data` and `content` entry has a `role`, and a query matches in two slots: - **`identity`**: what an asset is. For anything you look at, the picture; for anything else, the text that says what it is. - **`capability`**: what it does and how it is made. `interface` (the signatures or shape a caller uses) and `implementation` (the body) both count as capability, and a type with code usually declares both. Ask what a person would recognise an asset of the type by, and what it does, and point each role at the file that says it. For text, that is the asset's description: the file your template starts with a `[[describe]]` block, which the author writes or `services describe` fills in (see "Ask your assets to say what they are"). **`data`.** `extractor: verbatim` embeds a file's text as it is; `symbols` embeds the declared signatures of code. `source` is `{ file }` or `{ files: [...] }`. Never index a file name (`source: { field: name }`): one or two words carry nothing to match. **`content`.** `modality: image` embeds the picture itself, so a text query matches what the asset looks like. A type whose assets are looked at makes the picture its identity. **`facets`.** What a query narrows and re-ranks the matches by. `file` is embedded whole, so keys nobody declared in it are still found. Each further key is computed for every asset and states a value for every one, including `false`: a file can imply "not rigged" but never say it, and a query separates rigged from unrigged only because the unrigged ones say `rigged: false`. A key is `{ type: bool | number | enum, filter?: range, from }`, where `from` is `{ file, field }` (a field of one of the asset's files, dotted for nesting), `{ metadata: key }`, or `{ components: { contains | any_outside } }` (what the asset's entities carry). ## What blocks a push A push checks every asset it carries against its type. These refuse it: - a required file that is missing, a `content` check that fails, a `described` file not written yet; - an error from the type's `validate`. Unlisted files and warnings do not. A `described` file blocks only a push that changes the asset. When a push is refused, the message names each asset and what it lacks. `world.publishBlockers()` and `zm status` read the same list without pushing. ## Typing a result from the asset (`refShapes`) A `ref` method whose result depends on the asset (one entry per child folder, per row of a config, per control a map declares) can only be annotated as `{ [string]: Thing }`, which accepts any key. `refShapes` states the result for each asset instead: a function returning a Luau type expression for that asset, and the module whose types the expression uses. Read the asset; never run it. ```lua -- inputMap.assetType/behavior.luau M.refShapes = { activate = function(self): (string, string) local names = {} for _, control in ipairs(M.ref.controls(self)) do table.insert(names, control.name .. ": Handle") end if #names == 0 then return "", "" end return "{ " .. table.concat(names, ", ") .. " }", "@builtin::modules.zinput.scheme" end, } ``` With it, `map.jump:onPressed(fn)` is checked and `map.noexisting` is reported. A per-asset type applies where the call site names which asset: a component field whose default names it, or an annotation `AssetRef<"inputMap", "<identity>">`. `asset.resolve(name, category)` carries only the category, and a name computed at runtime carries nothing, so calls on those keep the declared return. The type belongs to the call's result: index it there, or bind what you need from it there, and the names stay checked. `require("@builtin::assetTypes.assetType.shared.refShapes").published()` shows what was published: `categories` (each type's method surface) and `returns` (per-asset results by identity, then method). An identity missing from `returns` was never published. Results are recomputed when an asset is written; at most 64 assets of one type are read. ## Putting an asset in a scene (`ref.instantiate`) A caller writes one piece of code against every instantiable type, so what `instantiate` returns is fixed: ```lua local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable") M.ref = { instantiate = function(self, target, opts) local root = Instantiable.root(self, target, opts) -- compose the asset under `root`, now return Instantiable.result(self, root, idMap) end, } ``` **In.** `target` is the entity the asset lands under, or onto for a hierarchy type; with none, the type spawns a new root. `position`, `rotation` (three numbers in degrees, or a quaternion), `scale`, `name` and `temporary` mean the same for every type: `Instantiable.root` applies them to a root you make, `Instantiable.place` to one you adopt. Document any options of your own in the hook's `--!arg` docs. **Out.** `(root, idMap)`. `root` is the composed root, live when you return: build synchronously, never defer to a component's `awake`. `idMap` maps each original id to the spawned one, so a component that composes the asset again on every load can pass it back in and keep references into the composition. Every call goes through `Instantiable.result`, which refuses a root that is not live and turns a missing `idMap` into `{}`. ## Inspecting an asset (`ref.inspect`) `asset.inspect(ref)` builds a record every asset shares (`identity`, `name`, `guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`, `description`, `tags`), then calls `ref.inspect(self)` for the type's own `detail`: ```lua M.ref = { inspect = function(self) -- read the asset's own files, never runtime state: inspect works on an asset -- that has not been compiled, uploaded or registered return { --[[ what makes this asset what it is ]] } end, } ``` Without it, the record is the shared part alone, and an agent inspecting the asset learns nothing of what it is. A hook that raises leaves `detail` empty and sets `record.warning`. ## Discovery - `asset.list("assetType")`: every registered type. - `asset.inspect("<typename>")`: the type, its README and its `about.yaml` texts. - `asset.resolve("<typename>", "assetType")`: the type itself.
▲ 0↑ born
❒
package · born here
❒asset
# reflections system Screen-space reflections — a polished floor reflects what stands on it, wet ground reflects what is above it, and metal picks up its surroundings, all from geometry the camera can already see. Environment reflections describe a surface's surroundings in general. They cannot show the character walking across the floor, because that character is not in the environment — it arrived this frame. Screen-space reflections read the frame the engine has just drawn, so anything visible can appear in anything reflective, with nothing authored per surface. What that buys and what it costs are the same thing: only what is **on screen** can be reflected. A reflection of something behind the camera, or off the edge of the frame, is not there to find. So reflections fade out toward the screen edge rather than cutting off, and where a ray finds nothing the surface keeps the shading it already had. ## Using it Reflections are a render feature. List it on the scene's `RenderFeatures` entity with the settings it should run under, and it persists with the scene: ```lua local id = entity.spawn("render features").id entity(id).component.add("RenderFeatures", { features = { { feature = "@builtin::systems.reflections.ssr", settings = { intensity = 1.0, -- how much of the reflection reaches the image maxDistance = 40, -- how far a reflection ray travels, world units quality = "auto", -- low | medium | high | ultra, or auto (the device's tier) } }, }, }) ``` Every setting is live: edit one in the inspector and the reflections follow. `renderer.feature.schema("@builtin::systems.reflections.ssr")` lists every knob with its default. For code that adjusts reflections at runtime — a quality slider, a cutscene, weather turning pavement wet — the module is the hand on the same knobs: ```lua local ssr = require("@builtin::systems.reflections.ssr") ssr.set({ intensity = 0.6, quality = "medium" }) -- any subset; the rest is kept ssr.get() -- the settings in force ssr.active() -- are the passes running ssr.clear() -- the passes down ``` `set` brings the feature up when none is live, and an `intensity` of 0 takes it down; the same feature is found rather than stacked when `RenderFeatures` already runs it. ## What the knobs do | field | effect | |---|---| | `intensity` | How much of the reflection reaches the image, in [0, 1]. 0 turns reflections off and releases the passes. | | `maxDistance` | How far a reflection ray travels, in world units. | | `thickness` | How thick a surface is assumed to be, in world units. A ray passing behind one by more than this went past it rather than onto it. | | `roughnessCutoff` | Perceptual roughness up to which a surface takes the full screen-space reflection. Above it the reflection hands over to the probes and the sky, and is gone 0.1 higher. | | `quality` | `low` / `medium` / `high` / `ultra` — how many steps the march spends and how many neighbouring rays a pixel gathers — or `auto` (the default), which follows the device's quality tier (`renderer.qualityTier()`): `high` on a desktop, `medium` on a handheld and at the medium tier, `low` at the low tier. `ssr.drawn()` reports the level in force and the sampling it spends. | | `edgeFade` | How far from the edge of the screen reflections fade out, in UV. | `roughnessCutoff` is the one to understand first. Every pixel traces one ray drawn from the lobe its roughness describes, and gathers the rays of its neighbours that stand on the same surface, so a rough floor shows a bright sign as the soft, stretched streak its lobe spreads the sign into, and a mirror shows it sharp. Up to the cutoff a surface takes the full screen-space reflection. Above it the reflection hands over to the probes and the sky, and it is gone 0.1 higher, so the hand-over has a soft edge in place of a line. The default, 0.75, covers wet asphalt and polished stone. A scene that states a lower cutoff (0.4 was the old default) leaves those surfaces to the probes. Where the screen holds only part of a surface's lobe (the lobe reaches off the edge of the frame, or behind the camera) the reflection covers the part it found and the probe or sky fills the rest. `maxDistance` and `quality` trade against each other: quality sets the step count, so a long distance at a low quality samples coarsely and reflections thin out at range. They thin rather than disappear because the hit refinement adapts to the step size on its own. How much of a reflection shows through is the surface's own Fresnel term, taken from the G-buffer's metallic. Metal takes nearly all of it; a dielectric floor takes a few percent head-on and much more at a grazing angle — which is why a wet road reads dry underfoot and mirror-like down the street. ## How it renders `ssr.renderFeature` runs two compute passes at the `afterDepthPrepass` seam, before anything shades. `ssr_trace` draws one ray per pixel from the pixel's GGX lobe (a visible-normal sample; a mirror, below roughness 0.1, keeps its one reflection ray) and marches it against this frame's depth. The surface's normal and roughness come from the G-buffer as the previous frame left them, reprojected through the previous view-projection. The pass writes where each ray hit and how confident the hit is, or the direction it travelled when it found nothing. A rough pixel's ray marches fewer steps, because the next pass blurs what the rays find. `ssr_resolve` gathers each pixel's lobe over its own ray and the rays of up to twelve neighbours (4 at `low` and `medium`, 8 at `high`, 12 at `ultra`), weighing every ray against the pixel's own lobe and counting a neighbour only where it shows the same surface. The light at a hit is read from the colour the previous frame ended with, where the hit stood then. The resolve accumulates the result over frames in a history target (one image pair per view), holds that history to the spread of the rays it gathered, and writes the scene's reflection channel, `@scene.reflection`: the light of the rays that found something on screen, and the share of the lobe those rays cover. A material reads that channel the same frame, at its own pixel, inside its environment term: it mixes the traced light over the probe and the sky by the share of the lobe the screen answered, so what the screen did not find comes from the environment, and the material's Fresnel, roughness and tint weigh the result into the pixel as they weigh any environment. The reflection stands where the camera is now; only the light in it is a frame old. The `reflection` capture pass shows it. Where the trace found nothing the channel holds zero and the material reflects its environment alone. A blended material (a `blend` other than `opaque` or `cutout`) reads none of the channel. It draws over the depth the trace ran against, so the channel at its pixel holds the reflection traced for the opaque surface behind it. A blended pane of glass reflects its environment, or the reflection its shader traces for itself through `@builtin::shaderModules.screenReflection`. A camera drawing a diagnostic pass holds readings in its colour target rather than light, so the passes have no light to read from that frame: such a frame is drawn lit first, unpresented, the passes run for that, and the diagnostic reads the channel gathered for where the camera stands now. A capture drawn once, or a camera drawn again from a new station, is drawn lit first for the same reason, so its first frame holds a reflection (without accumulated history, so it shows more grain than a continuously drawn view). The march steps uniformly in screen space and compares in world space; the full account, including why thickness is tested after refinement rather than during the march, is in the render feature's own readme. Each view that draws the feature holds three screen-sized images of its own: the rays and the history pair, about 50 MB at 1080p for the viewport. The pass takes its camera from `@frame.camera`, so reflections are correct in offscreen captures and render-to-texture cameras, not only the live viewport. ## The demo scene The scene `@builtin::systems.reflections.demo.polished_floor`, loaded with the `scene.load` tool, is a polished stone floor with three coloured pillars standing on it, under an afternoon sky, with the feature listed on the scene's `render_features` entity. The floor reflects the pillars and a player walking across it; delete the entity and it mirrors the sky alone. `demo/polished_floor.scene/build.luau` is the whole scene as code, materials included. ## Files ``` reflections.package/ ssr.renderFeature/ -- the trace and resolve passes, and the settings they take ssr_trace.computeShader/ -- draws and marches one lobe-sampled ray per pixel ssr_resolve.computeShader/ -- gathers each pixel's lobe, accumulates, writes the reflection channel ssr.module/ -- ssr.set / .get / .clear / .active, the runtime hand on them ScreenSpaceReflections.component/ -- the older one-feature component; RenderFeatures is the list demo/polished_floor.scene/ -- the showcase: a polished floor, three pillars, the feature on one entity ```
▲ 0↑ born
❒
package · born here
❒asset
# volumetrics Volumetric (3D-texture) rendering, end to end, in one package. Built entirely on the engine's generic `compute.*` GPU primitives — no Rust changes are needed to author new volumetric content. ## Layout | Asset | Identity | Role | |---|---|---| | `Volume.component` | `@builtin::systems.volumetrics.Volume` | Attach a 3D voxel texture to an entity; stands it in the scene through the entity's transform AABB, hidden by what stands in front of it. | | `VolumetricSky.component` | `@builtin::systems.volumetrics.VolumetricSky` | Clouds in the sky: one per scene, the procedural cloud layer lit by the scene's sun (through the physical atmosphere's air and sky when a `PhysicalAtmosphere` stands in the scene), drawn by `volumetricSky.renderFeature` with no composite authored. | | `VolumetricLighting.component` | `@builtin::systems.volumetrics.VolumetricLighting` | Light shafts, god rays and glowing air: light scattering between the camera and the scene, drawn by `lightScattering.renderFeature`. | | `ParticipatingMedium.component` | `@builtin::systems.volumetrics.ParticipatingMedium` | Mark an entity as fog/smoke/dust the camera sees through and that shades the sun on what is under it. | | `Smoke.component` | `@builtin::systems.volumetrics.Smoke` | Smoke rising from the entity's position: a chimney's column, steam, a smoulder, a black column over a big fire, smoke signals; lit by the scene with a shadow of its own. | | `Fire.component` | `@builtin::systems.volumetrics.Fire` | Fire with its smoke at the entity's position: a campfire, a torch, a bonfire, a building on fire, an explosion's fireball; flames glow along a blackbody ramp and a flickering point light halfway up them lights the surroundings. | | `plume.module` | `@builtin::systems.volumetrics.plume` | The smoke and fire plumes `Smoke` and `Fire` hold, from a script: styles, sizes, quality levels; fills a volume each drawn frame and stands it with `Volume:draw`. | | `mediaTransmittance.module` | `@builtin::systems.volumetrics.mediaTransmittance` | The registry of media and the settings every media pass reads. | | `mediaShadow.renderFeature` | `@builtin::systems.volumetrics.mediaShadow` | Writes the sun the media take to `@scene.sunOcclusion` and marches each view ray through the media. | | `volume.module` | `@builtin::systems.volumetrics.volume` | Builders (`noise`/`sphere`/`box`/`wrap`) + the `.zvol` header reader + occupancy + brick paging + the per-entity raymarch dispatch + the draws standing in the scene (`Volume:draw`). | | `volume.renderFeature` | `@builtin::systems.volumetrics.volume` | Runs every standing draw's march and composite for each view the frame draws, against its camera and depth. | | `VolumeSequence.component` | `@builtin::systems.volumetrics.VolumeSequence` | Play an open volume sequence through an entity's transform AABB. | | `volumeSequence.module` | `@builtin::systems.volumetrics.volumeSequence` | A run of `.zvol` frames streamed through a fixed ring of resident volumes. | | `volumeDemos.module` | `@builtin::systems.volumetrics.volumeDemos` | Shared pipeline for the showcase scenes (fill + emissive raymarch + composite). | | `volumetricSky.module` | `@builtin::systems.volumetrics.volumetricSky` | The cloud layer: tiling noise, weather map, raymarch, TAA and composite orchestration. | | `volumetricSky.renderFeature` | `@builtin::systems.volumetrics.volumetricSky` | The cloud layer's passes for every view the frame draws, brought up by `VolumetricSky`. | | `volumetricLighting.module` | `@builtin::systems.volumetrics.volumetricLighting` | The light-scattering settings, set from code. | | `lightScattering.renderFeature` | `@builtin::systems.volumetrics.lightScattering` | The light-scattering passes, brought up by `VolumetricLighting`. | | `shaders/*` | `@builtin::systems.volumetrics.shaders.*` | Compute shaders `volume_raymarch`, `volume_draw`, `plume_fill`, `volume_pages`, `volume_pack`, `cloud_noise`, `cloud_weather`, `cloud_raymarch`, `cloud_taa`, `cloud_layer_surfaces`; shaders `volume_draw_composite`, `cloud_layer_composite`, `cloud_layer_blit`, `cloud_sky_composite`; shader modules `volume_march`, `cloud_light`, `cloud_surface`, `cloud_shell`. | | `importers/vdb_to_zvol.importer` | (auto-discovered) | `.vdb` → dense `.zvol` via the `openvdb` WASM plugin (procedural fallback when the plugin isn't loaded). | | `presets/cumulus_default.preset` | `@builtin::systems.volumetrics.cumulus_default` | Canonical full `VolumetricSky` weather preset. | | `demo/*.scene` | `@builtin::systems.volumetrics.demo.*` | `sdf_solids`, `smoke_plume`, `nebula`, `godrays`, `zvol_viewer`, `sky`, `showcase`, with their fill shaders. | The guide `systems/volumetrics/documentation/README` (`guides { path = ... }`) names the component for each effect, clouds, fog, light shafts, a fog or smoke volume and the sky, with what each does and costs. ## Path convention — fully-qualified builtin identities Every intra-package reference uses the asset's fully-qualified builtin identity, the same convention every other builtin package follows: ```luau local Volume = require("@builtin::systems.volumetrics.volume") local Sky = require("@builtin::systems.volumetrics.volumetricSky") local V = require("@builtin::systems.volumetrics.volumeDemos") -- shader identities, e.g. asset.resolve("@builtin::systems.volumetrics.shaders.volume_raymarch") ``` Qualified identities are caller-independent: they resolve identically from a module, a scene entrypoint, or a component. Caller-relative (`.sibling`) requires are deliberately avoided here because the component runtime caller identity is `@builtin::components.<Name>`, so a `.sibling` require from a component resolves against the wrong root. (An earlier revision of this package used a `~volumetrics` package-root alias for relocatability; that alias is not resolvable on current main, so the package uses qualified identities throughout.) ## Usage ```luau -- Per-entity volume. The component resolves the name through `Volume.get`, -- so a volume paged into a brick pool renders from the pool under the same -- name: local Volume = require("@builtin::systems.volumetrics.volume") local cloud = Volume.noise({ name = "cloud", size = 64, scale = 4 }) cloud:buildSparse({ brickSize = 8 }) cloud:releaseDense() entity(id).component.add("Volume", { volumeName = "cloud", density = 6.0 }) -- Procedural sky: local sky = entity.spawn("sky") sky.component.add("VolumetricSky", {}) preset.apply("cumulus_default", { entity = sky.id, component = "VolumetricSky" }) -- VDB import: drop a `.vdb` into the VFS; the importer writes a `.zvol` -- alongside it. Load it with the zvol_viewer demo scene. -- Animated run: one `.zvol` per frame, played through a bounded ring. local Seq = require("@builtin::systems.volumetrics.volumeSequence") Seq.open({ name = "plume", frames = framePaths, resident = 3, fps = 24 }) entity(id).component.add("VolumeSequence", { sequenceName = "plume", density = 6.0 }) ``` ## Plugin dependency The VDB importer delegates real OpenVDB parsing to the `openvdb` plugin in the builtin library, `@builtin::plugins.openvdb`. Without the plugin the importer falls back to a deterministic procedural torus so the pipeline stays functional.
▲ 0↑ born
❒
package · born here
❒asset
▲ 0↑ born
❒
package · born here
❒asset
# areaLights system Lights that emit from a surface rather than from a point. Every screen, neon sign, glowing window, ceiling panel and lantern face is an area emitter. Standing a point light in the middle of one gets the brightness roughly right and the character completely wrong: a point puts a pinpoint reflection on the floor and a radial falloff on the wall, where the real thing puts the shape of the emitter and a falloff that follows its extent. ## Using it An emitter that should follow an entity's face is a component: ```lua local id = entity.spawn("tv").id entity(id).component.add("SurfaceLight", { width = 2.0, height = 1.2, face = "front", -- front | back | up | down | left | right intensity = 6.0, range = 12, }) ``` The rectangle turns with the entity, so a tilted screen lights the direction it actually points. Every field is live, and an `intensity` of 0 removes the light. For code placing emitters directly: ```lua local surfaceLight = require("@builtin::systems.areaLights.surfaceLight") surfaceLight.set("strip", { position = { 0, 5, -12 }, right = { 1, 0, 0 }, up = { 0, 1, 0 }, width = 0.6, height = 7, color = { 1, 0.72, 0.35 }, intensity = 5, }) surfaceLight.remove("strip") surfaceLight.configure({ diffuse = 1, specular = 0.5 }) surfaceLight.clear() ``` ## What the knobs do | field | effect | |---|---| | `width` / `height` | Size of the emitting rectangle, world units. The shape of the light is the shape of this. | | `face` | Which way the entity emits. | | `range` | How far the light carries, with a smooth cutoff at the end. | | `intensity` | Brightness. 0 removes the light. | | `colorR` / `colorG` / `colorB` | Emitter colour. | | `offset` | Distance the rectangle sits proud of the entity's origin, along the face's normal. | | `diffuse` / `specular` | Scales on the two terms — the wash across a surface, and the reflected shape of the emitter. | Shape is the point. A wide panel puts a broad pool on the floor; a narrow strip puts a narrow elongated one. That difference is not reachable with a point light at any brightness. At most 32 emitters are held at once, because the shader loops every light for every pixel. ## How it renders `areaLighting.renderFeature` runs one compute pass after lighting. Diffuse is the exact irradiance of the quad — Lambert's formula over its four edges — which matters where a point approximation fails hardest: a wide emitter close to a wall. Specular uses the representative point on the rectangle nearest the reflection ray, with the lobe widened to cover the emitter's solid angle and its peak scaled down to match, so a large emitter reads broader rather than brighter. ## Files ``` areaLights.package/ SurfaceLight.component/ -- an emitter on an entity's face surfaceLight.module/ -- the emitter registry and scales areaLighting.renderFeature/ -- the compute pass ```
▲ 0↑ born
❒
package · born here
❒asset
# quickGeometry Model a scene in Luau with three.js-shaped code. A `build.luau` or a `.sceneModule` builds `Group`s and `Mesh`es from geometry constructors and materials; at the end of the build the tree is stored in the scene as data, drawn by one `Generator`, and nothing runs per frame. A bare box reads as a placeholder. Every geometry takes **modifiers** that turn it into a modelled shape: round its edges, taper it, bend it, drill it, smooth it, or build it from a profile or cross-sections. A build whose parts are mostly bare boxes and planes logs a warning that names them. ## Using it The nouns are globals in a scene's `build.luau` and a `.sceneModule`'s entry script: `sceneNouns` and `quickLighting` join both scripts' contexts, so the engine binds their exports when it loads the script, and the language server knows the same names. ```luau function content() local paint = MeshStandardMaterial({ color = "#b0332f", metalness = 0.45, roughness = 0.28 }) local steel = MeshStandardMaterial({ color = "#aab2ba", metalness = 1, roughness = 0.25 }) local body = Mesh(BoxGeometry(1, 1, 1):round(0.14), paint, "rounded_box") body.position:set(0, 0.8, 0) local block = Mesh(BoxGeometry(1.1, 1.1, 1.1):subtract(CylinderGeometry(0.3, 0.3, 2, 24)), steel, "drilled_block") block.position:set(1.5, 0.8, 0) local hull = Mesh(LoftGeometry({ { shape = EllipseShape(0.45, 0.28), z = -1.2, scale = 0.25 }, { shape = EllipseShape(0.45, 0.28), z = -0.55, scale = 0.95 }, { shape = EllipseShape(0.45, 0.28), z = 0.4, scale = 1.0 }, { shape = EllipseShape(0.45, 0.28), z = 1.2, scale = 0.3, offset = { y = -0.06 } }, }), paint, "hull") hull.position:set(3.2, 0.8, 0) end ``` The same code works in a `.sceneModule`'s builder, where `inputs` declare what a placement may set. A module joins those contexts with `--!context sceneBuild sceneModule` in its leading comment block, the way these two do. A world's own module joins the same way, and its exports become globals in every build script beside the nouns. A name that starts with `_` stays inside its module. A module that exports `_beginRun` and `_finish` has them called around every run of a build. The `script_context` module's README covers contexts in full. ## Parts - `Group(name)` holds other objects. `Mesh(geometry, material, name)` draws a geometry. - `object.position`, `object.rotation` (Euler angles in radians, XYZ) and `object.scale` take `.x`, `.y`, `.z` and the vector methods `set`, `setScalar`, `copy`, `add`, `sub`, `multiplyScalar`, `clone` and `toArray`; calls chain. - `parent:add(a, b, ...)` nests objects under another, and their poses are then in the parent's frame; an object added elsewhere moves. `parent:remove(a, ...)` takes them out, and a removed object is not drawn until it is added again. `object.parent` and `object.children` hold the tree. - `object.visible = false` leaves the object and everything under it out of the scene. `object.userData` is a table for your own values. - `object:lookAt(x, y, z)` or `object:lookAt(Vector3)` turns the object so its +Z axis points at a point in its parent's frame; the object's position and the point are numbers. - `object:clone(recursive)` copies the object, its pose, components and (unless `recursive` is false) what is under it; the copy shares the geometry and material and is placed like a new `Mesh`. `object:traverse(fn)` calls `fn` on the object and everything under it, and `object:getObjectByName(name)` finds one. - `object:addComponent(type, data)` puts an engine component on the entity a part becomes (`Physics`, a collider, a `Joint`). A part whose pose follows a formula is drawn as an instance and takes none. - An object that never moves and carries a component becomes an entity named for it, with its parent and local pose; one that never moves and carries none is folded into the object above it. A moving object's leaves are drawn as instances. ## Geometry | Constructor | Shape | |-------------|-------| | `BoxGeometry(width, height, depth)` | box | | `CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded)` | cylinder; a cone when one radius is 0 | | `ConeGeometry(radius, height, radialSegments, heightSegments, openEnded)` | cone with its apex up | | `SphereGeometry(radius, widthSegments, heightSegments)` | UV sphere | | `TorusGeometry(radius, tube, radialSegments, tubularSegments, arc)` | torus | | `TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q)` | torus knot | | `CapsuleGeometry(radius, length, capSegments, radialSegments)` | capsule | | `PlaneGeometry(width, height, widthSegments, heightSegments)` | flat rectangle | | `CircleGeometry(radius, segments)` | flat disc | | `RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength)` | flat annulus | | `TetrahedronGeometry`, `OctahedronGeometry`, `IcosahedronGeometry`, `DodecahedronGeometry` `(radius, detail)` | regular polyhedra; `detail` above 0 rounds them toward a sphere | | `LatheGeometry(points, segments)` | a profile of `{ x = radius, y }` points revolved around Y | | `ExtrudeGeometry(shape, { depth, curveSegments })` | an outline extruded along +Z | | `ShapeGeometry(shape, curveSegments)` | a flat, filled outline | | `TubeGeometry(path, tubularSegments, radius, radialSegments, closed)` | a circle swept along a curve | | `LoftGeometry(sections, { caps })` | a surface through cross-sections along Z | | `BufferGeometry()` | a mesh from your own arrays | | `mergeGeometries(list)` | several geometries as one | Every geometry also takes `translate(x, y, z)`, `rotateX/Y/Z(angle)` and `scale(x, y, z)`, which move it. ### Outlines and curves `Shape()` records an outline with `moveTo`, `lineTo`, `quadraticCurveTo`, `bezierCurveTo` and `absarc`. `EllipseShape(rx, ry, segments)` and `RoundedRectShape(width, height, radius, segments)` return ready outlines. `CatmullRomCurve3(points, closed)` and `HelixCurve(radius, turns, height)` return curves for `TubeGeometry`. ### Loft `LoftGeometry` takes sections in order, each `{ shape, z, scale?, offset? }`: an outline, where along Z it stands, a scale (a number or `{ x, y }`) and a move (`{ x, y }`). `caps = false` leaves the ends open. A body, a hull, a fuselage or a bottle is a loft. ### Custom arrays ```luau local triangle = BufferGeometry() triangle:setAttribute("position", Float32BufferAttribute({ 0, 0, 0, 1, 0, 0, 0, 1, 0 }, 3)) ``` `setAttribute` takes `position`, `normal` and `uv`; `setIndex(list)` gives triangle indices; without normals they are computed and shared across triangles (`computeVertexNormals()`). ## Modifiers A modifier changes the shape in its own frame, before `translate`/`rotate`/`scale` move it, and modifiers stack in the order called. | Modifier | Effect | |----------|--------| | `:round(radius, segments)` | round every edge with that radius | | `:bevel(width, segments, angle)` | round only edges sharper than `angle` degrees; `width` is how far it reaches onto each face | | `:subdivide(levels, mode)` | split every triangle into four, `levels` 1 to 3 times; `"loop"` (default) also smooths, `"linear"` only adds points | | `:smooth()` | one round of Loop smoothing | | `:taper(amount, axis)` | scale the cross-section by `1 - amount * d` at distance `d` along `axis` (`"y"` by default) | | `:twist(angle, axis)` | turn the shape about `axis` by `angle` radians per metre along it | | `:bend(curvature, axis)` | curve it along `axis`; `curvature` is 1 over the bend's radius in metres | | `:subtract(other)`, `:union(other)`, `:intersect(other)` | combine with another closed solid, which stands where it was moved to | `subtract`, `union` and `intersect` take one shape and one shape; merge parts after combining. Both must be closed solids (a box, cylinder, sphere, torus, capsule or polyhedron, or a bevelled or smoothed one). ## Materials `MeshStandardMaterial({ color, roughness, metalness, emissive, emissiveIntensity, opacity, side })` and `MeshBasicMaterial({ color, opacity, side })`. A colour is a `Color`, a hex string (`"#a3141b"`), a number (`0xa3141b`), a name (`"red"`) or `{ r, g, b }`; hex colours are sRGB. `side = "double"` draws both faces; an `opacity` below 1 blends. ## Math `Vector3`, `Color` and `MathUtils` come from the same module as the other nouns and are described in the [math](math.module/README.md) module's README: vector methods and operators, colours from hex, names and HSL, and clamp, lerp, smoothstep and a seeded random. ```luau MathUtils.setSeed(3) for i = 1, 12 do local post = Mesh(CylinderGeometry(0.05, 0.05, 1):round(0.01), MeshStandardMaterial({ color = Color():setHSL(i / 12, 0.5, 0.5) }), "post" .. i) post.position:set(i * 0.5, 0.5, MathUtils.randFloatSpread(0.2)) end ``` ## Motion Write a pose as a formula of `Time` (seconds) and the `Expr` functions `sin`, `cos`, `sqrt`, `atan2`, `abs`, `min`, `max`, `mod` and `floor`, with `+ - * / ^`: ```luau local angle = Time * 6.28 piston.position.y = 1.74 * Expr.cos(angle) + Expr.sqrt(32 - 3 * Expr.sin(angle) ^ 2) crank.rotation.z = -angle ``` The formula is stored with the scene and runs on the device each frame; children follow their parent's motion. ## Lighting ```luau Lighting({ background = "#0c0f12", environment = 1, sun = { color = "#fff1dc", intensity = 1.6, position = { 18, 30, 22 } } }) PostProcessing({ exposure = 0.9, toneMapping = "aces", bloom = { threshold = 1.05, intensity = 0.55 } }) ``` A scene setup places a whole lighting composition as one asset. The V8Dyno scene places `studioLighting`, a studio backdrop, a warm key light and a sky light that lights the model from the backdrop: ```luau asset.resolve("@builtin::systems.quickGeometry.studioLighting", "sceneSetup"):instantiate(nil, { name = "lighting" }) ``` ## Where it lives Each build ends by spawning one entity named `model` with a `Generator` on the `ModelGraph` graph in this package. The tree is the Generator's `objects` and `channels` inputs, stored in `scene.json`; the shapes are made by the nodes of the `shape` nodebox and the modifiers by procgen's `geometry.*` nodes. Names that two parts share get a numeric suffix.
▲ 0↑ born
❒
package · born here
❒asset
▲ 0↑ born
❒
package · born here
❒asset
▲ 0↑ born
❒
package · born here
❒asset
▲ 0↑ born
·
interface · born here
❒asset
# applicable Can be applied for an owner, with values for its declared parameters. A type that lists `applicable` under `interfaces:` in its `type.yaml` guarantees that any of its assets can be put in effect for an **owner**, with values for the parameters the asset declares (`asset.schema`), and that the owner can change those values, turn the application off and on, and drop it, which leaves nothing behind, and that the owner can read the application's state as it stands. A caller applies any implementer with the same calls; here `ref` is any asset whose type lists `applicable`: ```lua local view = ref:as("applicable") local state = view:apply("owner-key", {}) view:setEnabled("owner-key", false) view:state("owner-key") view:drop("owner-key") ``` ## The members | Member | What it does | |---|---| | `apply(self, owner, values, opts?) -> ApplyState` | Puts the asset in effect for `owner` with `values`. Called again for the same owner, it changes the values. | | `setEnabled(self, owner, enabled) -> ApplyState` | Turns that application on or off while it stays applied; its values are kept. | | `drop(self, owner)` | Removes that application entirely. Dropping an owner with nothing applied does nothing. | | `state(self, owner) -> ApplyState?` | The application's state now, the answer `apply` would give, read without applying. `nil` when nothing is applied for `owner`. | `owner` is a key the caller forms from something only it holds, so two callers never share an application. With the asset, it identifies the application across the calls. `ApplyState` is `{ status = "inForce" | "off" | "held", heldBy?, notice? }`: `held` when another application is in force instead (`heldBy` names it), and `notice` the words a person should see about the application. A type may return more fields beside these and documents them itself. An application's state can change with no call for it, when another application of the same kind comes or goes; `state` answers it as it stands on the frame it is asked. ## The values an application receives Every call of a member passes through the interface's contract (`@builtin::interfaces.applicable.contract`), which keeps one record per application: the values the owner stated and whether it is on. The type's `apply` receives the asset's own values (`asset.settings`, else its schema's defaults) with what the owner stated laid over them. A name `values` gives that the schema does not declare, or a value its descriptor refuses, raises at the call, naming the asset and the parameter. `Apply.values(self, owner)` and `Apply.stated(self, owner)` read an application's record. After an edit/play flip, a render-device rebuild, and an edit of an applied asset, the contract applies every record again; no owner acts. A type's `apply` puts back what of its effect is gone and leaves what still stands as it is. ## Implementing it ```yaml # <type>.assetType/type.yaml interfaces: [applicable] settings: { values: "<type>.yaml", schema: { type: "settings.luau" } } ``` ```lua -- <type>.assetType/behavior.luau local Apply = require("@builtin::interfaces.applicable.contract") local M = {} M.ref = { apply = function(self, owner, values, opts) -- make the application `owner` be `values`, on when `opts.enabled` return { status = if opts.enabled then "inForce" else "off" } end, setEnabled = function(self, owner, enabled) return { status = if enabled then "inForce" else "off" } end, drop = function(self, owner) -- remove everything made for `owner` end, state = function(self, owner) -- the answer `apply` would give now, without applying local on = Apply.enabled(self, owner) return { status = if on then "inForce" else "off" } end, } return M ``` A type states `settings:` in its `type.yaml` so its parameters are readable with `asset.schema`; an empty schema is valid, and such an asset is applied with no values. A type whose own `apply` means something else meets the member under `M.interfaces.applicable.apply`. ## Required behaviour 1. **In effect on return.** When `apply` returns `inForce`, the asset's effect is in effect with those values. 2. **A change is a write.** After `apply(owner, changes)`, the effect is what a first `apply` with the complete changed values would have given. 3. **Edit and play.** In effect in edit mode and in play mode. 4. **Off keeps values.** `setEnabled(false)` takes the effect away; `setEnabled(true)` brings it back with the same values. 5. **Drop leaves nothing.** After `drop`, what the application made is gone: the engine's entities, render features, post-process entries and claims are as before the first `apply`. 6. **Nothing saved.** Nothing an application holds reaches a saved scene. 7. **Independent.** Two owners' applications of one asset are two: one changing, turning off or dropping never changes the other, except through the asset's own rule for which application is in force. 8. **One in force is the asset's rule.** An asset whose effect holds one application at a time decides among its applications and reports the others `held`. 9. **Kept in force.** What an application holds is put back after the events that remove it, by the contract's restatement. The conformance suite (`conformance`) checks these against every asset of every implementing type it can reach.
▲ 0↑ born
❒
package · born here
❒asset
▲ 0↑ born
❒
package · born here
❒asset
▲ 0↑ born
·
interface · born here
❒asset
# sceneInstantiable Can be placed in a scene. A type that lists `sceneInstantiable` under `interfaces:` in its `type.yaml` guarantees that `instantiate` composes any of its assets under or onto an owning entity, synchronously, and returns the live root and the map naming what it spawned. A consumer places any such asset with one call, `source:as("sceneInstantiable"):instantiate(target, opts)`, and it works for types the consumer has never heard of: the `Asset` component, a viewport drop, a procedural generator and a tool argument all place assets this way. ## Implementing it ```yaml # marker.assetType/type.yaml interfaces: [sceneInstantiable] ``` ```lua -- marker.assetType/behavior.luau local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable") local M = {} M.ref = { instantiate = function(self, target, opts) local root = Instantiable.root(self, target, opts) root.component.add("Text3D", { text = self.name }) return Instantiable.result(self, root, {}) end, } return M ``` A type whose own `instantiate` means something else meets the member under `M.interfaces.sceneInstantiable.instantiate`. ## The base inputs `target` is the owning entity; with none, the type spawns a fresh root. `opts.position`, `opts.rotation`, `opts.scale`, `opts.name` and `opts.temporary` mean the same for every type, and `Instantiable.root` applies them to a root the type makes (`Instantiable.place` to one it adopts). `opts.idMap`, `opts.diff` and `opts.sourceTag` are what the `Asset` component passes to every type: a type that spawns no addressable children ignores them. `opts.detached` composes a permanent copy that nothing composes again. A type's own extras (`raw`, `deferred`, `params`) travel in `opts` beside these, are always optional, and never change a base input's meaning. ## Required behaviour 1. `root` exists on return, with everything composed under it. 2. `idMap` maps each original id to the spawned id; `{}` for none. 3. Passing the returned `idMap` back reproduces the same ids. 4. `temporary = true` keeps the root and everything under it out of the saved scene. 5. Despawning `root`, or the composition the `Asset` component despawns, removes everything the call put in effect. The conformance suite, `sceneInstantiableConformance` beside this file, holds one asset of every implementing type (or of the types a run names) to the base options' meanings, the returned map reproducing its ids when passed back, and a detached composition's live root. `asset.validate` of a world's own type runs it over that type. ## Legacy types A type that defines `M.ref.instantiate` and lists nothing (one written before `interfaces:` existed, or defined by its `behavior.luau` alone) implements `sceneInstantiable` with a warning (`interfaces.implied`) naming the line to add.
▲ 0↑ born
❒
package · born here
❒asset
▲ 0↑ born
❒
package · 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
▣
module · born here
❒asset
# future A future is a promise held as a value: store it in a table, return it from a function, hand it to another task, and await it whenever the value is needed. Every promise-returning call (`http.get_json`, `delay`, `asset.load`, ...) already hands back one, a `PromiseHandle`; this module makes new ones, runs work as one, chains them, waits for several at once, bounds one in time and cancels them. ```lua local future = require("@builtin::modules.future") task.spawn(function() -- Start both loads; they run at the same time. local pending: { Future<any> } = {} table.insert(pending, http.get_json("https://example.com/a.json")) table.insert(pending, http.get_json("https://example.com/b.json")) -- Collect them. Each await returns once its load has settled. local results = {} for i, f in pending do results[i] = f:await() end end) ``` ## Members of a future | Member | What it answers | |---|---| | `f:await()` | Yields until the future settles and returns its value; a future that has already settled returns at once, with no yield. A rejection raises its error at this line. The same call as `await(f)` and `task.await(f)`. | | `f:state()` | `"pending"`, `"resolved"`, `"rejected"` or `"cancelled"`, read without taking the value. | | `f:rejection()` | Why the future was rejected: `{ message, origin?, stack? }`, the reason as text, the `chunk:line` the rejection came from and, when Luau rejected it, the stack there. `nil` while it is pending or once it resolved. | | `f:source()` | The `chunk:line` whose call created the promise, for finding what a hung await is waiting on. | | `f.handle` | The promise's id string. `tostring(f)` reads the same. | | `f:andThen(onResolve, onReject?)` | A future of what the handler returns; a future it returns is awaited and its value delivered. Without `onReject` a rejection passes through. A handler that raises rejects it. | | `f:catch(onReject)` | A future of `f`'s value, or of what `onReject` returns given the error. | | `f:finally(fn)` | A future settled the way `f` was, once `fn()` has run, whichever way `f` settled, cancelled included. | | `f:tap(fn)` | A future of `f`'s value, once `fn(value)` has seen it. | | `f:timeout(seconds, reason?)` | A future of `f`'s value that rejects with `reason` (a message naming the time by default) when `seconds` of real time pass first; `f` is then let go of. | | `f:cancel()` | Ends a pending `f` as cancelled: `true`, or `false` and the reason. | The chaining methods come with the module, which every world script VM loads, so a future an engine call hands back chains with no require. A handler runs in a task (it may wait) inside a `scopes.run`: the chained future settles once everything the handler started is over. Every task that awaits a future receives its value: the ones waiting when it settles and any that await it later, for as long as the future is held. ## Module functions | Call | Result | |---|---| | `future.wrap(promise)` | The future naming a promise, from its future or its id string. An id naming no promise the engine keeps raises. | | `future.new(onCancel?)` | A pending future plus `resolve(value)` and `reject(error)`, which settle it once. `error` is any value but nil. `onCancel()` runs when the future is cancelled. | | `future.resolved(value)` | A future already resolved with `value`. | | `future.rejected(err)` | A future already rejected with `err`. | | `future.after(seconds)` | A future resolving with `true` after `seconds` of real time (the promise `delay(seconds)` hands back). | | `future.spawn(fn, ...)` | Runs `fn(...)` as a task; the future resolves with what it returns (awaiting a future it returns) and rejects with what it raises. | | `future.all(futures)` | Every value, in the order given. The first rejection rejects it, the first cancel cancels it, and the rest are let go of. `{}` for none. | | `future.allSettled(futures)` | `{ status, value?, error? }` for each, in order, once all have settled. Never rejects. | | `future.race(futures)` | Settles the way the first to settle did; the rest are let go of. | | `future.any(futures)` | The first value resolved; the rest are let go of. When none resolves it rejects with `{ message, errors }`. | | `future.retry(fn, attempts, delaySeconds?)` | Calls `fn()` until it succeeds, at most `attempts` times, with `delaySeconds` of real time between. | | `future.fromEvent(event, predicate?)` | The first value of the next fire of `event` (a Signal, a component event, anything offering `:Connect(fn)` / `:connect(fn)`) that `predicate` accepts. Disconnects once settled or cancelled, and is cancelled when what started it ends. | ```lua local future = require("@builtin::modules.future") task.spawn(function() -- Both loads at once; the first failure fails the lot. local maps = future.all({ http.get_json(urlA), http.get_json(urlB) }):await() -- Whichever search answers first; the other is cancelled. local nearest = future.race({ future.spawn(searchNear), future.spawn(searchFar) }):await() -- No level within five seconds rejects, and the load is cancelled. local ok, err = pcall(function() return future.spawn(loadLevel, "forest"):timeout(5):await() end) end) ``` ## Cancellation `f:cancel()` ends a pending future as cancelled. Awaiting it raises the error `task.isCancellation(err)` recognises, and `f:state()` reads `"cancelled"`. A cancellation is never written to the error log. - **The work stops.** The task running a `future.spawn` or a handler is cancelled, and so is everything it started; each unwinds, so the `pcall` or cleanup around its wait runs. - **Downstream.** A future chained from a cancelled one (`andThen`, `catch`, `tap`, `timeout`, `all`, `race`, ...) is cancelled too, without calling its handler; `finally` runs its function first. - **Upstream.** A future counts the chains and combinators waiting on it. One whose last such consumer is cancelled, or settled without it (a `race` another input won, a `timeout` that ran out, an `all` another input rejected), is cancelled. A direct `await` is not a consumer. - **What started it.** The task running a handler belongs to what the calling code belongs to: a component instance, a scene load, a task scope. When that ends, the future is cancelled. A future an engine call handed back (`http.get_json`, `delay`) runs to its end whatever waits on it; its `cancel()` answers false and the reason. ## Rejections A rejection is kept apart from any value, so a future resolved with a table of any shape delivers that table. Awaiting a rejected future raises its error: a string at the await's line, any other value (an error table `reject` was given) as itself. Catch it with `pcall`, and read where it came from on the future: ```lua local f, _, reject = future.new() task.delay(1, function() reject({ code = 404, message = "no such level" }) end) local ok, err = pcall(f.await, f) if not ok then print(err.code) -- 404: the error value reject was given local why = f:rejection() print(why.origin) -- the line that called reject end ``` A rejection nothing sees (no await receives it and nothing reads `rejection()`) is written to the error log once the future is gone, so a future you hold and await later reports nothing on its own. A chain or combinator sees every rejection its inputs hold when it settles, so the second rejection of an `all`, or a `race` input already rejected when another won, writes nothing. ## Identity A VM holds one future object per promise. Every call that hands a promise to the VM while its future is alive, `future.wrap` included, hands back that same object: `future.wrap(f) == f`, `rawequal(future.wrap(f.handle), f)`, and a future is one table key. ## Types `Future<T>` is a future whose await delivers a `T`; `PromiseHandle` is a future whose value has no stated type. They name the same value, so either is accepted where the other is declared, and `f:await()` on a `Future<T>` checks as a `T`. `f:andThen(fn)` checks as a `Future` of what `fn` returns (a `Future<V>` it returns reads as `V`), `f:catch(fn)` as the value or what `fn` returns, `finally`, `tap` and `timeout` as `f`'s own type, and `future.all({ Future<T> })` as a `Future<{ T }>`.
▲ 0↑ born
▣
module · born here
❒asset
# test Test framework — simple unit testing with the `describe` / `it` / `expect` pattern. Used by the engine test suite and any user-authored suites that want a single dependency. Pure Luau; flag-based failure tracking instead of exceptions (works the same on native and WASM). ## Exports Definition: - `Test.describe(name: string, fn: () -> ()) -> Suite` — define a suite. The body declares the suite's cases, so only what it reached is in the run: a body that ends on a raise leaves a `<describe body did not finish>` case behind, naming the describe and what it raised, and the run ends on that case. A body that stands down leaves the same case marked skipped, carrying the reason. - `Test.it(name: string, fn: (TestContext) -> ()) -> any?` — define a test. - `Test.skip(name: string, fn: ((TestContext) -> ())?) -> any?` — skip a test. Inside a `describe` with a body it declares a skipped test; inside a running test (its body or one of its hooks) a reason alone stands that test down — the test ends there, is counted under `skipped`, and the reason reaches the console, the per-test record and the report. A reason alone anywhere a test is not running raises, naming the declaration form. - `Test.beforeEach(fn: () -> ())` / `Test.afterEach(fn: () -> ())` — per-test hooks. - `Test.expect(value: any) -> any` — expectation builder with `toBe`, `toBeTruthy`, `toBeFalsy`, `toBeNil`, `notToBeNil`, `toBeType`, `toBeGreaterThan`, `toBeLessThan`, `toBeCloseTo`, `toContain`, `toMatch`, `toHaveLength`, `toThrow`, `never()`. - `Test.captureFailure(fn: () -> ()) -> string?` — run a body and return the failure it records instead of recording it, for tests that assert a matcher rejects something. A body that records several returns the headline for them. - `Test.captureOutcome(fn: () -> ()) -> Outcome` — run a body the way the runner runs a test body and return `{ failed, error, failures, raised }`: its failures in the order they happened, with a raise that ended the body as the final entry. - `Test.captureTestOutcome(spec: TestSpec) -> TestOutcome`: run a whole test the way the runner runs one (`beforeEach`, the body, `afterEach`, then the cleanups registered while it ran) and return `{ skipped, reason, failed, error, failures, raised }`. The runner reads its verdict from the same place, so what this reports for a captured test is what a sweep reports for a real one. A scene layer the captured test leaves loaded that was not loaded when it started is unloaded afterwards, as the runner unloads one after each test. ## What a failing test reports A matcher records its failure and lets the body run on, so one body can produce several. They are kept in the order they happened: - `error` — the headline, and the one line the console, the engine log and the report's result table carry. It is the failure that came first, plus `(+N more)` counting the ones after it — `(+N more, ended by a raise)` when a raise is what stopped the body. - `failures` — the failures in order, on `Test.results[]`, in each per-test JSON file under `Test.PER_TEST_RESULTS_DIR`, and in the JSON report. The Markdown report lists them under the failing test's heading. A body that records more of them than the list keeps ends it with a line counting the rest and naming the last of them, so one test asserting inside a long loop stays one bounded entry in the report. The hooks that run around a body record onto the same list it does, so an assertion a `beforeEach`, an `afterEach` or a registered cleanup fails — and an error one of them raises — is a failure of the test it ran for and travels to every consumer the body's failures reach. Each names the phase it came from (`afterEach: Expected …`, `cleanup: Runtime error: …`); a body's own failures stay unlabelled. A cleanup that raises still leaves the cleanups behind it to run. ## Standing a test down A test whose precondition this engine does not meet has nothing to verify and has earned no pass. `Test.skip(reason)` from inside the running test says so: ```lua Test.it("renders N copies from one transform buffer", function() if engine.gpuCompute ~= true then Test.skip("GPU compute reported unavailable (engine.gpuCompute)") end -- …the test, on an engine that can run it end) ``` The test ends at that call. It is counted under `skipped`, printed as `○ <name> (skipped: <reason>)`, and the reason travels as the `error` field of its `Result` row, into its per-test JSON file, and into both reports. A `beforeEach` may stand the test down the same way, and then the body never runs. Whatever the test's hooks record around a stand-down is a failure of the test they ran for and outranks it: a teardown that fails after a body stood down reports the test as failed. A reason on its own reaches a test that is running. Inside a `describe`, where `Test.skip` declares, the call takes a body — a reason alone raises there, naming the declaration form. Run / inspect: - `Test.run() -> boolean` — execute every registered suite; `true` when all pass. Call from a yieldable context (the `tests` toolbox does) so multi-frame tests yield. Discovering + running every suite is the `tests` toolbox's job (`tests.run`), not this framework's. - `Test.clear()` — reset suites + stats (re-run from clean state). - `Test.getResults() -> { Result }`, `Test.getStats() -> Stats`. Multi-frame / sandboxing: - `Test.waitFrames(n: number?)` — yield until at least `n` engine frames elapse. - `Test.tmpPath(relativePath: string?) -> string` — sandboxed path under `Test.TMP_ROOT`. - `Test.prepareTmp()` / `Test.cleanupTmp()` — recreate / remove the tmp root. Notices: - `Test.noticeMark(template: string) -> NoticeMark` / `Test.noticesSince(mark) -> number`: how many times a notice posted under `template` fired after the mark. A drain seals the row it returns and the next emission starts a new row, so this counts across every row of the template. - `Test.latestNotice(template: string) -> any?`: the stored row of that template the most recent emission landed in. Scene layers: - `Test.useScene(opts?) -> SceneProxy` — mint an isolated scene for the current test from a `.scene` fixture and load it (root, or an additive overlay with `{ additive = true }`). Unloaded and removed at teardown. - `Test.useSceneEach(opts?)` — suite-level sugar: one freshly minted scene per test. - `Test.ensureRootLayer() -> SceneProxy` — take a root scene layer for the current test, so `layers.active` and the scene-scoped surfaces behind it answer inside a test. Returns the loaded root, loading a stand-in scene from `Test.BASELINE_SCENE` when none is; the layer is unloaded when the test ends. - `Test.releaseRootLayer()` — unload the stand-in and remove its source folder. The runner calls it when a run ends. - `Test.beginWorldBaseline() -> WorldBaseline` / `Test.restoreWorldBaseline(baseline)` — bracket a whole sweep: unload the layers the engine booted with (so no suite depends on ambient content) and put them back afterwards. Public state: - `Test.suites`, `Test.currentSuite`, `Test.currentTest`, `Test.stats`, `Test.results`, `Test.TMP_ROOT` (`/zero/source/tmp/tests`). Types: - `Stats = { total, passed, failed, skipped: number }` - `Result = { suite, test: string, passed, skipped: boolean, error: string? }` — on a skipped row `error` is the reason the test stood down - `TestContext = { waitFrames, expect, fail, suiteName, testName }` - `Suite = { name, tests, beforeEach?, afterEach? }` - `Outcome = { failed, raised: boolean, error: string?, failures: { string } }` - `TestOutcome = Outcome & { skipped: boolean, reason: string? }` - `TestSpec = { body: (TestContext) -> (), beforeEach?, afterEach?: () -> (), name: string? }` - `RunAllOpts = { path: string? }` - `NoticeMark = { template: string, counts: { [string]: number } }`: each stored row's count at the mark, by row ## Usage ```luau local Test = asset.containing(__FILE__).modules.shared Test.describe("My Suite", function() Test.it("does basic things", function() Test.expect(1 + 1).toBe(2) Test.expect("hello").toContain("ell") end) Test.it("cascade despawn cleans children across frames", function(t) local parent = entity.spawn("parent") local child = entity.spawn("child") child.setParent(parent.id) t.waitFrames(1) -- let setParent settle entity.despawn(parent.id) t.waitFrames(2) -- let cascade + ECS despawn run Test.expect(entity.exists(parent.id)).toBe(false) Test.expect(entity.exists(child.id)).toBe(false) end) end) Test.run() ``` ## Parts The module is a folder of parts, each a module of its own that `init.luau` requires: - `Test.valueText`: the structural, bounded rendering `Test.describeValue` gives a table. - `Test.worldReadings`: the readings of engine-wide state a teardown settle and the scene-rect hand-back compare. - `Test.ownership`: which modules, GPU buffers and compute resource rows are the engine's own, which the floor readings leave out of what a suite answers for. ## Notes - Failure is flag-based, not exception-based — every matcher records the failure but allows the body to keep executing. Avoids WASM C++ exception handling cost. - The runner records the loaded scene layers and the entity set before each test. Afterwards it unloads every scene layer the test left loaded that was not loaded before it, newest first, so the entities that layer's load built leave with the layer and the scene's source is what its next load builds from. It then despawns any other newly-spawned entity (mutations apply after the `execute()` batch returns; `cleanedUpIds` makes the snapshot tolerate deferred cleanup). - After each test the runner defensively returns the scene to `edit` mode if a body or its `afterEach` leaked `play`. This stops a single mode-leaking test from cascading silently into every downstream `vfs.write`-using suite. - Multi-frame `t.waitFrames` needs a yieldable call chain. A non-yieldable C-frame above `Test.run` (e.g. driving it from inside a `require`) makes `waitFrames` raise a sentinel and the test is marked SKIPPED — the body had nothing to verify, so what it recorded is dropped and what its setup recorded stands. A hook that fails around such a body still fails the test. The `tests` toolbox (`tests.run` → `AssetRef:run()`) runs the suite in a plain coroutine, so the real wait path exercises. - `toThrow` calls its subject under `pcall` and fails when the call returns normally. `toThrow("substring")` additionally requires the rendered raised value to contain that substring. `never().toThrow()` asserts the call completes.
▲ 0↑ born
▣
module · born here
❒asset
# luau_introspect (module) Parses Luau/asset source TEXT into structured declarations. Pure string/pattern parsing (`string.find` / `string.match` / `string.gmatch`) over the literal source — no compiling, no VM spawn, no runtime state, no engine FFI. Given source text, it extracts what is written in the file. This is the shared parser every per-assetType `M.ref.inspect` hook uses to turn a component/module/tool's own source into the structured record `asset.inspect` returns. ## Exports - `docstrings(src) -> DocMap` — scans `--!desc` / `--!arg` / `--!return` / `--!example` comment runs and binds each run to the name of the declaration on the next non-comment line (the identifier after `function`, `public:`, `local function`, or `M.`). - `publicFields(src) -> { FieldEntry }` — parses `public = { name = Field.<kind>(default, mode), ... }` table-literal entries and module-scope `public.<name> = Field.<kind>(...)` assignments. - `events(src) -> { EventEntry }` — parses `events = { name = Event(payloadSchema?, syncMode?), ... }` table-literal entries. - `methods(src) -> { MethodEntry }` — parses `function public:<name>(...)` / `typed function public:<name>(...)` declarations (params + optional return type). - `lifecycleHooks(src, catalog) -> { string }` — top-level `function <name>(` declarations whose name is in the caller-supplied `catalog` array. - `moduleExports(src) -> { ExportEntry }` — parses `M.<name> = function` assignments, `function M.<name>(...)` declarations, and a trailing `return { foo = foo, ... }` export table. - `forSource(src, computeFn) -> any` — memoises `computeFn(src)` keyed on `src` itself in a module-local table. The same source text returns the cached result without re-running `computeFn`; different source text recomputes. Keyed on the source content (not an asset checksum) because composite/container assets (component folders, scene folders, etc.) all hash to the empty-string checksum — a checksum-keyed cache collapses every such asset's detail onto whichever one was inspected first. ## Usage ```luau local Introspect = require("modules.luau_introspect") local src = self:getInitScript() local detail = Introspect.forSource(src, function(s) return { fields = Introspect.publicFields(s), events = Introspect.events(s), methods = Introspect.methods(s), hooks = Introspect.lifecycleHooks(s, lifecycleCatalog), } end) ``` ## Notes - Every function is a pure string→table transform: same source text in, same structured table out, every time. No reads of live component state, no entity/world queries. - Structural scanning runs over a comment- and string-aware **mask** of the source (a same-length copy where comment bodies and string-literal contents are blanked to spaces, delimiters and newlines preserved). Pattern matches and brace/paren balancing run on the mask — so a brace, `Field.`, `Event(`, or a whole entry that appears inside a comment or a string literal never registers — while captured values are sliced from the original source at the same (aligned) indices. This makes the parser robust to apostrophes in comments, commented-out entries, string defaults containing `}` / `Field.` / `Event(`, and `[[ ]]` long strings. - `default` / `category` are raw trimmed source-text slices (with any trailing comment stripped), not evaluated values. - For a **ref constructor** (`Field.assetRef` / `dataRef` / `resource` / `componentRef`) the FIRST positional argument is the category / contract / componentType selector, captured under `category`; the SECOND argument is captured under `default`. - For every **other** Field kind the first argument is the `default` and `category` is nil. - A trailing `Sync` / `NoSync` identifier is captured as `sync`, tolerating a trailing comma or a trailing comment after the last argument. - Field/Event entries whose key is a computed or indirect expression (`[expr] = Field.number(...)`) are omitted — only literal identifier keys are recognised. - `methods` captures a `...` variadic parameter (as `name = "..."`), with its `: <type>` annotation when present. - A `--!desc` written above a field/event declaration (`<name> = Field.<kind>(...)` / `<name> = Event(...)`) or a `public.<name> =` assignment binds to that name in `docstrings`, and is folded into the corresponding `publicFields` / `events` entry's `desc`. - `lifecycleHooks` never hardcodes the lifecycle-callback catalog; the caller passes the list of names to match against. - `forSource`'s memo is bounded (oldest-key eviction) so a long session touching many distinct asset versions can't grow it without limit.
▲ 0↑ born
·
toolbox · born here
❒asset
# ik Look at a rig's bones and at what an IK solve is actually doing. Debugging IK means answering three questions, and none of them can be answered from a screenshot: what are this rig's bones called, where are they right now, and is the chain reaching its target or merely near it. `bones` lists a body's bones with their world positions and parents — the names you need before naming a chain, and the positions you measure against when checking a solve from outside the component. Rigs rarely use the word you would guess: the standard humanoid here calls its feet `Ankle_L` and `Ankle_R`, with no bone containing "foot" anywhere. `reach` reports how far a limb can extend and how far away a point is, both in the same units. A target beyond a limb's reach has no solution — the chain extends straight toward it and stops, which is correct and looks exactly like a broken solver. This is the first thing to check when a solve looks inert. `state` gathers every IK component on an entity and reports what each one is doing, so "is anything solving at all" is one call rather than five.
▲ 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
backing path · tools/tests.toolbox

Problems

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

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

Usability ratings

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

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

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

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