Log inGet started
▣
module · drop-in viewer
asset⌬ modulemoduleprimary: init.luau·part ofpackage edui.package·originates fromworld 07158574-5…

topbar

No description provided.

by◐lumi·posted 2mo ago
What it does

No description provided yet.

Interface

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

conforms to

zero/source-extract/v2

module edui.topbar The editor menu bar on edui — a `ui.*` ctx-level `topPanel` above the dock: domain dropdown menus on the left (Scene / Content / Debug), the Window menu that opens/closes edui panels, and the play/pause transport on the right. On a window too narrow for that row (a phone's) the bar folds its menus and view toggles into one overflow menu, and unfolds once the window is wide enough again. Every menu entry names a panel this editor ships and focuses it. It owns one edui app on its own screen, so it composes above the shell's dock and toolstrip. require ~edui.topbar

__index(_: ?, key: ?) → void

argtypedescription
_?
key?

mergeParams(entry: any, row: any) → void

Fold a polled row's params into a ring entry: the queue drains under an agent's tool calls, so each poll may see a fresh row for a key the ring already holds, carrying values the earlier poll never saw. Keys keep the order they were first seen; each keeps its distinct values up to the cap and counts the distinct values past it, so a line always says WHAT the notice hit and how many other things it hit.

argtypedescription
entryany
rowany

agoLabel(atMs: number?) → string

How long ago a wall-clock millisecond stamp was, in the coarsest unit that still says something ("just now", "12s ago", "3m ago"), as the editor's language writes it.

argtypedescription
atMsnumber?

pollNotices( ) → void

severityWord(severity: string) → string

The word a notice's severity reads as in the bell.

argtypedescription
severitystring

bellSeverityColor(P: any, severity: string) → string

argtypedescription
Pany
severitystring

registeredMenu(id: string) → any

The registry's record for a menu, when a caller declared one with `editorRegistry.addMenu`: its label and order.

argtypedescription
idstring

labelFromId(id: string) → string

The label a menu declared only by a panel's `menu` field shows: its id with the first letter raised.

argtypedescription
idstring

menuHintOf(panel: any) → string

The short note a panel asks its menu entry to carry on the right, from the spec's `menuHint`. A function is read at menu-build time, so an entry whose note follows live state (a quota, a run state) says what is true now.

argtypedescription
panelany

ensureEditDeclared( ) → void

run( ) → void

domainMenus( ) → void

hasEntries(id: string, panels: { any }?) → boolean

argtypedescription
idstring
panels{ any }?

entriesOf(panels: { any }) → void

argtypedescription
panels{ any }

commandItems(menuId: string) → void

The entries of the commands declared under a menu, each running its command against the editor's selection: the Add menu's through `edui.create`, keyed as the Hierarchy's create menu keys them.

argtypedescription
menuIdstring

onClick( ) → void

domainItems(menu: any) → void

argtypedescription
menuany

onClick( ) → void

onClick( ) → void

editItems( ) → void

The Edit menu: the commands declared under it (Save Scene), the edit-history verbs, greyed when the stack has nothing for them, plus the selection operations. Undo/redo drain on the next engine tick; the shortcut hints name the bindings editor.component wires.

onClick( ) → void

onClick( ) → void

onClick( ) → void

onClick( ) → void

onClick( ) → void

renderedCameraId( ) → string

The viewport diagnostic pass: the active camera's current pass name, and the setter mapping a picked name back to its channel. The same read/write the Rendering panel's view-mode field uses.

activePassName( ) → string

setActivePass(name: string) → void

argtypedescription
namestring

passItems( ) → void

The pass menu: every diagnostic pass the renderer registers, the active one checked. Answering "why is this black" is picking `shadow` or `albedo` here, the way an agent captures the buffer.

onClick( ) → void

windowItems( ) → void

onClick( ) → void

onClick( ) → void

onClick( ) → void

onClick( ) → void

onAccept(choice: ?) → void

argtypedescription
choice?

onClick( ) → void

onAccept(choice: ?) → void

argtypedescription
choice?

onClick( ) → void

menuButton(app: any, menuId: string, label: string) → any

A menu-bar button — a labelled, hoverable click target with a stable id the popup anchors to. Clicking toggles this menu; the open menu is exclusive.

argtypedescription
appany
menuIdstring
labelstring

overflowButton(app: any) → any

The overflow button the folded bar shows in place of its menu row: one control that opens the menu holding every menu and view toggle.

argtypedescription
appany

holdWidth(node: any) → any

A row control keeps the width its content needs, so a row too long for the bar runs past its edge (which folds the bar) rather than squeezing its labels over one another.

argtypedescription
nodeany

lightingOn( ) → boolean

Whether the scene renders lit, as `renderer.lighting` answers.

overlayOn( ) → boolean

Whether the editor's overlay draws in the engine's current mode.

userScriptErrors( ) → void

The world's own script errors, read the way the Problems panel reads them, so the list a refusal shows and the list that panel shows are one list.

setMode(target: string) → void

Asks the engine for the mode it is in rather than the mode this bar last recorded, so a press never stops short on a reading the engine has moved on from. A refused Play is kept for the popup under the button: the refusal reaches the person who pressed it, not only the log. The switch runs in a task of its own, which can wait: entering play waits there, a frame at a time, for what the play gate needs built, rather than building it in the frame the press arrived in.

argtypedescription
targetstring

playPastErrors( ) → void

Enter play past the world's own script errors, for this one flip: the engine's own override, which leaves the world's setting where it is and leaves publishing refused until the errors are fixed.

openAt(path: string, line: number?) → void

Open `path` at `line` in the Code panel — where a refused Play sends the person to fix what refused it.

argtypedescription
pathstring
linenumber?

boundWorldGuid( ) → string

The bound world's guid, or nil on an engine that booted with no world.

brandItems( ) → void

The Zero menu: the world this engine runs. Reload takes the bound world again from the top; details shows its record; change switches the engine to another world without closing it. Each needs a bound world.

onClick( ) → void

onClick( ) → void

onClick( ) → void

brand(app: any) → any

argtypedescription
appany

worldLabel( ) → string

The bound world's name for the crumb: its title as ZeroMind records it, once the live connection has fetched it; nothing before that. The bar's update watches this and rebuilds when it changes.

currentBranch( ) → string

The branch this session is on, or "" while no world is bound.

refreshBranches( ) → void

Read the world's branches for the menu.

switchBranch(name: string) → void

Move this session onto `name`. Nobody else's session moves: the switch rebinds this one, and the world reloads the way it does on a world swap.

argtypedescription
namestring

createAndSwitch(raw: string) → void

Create `name` from where this session stands, and move onto it.

argtypedescription
rawstring

branchItems( ) → void

The branch menu: New branch… at the head, where a long list never pushes it out of view, then every branch the world has, the current one checked.

onClick( ) → void

onClick( ) → void

sceneSegment(app: any) → any

The open scene, as the crumb names it: the root layer's asset name, with the asset's identity and guid in the tooltip. The bar's update watches the loaded layers and rebuilds when the open scene changes.

argtypedescription
appany

crumb(app: any) → any

The world breadcrumb (right side) — "world / <name> / <branch> · <scene>", the reference's crumb; the branch segment opens the branch menu and the scene segment names the open scene asset.

argtypedescription
appany

toggleLighting( ) → void

The bar's view toggles, shared by the buttons of the unfolded row and the entries of the overflow menu.

toggleOverlay( ) → void

toggleStats( ) → void

switchLayoutSide( ) → void

layoutTitle(name: string?) → string

The title the layout switch shows for a layout name.

argtypedescription
namestring?

menus( ) →

The menus of the bar's row, in the order it shows them: Edit, the domain menus (Add first), Window, then Settings and Help, each with the label it shows and the panels and commands it lists (Window's panels: the ones a scene is edited with, then the ones no domain menu carries). of the panels the menu opens, `commands` the ids of the commands it runs.

examples

for _, m in ipairs(edui.topbar.menus()) do print(m.label) end

entry(menu: any) → any

argtypedescription
menuany

recordButton( ) →

The record button as the bar draws it: `lit` while a take runs, and the `tooltip` that says what a press does (start or end the take).

examples

edui.topbar.recordButton().lit

layoutSwitch( ) →

What the bar's layout switch shows: `label` is the text on the control, "Layout: " and the title of the layout in force, beside a chevron, and a press opens the menu listing every layout; `title` is that layout's title alone, `slot` the side of the switch it stands for ("a", "b", or nil for a layout in neither), and `tooltip` says what a press does.

examples

edui.topbar.layoutSwitch().label

layoutMenuItems( ) → void

The menu the layout switch opens: every layout the editor can apply, the one in force checked and each side of the switch marked A or B beside the layout it stands for; then the press that trades the layout in force for the one on the other side, the choosers that assign another layout to a side, and the reset.

onClick( ) → void

onClick( ) → void

layoutPickItems(side: string) → void

The layouts a person can assign to one side, the one standing there checked.

argtypedescription
sidestring

onClick( ) → void

overflowItems(menus: { any }, closing: { any }) → void

argtypedescription
menus{ any }
closing{ any }

opens(id: string, label: string) → void

argtypedescription
idstring
labelstring

onClick( ) → void

onClick( ) → void

onClick( ) → void

buildBar(app: any) → any

argtypedescription
appany

onClick( ) → void

anchorOf(menuId: string) → string

Popups render AFTER the button row so each anchor's rect is populated when the popup resolves it. One per domain menu + the Edit and Window menus. On the folded bar every menu opens under the overflow button that reached it.

argtypedescription
menuIdstring

onDismiss( ) → void

onDismiss( ) → void

onDismiss( ) → void

onDismiss( ) → void

onDismiss( ) → void

onDismiss( ) → void

onDismiss( ) → void

onDismiss( ) → void

onSubmit(v: ?) → void

argtypedescription
v?

onClick( ) → void

onClick( ) → void

onClick( ) → void

onClick( ) → void

onClick( ) → void

settleFold( ) → boolean

standing( ) → boolean

editorLayerMask( ) → number

The EditorUI render-layer mask, so the bar is editor chrome (a capture or camera whose mask omits the EditorUI bit drops it). nil when the layer registry is absent — the bar then renders on the default layer.

mount(layerMask: number?) → any

Mount the menu bar (idempotent). Registers its `ui.*` screen on the EditorUI layer and does the first build.

argtypedescription
layerMasknumber?Optional EditorUI render-layer mask; computed when omitted.

examples

edui.topbar.mount()

unmount( ) → void

Tear the menu bar down.

update(_dt: number?) → void

argtypedescription
_dtnumber?

openBranchMenu( ) → void

Open the branch menu under the top bar's breadcrumb, reading the world's branches afresh — the route another panel takes to switch branch.

screenName( ) → string

The bar's screen name (for `ui.showScreen` / capture `screen`).

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.

