# Scene setup (asset type)
A scene setup configures a scene as a whole in one asset: its sun and ambient
light, its fog, its render features and post effects, or any other effect that
applies to a scene. It is an ordered list of **members**, each an asset whose
type implements `applicable`, with the values the setup states for them.
Placed in a scene, it applies every member; selecting the placement shows every
parameter of every member, and an edit made there is that placement's own.
## Where it lives
- Source: `<name>.sceneSetup/`
- Identity: `<name>` (the `.sceneSetup` suffix strips from the identity)
- Folder shape:
- `sceneSetup.yaml`: the definition. **Required.**
- `README.md`: what the setup puts on a scene. **Required.**
- `.metadata`: `description` and `tags`. **Required.**
- `preview.png`: its picture. Optional.
## The definition
```yaml
members:
- id: sun # required, ^[a-z][A-Za-z0-9_]*$, unique
source: "./sun.sceneLight" # any asset that implements applicable
- id: ambient
source: "./fill.sceneLight"
values: { intensity: 0.12 } # values for the member's parameters
- id: fog
source: "<a fog render feature>"
enabled: false # optional, default true
- id: grade
source: "./grade.postEffect"
values: { saturation: 0.82, contrast: 1.12 }
```
A member's `values` are the values this setup states for that member; the
member asset keeps its own, and another holder of it states its own.
A member's `source` is one of:
- an identity: `lighting.harbour_fill`, `@builtin::<library>.<name>`. It
resolves among the assets that can be members, so a name another kind of
asset also answers to reaches the member;
- a path with its type suffix: absolute (`/source/lighting/harbour_fill.sceneLight`),
from the folder holding this setup (`harbour_fill.sceneLight`,
`./harbour_fill.sceneLight`, `../shared/fill.sceneLight`), or from the
world's source folder (`lighting/harbour_fill.sceneLight`). A path starting
`./` or `../` is read from the setup's folder alone.
An identity drops the type suffix, so `harbour_dusk.sky` and
`harbour_dusk.sceneSetup` in one folder share `lighting.harbour_dusk`; a
member naming that identity is skipped as `sceneSetup.member.ambiguous`, which
names both assets, and its path names the one meant. A source that names
nothing is `sceneSetup.member.missing`, and its values and overrides are kept
until it resolves.
A member whose type does not implement `applicable` is refused by name
(`sceneSetup.member.unsupported`). A key the engine does not read is a warning.
## Parameters and paths
A setup's parameters are its members': `<member id>/<name>` (`fog/density`), a
nested member's under its path (`look/reflections/intensity`), and
`<member id>/@enabled` for every member. `@lit` (true by default) says whether
the scene renders lit; off, every surface shows its own colour with no light on
it, for a stylised game or a menu. `asset.schema(setupRef)` lists every path
with the member's own Field descriptor.
A setup that nests another names its parameters through the member id it
gives the nested setup: a setup whose member `base` is another setup has
`base/fog/density` for that setup's `fog/density`, and a placement sets
`base/fog/density`. A path that is no parameter is refused naming the paths
that end in it.
The value a member receives, for each parameter, first present wins: the
placement's override, the outermost setup's `values`, each inner setup's
`values`, the member asset's live value, then its saved value.
## Placing and tuning
```lua
-- A world's setup by its identity (`lighting/harbour_dusk.sceneSetup` is
-- `lighting.harbour_dusk`), or by its absolute path, `/source/lighting/harbour_dusk.sceneSetup`.
local root = asset.resolve("lighting.harbour_dusk", "sceneSetup"):instantiate(nil, { name = "lighting" })
local setup = root.component.get("SceneSetup")
setup:set("fog/density", 0.05) -- this placement's override
setup:set("fog/density", { scale = 3.75 }) -- relative: the setup's density times 3.75
setup:set("fog/heightFalloff", { offset = -0.06 }) -- relative: the setup's value plus -0.06
setup:set("ao/@enabled", true) -- turns a member on for this placement
setup:reset("fog/density") -- back to what the setup says
for path, m in pairs(setup:members()) do print(path, m.state.status) end
```
The placed root holds the `Asset` component (its `source` is the setup) and the
`SceneSetup` component (this placement's `overrides`); the scene stores nothing
of any member. Removing the `Asset` removes the `SceneSetup`, and every member's
application goes with it.
A relative override (`{ scale = n }` or `{ offset = n }`, numeric parameters
only) lands at the value the setup supplies times `scale` or plus `offset`,
checked against the parameter's descriptor, and follows that value: edit the
setup's fog density and every placement scaling it moves with it. It is saved
and synced like any override, and the Inspector shows it as relative.
**Where each value comes from.** `setup:get(path)` and each member's `values`
in `setup:members()` say it: `origin` is `override` (this placement's, with
`relative` and `supplied` for a relative one), `definition` (with `definedBy`,
the setup stating it, and `definedAt`, the path it states it at there, so a
value inherited through a nested setup names that setup), `live` (the member
asset's live value) or `saved`. One line proves what a placement shares:
```lua
for name, v in pairs(setup:members()["fog"].values) do print(name, v.value, v.origin, v.definedBy) end
```
**A light that follows the sky lands at what the sky makes of it.** A sun, a
fill or a rim that follows the sky (`followSky`) states its intensity as its
noon peak: the sky gives it that intensity with the sun 30° up or higher and
dims it toward the horizon, to about a third at 7° and 0 below it. So a dusk
sun stated at 3.2 at 17:51 lands near 0.4. `setup:get(path).landed` (and
`setup:set(path, value)`, which returns the same read) is what it lands at
now, beside `value`, what it states; the card shows `3.2 → lands at 0.4 at
17:51` on the row. The member's `state.notice` in `setup:members()` names a
light the sky dims to under a third of what it states, a distant fill that
lands brighter than the sun it is meant to support, and an ambient term at
half the sun or more. Raise
the stated intensity, move the hour, or, for a fill or a rim, set
`followSkyIntensity` to `false` so it keeps what it states.
**`set` in edit mode is a scene edit.** In edit mode on a world scene, a `set`
is an authored edit of the scene, recorded and saved: it holds over what
`build.luau` states until it is reset or released (`sceneAuthoring`
`releaseAuthored`). A `reset` that leaves the placement with no override
records nothing and releases the edit an earlier `set` recorded. Overrides
stated in `build.luau` are the build's own.
## Auditioning another setup
Two placements, or a placement and an application from code, each apply their
own sun, ambient term and fog; the effect decides which is in force (the
light-tie rule for lights), so an application beside a placed setup reports the
members another application holds as `held`, with `heldBy`, and its
`ApplyState.notice` names each held member, its asset and its holder. To see a
setup in place of the placed one:
- audition it on the placement, a preview for the session:
`setup:audition(asset.resolve("lighting.harbour_night", "sceneSetup"))`
applies it in the placed setup's place and records nothing;
`setup:endAudition()` (or the card's End audition, a flip, a reload) puts
the placement's own setup back. `set` and `reset` are refused while it lasts;
- apply it from code (below): it holds over the placement across flips until
it is dropped;
- read its preview: `preview.png` lights the reference subject
`@builtin::preview.subjects.lookdev` with the setup alone, its exposure fit
so a night setup reads (below);
- point the placement's `Asset` source at it (a scene edit that stays;
`releaseAuthored` returns the placement to `build.luau`'s setup);
- or apply it in a scene with no setup placed, such as a scratch scene.
## Applying it from code
A setup implements `applicable` itself, so it can be applied for an owner
like any member: `setupRef:as("applicable"):apply(owner, values)` starts an
application and `setupRef:as("applicable"):drop(owner)` ends it. Each member is
applied with the owner `"<owner>/<member id>"`.
- **It takes the effects that hold one at a time.** The scene's sun, its
ambient term, its sky and each render feature's settings are held by one
application at a time: of the applications standing, the newest to state
something holds it, so an application made over a placed setup holds them
while it stands, and the placement's members report `held` by it.
- **It stays in force until it is dropped,** across edit/play flips and device
rebuilds.
- **Its drop hands every effect back** to the application before it: the
placement's own, or the scene's own lights.
Which of two suns or two fogs is in force is the effect's own to decide; the
setup decides nothing about its members. An audition (above) is a preview for
the session that a flip ends; an application from code stands until it is dropped.
```lua
local night = asset.resolve("lighting.harbour_night", "sceneSetup")
night:as("applicable"):apply("myGame:time", {}) -- night holds over the placement
-- … flips, rebuilds …
night:as("applicable"):drop("myGame:time") -- the placement's lighting is back
```
## Checking one
`asset.validate(setupRef)` (an engine API function) reads the definition and
every value and returns `{ ok, problems }`: each diagnostic (`sceneSetup.member.missing` and the rest) with its
code, severity, path and message. A problem of severity `error` refuses a push.
## Its picture
A setup's `preview.png` shows its own lighting on a fixed reference subject,
`@builtin::preview.subjects.lookdev` (a grey ground, a white diffuse sphere, a
chrome sphere and a grey card). The preview studio stands the subject and
applies the setup to the world with the owner `preview` for the shot, so its
sun, sky and effects are the ones in force, then drops it, which hands every
effect back to the scene's own holder. A frame that reads darker than mid
grey (a night setup) is shot with its exposure opened up for the picture
alone, by up to eight stops, so the night look reads without the setup
changing. For those frames the world shows the
setup's lighting, so the picture renders only on an explicit request
(`preview.writePreview`, `assets.generatePreviews`, staging) and never from
the preview queue or a live preview; the last picture stands otherwise.
## Make one
```lua
asset.create("sceneSetup", "dusk", { members = {
{ id = "sun", source = "./sun.sceneLight" },
{ id = "ambient", source = "./fill.sceneLight", values = { intensity = 0.1 } },
} })
```
# Example: a sky that drives the lights
An example scene setup. It composes a sky drawn by the procedural backdrop, a
directional light that follows that sky, an ambient light, a sky light and
height fog.
What it demonstrates: the sky states the time of day once, and the light that
follows it takes its direction, colour and strength from the sun the sky
draws. Moving `sky/backdrop/timeOfDay` moves the sun in the sky and the light
on the scene together; the ambient light and the fog keep what they state. The sky light member
lights the scene's surfaces from the sky the backdrop draws, since a backdrop
only draws.
Its sky and lights are its own assets, in this folder: `sky.sky`,
`sun.sceneLight` and `ambient.sceneLight`.
# 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.
# scene_instantiable (module)
The instantiation contract's shared implementation. An asset type opts into
scene instantiation by defining `instantiate(self, target?, opts?)` on its
behaviour `ref` table; this module carries the parts that mean the same thing
for every type, so a caller writes ONE piece of code against all of them.
```lua
local root, idMap = ref:instantiate(target?, opts?)
```
## The contract
**IN — the base opts.** `target` is an owning entity ref: the instance lands
under (or, for a hierarchy type like a bundle, onto) that owner. With no
target the type spawns a fresh root. `position`, `rotation`, `scale`, `name`
and `temporary` place that root and mean the same for every type. `rotation`
takes three numbers as pitch/yaw/roll in DEGREES, or four as a quaternion. A
type may honour more opts of its own — `params` for a type built from declared
inputs, `idMap` / `diff` / `sourceTag` for the bundle override contract — and
says so in its own `instantiate` docs.
**OUT — the two returned values.** Every type returns the same pair:
- **`root`** — the composed root, as an `EntityRef`. Composition is
**synchronous**: the root and everything the type built under it are live
the moment the call returns, so a caller can parent to it, read its
components and hand it on in the same statement. There is no frame to wait
for and no callback.
- **`idMap`** — the `originalId -> runtimeId` map naming what the composition
spawned, `{}` for a type with no addressable children. **Never nil.** A
component that re-composes the asset on every load (`Asset`) keeps this map
and passes it back in, which is how a cross-entity reference into the
composition — `SkinnedModel.skeletonRoot` pointing at a bone — survives a
reload.
The return is enforced, not merely described: `AssetRef` dispatches every
`ref:instantiate(...)` through `result` on the way out, whether or not the
type called it. A type that returns something else fails at its own call
rather than handing its caller a nil root or a map that is sometimes absent.
## Exports
- `M.root(self, target?, opts?) -> root` — stand the root entity for a type
that spawns one: parented to `target`, born temporary when
`opts.temporary`, named `opts.name` else the asset's own name, placed.
- `M.place(root, opts?) -> root` — apply the placement opts to a root the type
already has (the adopt path: a bundle exploding onto its target, a
sceneModule reconciling under one).
- `M.result(self, root, idMap?) -> (root, idMap)` — return through the
contract. Checks `root` is a live entity ref, normalises a missing map to
`{}`, and errors naming the asset type when either is something else.
- `M.isOwned(opts?) -> boolean` — whether a component drives this call. The
`Asset` / `SceneModule` components tag their own calls with `sourceTag`;
they hold the reference and re-compose on every load. An untagged call came
straight from `ref:instantiate(...)` and has no such owner.
- `M.own(root, self, idMap?) -> root` — hand an already-composed root to an
`Asset` component pointing at `self`, so the reference and its map persist
and the composition is rebuilt on the next load. The component adopts the
live composition rather than building a second one.
- `M.check(value, constraint) -> ok, reason?` — the `sceneInstantiable`
field-constraint validator, also registered under that kind on load.
## The field constraint
`Field.instantiableRef` emits `constraint = { kind = "sceneInstantiable" }`,
and this module registers the validator for it on load. Given a written value:
1. `nil` passes — the field is optional (no asset assigned).
2. Reads the value's identity — a bare string, or a table's `__ref` / `guid` /
`identity` / `name`.
3. Resolves it (`asset.resolve(identity)` — any category) and asks the
resolved ref `ref:canInstantiate()`: true iff the asset's type defines an
`instantiate` method.
This is what lets `Field.instantiableRef` accept by CAPABILITY rather than a
hardcoded type list — a new scene-instantiable asset type is accepted the
moment it defines the hook, with no edit to the field or its consumers.
# SceneSetup
The per-instance state of a placed scene setup. A setup's `instantiate` adds it
to the placed root beside the `Asset` component whose `source` is the setup. It
holds this placement's `overrides`, by parameter path, and applies the setup with
them; the setup's members are applications of their assets, so the scene records
the root, its `Asset` and these overrides alone.
```luau
local setup = entity(root).component.get("SceneSetup")
setup:members() -- { [path]: { source, state } }, every depth
setup:get("fog/density") -- { value, origin, definedBy?, desc }
setup:set("fog/density", 0.05) -- this placement's override
setup:set("ao/@enabled", false) -- turns a member off here
setup:reset("fog/density") -- back to what the setup says
setup:orphans() -- overrides that address nothing
```
It applies the setup when it wakes and when it is enabled, applies a change of
`overrides`, turns the setup off when it is disabled and drops it when it is
removed; removing the `Asset` removes it. While it is disabled, a change of its
overrides applies the setup off. Across an edit/play flip the setup
stays applied: the instance that ends hands its application to the one that
wakes on the same root, so no frame is drawn without its sky, sun or fog. It
runs nothing per frame. A system
API's write of a parameter this placement states (`fog.set`) becomes this
placement's override.
Its application is one of the scene's applications: the effects that hold one
at a time (the sun, the ambient term, the sky, each render feature's settings)
go to the newest application standing. Another setup applied from code
(`setupRef:as("applicable"):apply(owner)`) holds them over this placement
until it is dropped, across flips, and its drop hands them back to this
placement. `audition(setup)` shows another setup in this placement's place as a
preview for the session; `endAudition()`, a flip or a reload ends it.
# contract
The shared half of `applicable`. Every call of `apply`, `setEnabled` and
`drop` on an asset whose type implements the interface passes through `gate`,
which checks the owner, the values against `asset.schema`, and `opts.enabled`;
keeps one record per application (the values the owner stated and whether it
is on); calls the type with the asset's own values and what the owner stated
laid over them; and checks the returned `ApplyState` (`status`, `heldBy`,
`notice`).
```lua
local Apply = require("@builtin::interfaces.applicable.contract")
Apply.values(self, owner) -- the values the application receives
Apply.stated(self, owner) -- what the owner stated, sparse
Apply.restate(guid?) -- apply the records again
```
After an edit/play flip, a render-device rebuild and an edit of an applied
asset, the contract applies every record of the asset again, and each type puts
back what of its effect is gone.
# 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.
# 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**.
# lookdev (bundle)
The reference subject a lighting preview is photographed on: a grey ground,
a white diffuse sphere, a chrome sphere and an 18% grey card standing behind
them. The diffuse sphere shows the light's direction, colour and softness, the
chrome sphere reflects the sky and the light sources, and the grey card reads
the exposure. Five entities under one root, built from builtin meshes and
materials.
A type whose pictures show what an asset does to a scene names it as its
preview `subject` (a scene setup's preview, for one); the asset is applied to
the world while the subject is photographed.
```lua
asset.resolve("@builtin::preview.subjects.lookdev", "bundle"):instantiate(nil, { position = { 0, 0, 0 } })
```
# applicable
Can be applied for an owner, with values for its declared parameters. A type
that lists `applicable` under `interfaces:` in its `type.yaml` guarantees that
any of its assets can be put in effect for an **owner**, with values for the
parameters the asset declares (`asset.schema`), and that the owner can change
those values, turn the application off and on, and drop it, which leaves
nothing behind, and that the owner can read the application's state as it
stands. A caller applies any implementer with the same calls; here `ref` is
any asset whose type lists `applicable`:
```lua
local view = ref:as("applicable")
local state = view:apply("owner-key", {})
view:setEnabled("owner-key", false)
view:state("owner-key")
view:drop("owner-key")
```
## The members
| Member | What it does |
|---|---|
| `apply(self, owner, values, opts?) -> ApplyState` | Puts the asset in effect for `owner` with `values`. Called again for the same owner, it changes the values. |
| `setEnabled(self, owner, enabled) -> ApplyState` | Turns that application on or off while it stays applied; its values are kept. |
| `drop(self, owner)` | Removes that application entirely. Dropping an owner with nothing applied does nothing. |
| `state(self, owner) -> ApplyState?` | The application's state now, the answer `apply` would give, read without applying. `nil` when nothing is applied for `owner`. |
`owner` is a key the caller forms from something only it holds, so two callers
never share an application. With the asset, it identifies the application
across the calls.
`ApplyState` is `{ status = "inForce" | "off" | "held", heldBy?, notice? }`:
`held` when another application is in force instead (`heldBy` names it), and
`notice` the words a person should see about the application. A type may return
more fields beside these and documents them itself. An application's state can
change with no call for it, when another application of the same kind comes or
goes; `state` answers it as it stands on the frame it is asked.
## The values an application receives
Every call of a member passes through the interface's contract
(`@builtin::interfaces.applicable.contract`), which keeps one record per
application: the values the owner stated and whether it is on. The type's
`apply` receives the asset's own values (`asset.settings`, else its schema's
defaults) with what the owner stated laid over them. A name `values` gives that
the schema does not declare, or a value its descriptor refuses, raises at the
call, naming the asset and the parameter. `Apply.values(self, owner)` and
`Apply.stated(self, owner)` read an application's record.
After an edit/play flip, a render-device rebuild, and an edit of an applied
asset, the contract applies every record again; no owner acts. A type's `apply`
puts back what of its effect is gone and leaves what still stands as it is.
## Implementing it
```yaml
# <type>.assetType/type.yaml
interfaces: [applicable]
settings: { values: "<type>.yaml", schema: { type: "settings.luau" } }
```
```lua
-- <type>.assetType/behavior.luau
local Apply = require("@builtin::interfaces.applicable.contract")
local M = {}
M.ref = {
apply = function(self, owner, values, opts)
-- make the application `owner` be `values`, on when `opts.enabled`
return { status = if opts.enabled then "inForce" else "off" }
end,
setEnabled = function(self, owner, enabled)
return { status = if enabled then "inForce" else "off" }
end,
drop = function(self, owner)
-- remove everything made for `owner`
end,
state = function(self, owner)
-- the answer `apply` would give now, without applying
local on = Apply.enabled(self, owner)
return { status = if on then "inForce" else "off" }
end,
}
return M
```
A type states `settings:` in its `type.yaml` so its parameters are readable
with `asset.schema`; an empty schema is valid, and such an asset is applied
with no values. A type whose own `apply` means something else meets the member
under `M.interfaces.applicable.apply`.
## Required behaviour
1. **In effect on return.** When `apply` returns `inForce`, the asset's effect
is in effect with those values.
2. **A change is a write.** After `apply(owner, changes)`, the effect is what a
first `apply` with the complete changed values would have given.
3. **Edit and play.** In effect in edit mode and in play mode.
4. **Off keeps values.** `setEnabled(false)` takes the effect away;
`setEnabled(true)` brings it back with the same values.
5. **Drop leaves nothing.** After `drop`, what the application made is gone:
the engine's entities, render features, post-process entries and claims are
as before the first `apply`.
6. **Nothing saved.** Nothing an application holds reaches a saved scene.
7. **Independent.** Two owners' applications of one asset are two: one
changing, turning off or dropping never changes the other, except through
the asset's own rule for which application is in force.
8. **One in force is the asset's rule.** An asset whose effect holds one
application at a time decides among its applications and reports the others
`held`.
9. **Kept in force.** What an application holds is put back after the events
that remove it, by the contract's restatement.
The conformance suite (`conformance`) checks these against every asset of every
implementing type it can reach.
# sceneInstantiable
Can be placed in a scene. A type that lists `sceneInstantiable` under
`interfaces:` in its `type.yaml` guarantees that `instantiate` composes any of
its assets under or onto an owning entity, synchronously, and returns the live
root and the map naming what it spawned. A consumer places any such asset with
one call, `source:as("sceneInstantiable"):instantiate(target, opts)`, and it
works for types the consumer has never heard of: the `Asset` component, a
viewport drop, a procedural generator and a tool argument all place assets this
way.
## Implementing it
```yaml
# marker.assetType/type.yaml
interfaces: [sceneInstantiable]
```
```lua
-- marker.assetType/behavior.luau
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
local M = {}
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts)
root.component.add("Text3D", { text = self.name })
return Instantiable.result(self, root, {})
end,
}
return M
```
A type whose own `instantiate` means something else meets the member under
`M.interfaces.sceneInstantiable.instantiate`.
## The base inputs
`target` is the owning entity; with none, the type spawns a fresh root.
`opts.position`, `opts.rotation`, `opts.scale`, `opts.name` and
`opts.temporary` mean the same for every type, and `Instantiable.root` applies
them to a root the type makes (`Instantiable.place` to one it adopts).
`opts.idMap`, `opts.diff` and `opts.sourceTag` are what the `Asset` component
passes to every type: a type that spawns no addressable children ignores them.
`opts.detached` composes a permanent copy that nothing composes again. A type's
own extras (`raw`, `deferred`, `params`) travel in `opts` beside these, are
always optional, and never change a base input's meaning.
## Required behaviour
1. `root` exists on return, with everything composed under it.
2. `idMap` maps each original id to the spawned id; `{}` for none.
3. Passing the returned `idMap` back reproduces the same ids.
4. `temporary = true` keeps the root and everything under it out of the saved
scene.
5. Despawning `root`, or the composition the `Asset` component despawns, removes
everything the call put in effect.
The conformance suite, `sceneInstantiableConformance` beside this file, holds
one asset of every implementing type (or of the types a run names) to the base
options' meanings, the returned map reproducing its ids when passed back, and
a detached composition's live root. `asset.validate` of a world's own type runs
it over that type.
## Legacy types
A type that defines `M.ref.instantiate` and lists nothing (one written
before `interfaces:` existed, or defined by its `behavior.luau` alone)
implements `sceneInstantiable` with a warning (`interfaces.implied`) naming the
line to add.
# 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.