150+items
·
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
# clientSettings The client's settings: the person's own on this device for the account signed in, the same in every world, on every platform and in a headset. They are a different thing from a world's own settings: `settings` is the world's settings file (`/zero/source/.world_settings`), authored with the world. - **Declared once, by the engine.** A group is one tab of the settings menu: `clientSettings.registerGroup{ id, title, description, icon, order, visible }`, where `visible()` says whether the tab shows on this client now. Entries name their group: `clientSettings.register{ ... }`. A setting carries - a `field` its every value is held to (`Field.enum`, `Field.range`, `Field.bool`), whose default is the setting's default; `labels` names an enum's members, `step` and `format` shape a range; - a `scope`: `"device"` for what depends on this machine, `"userPlatform"` for what follows the person on this kind of platform; - an `effect` of kind `"engine"`: `apply(value)` takes the value into the engine (on register, on every change and when the account changes), and `changed(value)` runs only when the person changes or resets it. An action carries no field and no value: its effect is `run()`, shown as a `button`. `available()` on either says whether it can be used now and, when it cannot, why. Every word a person reads (`title`, `description`, `label`, `button`, an enum's `labels`) is text or `{ key = "namespace.key", values? }`, the catalog message said in the player's language each time the menu is drawn. - **Reading.** `clientSettings.get(key)` is the value the person chose, or the setting's default. `clientSettings.list()` states every group with each entry's value, default, `source` (`"player"` once the person chose one, `"default"` before), scope, choices or range, and availability; the menu draws exactly that list. A world reads the settings it needs, e.g. `clientSettings.get("xr.perspective")`. - **Changing.** `clientSettings.set(key, value)` holds the value to the field, keeps it and carries out the effect; `clientSettings.reset(key | group)` returns a setting or a whole group to its defaults; `clientSettings.run(key)` runs an action. Each is refused with world or agent code on the Luau stack, naming the setting: the person changes their settings in the menu, and a world reads them and never changes them. - **The System tab.** The settings show as the System tab of the app menu (`appMenu`), the menu the pause action opens: every visible group a section, with **Reset to defaults** on a section where the person chose something. `clientSettings.open(group?)` opens the menu on that tab, from anywhere, a world's own code included; the editor's **Settings…** and the gear on its dock in a headset do the same. The tab shows while `clientSettings.reachable()` is true, that is while some group is visible. - **The groups.** **VR** (`xr_menu`) shows while this client can draw to a headset; every other group shows in a headset as it does on a desktop. - **Where values are kept.** As preferences of the signed-in account on this device (`zero_account_prefs`, under `setting.<key>`), whatever the scope; with nobody signed in, the signed-out record. Signing in or out switches to that account's settings and applies them. `clientSettings.onChanged(fn)` hears each change, and `fn(nil)` when the account changes. `clientSettings.buildSection(model)` returns the System tab's widget tree for a state, laid out for a desktop, a phone or a headset's panel.
▲ 0↑ born
◇
component · born here
❒asset
# Model Loads and displays a 3D mesh on an entity. Disabling the component hides the mesh. Supports procedural meshes (`cube`, `sphere`, ...), model files, and remote URLs. Tint and outline are shader effects applied to the mesh. **Material lives on this component.** There is no standalone `Material` component — a material only renders where there is a mesh to render it on, so the `material` field is part of Model (and SkinnedModel). Set it at add time or assign the field later; properties are registry-wide. Public fields: `model`, `material` (`AssetRef<material>`), `tintR/G/B`, `tintBlend`, `outlineR/G/B`, `outlineIntensity`, `outlineOccluded` (`"hide"`, the default, hides the rim where geometry stands in front of the mesh; `"dashed"` draws it there in dashes, the `occluded` choice of `@builtin::modules.outline`). Methods: `:setTint(color, blend?)` (color: `{r, g, b}` array or `{r=, g=, b=}` map), `:clearTint()`, `:setOutline(color, intensity?)`, `:clearOutline()`, `:setMaterialProperty(prop, value)`, `:getMaterialProperty(prop)`, `:getMaterialPropertyNames()`. ```luau entity(id).component.add("Model", { model = "cube", material = "gold" }) entity(id).component.get("Model").material = "checkerboard" -- swap material entity(id).component.get("Model"):setTint({1, 0, 0}, 0.5) entity(id).component.get("Model"):setMaterialProperty("roughness", 0.2) ``` **Tint is synced.** Every `tint*` field replicates, so `:setTint` is the colour every participant sees. A colour that changes every frame on many entities (a stress map, a heat map, a damage flash, per instance colour) belongs in an instance-data lane instead: wear `@builtin::materials.instance_color` (or `instance_color_unlit`) and write `renderer.instanceData.set(id, 2, r, g, b, coverage)`, which replicates nothing and costs about a twentieth of a tint write. `guides { path = "topics/rendering-instance-data" }` has the lane layout.
▲ 0↑ born
▣
module · born here
❒asset
# recording The editor's recording service. The F9 command, the Recording panel, the top bar's record button and the `recording` toolbox all call it. A take is an `av.record` take filed under `/zero/source/local/recordings/`: this machine's own content, streamed to disk as it records, kept across restarts and outside the world's sync. The service keeps no state; what is recording, where, and how far along it is reads off `av.status()`, so any caller reports the same take. ## Exports - `M.start(opts?) -> (path?, reason?)` — `opts = { scope?, camera?, fps?, audio?, width?, height? }`. `scope` is `"viewport"` (the scene view as it shows, no panels; the default) or `"window"` (the whole editor window). Yields: run it where it can. - `M.stop() -> (Take?, reason?)` — `Take = { path, bytes, seconds }`. Waits for the engine to file the take. - `M.toggle(opts?) -> boolean` — true when it started a take. - `M.status() -> Status` — `{ recording, path, seconds, bytes, scope, error }`. - `M.list() -> { Entry }` — `{ path, bytes, modified? }`, newest first. - `M.delete(path) -> boolean` — a take by file name or path; the take in flight is refused. - `M.save(path) -> (boolean, string?)` — `userfile.save` of the take. - `M.declareCommand()` — declares `recording.toggle` on F9. ## Usage ```luau local Recording = require("modules.api.editor.recording") task.spawn(function() local path = Recording.start({ scope = "window" }) task.wait(5) local take = Recording.stop() print(take and take.path, take and take.bytes) end) ```
▲ 0↑ born
▣
module · born here
❒asset
# editorRegistry The single registry every editor surface is built from — builtin tabs and world panels alike. The engine's own tools register through the same public API a world uses. Two surfaces consume the registry: the dock service (`system_tools.module`) renders whatever panels are registered, sorted by `order`, and the top bar (`EditorTopBar.component`) builds its menu bar from the registered menus and each panel's `menu`/`order`. Both subscribe to `onChanged` so add/remove is live. Registrations run through two paths, both ending in `addPanel`: builtin tabs register from `modules.api.editor.system_tools.panels` (the require IS the registration), and world panels register via an `editorPanel` asset whose `onRegister(self)` hook calls `addPanel`. State lives in a fixed `_G` slot so it survives hot-reload and edit↔play mode flips. A duplicate id replaces the prior registration, which is how a world overrides a builtin tab and how hot-reload re-registers cleanly. ## Panels and menus - `M.addPanel(spec) -> boolean` — add (or replace) a dock panel. `spec`: `id` (required, unique), `build` (required, `(state) -> widget`), `label?`, `menu?` (default `"window"`), `order?`, `refresh?`, `onCallback?`, `onMount?`, `tick?`, `float?`. - `M.removePanel(id) -> boolean` — remove a registered panel by id. - `M.addMenuItem(spec) -> boolean` — add (or replace) a clickable action item that runs `onClick`, with no associated panel. `spec`: `id` (required), `onClick` (required), `label?`, `menu?`, `order?`. - `M.removeMenuItem(id) -> boolean` — remove a registered action item. - `M.addMenu(spec) -> boolean` — add (or replace) a top-level menu in the bar. `spec`: `id` (required), `label?`, `order?`. - `M.removeMenu(id) -> boolean` — remove a top-level menu and cascade-drop every item/panel that targeted it. ## Introspection and subscription - `M.list() -> { panels, items, menus }` — snapshot copies of current registrations for introspection. - `M.onChanged(fn) -> handle` — subscribe to any add/remove mutation; `fn` runs with no args. - `M.offChanged(handle) -> boolean` — unsubscribe. ## Host accessors (dock service + top bar) - `M.setDock(controller?)` — publish (or clear with `nil`) the live `DockController`. - `M.dock() -> DockController?` — the live dock controller, or `nil` when no dock is mounted. - `M.panelsSorted() -> {spec}` — live dock panels sorted by `(order, id)`, including `build`. - `M.menuModel() -> {menu}` — the full top-bar menu model: every menu in bar order, each carrying its entries (`{kind="panel", id, label}` or `{kind="action", id, label}`) in `order`. The `DockController` type is `{ open, close, toggle, isOpen }` plus optional `getLayout` / `restoreLayout` for layout persistence. ## Usage ```luau local editor = require("@builtin::modules.api.editor.registry") editor.addMenu({ id = "mygame", label = "My Game", order = 70 }) editor.addPanel({ id = "my_tools", label = "My Tools", menu = "scene", order = 50, build = function(state) return Z.lbl("hello") end, }) editor.addMenuItem({ id = "act", menu = "scene", label = "Go", onClick = function() end }) ```
▲ 0↑ born
▣
module · born here
❒asset
# editor_ops Delete and duplicate the current editor selection, each as one undo step. Delete despawns every selected entity and clears the selection; duplicate clones each selected entity via `entity.duplicate` — a full component, attribute, visual, and material clone that includes descendants — and selects the copies. Both wrap the batch in a multiplayer undo operation so a single Ctrl+Z reverts the whole action. The editor scene entrypoint binds these to Delete and Ctrl+D.
▲ 0↑ born
▣
module · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
# watch A watch over the entities holding a set of components. `w:changed()` answers whether anything a reader of those entities could see is different from the last time it was asked, so a system that derives something from them every frame (an overlay, a validation, a cache) derives it again only when it has to. ## Exports - `M.new(...) -> Watch`: a watch over the entities holding any of the terms. A term is a native component type (`ecs.Light`) or the name of a script component (`"PlayerSpawn"`); anything else raises. - `watch:changed() -> boolean`: true when, since the previous call, a native component the watch names was added to or written on an entity, an entity holding one left that set (despawned, or the component removed), or an entity holding any of its terms moved. For script terms it is also true when a component was added to or removed from any entity, or any component's public field was written. The first call answers true. ## Usage ```luau local EcsWatch = require("modules.api.engine.ecs.watch") local lights = EcsWatch.new(ecs.Light, "ReflectionProbe") task.loop(function() if lights:changed() then rebuildOverlay() end end) ```
▲ 0↑ born
▣
module · born here
❒asset
# frame_bounds Bounds union and exact frustum fitting — the math behind "put this subject in frame". `fit` solves for the camera distance that keeps every corner of a box inside the frustum at a given orbit angle. That is exact for any shape at any angle, which a circumscribed sphere is not: a sphere frames the DIAGONAL of the box from every direction, so a 14 x 0.5 x 14 plate backs the camera off nearly 1.4x further than its silhouette needs. Two consumers share this one implementation: the capture toolbox's framed shots and editor frame-selection. Toolboxes are self-contained and never cross-require, so the math lives here as a module rather than inside either. ```lua local FrameBounds = require("@builtin::modules.frame_bounds") local box = FrameBounds.union({ FrameBounds.ofEntity(entity.find("player")), FrameBounds.ofEntity(entity.find("prop")), }) local framed = FrameBounds.fit(box, { fov = 60, aspect = 16 / 9, angle = { 0, 20 } }) -- framed.px/py/pz is where the camera goes, framed.cx/cy/cz is what it looks at. ``` ## Exports - `FrameBounds.union(boxes) -> Aabb?` — the AABB enclosing every box in the list. `nil` when the list is empty (or holds nothing with `min`/`max`), which is the signal that there is nothing to frame. - `FrameBounds.ofEntity(target) -> Aabb?` — world-space bounds of an entity and its descendants (`hierarchyBounds`, covering a character root plus its skinned mesh and bones), falling back to the entity's own mesh `bounds`. `nil` when the target has no renderable geometry. - `FrameBounds.fit(box, opts?) -> Framed` — a camera pose that frames `box`. `opts` is `{ fov = 60, aspect = 16/9, margin = 1.15, angle = { yawDeg, pitchDeg } }`; `angle` also accepts `{ yaw = , pitch = }`. Returns `{ px, py, pz, cx, cy, cz, distance, radius, fov, near, far, center, size }` — camera position, look-at point (the box centre), the fitted distance, the bounding-sphere radius, geometry-derived near/far clip planes, and the box's centre and full size. A degenerate (point) box gets a short fixed distance so the camera is not sitting inside the subject. - `FrameBounds.fitDistance(hx, hy, hz, dx, dy, dz, tanH, tanV) -> number` — the corner projection itself: the smallest distance along the orbit direction `(dx, dy, dz)` (subject toward camera, unit length) that keeps all eight corners of the half-extent box inside a frustum with half-angle tangents `tanH` / `tanV`. `fit` applies `margin` to this; call it directly when you already have a direction and want the raw fit.
▲ 0↑ born
▣
module · born here
❒asset
# edui.app (module) The `edui` reactive core. An `App` owns one `ui.*` screen and turns the string-callback-id protocol into ordinary closures. `ui.*` dispatches interaction through string ids because closures cannot cross the FFI boundary: a widget carries `props.onClick = "<id>"`, and the screen's registered env receives `onCallback(id, data)`. An `App` hides that — during a build it allocates an id per closure and records id→closure, and its single `onCallback` looks the id up, calls the closure, and rebuilds. ## Surface - `new(screenName, opts?) -> App` — `opts.layer` is a render-layer mask applied via `ui.setScreenRenderLayer` on first register; `opts.callbackKey` overrides the env key. - `App:mount(builderFn)` — register the callback env, run the first build. `builderFn(app) -> widgetTree` is re-run on every rebuild. - `App:cb(closure, key?) -> id` — the id to place in a widget's `on*` prop. Pass a stable `key` so the id survives a rebuild, which is required for anything the renderer tracks by id (focus, drag, `ui.widgetState`). - `App:dispatch(id, data) -> handled` — what the broadcast calls. Returns false for an id belonging to another surface so a host can keep routing. - `App:markDirty()` / `App:rebuild()` — a rebuild requested *during* a build is coalesced into a single follow-up, so a handler that mutates state and a builder that reads it never recurse. - `App:unmount()` — release the env and unregister the screen. - `current()` — the app whose builder is running right now, or nil outside a build. The `edui` primitives read this, which is why an author passes a closure and never threads the app through every call. Builder errors are logged rather than thrown, so one bad build never wedges the editor. ```luau local edui = require("modules.edui") local app = edui.createApp("myPanel") app:mount(function(a) return { type = "vertical", children = { { type = "button", props = { text = "Save", onClick = a:cb(function() save() end, "save"), } }, }, } end) ```
▲ 0↑ born
▣
module · born here
❒asset
# editorCommands The command registry — the single place an editor action is declared. One declaration is rendered by four surfaces: the menu bar, DataView context menus, the command palette, and the keymap. `EditorRegistry`'s `addMenuItem` is a thin wrapper over `declare`, so every menu action is a command. A command is `{ id, title, category, menu?, order?, keys?, enabledWhen?, run }`. `ctx` passed to `enabledWhen`/`run` is the selection service's `context()` augmented by the caller: `{ scope, refs, primary, view?, item? }`. ## Exports - `M.declare(cmd) -> boolean` — register/replace by id (duplicate replaces). - `M.get(id) -> Command?` - `M.list() -> { Command }` — sorted by (category, title). - `M.remove(id) -> boolean` - `M.isEnabled(id, ctx) -> boolean` — true when no predicate, else its result. - `M.run(id, ctx) -> boolean` — runs only when enabled; returns whether it ran. - `M.conflicts() -> { { keys, ids } }` — keys claimed by more than one command. - `M.commandForKey(keys) -> id?` — the last declarer wins a contested key. ## Usage ```luau local Commands = require("@builtin::modules.api.editor.commands") Commands.declare({ id = "asset.delete", title = "Delete Asset", category = "Assets", keys = "Delete", enabledWhen = function(ctx) return #ctx.refs > 0 end, run = function(ctx) ... end, }) ``` ## Notes - State lives in a fixed `_G` slot, seeded pre-seal by the boot chain; it survives hot-reload and edit↔play flips. Mutations after boot write into the nested `byId` / `keyClaims` tables only. - A duplicate id replaces the prior declaration and rebinds its key. - Conflicts are surfaced (`conflicts()`), never silently dropped; the last declarer wins the live binding via `commandForKey`.
▲ 0↑ born
▣
module · born here
❒asset
# editorSelection Named selection scopes for the editor. A scope is an independently tracked, ordered set of typed refs plus a primary (the last ref added or clicked). Distinct scopes never clobber each other, so viewport, outliner, inspector and asset browser share one answer to "what is selected" per kind. A ref is `{ kind: string, id: string }` — a stable id, never a display string, so rename/move never invalidates a selection. ## Exports - `M.scope(name) -> Scope` — get/create a named scope handle. - `M.set(scope, refs)` — replace refs in order; primary becomes the last. - `M.get(scope) -> { Ref }` — refs in click order (fresh array). - `M.primary(scope) -> Ref?` — last-clicked ref, or nil. - `M.clear(scope)` — empty a scope. - `M.toggle(scope, ref)` — add if absent, remove if present. - `M.add(scope, refs)` — add each ref not already present; primary becomes the last added. - `M.remove(scope, refs)` — remove each of `refs`; primary becomes the last remaining or nil. - `M.contains(scope, ref) -> boolean` — membership by `(kind, id)`. - `M.count(scope) -> number` — the scope's selection size. - `M.subscribe(scope, fn) -> handle` / `M.unsubscribe(scope, handle) -> boolean`. - `M.context() -> { scope, refs, primary }` — last-focused scope, for command ctx. ## Usage ```luau local Selection = require("@builtin::modules.api.editor.selection") local scope = Selection.scope("entity") Selection.set(scope, { { kind = "entity", id = "player_1" } }) Selection.subscribe(scope, function() refreshInspector() end) ``` ## Notes - State lives in a fixed `_G` slot, seeded pre-seal by the boot chain (`prelude.luau`); it survives hot-reload and edit↔play flips. Mutations after boot write into nested tables only. - `set` / `toggle` / `clear` mark their scope as last-focused, which drives `context()` and therefore which scope commands act on. - The service holds the editor's selection state in Luau. Refs handed back by `get` / `primary` / `context` are copies, so a caller can hold or mutate them without touching internal state.
▲ 0↑ born
▣
module · born here
❒asset
# appMenu The app's menu: the one menu the pause action opens, in every profile and on every platform. The pause action is Escape, a gamepad's Start, the on-screen Menu button on a touch screen (`inputMaps/app.inputMap`), and the left controller's menu button in a headset. Pressing it again goes back one step inside the tab on screen, and closes the menu from the tab's first step. Opening the menu pauses nothing: every world is shared, and keeps running. ## Tabs The menu is a host of tabs, and every tab is a `.menuTab` asset (`assetTypes/menuTab.assetType`): - **World**, the world's own tab: the `.menuTab` in the world's `/source`. A new world starts with `menuTabs/game.menuTab` to rewrite; a world with none shows its title, Resume and the way to another world. - **People** (`menuTabs/people.menuTab`): while a world runs, the world, the people and agents on it and its world chat, each with Report, which opens the report sheet, and Block; and every account the person blocked, each with Unblock (`people`, `report`, `blocks`). - **ZeroMind** (`menuTabs/zeromind.menuTab`): the worlds to play and make, search, and every world, part and creator page (`launcher`). - **System** (`menuTabs/system.menuTab`): the client settings, each group a section, VR among them in a headset (`clientSettings`). A tab asset in another library, or in the dependency tree of a world installed into this one, adds nothing. ## Presentations The menu draws a frame around the tab on screen, laid out for the device (`appMenu.presentation()`): - **desktop**: full-window, the brand and the tabs across the top beside Resume and Enter VR; - **phone** (Android, or a screen narrower than a tablet): full-screen, a header naming the tab over the body and the tabs along the bottom, within thumb reach; - **vr**: a home menu on a curved world panel at arm's reach, Resume, Recenter and Exit VR along its top and the tabs along its bottom edge, sized for a laser or a pinch. A standalone headset app, which has no window to return to (`xr.returnsToFlat()`), offers Quit in place of Exit VR, ending the app as the headset's own Quit does. A tab's `build(ctx)` draws its body for `ctx.presentation` in the room `ctx.width` x `ctx.height` the frame leaves it. ## Reaching it `appMenu.open(tab?)`, `appMenu.close()`, `appMenu.toggle()` (what the pause action does), `appMenu.select(tab)`, `appMenu.isOpen()`, `appMenu.activeTab()`, `appMenu.tabs()`, `appMenu.presentation()` and `appMenu.redraw()`, which a tab calls after its own state changes to have the menu build its body again.
▲ 0↑ born
◇
component · born here
❒asset
# Camera Manages viewport priority, render-to-texture, and capture. State is stored in the native `Camera` ECS component; the Rust camera system handles render scheduling and render targets. Public fields: `fov`, `near`, `far`, `priority`, `textureHandle` (the guid of the texture the camera renders into; empty = main viewport), `renderLayers` (which render layers this camera draws — a space-separated spec of names, e.g. `"all"`, `"all !ui"`, or `"default sky"`; `ui`/`sky`/`debug`/`EditorUI` are built-in layers), `postProcessing` (whether this camera runs the post-process chain), `debugChannel`, plus the behavior slot below. Methods: `:lookAt(target)` (entity id string OR `{x, y, z}` table), `:render()`, `:capture()`, `:setTargetTexture(tex?)` (a `renderer.texture.create` handle to render into, or nil for the viewport). ```luau entity(id).component.add("Camera", { fov = 90, priority = 10 }) entity(id).component.get("Camera"):capture() ``` The scene's play-mode camera is reached as `layers.active.camera`, a handle that reads and writes the fields above on whichever entity currently carries them. `layers.active.camera.entity` is the entity ref for that camera and `layers.active.camera.entityId` its id string, so a script that needs to attach something to the camera — an `AudioListener`, a child entity — goes through the ref: ```luau local cam = layers.active.camera cam.fov = 70 -- the camera's settings cam.entity.component.add("AudioListener") -- the entity carrying them ``` ## How the camera moves: `behavior` and `follow` A `Camera` does not move itself. `behavior` names a component that does, and setting it attaches that component to this entity. Clearing it detaches whatever was attached. ```luau local cam = entity(id).component.get("Camera") cam.behavior = asset.ref("@builtin::controller.orbital_follow", "component") cam.follow = playerBody ``` The attached behavior is an ordinary component on the camera's entity, so it is tuned the way any component is: read it with `component.get` and set its fields there. A `component.add` of the same type configures the instance the slot attached instead of adding a second one: the values it passes are written onto that instance and its proxy is returned. That add is the form a scene `build.luau` tunes the behavior with, because its values are saved with the scene and the loaded Camera's behavior takes them back. A key the component reads only as it is created (one of its `initKeys`, a private field) refuses the add and names the key. ```luau cam.behavior = asset.ref("@builtin::controller.third_person_follow", "component") local rig = entity(id).component.get("third_person_follow") rig.cameraDistance = 6 -- the same, as an add of the type the slot attached entity(id).component.add("third_person_follow", { cameraDistance = 6 }) ``` `follow` is the standard slot every shipped behavior reads. Set the follow target on the **Camera**, not on the behavior, so swapping behaviors keeps it. A behavior that finds its own `follow` field empty falls back to this one, which is what lets a rig keep tracking the player across a behavior swap. `followResolves` answers whether that slot names an entity that is live — `true` while it names a live one or names nothing at all, `false` once the target is despawned or the id names no entity. A rig whose target does not resolve holds its last pose, and this is the field that tells it from a rig posed correctly on a subject that has not moved. `camera.get` carries the same value beside `follow`, and a write naming an id with no entity behind it draws a warning where it lands. ```luau cam.followResolves -- false once the followed entity is gone tools.use("camera", "get", id).followResolves -- the same answer off the tool ``` The shipped behaviors live under `@builtin::controller.*`: `orbital_follow`, `third_person_follow`, `first_person`, `free`, `orbit`, `chase`, `isometric`, `rts`, `birds_eye`, `side_scroller`, `cinematic`, `menu`. ## Writing your own Any component can be a camera behavior. Write one that moves its own entity and attach it the same way: ```luau cam.behavior = asset.ref("MyChaseCam", "component") ``` `follow` lives on the Camera, so a behavior gets no property notification of its own when the target changes. Declare `onFollowChanged(newFollow, oldFollow)` to be told the moment it does — the Camera calls it on the component it attached, which is what lets a rig re-pose on the new subject at once. A behavior that reads `Camera.follow` on its own schedule declares nothing and is attached the same way. ```luau typed function public:onFollowChanged(newFollow: any, oldFollow: any) -- pose this entity against the new target end ``` To make it appear in the discovery catalog alongside the shipped ones, declare the `cameraBehavior` tag in the component's `.metadata`: ```json { "tags": ["cameraBehavior"] } ``` The tag governs **discovery**, not attachment. A tagged component is listed by `layers.active.camera.behaviors` and is what tooling offers when something asks "which camera behaviors exist"; an untagged component attaches just as well and simply stays out of that list. Tag the ones you want other people (and agents) to find. ```luau for name, ref in pairs(layers.active.camera.behaviors) do print(name, ref.identity) end ``` ## Texture colour space `textureColorSpace = "display"` applies the display transform when rendering into a texture. `"linear"` writes scene-linear values instead. `postProcessing` independently controls the effects chain in either mode. Floating-point targets retain values above one; normalized targets clamp to their representable range. The main viewport uses display encoding.
▲ 0↑ born
▣
module · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
# cmdPalette The editor's command palette: the whole engine tool registry under one keystroke. The menu bar's Tools button (Ctrl+K) opens a floating card — type to search every toolbox by name and purpose, pick a tool, and its typed argument schema renders as a form of real controls: text for strings, numeric fields for numbers, a checkbox for booleans, option chips for string-literal unions, three axis fields for a Vec3, and an options table expanded one level into its own typed rows. Run executes the tool and shows the returned value and stdout in place. The form is generated from `tools.get`'s schema, so every registered tool is reachable and a new tool appears with no UI work. Consumed by `edui.topbar`, which mounts it beside the menu bar and re-mounts it through `modules.watch` when this module's source changes.
▲ 0↑ born
▣
module · born here
❒asset
# `scene.shared.saver` Luau-side scene saver. Writes `scene.json` v6 — **authored intent only**. No captured runtime state. ## Public surface ```lua local saver = require("@builtin::assetTypes.scene.shared.saver") saver.save(name, opts?) -- name: logical scene name ("main") OR full VFS path -- opts.layer: layer name to read from (default layers.active.name or "main") -- Returns: the absolute VFS path written. ``` ## What is captured | Field | Source | Notes | |---|---|---| | `format`, `version` | constants | Always `"scene"` + `6`. | | `entities` | `entity.findAll()` walk | Excludes `temporary` entities + the spawner-managed Player + primary Camera. | | `entities[].transform` | local position / rotation / scale | NOT world transform — local only. | | `entities[].components` | component.list + component.get | Strips `_`-prefixed runtime fields. | | `entities[].attributes` | `attribute.list` + `attribute.get` | The entity's key/value bag, written as a `{ [key] = value }` map; omitted for an entity that holds none. Holds the authored keys — a `_`-prefixed key is the engine's own session bookkeeping. | | `lighting` | `lights.snapshot()`, filtered | Scene-level `clear_color` + `sky` only. Directional / ambient / point lights persist as `Light` entities in `entities[]`. | | `player` | `sceneProxy.player_config` | Carried forward from load-time, authored only. | | `camera` | `sceneProxy.camera_config` | Carried forward from load-time, authored only. | ## What is NOT captured - Local player's position / rotation. Runtime drift; not authored intent. - Primary camera's transform. Runtime; behavior-driven. - Any entity flagged `temporary = true`. Debug helpers, runtime markers. - Internal component fields prefixed with `_` (e.g. `_velocity` on CharacterController). The spawner-managed entities (Player + primary Camera) are excluded because they're created on load by player_spawner / camera_spawner from the scene's declarative `player` + `camera` blocks. Saving them would double them on the next load. ## Parts The module is a folder of parts, each a module of its own that `init.luau` requires: - `scene_saver.serialize`: one live entity as the record a scene file carries. - `scene_saver.recordDiff`: the comparisons the record diffs are built from. ## When to use `layers.active:save(name)` (Phase 6) routes through this module. Callers that want a state snapshot (save-game systems, undo stacks) should use `world.debugSaveToDisk(...)` instead — that captures runtime state by design.
▲ 0↑ born
◇
component · born here
❒asset
# Asset Promote the bundle's spawned children from temporary to permanent scene state and remove the Asset component, "baking" the bundle's contents directly into the owning scene. Subsequent saves persist the baked entities verbatim and stop replaying the bundle template. Location: `src/lua/lib/components/Asset.component`
▲ 0↑ born
▣
module · born here
❒asset
# gizmo Transform gizmo — draggable translate/rotate/scale handles at the selection pivot. Handles draw through a debugViz provider; hit-testing and dragging use `gizmo_math` against the cursor's `screenToRay`. Each drag edits every selected entity through the entity proxy transform setters and is wrapped in a multiplayer undo operation, so a whole drag reverts as a single Ctrl+Z. The mode (translate / rotate / scale), the local/world space toggle, and the active drag live in module state; the editor scene entrypoint calls `tick` every frame and switches mode from the tool hotkeys. Handles size themselves to stay a roughly constant on-screen length, and holding the snap modifier quantizes translation to a grid, rotation to angle steps, and scale to fixed steps.
▲ 0↑ born
▣
module · born here
❒asset
# edui.shell (module) The editor dock shell on the CSS-parity `ui.*` surface. One edui app owns a `ui.*` native `dockArea` whose children are a `dockPanel` per registered edui panel — real `egui_dock` tabs, splits and drag, with the arrangement persisting across rebuilds because the dockArea and each dockPanel carry a stable `id`. ## Why a separate registry The shell keeps its own panel registry (`addPanel` / `removePanel` / `panelsSorted`), distinct from the deprecated zui `editor.registry`. That keeps the zui editor completely untouched while panels migrate to edui one at a time: the zui dock renders the zui-framework panels it always has, and the edui shell renders the edui panels registered here. The two registries fold into one at cutover, when the zui dock is retired. ## One app, one reactive loop `App.rebuild` sets the shell as the building app before it calls `buildShell`, so a panel's `build()` — which uses `edui.current()` to register its closures — wires every callback onto the ONE shell app. All interaction for every panel flows through the shell's single callback env, and a click anywhere rebuilds the whole dockArea. That is why the shell needs no per-tab scheduler (unlike zui's `dockApp`): the edui App is the scheduler. ## Usage ```lua local edui = require("@builtin::modules.edui") edui.shell.addPanel{ id = "entities", title = "Entities", order = 10, build = function() return edui.panel{ title = "Entities", body = edui.tree{ ... } } end, } edui.shell.mount() -- registers the screen on the EditorUI layer -- each editor-update frame: edui.shell.update(dt) -- liveness rebuild every `refresh` seconds ``` `mount(opts?)` takes `{ refresh? }` (seconds between liveness rebuilds, default 0.5). `refresh()` forces an immediate rebuild; `unmount()` tears the screen down but keeps the panel registrations for a later `mount`.
▲ 0↑ born
▣
module · born here
❒asset
# create What the editor's Add menu creates. `edui.create` makes an empty entity, each built-in primitive the mesh registry resolves (cube, sphere, plane, ...), a point light, a spot light and a camera, five metres along the editor camera's view and no lower than half a metre above the ground, as one undoable step, and selects what it made. `declare` puts each of them in the editor command registry under the `add` menu (`add.cube`, `add.light.point`, `add.camera`, `add.empty`, ...). The top bar's Add menu and the Hierarchy's `+` menu both list every command declared under `add`, so a world or a panel that declares one of its own (`commands.declare{ id, title, category, menu = "add", order, run }`) appears in both.
▲ 0↑ born
▣
module · born here
❒asset
# help The editor's Help menu and the dialog it opens. `edui.help.open(page)` shows one page over the editor: - `start`: Getting started, the first things a person does in the editor (add an object, select it, move it, look around and move the view, play, save the scene, build with DotBot, change the layout, find more). Its Help menu entry names moving the view, the first thing a person asks. - `shortcuts`: the keyboard shortcuts, read from the live keymap every time the page builds: each control a live input map binds to the keyboard or the mouse, keys and mouse input named the way a person names them (`Left Ctrl`, `Mouse movement`, `Mouse wheel`), a control whose gate waits for the right mouse button held prefixed with that hold, and each command declared on a key no control already answers (`edui.help.shortcuts()` returns the same rows as data). - `about`: the editor and the world it is bound to. `declare` puts `help.start`, `help.shortcuts`, `help.docs` (the Docs panel, its search field focused) and `help.about` in the editor command registry under the `help` menu. The top bar's Help menu lists every command declared under `help`, so a world or a panel adds an entry by declaring one there.
▲ 0↑ born
▣
module · born here
❒asset
# edui.widgets (module) Editor-chrome primitive builders for `edui`. Each returns a styled `ui.*` widget subtree; the common ones are re-exported flat onto `edui` (`edui.panel{...}`, `edui.text{...}`, `edui.iconButton{...}`, …). Two things make these "framework" primitives rather than raw `ui.*`: 1. **They read the active theme's editor tokens** (`editor-row-height`, `editor-selection-bg`, `editor-hover-bg`, `border`, `radius-md`, …) via `ui.getToken`, so chrome looks like the editor by default and restyles with the theme. `edui.palette()` returns the resolved set. 2. **Interactive builders register their closures with the currently-building `edui` app** (`edui.current()`), so you pass `onClick = function() end` and never touch a callback id. ## Builders - Containers: `vbox`, `hbox`, `spacer`, `divider`, `panel`, `toolbar`. - Content: `text`, `svgIcon`, `iconButton`, `button`. - `panel{ title? | toolbar?, body }` is the standard dockable-panel shell (a header over a height-filling body). - `nodeGraph{ key, nodes, edges, selected?, height?, onSelect?, onMove?, onConnect?, onDisconnect?, onDelete?, onOpen?, onField?, redraw? }` — a node graph on one canvas: titled nodes with output and input ports, wires between them, and a value on every input port that has no wire into it. Drag the background to pan, scroll to zoom, drag a node to move it, drag from a port to another port to connect, drag a connected input away to pick its wire up, click a value to edit it where it stands, press Delete to remove the selection. The widget draws and reports; the owner holds the graph and applies what `onField`, `onConnect`, `onDisconnect`, `onMove` and `onDelete` report. Nodes with no position are laid out left to right over the wires. `edui.nodeGraphView(key)` answers where the view stands and, through its `locate`, where a port or a value is on the canvas. - `iconButton{ d, tooltip?, active?, onClick, key }` — a hoverable/active icon square; `d` is an SVG path (or full `<svg>`). Icons are inline SVG (feather/lucide-style 24-view stroke paths), matching the editor's icon language — pass a path `d` and it is wrapped for you.
▲ 0↑ born
▣
module · born here
❒asset
# Observed scene operations SceneJournal stores field edits with their original observed and proposed values. Each entry belongs to a world, branch, scene GUID and unique editing session. Session sequence numbers order operations under `scene_dirty/operations/<session>/<sequence>.json`. `session()` creates a session token. `create(snapshot, session, sequence, previous, current, resolvers, attribution?)` normalizes the two scene documents and records their field differences. `append(sceneFolder, entry)` writes an immutable entry; it returns the path and whether an accepted receipt already settles the entry. Reusing a pending sequence with different bytes is refused. The latest retired sequence can be retried with identical bytes; older retired sequences are refused. `createChanges(observed, session, sequence, entities, settingsEdits, attribution?)` records incremental normalized changes. `observed` carries the scene GUID, world, branch and accepted revision. The live scene writer uses this form for changed entities and settings. `visible(sceneFolder, resolvers, session?, previous?)` composes pending entries over the locally accepted artifact. An optional session restricts which pending values are shown. Conflicts identify their journal operation. Structural conflicts retain the supplied previous complete document, or the accepted artifact. The read leaves all source files unchanged. `resolveFields(snapshot, path, resolutions, resolvers)` chooses values for exact changed fields. Each selection has an entity id (omit it for scene settings), a field path and a `recorded` or `accepted` choice. Other proposed changes remain. Every remaining conflict must be resolved before the transaction is ready, and duplicate or absent field selections are refused. `review(snapshot, resolvers)` returns captured operation rows, their recorded changes, current conflicts, and whether an earlier entry in the same session must settle first. `resolve(snapshot, path, choice, resolvers)` prepares a resolution of one whole reviewed operation. Choose `recorded` to retain its proposed fields against the reviewed accepted values, or `accepted` to keep those accepted values. Structural validation still applies. The resulting transaction checks the reviewed source revisions and retires only that operation with its receipt; a stale resolution leaves it intact. `prepare(latestSnapshot, path, resolvers)` recovers the captured entry, verifies its identities and predecessor, and prepares a scene transaction. Commit it with `SceneCoordinator.commit`, then use `awaitApplied` before reading the accepted revision locally. Successful commit updates the artifact and authored intents, removes the consumed journal entry, and records its sequence and checksum atomically. A stale operation, validation failure or field conflict retains the entry for inspection and resolution. The accepted scene state retains one receipt per editing session.
▲ 0↑ born
▣
module · born here
❒asset
# debugViz The shared edit-mode debug-visualization core. Owns the ONE anchor entity, the ONE vertex-colour line material, the ONE batched vertex/index compute-buffer pair, and the ONE render feature that every debug-visualization gizmo draws through. Individual gizmos (bounds boxes, camera frustums, ...) are **providers** — small modules that append their own geometry into the shared batch every tick, instead of each owning their own GPU state. ```lua entity.spawn("DebugViz"):component.add("DebugViz") ``` ## How it fits together - `DebugViz.component` owns the lifecycle: registers the built-in providers and calls `debugViz.update(dt)` every edit-mode tick; `onDisable`/`onDestroy` call `debugViz.teardown()`. - `debugViz.registerProvider(name, fn)` registers `fn(emit)` under `name`. Registering an existing name replaces its function. - `debugViz.update(dt)` calls every registered provider with an `emit` handle, which records what each call asked to draw, then uploads the combined vertex/index buffers (grow-only capacity). The upload follows what changed: a tick that drew the same thing writes nothing, a tick where some draws changed in place (the same commands, the same vertex counts) writes only their vertices, and a tick where a draw appeared, went or changed its vertex count writes the whole batch. - `emit.section(changed, draw)` marks a part of a provider's drawing that changes apart from the rest: `draw(emit)` runs when `changed` is true or the section has not drawn before, and otherwise its last recording is replayed without running `draw`. - `debugViz.state()` returns the latest `{ vtx, idx, anchor, indexCount, uploadedBytes, shapes, icons }` for the render feature to draw. - `@builtin::renderFeatures.debugViz` reads `state()` every frame and draws the batch through one Draw pass, using `@builtin::shaders.debugGeometry` — a solid-colour shader that reads each vertex's baked colour, so every provider can use its own colour in the same draw call. Each instanced shape (below) draws in a Draw pass of its own. The draw needs an anchor entity with an IDENTITY world transform and a render-object (so the Draw pass has a valid instance slot and a material to override) — this module owns one, spawned lazily, internal so it stays out of the inspector and excluded from scene saves. ## Writing a provider ```lua local debugViz = require("@builtin::modules.debugViz") local function tick(emit) emit.box({ x = -1, y = -1, z = -1 }, { x = 1, y = 1, z = 1 }, { 1, 0, 1, 1 }) emit.line({ x = 0, y = 0, z = 0 }, { x = 0, y = 5, z = 0 }, { 1, 0, 1, 1 }) end debugViz.registerProvider("my_gizmo", tick) ``` `emit.box(min, max, color?)` and `emit.line(a, b, color?)` append world-space geometry into the shared batch for this tick; `color` is an `{r, g, b, a}` array baked per-vertex (defaults to amber if omitted). A provider that needs to exclude the shared anchor entity from its own scene queries reads `debugViz.anchorId()`. A provider that hands the same packed geometry back every tick (`emit.rawLineSoup(bytes, vertexCount)`) costs nothing to upload while the geometry stays the same string. ### Instanced shapes `emit.shape(entityId, key, bytes, vertexCount)` draws a line-list blob in the local space of `entityId`. The blob is uploaded once under `key` and drawn once per entity that asks for it, through that entity's own world transform: any number of entities sharing a shape cost one GPU buffer, and moving them costs no per-tick work. A `key` names immutable bytes (geometry that changes takes a new key), the buffer lives for as long as some entity asks for the key each tick, and the entity needs a render object (a Mesh). `debug_wireframe` draws every mesh this way. ## API - `debugViz.registerProvider(name, fn, opts?)` — register (or replace) a provider. `fn(emit)` runs once per edit-mode tick. `opts.label` is the name the Debug menu and the Rendering panel list the overlay under: text as written, or an `i18n.text` value (`i18n.text("hud.my_gizmo")`), which reads in the editor's language. Without one the overlay is listed by `name`. `opts.default` is whether the overlay starts on, and `opts.available()` whether it currently has anything to show. - `debugViz.providers()` — every provider that currently has something to draw, in registration order, as `{ name, label, enabled }` with the label in the editor's language. - `debugViz.anchorId()` — the anchor entity's id, or `nil` before the first tick. - `debugViz.update(dt)` — run every provider and upload what their drawing changed. - `debugViz.state()` — the latest batched draw, or `nil` before the first tick. - `debugViz.teardown()` — tear down the feature, material, buffers, and anchor entity. Registered providers stay registered. - `debugViz.MATERIAL` — the registry key of the shared vertex-colour line material the render feature draws with.
▲ 0↑ born
·
toolbox · born here
❒asset
# sceneAuthoring The scene-change contract — the scene only ever changes by reviewing the pending changes and accepting them. You build live — spawn entities, edit existing ones, create assets in play, register effects and UI — and the scene stays untouched until you review and accept. There is no silent save anywhere in this flow. A review is composed within the frame it is called in, so it describes that frame, and the session keeps running — on a world several agents share, one agent reading its own pending changes leaves every other agent working. A verdict reached later reconciles what it writes against the scene as it stands then. Accepting writes the reviewed items into the world's source; rejecting keeps them live for the session but never enters them into the scene. A review can be accepted or rejected whole, or narrowed to numbered items, entity names, name parts, or group labels. The review reports, per numbered item: - **added entities** — clustered so one spawn batch reads as one decision, with component shape, spatial span, and materials on the line. - **updated entities** — field-level diffs against the scene. - **assets the changes use** — play-created ones are saved into the world's source on accept; references with no backing asset are flagged as broken-on-reload. - **edited source files**: code and assets modified during play, saved over the originals on accept. A folder asset is one item, its edited files kept or dropped together. - **session effects and UI screens** — runtime-only registrations that will not come back on reload. Accepting also saves the play-created assets the accepted entities reference — a scene must never point at files that vanish when play ends.
▲ 0↑ born
▣
module · born here
❒asset
# language_menu The person's language on this client. It declares the **Language** group of the client settings (`clientSettings`), a tab of the app menu's System section. A player reaches it from the pause menu and from the world chooser; the editor reaches it from its Zero menu (**Settings**), and its own **Settings** menu lists the same choices under **Language**. The group holds one setting, `language.locale`: - **Follow my device**: no choice of the person's, so the language follows the chain `i18n.sources()` states: the language ZeroMind shows them, then their device's (or browser's) languages, then English; - every language the engine offers (`i18n.offered()`), each by its own name (`nativeName`), so a person always recognises their own. The setting's description says which language is in force and why (`language_menu.inForce()`). A pick is the person's choice (`i18n.choose`), kept on the device for their account, so it holds on the next start; the setting reads it back from `i18n.choice()` rather than keeping a copy of its own (`kept` in `clientSettings.register`). `choices()` lists the choices with the one the setting holds marked, and `pick(value)` takes one (`"device"` clears the choice).
▲ 0↑ born
▣
module · born here
❒asset
▲ 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
·
assettype · born here
❒asset
# Component (asset type) A component is a reusable behavior + data unit attached to an entity. The component file declares public fields, methods, and lifecycle callbacks; the engine instantiates one per attachment and drives its hooks every frame. Components are the primary unit of gameplay code — movement, AI, animations, UI panels, network sync, and per-entity state all live here. ## When to use one - You need per-entity state that survives across frames. - You need per-entity behavior driven by engine lifecycle hooks (`start`, `update`, `onDestroy`). - You want to expose configurable fields to designers / `entity.spawn` callers / scenes without code changes. If you need a stateless pure-function library, use a `.module`. If you need to generate content declaratively, use a `.service`; compute work belongs in a `.computeShader`. ## Where it lives - Source: `/zero/source/.../<Name>.component/` - Identity: `<Name>` (the `.component` suffix strips from the identity, but the folder retains the suffix on disk). - Folder shape: - `init.luau` (or `init.lua`) — declares the component. **Required.** - `README.md` — instance-level documentation. **Required.** - `.metadata` — agent-editable tags + free-form fields. **Required.** The structural contract is enforced by `asset.validate` against this type's `type.yaml`. ## How to create one Always start with the scaffold — it guarantees the folder shape matches `type.yaml` from the moment it's on disk: ```luau asset.create("component", "<Name>") -- Creates: /zero/source/<Name>.component/ -- init.luau (canonical declare + public block + hooks stubbed) -- README.md (instance README template) ``` After scaffolding, edit `init.luau` to fill in the actual fields and behaviour. The component registers as soon as the file is written — hot-reload is automatic; no engine restart required. ## How it operates 1. **Registration.** Writing `init.luau` into a `.component/` folder indexes the asset, mints a guid (in the `.meta` sidecar), and surfaces the type to the engine's component registry. Same-frame visible to `entity.component.add`. 2. **Attachment.** `entity(id).component.add(name, data)` (or the batch form `tools.use("entityOps", "addComponents", targets, { [name] = data })`) attaches an instance. The `data` table's fields override the component's declared defaults; omitted fields take the declared default. The `data` values are copied into `public.*` BEFORE `awake()` runs. 3. **Lifecycle.** The hooks run in this order: - `awake()` — same frame as attach, immediately after the data copy. Initialise state, set up native bridges, register with other systems. Other components on the same entity may not have awoken yet. - `start()` — the next frame. Every component on the entity has completed `awake()` by then, so cross-component setup is safe here. - `update(dt)` — same frame as `start()`, then every frame after, for as long as the gameplay clock is running. `fixedUpdate(dt)` runs once per physics step, straight after it, with the step's `dt`, so a frame can run it several times or not at all; `editorUpdate(dt)` runs while the clock is held. Which of them ticks is decided by `engine.mode` AND `engine.paused` together — see **Per-frame hooks and the two axes** below, and `man modes`. - `onDestroy()` — when the component is removed via `component.remove` or when the owning entity is despawned. Release resources, drop native ECS components. For the full list (`onEnable`, `onDisable`, `fixedUpdate`, `editorUpdate`, `onPropertyChanged`, `onAssetReload`, `onModuleReload`, `onBeforeSave`, …) and the timing details, **read `man components` — that is the canonical lifecycle reference. Generic component patterns (declare blocks, public fields, sync, ECS bindings, typed methods) all live there.** 4. **Public surface.** Fields declared in `public` are inspectable, editable in the inspector, and persist with the entity. Methods are declared on that same table with a colon — `typed function public:method(args)` — and every one of them takes the component ref as `self`, so a caller invokes it with a colon too: `entity(id).component.get(name):method(args)`. That is the one calling convention a component ref answers to: the reflection methods `ref:fields()` / `ref:getField(name)` / `ref:setField(name, value)` take the same spelling. A function the chunk declares at file scope (`function helper()`) is the component's own, reachable from its hooks under its bare name; `public` is what the ref carries. 5. **Settings and the Inspector card.** `type.yaml` names the component's settings schema as `settings: { schema: { instance: "init.luau", export: "public" } }`: the `public` table IS the schema, and its values live on each entity the component is on, so `asset.schema(componentRef)` answers the Field descriptors and no values file exists. On an entity the Inspector shows the component as a card whose generic `settings` section edits those fields as typed controls, each edit checked against the schema and written to the live component as one undoable operation. `type.yaml` also names `inspector: { instance: "inspector.luau" }`: a component that ships an `inspector.luau` beside its `init.luau` shapes its card — the file returns `{ sections, replace, order }` (see `assetTypes/README.md`, "`inspector:`"), each section's `build(ctx)` reading `ctx.component` (the live component) and `ctx.selection.id` (the entity). `SceneModule.component/inspector.luau` replaces `settings` with the bound module's declared inputs. 6. **Events.** An `events` block declares typed moments the component fires from inside — `events = { onHit = Event({ dmg = Field.number(0, NoSync) }) }`. The owner fires with `events.onHit:fire({ dmg = 10 })`; outside code subscribes through the proxy's subscribe-only facade, `entity(id).component.get(name).events.onHit:connect(fn)` (`:once` / `:wait` too). Pass `Sync` as the event's second argument to replicate a fire to other peers. Events let one component react to another's moments without polling. Full reference: **`man components`**, Events section. 7. **Hot reload.** Editing `init.luau` reloads the component definition; live instances are reconciled with the new declaration in-place, and each crosses one lifecycle boundary: `onDestroy()` ends the running life, then `awake()` and `start()` construct the one that replaces it, and `update()` resumes on the next frame. `public` and `private` values carry across; module-level `local`s belong to the chunk, so the new life starts with them at their initial values and its `awake`/`start` are what fill them in. Whatever the old life handed elsewhere — a subscription, a shared registration, a spawned entity — is released in `onDestroy`, the call that pairs with the construction about to run. An edit that leaves the source byte-identical crosses no boundary at all. A field carries its value across when something stated it: a key of the `data` table the instance was attached with (a scene record's data is that table), or a write made since. Every other field takes the edited source's declared default, so changing a default reaches every instance that left the field to it. An instance that states its own value for a field whose default the edit changed keeps that value, and the reload logs a `[HotReload]` warning naming the field, the entity, the value kept and both defaults. ## Discovery - `asset.list("component")` — every registered component (engine + world + libraries). - `asset.inspect("<name>")` — identity, scope, public fields, lifecycle methods, source path, and this type README. `detail` carries the component's declared `fields`, `methods`, and `events`, parsed from its source — `tools.use("assets","describe", "<name>")` renders it as markdown, so a component's events are visible without opening its source. - `ls /zero/source/<Name>.component` lists the files the folder holds. - `entity(id).component.list()` — components attached to an entity. ## Per-frame hooks and the two axes `engine.mode` (`"edit"` / `"play"`) and `engine.paused` (the gameplay clock) are independent, and the per-frame hooks read them separately: - `update(dt)` / `fixedUpdate(dt)` tick while **the gameplay clock is running** — whichever mode the engine is in. - `editorUpdate(dt)` ticks while **the clock is held** — because the mode is `edit`, or because play is paused — and also alongside `update` whenever edit is running. Which gives four states, and this table is the contract: | `engine.mode` | `engine.paused` | hooks that tick | |---|---|---| | `edit` | `true` | `editorUpdate` | | `edit` | `false` | `update`, `fixedUpdate`, `editorUpdate` | | `play` | `false` | `update`, `fixedUpdate` | | `play` | `true` | `editorUpdate` | Entering edit sets `paused = true` and entering play sets it back to `false`, so a session that never writes `engine.paused` only ever sees rows 1 and 3 — which is where the shorthand "`update` is the play tick, `editorUpdate` is the edit tick" comes from. It is the two default rows of a four-row table, not the rule. **Row 2 is the one that surprises.** With `engine.paused = false` in edit — set by hand, or by a tool that advances the gameplay clock to sample it, such as a `capture.collage` given a `duration` — `update` and `editorUpdate` both fire, once each, every frame. A component that declares both and routes them to one body therefore runs that body **twice per frame**: ```luau local function drive(dt) ... end function update(dt) drive(dt) end function editorUpdate(dt) drive(dt) end -- twice per frame in row 2 ``` Nothing reports the doubling; it reads as an animation running at twice its intended speed. To get exactly one tick per frame in every row, ask which axis you meant and answer it in the body: ```luau function update(dt) drive(dt) end function editorUpdate(dt) if engine.paused then drive(dt) end end ``` A scene `entrypoint.luau` declaring the same two hook names is dispatched by the scene loader, not by this table: there `update` needs play AND running, `editorUpdate` needs edit, and play-paused ticks neither. Read `man scenes` before carrying a component's rule to an entrypoint. ## Authoring conventions - Annotate public fields with `--!desc` so the inspector + LSP show documentation alongside the field name. - Declare lifecycle hooks (`start`, `update`, `onDestroy`) explicitly rather than relying on engine defaults — readers can see at a glance what runs when. - Keep `update(dt)` cheap — it runs every frame per instance. Move heavy work to `start`, to a `.computeShader`, or behind a job (`man jobs`). - For multi-entity batching, prefer `tools.use("entityOps", "addComponents", targets, components)` over a loop of `entity(id).component.add` — it takes many targets and many components in one call. ## Common pitfalls - **Naming.** The component identity is the folder stem with `.component` stripped (e.g. `<Spinner>.component/` → identity `Spinner`). Don't repeat the suffix in the identity passed to `component.add`. - **`init.lua` vs `init.luau`.** Either is accepted (it's a `one_of_group: "entrypoint"`), but `.luau` is canonical. Mixing both in one folder is invalid. - **`update` in edit mode.** It runs whenever the gameplay clock is running, and entering edit stops that clock — so `update` is idle in a freshly-entered edit session and ticks again the moment anything sets `engine.paused = false`. Use `tools.use("wld", "play")` to test update logic under the mode it ships in; `tools.use("wld", "edit")` to return. See **Per-frame hooks and the two axes** above. - **Renaming.** Renaming the folder changes the identity. References to the component are recorded against the component itself, so renaming or moving it does not break them. ## Related types - `.module` — pure-function library, no per-entity state. - `.service`: a declarative content generator, no per-entity state. - `.preset` — a captured component configuration, replayable into `component.add` without re-typing fields. - `.bundle` — entity hierarchies that may carry component attachments as part of the bundle. ## In the Inspector Fields: its execution order, hooks, and how many methods and events it declares, then the fields its `public` table declares as read-only typed controls holding their defaults, with **Check** and **Open** for its entry file. Instances: a link to every entity carrying it. What its card shows on an entity comes from the component's own `inspector.luau`.
▲ 0↑ born
❒
package · born here
❒asset
# edui The editor UI framework, on the CSS-parity `ui.*` surface. An editor-only toolkit: panels author closures instead of callback ids, a dock shell over `ui.*` native docking, and typed editor-chrome primitives. Gameplay and normal world UI author raw `ui.*` trees and need none of this. **`edui.guide` beside this file is how to use it** — creating a panel, the spec it returns, how a panel is drawn and redrawn, the whole widget vocabulary, and how a panel reaches the selection and the dock. ## What installs - **`framework`** — everything under one table. From outside the package, `require("@builtin::~edui.framework")`; inside it, `require("~.framework")`. It carries `app`, `widgets`, `shell`, `topbar`, `query`, `fileDialog`, `worldDialog`, `stats`, and the chrome primitives flat (`panel`, `tree`, `field`, `section`, `text`, `button`, `menu`, …). - **`app`** — maps a panel's closures to `ui.*` callback ids, dispatches to them, and coalesces redraws. - **`widgets`** — the primitives, plus the typed inspector layer (`widgets.tree`, `widgets.fields`, `widgets.controls`). - **`inspector`** — the Inspector as an ordered list of sections: the generic asset sections, the Settings section and its actions, and the merge with the sections a type's `inspector.luau` declares (`inspector.assetSections`, `inspector.settingsSection`), and the building blocks those sections compose (`inspector.parts`, reached as `ctx.parts`). - **`shell`** — the dock: one `ui.*` `dockArea` holding a `dockPanel` per registered panel, and the panel registry behind it. ## Referencing - Inside this package, modules reference siblings with `~.` — e.g. `require("~.app")`, `require("~.widgets.fields")`. - Editor content built on the framework references it by package identity — `require("~edui.framework")`, `require("~edui.shell")`.
▲ 0↑ born
▣
module · born here
❒asset
# ecs Public, typed, discoverable API for native ECS components. Generic verbs (`insert`, `get`, `set`, `has`, `remove`, `query`, ...) operate on any component, while per-component typed constructors (`ecs.Mesh`, `ecs.Material`, `ecs.Transform`, ...) build the Rust-shaped value the verbs apply. Each constructor is minted at module load from a spec under `ecs.components.<Name>`. ## Typed constructors `ecs.<Name>{...}` builds a component value: it runs the compiled conversion plan (asset-handle resolution, camelCase → snake_case field mapping, `vec3` expansion) and raises on an unknown field. The result is a value the upsert verbs accept. ```luau local ecs = require("modules.api.engine.ecs") local value = ecs.Transform{ position = { x = 0, y = 1, z = 0 } } ecs.insertSync(id, value) ``` The constructor also takes every shape the component is read back as, so a read hands straight to the constructor it came from: - the `ecs.get` handle — `ecs.Light(ecs.get(id, ecs.Light))`, - the engine-side field table `handle:read()` and `ecs.snapshot(id).<Name>` give back, - a value the constructor already built (copied, so the two are separately writable), - a table keyed by public field names, engine-side field names, or both. That makes changing one field a read, an assignment and a write back: ```luau local h = ecs.get(id, ecs.Light) h.intensity = 0 ecs.set(id, ecs.Light(h)) -- every other field keeps what it held ``` Each of those shapes names the component it holds, so handing one to another component's constructor says which component it is and which constructor takes it. The `ecs.get` handle writes its own fields as well — `h.intensity = 0` is already the whole write — so reach for the round trip when you want the component's value in hand. ## Verbs Every verb accepts an entity proxy (what `entity.spawn` returns) or a raw id string. - `ecs.insert(id, value) -> promise` — async upsert; await for same-tick visibility. - `ecs.insertSync(id, value)` — upsert visible this tick; raises on failure. - `ecs.insertMany(ids, value) -> number` — insert one value into many entities in a single crossing; returns the count applied. The three insert verbs warn per field a component could not hold the value it was given, naming the component, the entity, the field under its engine-side name and the value; the component holds that field's default and every other field lands. - `ecs.get(id, ecs.<Name>) -> handle?` — retained handle over a present component (`nil` when absent). See `handle`. - `ecs.set(id, value) -> ok, rejected` — patch fields of an already-present component; raises if the component is absent. `ok` is false and `rejected` lists the public field names that did not land when a field cannot hold the value it was given (a string outside an enum field's set, a shape the field's type does not read). Each name appears once and is warned once, with the component, the entity and every value that name refused — under the name you wrote it as, where the insert verbs name the engine-side one. Every field is attempted, so one refusal leaves the rest applied. - `ecs.has(id, ecs.<Name>) -> boolean` - `ecs.len(id, ecs.<Name>, field) -> number?` — element count of a collection-valued field (list/array/map/set), counted without building any element; `nil` when the component is absent or the field is not a collection. Reading the field to measure it converts everything in it — `#h.bones` on a 50-bone `Skeleton` costs ~1ms against one crossing here — so ask this whenever the question is how many, or whether any. - `ecs.remove(id, ecs.<Name>)` - `ecs.components(id) -> {string}?` — public component names present on the entity. - `ecs.snapshot(id) -> table?` — every native component on the entity, nested and keyed by public name, each holding that component's fields under the names the component itself uses. A catalogued component's field table names the component it came from, so it goes straight to that constructor. - `ecs.queryIds(...) -> {string}` — ids holding ALL the given `ecs.<Name>` types. - `ecs.query(...) -> {proxy}` — like `queryIds` but returns entity proxies. - `ecs.bind(id, component, field, mode?)` — retained component-field accessor by rust component name. - `ecs.bindEntities(ids)`. ## Discovery The engine is driven at runtime, so the catalog is introspectable in-engine: - `ecs.types() -> {string}` — public component names available as `ecs.<Name>`. - `ecs.describe() -> { schema, ... }` — the full catalog: every component with its fields. `ecs.describe(name | ecs.<Name>)` returns the schema for one component. - `ecs.<Name>:schema() -> { component, rust, fields = { {name, type, rust}, ... }, methods?, accepts }` — runtime field discovery for a single component; `accepts` lists the calls the name is accepted by, the round trip among them; behavior-bearing components also list their handle `methods`. ```luau for _, schema in ecs.describe() do print(schema.component, #schema.fields) end ``` ## Saved native components A saved record (a scene entity, a bundle `entity_template` entry) lists its native components in an `ecs` array beside `components`: `ecs = { { type = "Mesh", data = { mesh = "<mesh asset guid>" } }, { type = "Material", data = { id = "<material asset guid>" } } }`. `type` is the name under `ecs` and `data` the row `ecs.snapshot` answers, with every handle-typed field written as the guid of the asset the handle came from. The scene loader and `bundle:instantiate` resolve each guid to the handle the component holds (`ecs.handles`, see its README) and insert one value into every entity that states the same entry.
▲ 0↑ born
▣
module · born here
❒asset
# scene_saver.recordDiff The comparisons the saver's record diffs (`transformDiffLines`, `recordDiffLines`, the pending scene edits) are built from. - `diffEqual(a, b)` and `valuesEqual(a, b)` compare two record values, numbers within a tolerance that absorbs the f32 round trip of a live read. - `componentMatchName(t)` answers the name a component type matches by, whichever spelling the record used; `componentList(rec)`, `componentMatchNameOf(c)`, `componentInstanceLabel(c, typeName)` and `componentData(c)` read a record's components the way the comparison needs them, answering empty for a malformed record. - `selfWrittenFieldSet(entityId, componentType, instanceName)` answers the fields a component instance wrote about its own runtime. - `pushAttributeDiffLines(oldRec, newRec, push)` hands `push` one line per attribute added, changed or removed. ```luau local RecordDiff = require("@builtin::assetTypes.scene.shared.saver.recordDiff") assert(RecordDiff.diffEqual({ 1, 2 }, { 1.00001, 2 })) RecordDiff.pushAttributeDiffLines({ attributes = { hp = 1 } }, { attributes = {} }, print) -- - attribute.hp ```
▲ 0↑ born
▣
module · born here
❒asset
# scene_saver.serialize One live entity as the record a scene file carries, and the reads the saver asks of a live entity while it decides what to record. - `serializeEntity(id, parentById)` answers the record for a live entity: its name, parent reference, transform, components (each field value serialized), participation, network scope, render layer and attributes. A field holding a runtime GPU handle is reported once, with the remedy, and left out of the record. - `serializeFieldValue(v)` answers one component field value as a record states it, with the reason when the value has no record form. - `entityDisplayName(id)` answers the name an entity is shown by, and `entityIsTemporary(id)` whether it is marked as never saved. ```luau local Serialize = require("@builtin::assetTypes.scene.shared.saver.serialize") for _, e in ipairs(entity.findAll()) do print(Serialize.serializeEntity(e.id).name) end ```
▲ 0↑ born
▣
module · born here
❒asset
# scene runtime What a `.scene` folder does when it is loaded, saved, built, or swapped. A `<name>.scene/` carries `scene.json` (the entity arrangement), an optional `build.luau` (the code author's half), an optional `entrypoint.luau`, and a `scene_dirty/` overlay of unsaved edits. Reading, composing and writing all four is the scene type's own behaviour, so it lives in the type. ## Sub-modules | Module | Responsibility | |---|---| | `loader.module` | Reads scene.json v6 and v7, refuses versions it does not know, composes canonical + dirty overlay, spawns the entities, and runs the entrypoint. | | `saver.module` | Persists scene state as a delta overlay against the canonical file, promotes that overlay on save, and answers which edits are still pending. | | `build.module` | Runs a `build.luau` inside an entity capture scope and composes what it spawned into scene records. | | `observe.module` | The read side — the per-scene counts and costs `layers` and `loader` write. | | `swapOrchestrator.module` | Drives multiplayer room transitions and the scene-swap gate, so a local swap does not leak despawns to peers in the old room. | ## Reaching it ```luau local rt = require("@builtin::assetTypes.scene.shared") rt.saver.hasPendingSceneEdits(layers.active.name) ``` Fields resolve lazily. The prelude installs `swapOrchestrator` and starts `saver`'s dirty writer in a fixed order, which a table that required all five on load would take away from it.
▲ 0↑ born
▣
module · born here
❒asset
# argForm <!-- zero:scaffolded-readme --> <!-- Replace the line below with what this module provides and who consumes it, then delete both comment lines. --> TODO: describe this module.
▲ 0↑ born
▣
module · born here
❒asset
# assetBrowser <!-- zero:scaffolded-readme --> <!-- Replace the line below with what this module provides and who consumes it, then delete both comment lines. --> TODO: describe this module.
▲ 0↑ born
▣
module · born here
❒asset
# edui.widgets.controls edui's own interactive controls, drawn on the `ui.*` canvas substrate (paint commands + pointer/key/scroll events) rather than the generic `ui.*` widgets, so an editor control looks and behaves like an editor control and enforces its type. `Controls.make(W)` binds them to the widgets barrel and returns: - **`numberField(P, o)`** — a numeric field that only ever holds a number. Drag the value to scrub, scroll to nudge, double-click to type digits (letters can't enter); an optional ▲▼ stepper sits on the right. `o = { value, onChange, key, readOnly, width?, stepper? }`. - **`boolToggle(P, o)`** — a pill/knob toggle switch, distinct from a checkbox. `o = { value, onChange, key, readOnly }`. Canvas paint points are POSITIONAL `{x, y}` arrays. Interaction payloads arrive as the value the edui app unwraps from the engine event envelope (`d.dx`/`d.dy` for drag/scroll).
▲ 0↑ born
▣
module · born here
❒asset
# edui.document One open document in an editor panel. `edui.document.new{ id }` makes one; `doc:open(path, line?)` shows a VFS file or asset in the viewer its kind calls for; `doc:build(edui.palette())` is the panel content. Text is editable (`doc:save()` writes it and runs a .luau file through the LSP) and the document follows its file on disk: a write lands in a buffer with no unsaved edits, and raises a "changed on disk" bar over one that has them. `doc:setText` tells the owner (`onChange`) when it moves `doc:dirty()`, so a panel can mark its tab. `doc:suspend()` sets a document aside while its panel is closed: the watch and the viewer's resources go, the path and the unsaved edits stay. `doc:resume()` picks it back up and reads the file as it is now — a clean buffer adopts what changed meanwhile, an edited one raises the conflict. Viewers are modes. The built-in ones are `code`, `markdown` (rendered, with a Source toggle), `image`, `asset` (a live orbitable render for any asset type that declares a preview) and `info`. `edui.document.registerMode{ name, match, build }` adds another. The Code panel is one document; `edui.shown` opens a panel around another.
▲ 0↑ born
▣
module · born here
❒asset
# entityPicker <!-- zero:scaffolded-readme --> <!-- Replace the line below with what this module provides and who consumes it, then delete both comment lines. --> TODO: describe this module.
▲ 0↑ born
▣
module · born here
❒asset
# edui.widgets.fields Inspector field rows for edui — a two-column (label + control) row whose control is chosen by the field's declared TYPE (from the component's backing schema), falling back to the value's shape when no type is given. The label column carries the field name and a per-type **badge** (num/str/bool/enum/rgb/vec3/rot/ref/obj, each in its own hue) so a row's type reads at a glance. The control column maps: - `number` → drag-scrub numeric field (`controls.numberField`); a spec carrying `min` / `max` shows its bounds beside the input (`1 – 16`, an open side as `…`) - `bool` → toggle switch (`controls.boolToggle`) - `string` → framed text input - `enum` → a value button that opens a menu of members - `color` → swatch + native colour picker - `vec3` → three axis-coloured (x/y/z) numeric cells - `quat` → an editable euler (X/Y/Z degrees), read back to a quaternion - `assetRef` → a live-asset chip - nested table → a recursing disclosure Each editable leaf fires `onChange(newValue)` (vec3/quat fire the full new table). A row spec's `description` is the label's tooltip, and its `error` is drawn beneath the row in the danger colour. Every committed edit is one undoable operation named after the field. ## `schemaField` — a row from a Field descriptor `edui.schemaField{ label, desc, value, key, onChange?, readOnly?, error?, errors?, nameOf? }` is the one place a `Field.*` descriptor becomes its control. The descriptor decides the control: | Descriptor | Control | |---|---| | `Field.enum` (string with an enum constraint) | dropdown of its members | | `Field.number` / `Field.range` / `Field.bitmask` | number; a range shows `min – max`, a bitmask `0 – 2^bits-1` | | `Field.bool` / `Field.string` | toggle / text input | | `Field.color` | swatch + picker; an edit keeps the value's alpha | | `Field.vec2` | two axis cells (x/y), each edit emits `{ x, y }` | | `Field.vec3` / `Field.quat` | axis triple / editable euler | | `Field.assetRef` / `Field.resource` / `Field.dataRef` | asset chip accepting the descriptor's category | | `Field.instantiableRef` | asset chip accepting the spawnable kinds (`"*"` is the wildcard category and narrows nothing; the scene-instantiable constraint does) | | `Field.taggedRef` | asset chip accepting any kind, reading "accepts assets tagged <tag>" — the field's own constraint checks the tag | | `Field.entityRef` | entity chip, named through `nameOf` | | `Field.struct` (and `Field.settingsOf`) | a disclosure of its subfields, each a `schemaField` in declaration order (`Settings.orderedNames`); an edit emits the whole struct | | `Field.list` | a disclosure of its elements, each a `schemaField`, with **Add**, **Remove**, **Move up** and **Move down**; every action emits the whole new list. The first element has no Move up and the last no Move down; Add appends the element descriptor's default | | `Field.table` / `Field.componentRef` | the value-shaped control `field` would choose | A value stored as an array (`{ 1, 0, 0, 1 }`) reads as its map form (`{ r, g, b, a }`), and a missing value shows the descriptor's default. `error` is this row's own message. `errors` maps paths **relative to this field** to messages — `"filter"`, `"[2]"`, `"[2].name"` — and each nested row of a struct or list receives the part under its own name (`edui.widgets.subErrors(errors, head)` does the re-keying). The descriptor's `description` is the label's tooltip. Callback keys, for a row keyed `k`: the disclosure `k:disc`; a subfield or element `k/<name>` / `k/<i>`; list Add `k:add`; Remove `k:rm:<i>`; Move up `k:up:<i>`; Move down `k:down:<i>`; a vec2 axis `k:x` / `k:y`. `Fields.make(W)` binds these to the widgets barrel; the barrel exposes `edui.field`, `edui.schemaField` and `edui.section`, and `edui.widgets.subErrors`.
▲ 0↑ born
▣
module · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
# edui.widgets.tree (module) The editor hierarchy tree primitive — `edui.tree{...}`. The tree is **generic over its nodes**. It never reads an `entity` field: a caller supplies the accessors and owns the state, and the tree only reports clicks. That is what lets one primitive back the Entities hierarchy, an asset folder listing, and a scene-layer list with no branch per caller. - Accessors: `idOf(node)`, `childrenOf(node)`, `labelOf(node)` — defaulting to `node.id`, `node.children`, and `node.label`/`node.name`. - Expand state is the caller's: pass an `expanded` set (`{ [id] = true }`) or an `isExpanded(node, id)` predicate, and handle `onToggle(node, id)`. - Selection is the caller's: pass `selected` (an id, or an `{ [id] = true }` set for multi-selection) and handle `onSelect(node, id)`. - `renderRow(node, row, selected)` replaces the default label with your own content (badges, per-row icon buttons); return one widget or a list. ## Flattening `flatten{ roots, ... } -> { { node, id, depth, hasChildren, expanded, parent } }` is exported separately (`edui.widgets.flattenTree`) and is **pure** — no `ui.*` calls and no app — so display order is testable without a rendered frame. A node's children appear only while that node is expanded, so a collapsed tree costs nothing to build. A node that appears on its own ancestry is reported and skipped instead of recursing forever. ## The window `windowBounds(total, offset, viewport, rowH, overscan?, quantum?) -> first, last` (`edui.widgets.windowBounds`) is the pure arithmetic behind the windowed shape: the rows in view plus an overscan on each side, the start snapped to a multiple of the quantum so a small scroll moves nothing. `first` is the 0-based index of the band's first row and `last` the 1-based index of its last, so the rows are `first + 1` through `last`. ## Row rendering Rows are uniform-height, which is exactly the shape `scrollArea`'s `virtual` prop wants — the renderer then draws only the band in view. Leaf rows still reserve the disclosure-chevron slot so every label at a given depth starts on the same column. Row keys are stable (`"<key>:<id>"`), so the callback ids survive a rebuild and anything the renderer tracks by id (focus, `ui.widgetState`) stays put. The disclosure chevron and the select target are **siblings, never nested** — a click lands on exactly one, so opening a node cannot also select it. The select target grows to fill the rest of the row, which is what keeps the whole row clickable rather than just the label. The selection background sits on the non-clickable row container so it spans the indent and chevron too. Note that `virtual` is *render*-side windowing: the row widgets are still built for every visible node. Construction-side windowing (building only the scrolled band) needs the `virtualTotal`/`virtualFirst` scrollArea props, which are not on this branch.
▲ 0↑ born
·
tool · born here
❒asset
# sceneAuthoring.acceptChanges The apply half of the scene-change contract: the only thing that makes reviewed changes part of the scene. Writes the scene body, saves the play-created assets the accepted entities reference into the world's source (the scene must never point at files that vanish when play ends), saves play-edited source files when included. The session keeps running throughout, so a verdict on a shared world leaves every other agent on it working. Accepting can take the whole review or a selection — numbered items, entity names, name parts, or group labels. The scene file is written by the verdicts that carry something for it to record: entities accepted, or a carrier minted by an effect, screen or feature conversion. A verdict that carries none of those — a selection naming only source files, or a review whose only item is an edited file — promotes what it was given and leaves the scene file's bytes, its checksum sidecar and its place in the world's dirty set exactly as they stand. Such a result carries `sceneUntouched` where a writing one carries `written`.
▲ 0↑ born
·
tool · born here
❒asset
# sceneAuthoring.changes The review half of the scene-change contract: the scene only ever changes by reviewing the pending changes and accepting them. This tool scans the live world within the frame it is called in, diffs it against the canonical scene, and renders the decisions on the table. The session keeps running, so a review one agent holds open leaves every other agent on the world their frames. It writes **nothing** — `sceneAuthoring.acceptChanges` is the only thing that does. The listing is bounded. It shows at most `limit` numbered items (20 by default; `limit = 0` answers the counts per kind alone), `kind` lists only the items of one kind (`added`, `updated`, `removed`, `assets`, `edits`, `foreignEdits`, `fx`, `ui`, `features`, `others`) and `author` only one author's (`mine`, `others`, or an agent's name). A listing that leaves items out says how many and how to list them, and every item keeps its number, so a verdict reaches an item the listing left out by its number or name all the same.
▲ 0↑ born
·
tool · born here
❒asset
# Discard recorded scene edits Remove saved authored edits that `reviewRecorded` lists under `authored`, so those fields follow the build again, or forget edits listed under `retired`. Pass the review receipt and what to discard. ```lua local report=tools.use("sceneAuthoring","reviewRecorded",{}) tools.use("sceneAuthoring","discardRecorded",{review=report.review,entity="lamp"}) -- every saved edit of the entity tools.use("sceneAuthoring","discardRecorded",{review=report.review,entity="lamp",paths={{"transform","position"}}}) tools.use("sceneAuthoring","discardRecorded",{review=report.review,retired=true}) -- forget every retired edit ``` The discard is one atomic scene transaction: the composition, the authoring records and the artifact change together, and a stale receipt is refused.
▲ 0↑ born
·
tool · born here
❒asset
# Reapply retired scene edits A build retires an authored edit when the entity, parent, reference or component it named is no longer in the scene. `reviewRecorded` lists those edits under `retired` with the entity's name, the field path and the value the edit held. Reapply moves the field edits of one entity onto another entity that exists in the scene, for example after a rename in `build.luau`. ```lua local report=tools.use("sceneAuthoring","reviewRecorded",{}) tools.use("sceneAuthoring","reapplyRetired",{review=report.review,from="lamp",to="lantern"}) tools.use("sceneAuthoring","reapplyRetired",{review=report.review,from="lamp",to="lantern",paths={{"transform","position"}}}) ``` Only field edits move: an edit that added or removed a whole entity stays listed. A moved edit leaves the retired list; a field the target already holds at another value is reported as a conflict and nothing changes.
▲ 0↑ born
▣
module · born here
❒asset
# Recorded scene operations Shared implementation of reviewRecorded and resolveRecorded. Review returns a compact receipt bound to the captured world, branch, file revisions and directory membership. Resolve captures again and compares that receipt before preparing a checked journal resolution. The backend checks the read set again at commit. ```lua local Recorded=require("@builtin::tools.sceneAuthoring.recorded") local report=Recorded.review({limit=20}) local result=Recorded.resolve({review=report.review,operation=report.operations[1].path,choice="recorded"}) ``` Whole-operation choices apply to every recorded field. Exact field choices preserve other proposed changes. A committed result distinguishes backend persistence from local revision visibility. Uncertain results expose the source transaction identity for inspection or retry through SourceOperations. Saved overrides are returned separately in `authored`: `rows`, `total`, `offset` and `nextOffset`. Each row names the entity or scene settings, the field path, and its `before` and `after` presence/value states. `authoredOffset` pages these saved fields independently of pending operations. Saved overrides remain reviewable after the operation journal has been incorporated.
▲ 0↑ born
·
tool · born here
❒asset
# sceneAuthoring.rejectChanges The drop half of the scene-change contract. Rejected changes never enter the scene; the live objects stay live for this session and are hidden from later reviews so they stop nagging. Each rejected change is taken back out of the scene's pending set, so the publication gate that refuses a commit while a scene carries unbaked entity edits reads the scene as settled. A rejected REMOVAL keeps the entity in the scene: the despawn holds for this session, and the entity is there again on the next load. Rejecting takes a selection — numbered items, entity names, name parts, or group labels — or the whole review with no argument.
▲ 0↑ born
·
tool · born here
❒asset
# Replace a scene source input Apply a reviewed input replacement atomically with its regenerated scene and source bindings. Authored overrides remain composed over the generated result. ```lua local report=tools.use("sceneAuthoring","reviewSources",{limit=20}) local input=report.inputs[1] local result=tools.use("sceneAuthoring","replaceSource",{ review=report.review,owner=input.owner,id=input.id, replacement='"New name"',outputs=input.outputs, }) ``` Replacement is source text: use SourceEditing.literal for a Luau scalar and Json.encode for a JSON value. JSON inputs must be consumed through SourceEditing.read during candidate evaluation. Supply every reviewed output identity. For one placement, choose an input scoped to that placement. Changed review receipts and incomplete output scopes are refused. Unconfirmed outcomes include the transaction identity and scope for recovery.
▲ 0↑ born
·
tool · born here
❒asset
# Resolve recorded scene edits Resolve an operation returned by reviewRecorded. Pass its review receipt and operation path, then either a whole-operation choice or exact field choices. recorded keeps proposed values; accepted keeps the reviewed accepted values. Unselected fields in a field-level resolution retain their proposed changes. Remaining conflicts prevent the transaction. ```lua local result=tools.use("sceneAuthoring","resolveRecorded",{ review=report.review, operation=report.operations[1].path, fields={{entity=entityId,path={"name"},choice="accepted"}}, }) ``` Pass `through`, the path of a later operation of the same editing session, to resolve the whole run from `operation` through it as one transaction: each field the run changes lands as its net change (its last value, over the value its last unbroken chain of edits started from), the choice applies to those net changes, and every operation of the run retires together. A run of moves that collided with another participant's edit settles this way in one call. ```lua local session=report.operations[1].entry.session local last=report.operations[1].path for _,operation in ipairs(report.operations) do if operation.entry.session==session then last=operation.path end end tools.use("sceneAuthoring","resolveRecorded",{review=report.review,operation=report.operations[1].path,through=last,choice="accepted"}) ``` An unconfirmed outcome returns the transaction identity and scope for inspection with SourceOperations; it must be inspected before treating the edit as applied or retrying it. A committed result reports local revision visibility separately, including a visibility error if the active world or branch changed. A stale receipt is refused. Successful resolution atomically updates the composition, acknowledges the operation and retires its journal file. The response names the source transaction for recovery and reports local revision visibility separately.
▲ 0↑ born
·
tool · born here
❒asset
# Review recorded scene edits Review pending journal operations in the open scene, including collaborator changes and edits outside build.luau. Each operation reports observed, accepted and recorded field values, conflicts and session ordering. The response includes a compact review receipt for resolveRecorded. Source files are unchanged. ```lua local report=tools.use("sceneAuthoring","reviewRecorded",{limit=20}) ``` Use offset and limit to page operations. A new scene revision or guarded source change invalidates an older receipt. Saved overrides are returned separately in `authored`: `rows`, `total`, `offset` and `nextOffset`. Each row names the entity or scene settings, the field path, and its `before` and `after` presence/value states. `authoredOffset` pages these saved fields independently of pending operations. Saved overrides remain reviewable after the operation journal has been incorporated.
▲ 0↑ born
·
tool · born here
❒asset
# Review scene source inputs List registered source inputs in the open scene with exact ranges, affected outputs, scope completeness and revision status. ```lua local report=tools.use("sceneAuthoring","reviewSources",{limit=20}) ``` Filter by entity to find inputs affecting a placement. Use offset and limit for pagination. A shared input lists all affected placements. The replaceable field states whether candidate replacement is supported for that input.
▲ 0↑ born
·
tool · born here
❒asset
# sceneAuthoring.reviewState The read of the review the rest of this toolbox writes. `changes` opens a review, `acceptChanges` and `rejectChanges` consume one and refuse when none is open — this reports whether one is open and how much is in it, so a script picks the call to make instead of learning the ordering by being refused. ```lua local s = tools.use("sceneAuthoring", "reviewState") if not s.open then tools.use("sceneAuthoring", "changes") end tools.use("sceneAuthoring", "acceptChanges", "edits") ``` Returns `{ open, added, updated, removed, edits, total, scene }`. With no review open, `open` is false and every count is zero — which is also the answer after a review is fully accepted or rejected, since consuming one closes it.
▲ 0↑ born
▣
module · born here
❒asset
# sceneAuthoring.shared Genuine cross-tool sharing for the `sceneAuthoring` toolbox: the review types, the pending-review stash, the session rejected set, and the selection resolver that `acceptChanges` and `rejectChanges` both use. The workflow logic lives in each tool (`changes` scans and renders; `acceptChanges` applies and promotes; `rejectChanges` drops) — this module is the state they hand each other.
▲ 0↑ born
▣
module · born here
❒asset
# Scene source inputs Reviews persisted build input bindings and replaces an exact input against a review receipt. Replacement evaluates the candidate build and commits its source, scene and refreshed bindings together while retaining authored overrides. ```lua local Sources=require(".sources") local report=Sources.review({limit=20}) local input=report.inputs[1] local result=Sources.replace({review=report.review,owner=input.owner,id=input.id, replacement='"New name"',outputs=input.outputs}) ``` Every affected output must be supplied. Incomplete scopes and stale review receipts are refused. A result marked unconfirmed carries its transaction identity for recovery through SourceOperations.
▲ 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
▣
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
▣
module · born here
❒asset
# assetType.shared.ref Builds the metatable every `AssetRef` (the `{ __ref, type, name, guid, identity, path }` envelope returned by `asset.resolve` / `asset.ref`) carries. Replaces the per-call C metatable that used to live in `crates/zero_scripting/src/ffi/bindings/asset.rs::attach_asset_ref_metatable`. ## Public API ```lua local assetRef = require("@builtin::assetTypes.assetType.shared.ref") -- Called by the Rust factory (push_asset_ref_handle) via -- _G.__build_asset_ref_proxy after the envelope fields are set. assetRef.build(envelope) -- attaches AssetRefMT, returns the table ``` The module exposes no invalidation surface — discovery is registry-driven and hot-reload is transparent (see "Discovery and hot-reload" below). ## Method dispatch order `ref.foo` is resolved in this order: 1. **Default methods** — `getSource` / `getBytes` / `getText` / `exists` / `inspect` and the lazy `meta` property. Per-type definitions cannot override these (engine contract from gh#1889). 2. **Per-type `ref` table** — discovered through `asset.resolve(<typename>, "assetType")` + `require(<identity>.behavior)`. The lookup resolves to whichever `<typename>.assetType/` folder is currently registered for the typename (built-in, user, or library-vendored) and pulls its `ref` methods. 3. **Nil** — unknown key, same shape as the original C metatable. ## Adding methods for a new asset type Drop a `behavior.luau` into the type folder: ``` src/lua/lib/assetTypes/<typename>.assetType/ ├── type.yaml -- structural spec (existing) ├── behavior.luau -- ref + global behaviour (new) └── template/ -- placeholder body (existing) ``` `behavior.luau` returns: ```lua return { ref = { --!desc Per-instance method on every `<typename>` AssetRef. myMethod = function(self, ...) ... end, }, global = { -- Reserved for the asset.<typename>.* surface — not consumed -- yet; included so the contract from gh#1889 lands cleanly. }, } ``` Within `ref` methods, `self` is the AssetRef envelope: `self.path`, `self.identity`, `self.guid`, `self.type`, `self.name` are available. Engine-required fields (`guid`, `path`, `identity`, `type`) must not be redefined. ## Discovery and hot-reload Type discovery uses the asset registry, so it doesn't matter where a `<typename>.assetType/` folder lives — engine built-ins under `@builtin::assetTypes.<X>`, user types dropped under `/zero/source/<X>.assetType/`, or types vendored inside an imported library all resolve identically. The dispatcher walks `asset.resolve(<typename>, "assetType")` → canonical identity → `require <identity>.behavior` on every miss; the asset registry is the cache for the resolve half and Luau's `_LOADED` is the cache for the require half. Hot-reload is transparent. When a `<typename>.assetType/behavior.luau` is rewritten through VFS, the engine's `invalidate_require_cache_for_state` re-runs the module and mutates the cached `_LOADED[<identity>.behavior]` table in place. Dispatch reads `mod.ref` on every access (rather than caching a sub-pointer), so existing AssetRefs see the new methods on the very next access — no Rust-side hook into this module is needed, and no invalidation API is exposed for callers to call. The same registry-driven path also handles type **registration** correctness: dropping a new `<typename>.assetType/behavior.luau` updates the asset registry, the next `asset.resolve(<typename>, "assetType")` returns the new ref, and AssetRefs of that type immediately gain the new methods. ## Why Luau, not Rust The asset surface needed per-category behaviour (`material:getProperties()`, `bundle:instantiate(entityId)`, `tool:run(args)`) and the old shape couldn't grow without an FFI change per method. Owning the proxy in Luau means: - Type-specific methods ship as content (the `<typename>.assetType/` folder), not engine code. - Adding a new asset type drops in a new folder; no Rust rebuild. - Methods can call any other Luau global (`vfs`, `asset`, `Material`, `entity`, etc.) directly, instead of going through narrow FFI primitives. ## Consumers - `crates/zero_scripting/src/ffi/bindings/asset.rs::attach_asset_ref_metatable` — the Rust factory that pushes envelopes invokes `_G.__build_asset_ref_proxy` once per push. - Every Luau call site of `asset.resolve` / `asset.ref` / `entity(id).component.X.material` / any binding declared `AssetRef<...>` — they all receive envelopes built through this module.
▲ 0↑ born
▣
module · born here
❒asset
# yaml.module YAML decode + encode for authored engine content. Pure Luau, no engine dependencies — a general parsing library, not data-system plumbing. ```luau local Yaml = require("@builtin::modules.yaml") local doc = Yaml.decode(vfs.read(path)) vfs.write(path, Yaml.encode(doc)) ``` ## Supported subset - Block mappings (`key: value`) and block sequences (`- item`), nested to any depth. - Compact sequence-of-mapping entries (`- path: x` / ` kind: y`). - Flow collections — `{ a: 1, b: 2 }` and `[1, 2, 3]` — single line. - Plain scalars with type inference: `~` / `null` → nil, `true` / `false` → boolean, numeric literals → number, everything else → string. - Single- and double-quoted strings (`''` escapes a literal quote inside a single-quoted string; `\n` `\t` `\r` `\\` `\"` inside a double-quoted one). A quote opens a quoted scalar where a scalar begins — after `key:`, after a `- ` entry marker, or inside a flow collection — so a plain scalar carries an apostrophe as data (`note: the world's rules`). Quoted keys are read in flow mappings. - `#` comments — honored outside quotes, so a `#` inside a quoted string is kept as data. - Literal (`|`) and folded (`>`) block scalars, with a chomping indicator (`-` strips the final newline, `+` keeps every trailing blank line, none keeps one newline) and an indentation indicator (`1`-`9`: the content's indent past the parent's), in either order (`|-`, `>+`, `|2`, `>1-`). A block scalar's content is literal text: quotes (balanced or not), `#`, `key: value` and `---` inside it are data. - An optional leading `---` document marker. ## Loud-error contract Constructs outside the subset above raise instead of misparsing: anchors/aliases (`&`, `*`), tags (`!`), directives (`%`), multi-document streams (a second `---`), a block-scalar header it cannot read (`|x`, `|-+`, `|0`), tab indentation, and inconsistent indentation (both block structure and block-scalar bodies). Every error carries the offending line number (`yaml: line N: ...`), so a bad config points straight at the line to fix. Tab indentation is rejected everywhere — including block-scalar body lines whose leading whitespace contains a tab. A tab after the first non-space character of a line is content and passes through. ## API - `Yaml.decode(text: string): any` — decode a YAML document into a Luau value (table, scalar, or nil for an empty document). Raises on malformed input or an unsupported construct. - `Yaml.decodeWithComments(text: string): (any, boolean)` — decode as `decode` does, and report whether the text carries a comment by the decoder's own rule: a `#` at a line's start or after whitespace, outside a quoted scalar and outside a block scalar. Re-encoding the value drops such comments, so an editor that writes a document back reads this first. - `Yaml.encode(value: table): string` — encode a Luau table as YAML (block style, two-space indent, alphabetically sorted keys). Raises on values YAML can't represent (functions, userdata, non-string mapping keys). A top-level empty table encodes to an empty document, which decodes back to `nil` (the YAML empty-document ambiguity).
▲ 0↑ born
▣
module · born here
❒asset
# 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
# 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 · editor/edui.package/topbar.module

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.