# shape.box
A box centred on the origin with flat faces.
In a scene: `BoxGeometry(width, height, depth)`.
| Input | Default | Meaning |
|-------|---------|---------|
| `width` | 1 | Its size along X. |
| `height` | 1 | Its size along Y. |
| `depth` | 1 | Its size along Z. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
BoxGeometry(2, 1, 1.2):round(0.1)
```
# shape.buffer
A mesh from arrays: positions, optional triangle indices, optional normals and uvs. Without normals they are computed, smooth or flat. Indices out of range and lists of the wrong length are refused by name.
In a scene: `BufferGeometry() with setAttribute('position' | 'normal' | 'uv', Float32BufferAttribute(array, itemSize)), setIndex(list) and computeVertexNormals()`.
| Input | Default | Meaning |
|-------|---------|---------|
| `positions` | {} | Flat list of vertex positions, three numbers per vertex. |
| `indices` | {} | Flat list of triangle corner indices from 0, three per triangle; empty takes the vertices in order, three at a time. |
| `normals` | {} | Flat list of vertex normals, three per vertex; empty computes them. |
| `uvs` | {} | Flat list of texture coordinates, two per vertex; empty gives none. |
| `smooth` | true | With no normals given: true shares each vertex's normal across the triangles that meet at it, false gives every triangle its own. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
local geometry = BufferGeometry()
geometry:setAttribute('position', Float32BufferAttribute({ 0, 0, 0, 1, 0, 0, 0, 1, 0 }, 3))
```
# shape.capsule
A capsule along Y: a cylinder of `length` with a hemisphere on each end.
In a scene: `CapsuleGeometry(radius, length, capSegments, radialSegments)`.
| Input | Default | Meaning |
|-------|---------|---------|
| `radius` | 0.5 | The radius of the cylinder and the caps. |
| `length` | 1 | The length of the straight middle part. |
| `capSegments` | 4 | Segments along each cap's arc. |
| `radialSegments` | 16 | Segments around. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
CapsuleGeometry(0.35, 0.9, 6, 20)
```
# shape.circle
A flat disc in the XY plane facing +Z.
In a scene: `CircleGeometry(radius, segments)`.
| Input | Default | Meaning |
|-------|---------|---------|
| `radius` | 1 | Its radius. |
| `segments` | 32 | Segments round its edge. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
CircleGeometry(0.5, 48)
```
# shape.cylinder
A cylinder along Y, capped, with different radii at its two ends: a cone when one is 0. The fifth argument of `CylinderGeometry` and the fourth of `ConeGeometry` is `heightSegments`, in the place three.js has it; the side is one band.
In a scene: `CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded) and ConeGeometry(radius, height, radialSegments, heightSegments, openEnded)`.
| Input | Default | Meaning |
|-------|---------|---------|
| `radiusTop` | 1 | The radius of its top. |
| `radiusBottom` | 1 | The radius of its bottom. |
| `height` | 1 | Its length along Y. |
| `radialSegments` | 32 | How many sides it has round. |
| `openEnded` | false | Whether the top and bottom are left open, as a pipe or a liner. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
CylinderGeometry(0.3, 0.5, 1.4, 24):bend(0.5)
```
# shape.extrude
A 2D shape path extruded along +Z with flat caps.
In a scene: `ExtrudeGeometry(shape, { depth, curveSegments })`.
| Input | Default | Meaning |
|-------|---------|---------|
| `shape` | {} | The outline as path commands: `{ 'moveTo', x, y }`, `{ 'lineTo', x, y }`, `{ 'arc', cx, cy, r, a0, a1, clockwise }` and the rest. A `Shape` writes them. |
| `depth` | 1 | How far it extrudes along +Z. |
| `curveSegments` | 12 | Segments used for curved path commands. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
ExtrudeGeometry(RoundedRectShape(1, 0.6, 0.1), { depth = 0.2 })
```
# shape.flatShape
A flat, filled 2D shape in the XY plane facing +Z, from path commands.
In a scene: `ShapeGeometry(shape, curveSegments)`.
| Input | Default | Meaning |
|-------|---------|---------|
| `shape` | {} | The outline as path commands, as for `extrude`. |
| `curveSegments` | 12 | Segments used for curved path commands. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
ShapeGeometry(EllipseShape(0.5, 0.3))
```
# shape.lathe
A surface of revolution: a profile of `{ radius, y }` points revolved around Y.
In a scene: `LatheGeometry(points, segments)`.
| Input | Default | Meaning |
|-------|---------|---------|
| `points` | {} | The profile: a list of `{ radius, y }` pairs. |
| `segments` | 12 | Segments around the axis. |
| `phiStart` | 0 | Where the revolution starts, in radians. |
| `phiLength` | 2 pi | How far it revolves, in radians. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
LatheGeometry({ Vector3(0, 0), Vector3(0.4, 0.1), Vector3(0.3, 0.8), Vector3(0, 1) }, 32)
```
# shape.plane
A flat rectangle in the XY plane facing +Z, centred on the origin.
In a scene: `PlaneGeometry(width, height, widthSegments, heightSegments)`.
| Input | Default | Meaning |
|-------|---------|---------|
| `width` | 1 | Its size along X. |
| `height` | 1 | Its size along Y. |
| `widthSegments` | 1 | Segments along X. |
| `heightSegments` | 1 | Segments along Y. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
PlaneGeometry(2, 2, 16, 16):bend(0.3)
```
# shape.polyhedron
A regular polyhedron inscribed in a sphere. With `detail` 0 its faces are flat; above 0 each face is split and the surface rounds toward the sphere.
In a scene: `TetrahedronGeometry, OctahedronGeometry, IcosahedronGeometry and DodecahedronGeometry (radius, detail)`.
| Input | Default | Meaning |
|-------|---------|---------|
| `kind` | icosahedron | Which solid: tetrahedron, octahedron, icosahedron or dodecahedron. |
| `radius` | 1 | The radius of the sphere it is inscribed in. |
| `detail` | 0 | How many extra points each edge gets. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
IcosahedronGeometry(0.6, 1):smooth()
```
# shape.ring
A flat annulus in the XY plane facing +Z.
In a scene: `RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength)`.
| Input | Default | Meaning |
|-------|---------|---------|
| `innerRadius` | 0.5 | The radius of the hole. |
| `outerRadius` | 1 | The outer radius. |
| `thetaSegments` | 32 | Segments around. |
| `phiSegments` | 1 | Segments from the inner to the outer radius. |
| `thetaStart` | 0 | Where the arc starts, in radians. |
| `thetaLength` | 2 pi | How far the arc runs, in radians. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
RingGeometry(0.3, 0.5, 48)
```
# shape.sphere
A UV sphere.
In a scene: `SphereGeometry(radius, widthSegments, heightSegments)`.
| Input | Default | Meaning |
|-------|---------|---------|
| `radius` | 1 | Its radius. |
| `widthSegments` | 32 | Segments around its equator. |
| `heightSegments` | 16 | Segments from pole to pole. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
SphereGeometry(0.5, 32, 16):taper(0.4)
```
# shape.torus
A torus in the XY plane around Z.
In a scene: `TorusGeometry(radius, tube, radialSegments, tubularSegments, arc)`.
| Input | Default | Meaning |
|-------|---------|---------|
| `radius` | 1 | The radius of the ring. |
| `tube` | 0.4 | The radius of the tube. |
| `radialSegments` | 12 | Segments around the tube. |
| `tubularSegments` | 48 | Segments around the ring. |
| `arc` | 2 pi | How much of the ring, in radians. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
TorusGeometry(0.255, 0.105, 14, 32)
```
# shape.torusKnot
A (p, q) torus knot: a tube swept along a knot that winds `p` times around its axis and `q` times through the hole.
In a scene: `TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q)`.
| Input | Default | Meaning |
|-------|---------|---------|
| `radius` | 1 | The radius of the knot's overall torus. |
| `tube` | 0.3 | The radius of the tube. |
| `tubularSegments` | 64 | Segments along the knot. |
| `radialSegments` | 8 | Segments around the tube. |
| `p` | 2 | How many times it winds around its axis. |
| `q` | 3 | How many times it winds through the hole. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
TorusKnotGeometry(0.45, 0.14, 96, 10, 2, 3)
```
# shape.tube
A circle swept along a curve: pipes, springs, hoses and headers.
In a scene: `TubeGeometry(path, tubularSegments, radius, radialSegments, closed)`.
| Input | Default | Meaning |
|-------|---------|---------|
| `curve` | {} | The curve: `{ type = 'catmullrom', points = {...} }` or `{ type = 'helix', radius, turns, height }`. `CatmullRomCurve3` and `HelixCurve` write them. |
| `tubularSegments` | 64 | Segments along the curve. |
| `radius` | 1 | The radius of the tube. |
| `radialSegments` | 8 | Segments around the tube. |
| `closed` | false | Whether the curve closes on itself. |
The node answers `geometry`: a mesh with positions, normals and uvs. Its body is a call into the module in its own folder, so a graph of many parts cooks without a device dispatch per shape.
```luau
TubeGeometry(CatmullRomCurve3({ Vector3(0, 0, 0), Vector3(1, 0.4, 0), Vector3(2, 0, 0) }), 48, 0.05, 8)
```
# Nodebox (asset type)
A nodebox is a namespace folder that groups related `.procNode/` children, the way a toolbox groups
`.tool/` children. A node's name is its folder name inside its box: `points.nodebox/disc.procNode` is
called `points.disc`, and nothing inside the node states that name. Moving or renaming a node is a VFS
move that keeps its guid.
## Where it lives
- Source: `<anywhere>/<family>.nodebox/`, usually inside a `.package`, an effect or a world's content.
- Identity: the folders above it and `<family>` (`fx.points` for `fx/points.nodebox`; the `.nodebox`
suffix strips). A graph calls its nodes by `<family>.<node>` alone.
- Folder shape (open child set):
- `README.md`: what the family is for. Required.
- `.metadata`: description and tags. Required. It also states where the box's nodes work: `context` (one of
`proc.registry.contexts()`: `geometry`, `field`, `value`, `sim`, `raster`, `material`, `prefab`) and, when every
node of the box reads the scene or assets beside its inputs or writes them beside its outputs, `pulls` /
`pushes` (`scene` or `asset`). A node that works elsewhere states its own in its `.metadata`.
`procgen` `describeNode` and the `context`, `pulls` and `pushes` filters of `searchNodes` read them.
- `<node>.procNode/`: any number of nodes.
## How a graph reaches a node
`g.<family>.<node>(args)` resolves the node by its asset identity: the box and the folder name together
(`g.points.disc`), a path (`g["/zero/source/fx/ring.procNode"]`), `~` (the nearest enclosing package,
effect or world root: `g["~/ring"]`) or a short name the asset system resolves (`g.disc`). A name that
matches two nodes is an error naming both; a name that matches none is an error naming the closest nodes.
Each call is recorded in the graph's reference table by the node's guid.
## How to create one
```luau
asset.create("nodebox", "points", { folder = "fx" })
local box = asset.resolve("points.nodebox")
asset.create("procNode", "disc", { into = box })
```
## Discovery
- `asset.list("nodebox")`: every box.
- `asset.inspect("points")`: the nodes in it and what each does.
- `asset.list("procNode")`: every node, in or out of a box.
## In the Inspector
Nodes: how many nodes the box holds, each node's full name and what it does, and a link to each.
# box
The CPU code behind the `shape.box` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# procNode: one reusable step of procedural generation
A `.procNode` is a node authored as content: a folder whose `init.luau` is the node. It
returns `proc.define(function(g) ... end)`, the same function-of-`g` form a `.procGraph` is
written in, so a node is a small graph that other graphs call. Its `g:describe` text says
what it makes and when to use it, its `g:input` declarations are what a call passes, and
what it returns (or declares with `g:output`) is what the call gives back.
```
MyNode.procNode/
init.luau -- the node
README.md -- what it produces, its inputs, its outputs
.metadata -- description and tags
```
## What a node states
- **`g:describe(text)`**: what the node produces and when to use it. It is the text search,
the node catalogue and the Inspector show.
- **`g:input(name, default, opts)`**: one input of the node. The default types it (`Float`,
`String`, `Bool`, `Vec3`, `Color`, `List<T>`, `Record`); `opts` adds `type` (for a default
that does not state one, or none), `description`, `options`, `min`, `max` and `optional`. A
call names inputs in a table, or passes them in declaration order.
- **Outputs**: the returned table names them (`return { geometry = geometry }`), and
`g:output(name, value)` declares one as the node builds. A node with one output answers
that value to its caller; a node with several answers a record by output name; a node with
none answers nothing.
- **Written as literals.** What a node takes and gives is read from its source without running
it, the way search and description read it here and the way ZeroMind reads it, so each
declaration states its values as written: `g:describe` and each `g:input` once, at the top
level of the function, with a literal name, default and options (a file constant holding a
literal, or `asset.resolve("<identity>", "<type>")`, reads as one); outputs named by the table
the function returns, or by `g:output`, the same names on every branch of a condition and never
inside a loop. `asset.interface(node)` answers what the source declares, with each part it
cannot read as a problem, and a push refuses a node with such a problem
(`interface.unreadable`).
- **The body** is the node's work: calls to other nodes, arithmetic over sockets, `for`, folds,
steps and state, as the builder README (`proc.module/builder.module/README.md`) describes.
A node that uses another node is recorded in the graph that calls it, so a node can be built
from nodes.
## How a graph calls a node
A node inside a `<family>.nodebox` is called by its box and folder name:
`points.nodebox/disc.procNode` is `g.points.disc({ ... })`, and nothing inside the node states
that name. A node is also reached by:
- its path (`g["/zero/source/fx/ring.procNode"]`),
- `~`, the nearest enclosing package, effect or world root (`g["~/ring"]`),
- its guid,
- a short name only one node answers to (`g.disc`).
A name that matches two nodes and a name that matches none are errors that name the
candidates. Each call is recorded in the calling graph by the node's guid, so the node travels
with every graph that uses it, and a rename or a move keeps the reference. A `.procGraph` is
called the same way and answers what it returns.
## Nodeboxes
A nodebox is the family a node lives in: a namespace folder grouping related nodes (`points`,
`mesh`, `field`, `terrain`). `nodebox.assetType` describes it. A node placed in a box takes the
box's name as its prefix; a node outside any box is reached by path, `~` or guid.
`asset.create("nodebox", family)` makes a box and `asset.create("procNode", name, { into = box })`
makes a node in it.
## Finding nodes
`asset.list("procNode")` lists every node. The `procgen` toolbox's `searchNodes` finds them by
meaning across every published node, and with no query lists the ones this engine holds grouped
by family; its `describeNode` answers one node's inputs, their types and defaults, and its
outputs. Both read what each node's source declares and run no node. The type's `indexing`
recipe embeds a node's README and its source, so a search by meaning finds a node by what its
description and README say it is for: write them in the words someone looking for the node
would use.
## Registration
Every node the asset index lists is known to the procgen registry by what its source declares,
read when it is asked for and read again when the source changes; nothing runs a node to list
it. Its code loads the first time a build runs it. After that, the lifecycle hooks keep it
current: `onChange` loads it again and hot-reloads on an edit, `onDelete` removes it. Editing
`init.luau` cooks again every graph that reaches the node, and only the nodes downstream of the
change do work. `init.luau` is compiled from its current source on each load, so a module it
pulls in uses an absolute require
(`require("@builtin::systems.procgen.proc")`).
What a node is built from is more than its own file. A module its `init.luau` requires while it
builds, at any depth of requires, is part of it: when that module changes, `onDependencyChange`
loads the node again from the module as it now stands. A file its `init.luau` reads with
`vfs.read` while it builds is part of it too, and so is a file a module it calls reads with
`proc.read` (a module's own `vfs.read` is its own and makes no dependency). Writing such a file
loads the node again (`proc.sourceChanged`). Either way the node's definition moves, so every
graph and Generator reaching it cooks again, from one version of everything it was built from.
`proc.builder.readsOf("<node>.procNode/init.luau")` lists the files its last build read. A graph that references a node which is not
registered errors at load, naming the missing guid. A graph that reaches itself, directly or
through other nodes, errors at cook.
## Content requirements
`README.md` carries real text: what the node produces, its inputs and its outputs. `.metadata`
carries a `description` (what the node computes and the value type it answers) and `tags` (the
family, so search finds it). It may state where the node works: `context`, `pulls` and `pushes`
(the values `proc.registry.contexts()`, `"scene"` and `"asset"` name). A node in a nodebox that
states none takes its box's; `procgen` `describeNode` and `searchNodes` answer them.
A node written with `proc.graph` and `g:node` (the `procNodes/` of the procgen package) is called only
by a `proc.graph` graph, through `g:node`. A graph built with `proc.define` does not call it: `g.op.<name>`
of it is refused where it is written, naming the node written in the call form that answers to the same name.
## In the Inspector
Operation: the node's id and what it does, its cost and caching when it declares them, and its
inputs and outputs, from the procgen registry's schema for it. A node that did not register says
so.
# buffer
The CPU code behind the `shape.buffer` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# capsule
The CPU code behind the `shape.capsule` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# circle
The CPU code behind the `shape.circle` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# cylinder
The CPU code behind the `shape.cylinder` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# extrude
The CPU code behind the `shape.extrude` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# flatShape
The CPU code behind the `shape.flatShape` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# lathe
The CPU code behind the `shape.lathe` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# plane
The CPU code behind the `shape.plane` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# polyhedron
The CPU code behind the `shape.polyhedron` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# ring
The CPU code behind the `shape.ring` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# sphere
The CPU code behind the `shape.sphere` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# torus
The CPU code behind the `shape.torus` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# torusKnot
The CPU code behind the `shape.torusKnot` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# tube
The CPU code behind the `shape.tube` node: it takes the node's inputs and returns the mesh as a procgen Geometry (`proc.substrate.fromArrays`). The node's README lists the inputs.
# 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.
# 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**.
# proc
Code-authored, graph-backed procedural generation for the Zero engine.
A graph is one function of `g`: `proc.define(function(g) ... end)`. Nodes are called by
family and name (`g.<family>.<name>({ ... })`), inputs are declared with `g:input(name, default, opts)`,
the returned table is the graph's outputs, and `io.output` is how the graph stands in the world.
`builder.module/README.md` holds every rule of that form.
This module owns the whole procedural model: the graph builder + data model,
the operation registry, the type system, the lazy cached evaluator, deterministic scoped hashing, and the node-family op
implementations. Authored `.procGraph` graphs are persisted via
`procGraph.assetType`; the `procgen.preview` / `procgen.spawn` operations live in
`procgen.toolbox` and are invoked as tools: `tools.use("procgen", "preview", args)`
from a script or an agent's `tool_exec` script, or `zero procgen preview` in the
shell. Generated
meshes/materials/textures/bundles are persisted through their own `.assetType`.
An op family can also come from outside this package: a `.procPack` asset
registers its ops in the same registry, called as `g.op.<id>(...)` exactly like the ones
shipped here (`proc.registerPack(name, ops)` is what it registers through, and
what a test or a tool calls to hold a family for the life of one VM).
`terrain.*` is one such pack, shipped in `terrainSystem.package/procPacks/`
and covering a whole landscape; `guides { path =
"systems/terrainSystem/documentation/terrain" }` is its guide.
To find out what the registry holds, use the `procgen` toolbox: `searchNodes`
searches it and `describeNode` describes one node or op. `proc.search_ops(query)` and
`proc.schema(id)` are the same answers in-process, for a graph builder looking
something up while it runs.
# io.luau (procNode)
Run a function of a Luau module on the CPU and answer what it returns. The module is required, the function read by name, and the function called with the arguments; the result is cached by the module's checksum, the function name and the arguments, so a module edit re-cooks it.
Built from `op.cpu.call` of `require` on the module, a member read of the function by name, and `op.cpu.call` of that function (`op.cpu.read` when `live` names a digest). Both calls run on the CPU, so a graph holding this node shows a CPU call wherever it sits.
```luau
local label = g.io.luau({ module = "@builtin::systems.procgen.nodes.instances.pack.pack", fn = "nameOf", args = { 3 }, returns = { "String" } }).value
```
## What a function receives and returns
A number, text or vector reaches the function as itself. A Geometry reaches it as an object of its columns, read to the CPU first (as they stand on the device when `device` is on):
- `geometry:count(class)` is how many elements the class holds. `class` is `"point"`, `"vertex"`, `"edge"`, `"primitive"` or `"detail"`.
- `geometry:column(class, name)` is the column of that class and name, or nil where the Geometry holds none. `geometry:column("point", "P")` holds the positions.
- A column answers `column:count()` (its elements), `column:type()` (`"Vec3"`), `column:lanes()` (the numbers one element holds, 3 for a Vec3) and `column:read()`, every number of it in one flat list, element after element: a grid of six points reads 18 numbers from its `P`.
A function answers by returning values, one for each type in `returns`. A Geometry is returned as one built from flat lists, `proc.geometry.new({ positions = { ... }, indices = { ... } })`, with `normals` and `uvs` optional, and is declared `"Geometry"` in `returns`: `value` is then that Geometry, its point `P` column holding the positions.
```luau
-- The module /source/shapes.module:
local proc = require("@builtin::systems.procgen.proc")
local M = {}
function M.heights(geometry)
local positions = geometry:column("point", "P"):read()
local low, high = math.huge, -math.huge
for i = 2, #positions, 3 do
low, high = math.min(low, positions[i]), math.max(high, positions[i])
end
return low, high
end
function M.triangle(size)
return proc.geometry.new({ positions = { 0, 0, 0, size, 0, 0, 0, size, 0 }, indices = { 0, 1, 2 } })
end
return M
```
```luau
local range = g.io.luau({ module = "/source/shapes.module", fn = "heights", args = { points }, returns = { "Float", "Float" } }).values
local triangle = g.io.luau({ module = "/source/shapes.module", fn = "triangle", args = { 2 }, returns = { "Geometry" } }).value
```
## Inputs
- `module` (AssetRef<module>, default ""). The module that holds the function: its identity, path, AssetRef or guid. It is recorded as a dependency of the graph.
- `fn` (String, default ""). The name of the module's function to call.
- `args` (List<Value>, optional). The values the function is called with, in order. A device column is passed as a reference to its buffer.
- `returns` (List<TypeName>, optional). The procgen types of the values the function returns, in order.
- `ceilingMs` (Float, default 0, at least 0). The CPU time the function may run for, in milliseconds, counting the work it runs in any coroutine it resumes and in any task it starts while the call lasts; a call past it is refused. The time it waits on a frame, a program build, a read-back or a task, and the time its thread waits for a core on a busy machine, are not counted. 0 leaves the runtime's default ceiling.
- `device` (Bool, default false). On, a Geometry in `args` reaches the function as it stands on the device, its columns left where they are; off, its columns are read to the CPU first.
- `live` (String, default ""). The name of a function of the module that answers a digest of the state `fn` reads, called with the same arguments. A call that names one reads state outside the graph, such as entities in the scene: the graph's live digest folds the digest in, so a Generator cooks it again when that state changes. Left empty, the call reads nothing the graph does not hold.
- `pure` (Bool, default false). On, what `fn` returns is a function of `args` alone and the call changes nothing: a call whose arguments are known while the graph is planned is made then, once, and its results stand in the plan as constants.
- `curves` (Bool, default false). On, an animated value among `args` reaches `fn` as the curve it is, and `fn` answers with what follows it: a curve, or a field reading it as a live value, so a later time is presented on the device without a cook. Off, it reaches `fn` as the value it holds at the cook's time.
## Outputs
- `value`: the first returned value.
- `values`: every returned value, in order.
# prefab (nodebox)
Prefabs: the entity records a spawned hierarchy is made of, as record and list values. prefab.empty makes a root, prefab.entity, prefab.parent, prefab.add_component and prefab.link shape the hierarchy (each calls prefab.edit, which holds the record-list edits and the name lookup that prefab.find answers), and prefab.from_geometry, prefab.from_geometries, prefab.from_instances, prefab.from_population and prefab.from_asset make prefabs from what a graph built. The output node shows a prefab and the export node saves it as a bundle.
prefab.record and prefab.find are the parts the others are built from: one entity record, and a lookup of an entity by name.
# field.distance (procNode)
How far each element's position is from a target, as a Float field. It makes the target the wired `b` field or,
when `b` is left unwired, the fixed `point` as a constant field (`value.fallback`, `field.constant`), then
measures with `field.vector_math` in `distance` mode from `a` to that target. The result compiles to the device with
the rest of the field chain.
## Inputs
- `a` (`Field<Vec3> | Vec3`): the positions being measured, one per element.
- `b` (`Field<Vec3> | Vec3`): what each element is measured to, per element, so the target can move with the
element. Wired, it stands in for `point`.
- `point` (`Vec3`, default `{ 0, 0, 0 }`): one fixed position every element is measured to when `b` is unwired. It is
how a radial falloff around a place is built.
## Outputs
- `field`: the distance, a Float field.
# instances (nodebox)
Instances: pack a geometry into a piece (instances.pack), place a piece set on target points (instances.to_points) and take a population or piece set apart (instances.unpack). A piece is one point whose `Mesh` holds a geometry whole, as the node that made it left it: a geometry whose elements are counted on the device (what `geometry.triangulate` makes) keeps its counts there, and draining the piece set (`Geometry.drain`) drains the geometries its records hold with it, so a CPU reader reads each piece's elements; `geometry.merge` with `pack` puts several together into a piece set. The copies `instances.to_points` makes are a population, which the output node draws as instanced draws, one per piece and material, and export saves as a population asset; any other points stand as one entity each.
instances.pack, instances.to_points and instances.unpack are the nodes of that chain, with `points.pose` composing the instance attributes (`P`, `orient`, `scale`, `N`, `v`, `up`, `pscale`, `rot`, `trans`, `pivot`) the copies stand at.
Earlier nodes of the nodebox stand a source on points (instances.on_points), deal one of several sources to each point (instances.pick_random, instances.pick_by_attribute), vary and move the copies (instances.randomize_transform, instances.transform, instances.set_material) and merge them into one geometry (instances.realize). The points they make carry a `Mesh` and stand as entities through the output node.
instances.place, instances.variants, instances.turn and instances.sources are the parts the others are built from: a transform written onto points, a variant index written onto points, the product of two rotations, and the geometries a population stands (the ones given, else the ones its points carry).
# value (nodebox)
Single values in a graph: value.math and value.compare do arithmetic and comparison with the operation picked by a parameter, value.expr follows a Luau expression over the graph's clock, value.get reads one field of a record by a dotted path, and value.switch picks one of two values by a Bool. value.present and value.fallback are how a graph used as a node handles an input its caller may leave unwired: present answers whether anything is wired, fallback takes the wired value or a fallback.
# part (nodebox)
part.merge packs several values into one part, each piece keeping what it is; part.unpack gives one piece back by its name.
# math
One node per operator and per function of Luau's `math` table that is a function of its numbers alone: add, sub, mul, div, mod, pow, neg, abs, min, max, floor, ceil, round, sqrt, sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, exp, log, log10, fmod, ldexp, frexp, modf, noise, map, sign, deg, rad, clamp, lerp, smoothstep, isnan, isinf, isfinite, length, normalize, dot, cross, vec2, vec3, vec4, the comparisons (lt, le, gt, ge, eq, ne, and `compare` over them), `where`, the integer functions (to_int, to_float, bor, bxor, shl, floordiv), and `concat` for text. `math.random` and `math.randomseed` have no node: they draw from state outside the graph, a graph that called one would cook differently each time, and a call of either in a graph is refused, naming `field.rand`, `field.random` and `rand.unit`, which draw from a seed.
Operators and `math.*` over sockets resolve to these nodes, and `vector.create` over sockets resolves to `math.vec2`, `math.vec3` or `math.vec4` by its component count; with plain numbers only, `math.*` and `vector.create` are Luau's own, and `vector.create` holds three components. Each node but `compare` (built from the comparisons) and `concat` (text) calls an operation of `proc.fieldc.operators`: over plain numbers and vectors it answers the plain result, over a Column or a Field it answers a Field (a fieldc template), so a chain of math nodes is one expression that the node consuming it evaluates in a single dispatch (`fieldc.evaluate`).
`math.min` and `math.max` over sockets take any number of operands, folded two at a time; `math.log(x, base)` is the `log` node with its `base`. Operands of different widths widen to the widest: a number applies to every component, and a shorter vector reads 0 for the components it lacks. Division, `floordiv`, `mod` and `fmod` by 0 answer 0, `sqrt`, `log` and `log10` of a value at or below 0 answer 0, `asin` and `acos` of a value past -1 or 1 read the nearest of the two, and `map` over an input range of no width answers its output minimum, so a chain keeps producing numbers. The orderings (`lt`, `le`, `gt`, `ge`) compare first components; `eq` and `ne` compare every component.
# core
The parts the other procgen nodes are built from: connectivity (edges, boundary, adjacency, islands, owner, corners), normals, weld, select, stitch, curve measure and resample, sampling, neighbours, realize, the raster set (`raster.new`, `raster.read`, `raster.stencil`, `raster.sample`, `raster.add_layer`, `raster.remove_layer`, `raster.reduce`, `raster.column`, `raster.resolve`, `raster.blend`, and `raster.cells` under them), `column`, and `entity.read`, which brings scene entities in (assets come in through `io.import`).
Each is a graph of the four ops, the kernels of `kernels/` and other core nodes. `join` holds the module that places the parts of a join, called by `concat` and `realize`.
A graph calls them as `g.core.<name>`, for instance `g.core.edges`. A node with several outputs answers a record: `local faces = g.core.normals.face(...)` then `faces.geometry`, `faces.scaled`. Every node's README states its inputs and outputs.
# Scatter (node)
A scattering node: its `init.luau` holds the graph that does the work, so the declared inputs are this node's inputs
and the declared output is this node's output. The node is its pipeline, in one self-contained asset.
It makes points on the surface (`points.on_surface`, area-weighted), gives every point its own random yaw, lean and
scale (`instances.randomize_transform`), and places the source on those points (`instances.on_points`). The
transform is read from the same point cloud the instances sit on, so each copy takes the pose of its own point.
A node is findable by what it does: the `procgen` toolbox's `ops` with the query `scatter` lists it beside
`points.on_surface` and `instances.on_points`. Editing this node's `init.luau` cooks again every graph that calls it.
## Inputs
- `surface` (Geometry): what the copies land on.
- `source` (Geometry): the shape being copied.
- `count` (Int, default 200): how many.
- `seed` (Int, default 1): changes the arrangement.
- `scaleMin` / `scaleMax` (Float, defaults 0.8 and 1.4): per-copy size range.
- `tilt` (Float, default 0.15): radians of random lean.
## Output
- `instances`: a population, the points each carrying the source as its `Mesh`.
## Authoring a node
A node is a graph returned from a `.procNode`'s `init.luau` (`proc.define`). `asset.create("procNode", name)`
scaffolds that shape, and `procNode.assetType/README.md` describes what a node states and how graphs call it.
# field.ramp (procNode)
A ramp read at every element by a value it carries: a particle's colour, size or opacity following its age. It takes
the value each element reads by (the wired `t`, else the element's own `by` attribute, through `value.fallback` and
`field.attribute`), maps it from `range` onto 0..1 (`field.map_range`, the ends read off `range` by `value.get`), and
reads the ramp there with `ramp.sample`, compiled into the element's dispatch. A value past either end of `range` reads
that end of the ramp.
## Inputs
- `ramp` (`Ramp`): the ramp to read.
- `t` (`Field<Float> | Float`): where along the ramp each element reads. Unwired, it is the element's own `by`
attribute.
- `by` (`String`, default `"life"`): the Float attribute each element reads the ramp by when `t` is unwired. A particle
solver's particles carry `life`, 0 at birth to 1 at death.
- `range` (`Vec2`, default `{ 0, 1 }`): the values of `t` that land at 0 and at 1 on the ramp, so a speed from 0 to 20
or a temperature from 300 to 3000 reads the whole ramp.
## Outputs
- `field`: the ramp's value at each element.
# quickGeometry
Model a scene in Luau with three.js-shaped code. A `build.luau` or a `.sceneModule` builds `Group`s and `Mesh`es from geometry constructors and materials; at the end of the build the tree is stored in the scene as data, drawn by one `Generator`, and nothing runs per frame.
A bare box reads as a placeholder. Every geometry takes **modifiers** that turn it into a modelled shape: round its edges, taper it, bend it, drill it, smooth it, or build it from a profile or cross-sections. A build whose parts are mostly bare boxes and planes logs a warning that names them.
## Using it
The nouns are globals in a scene's `build.luau` and a `.sceneModule`'s entry script: `sceneNouns` and `quickLighting` join both scripts' contexts, so the engine binds their exports when it loads the script, and the language server knows the same names.
```luau
function content()
local paint = MeshStandardMaterial({ color = "#b0332f", metalness = 0.45, roughness = 0.28 })
local steel = MeshStandardMaterial({ color = "#aab2ba", metalness = 1, roughness = 0.25 })
local body = Mesh(BoxGeometry(1, 1, 1):round(0.14), paint, "rounded_box")
body.position:set(0, 0.8, 0)
local block = Mesh(BoxGeometry(1.1, 1.1, 1.1):subtract(CylinderGeometry(0.3, 0.3, 2, 24)), steel, "drilled_block")
block.position:set(1.5, 0.8, 0)
local hull = Mesh(LoftGeometry({
{ shape = EllipseShape(0.45, 0.28), z = -1.2, scale = 0.25 },
{ shape = EllipseShape(0.45, 0.28), z = -0.55, scale = 0.95 },
{ shape = EllipseShape(0.45, 0.28), z = 0.4, scale = 1.0 },
{ shape = EllipseShape(0.45, 0.28), z = 1.2, scale = 0.3, offset = { y = -0.06 } },
}), paint, "hull")
hull.position:set(3.2, 0.8, 0)
end
```
The same code works in a `.sceneModule`'s builder, where `inputs` declare what a placement may set.
A module joins those contexts with `--!context sceneBuild sceneModule` in its leading comment block, the way these two do. A world's own module joins the same way, and its exports become globals in every build script beside the nouns. A name that starts with `_` stays inside its module. A module that exports `_beginRun` and `_finish` has them called around every run of a build. The `script_context` module's README covers contexts in full.
## Parts
- `Group(name)` holds other objects. `Mesh(geometry, material, name)` draws a geometry.
- `object.position`, `object.rotation` (Euler angles in radians, XYZ) and `object.scale` take `.x`, `.y`, `.z` and the vector methods `set`, `setScalar`, `copy`, `add`, `sub`, `multiplyScalar`, `clone` and `toArray`; calls chain.
- `parent:add(a, b, ...)` nests objects under another, and their poses are then in the parent's frame; an object added elsewhere moves. `parent:remove(a, ...)` takes them out, and a removed object is not drawn until it is added again. `object.parent` and `object.children` hold the tree.
- `object.visible = false` leaves the object and everything under it out of the scene. `object.userData` is a table for your own values.
- `object:lookAt(x, y, z)` or `object:lookAt(Vector3)` turns the object so its +Z axis points at a point in its parent's frame; the object's position and the point are numbers.
- `object:clone(recursive)` copies the object, its pose, components and (unless `recursive` is false) what is under it; the copy shares the geometry and material and is placed like a new `Mesh`. `object:traverse(fn)` calls `fn` on the object and everything under it, and `object:getObjectByName(name)` finds one.
- `object:addComponent(type, data)` puts an engine component on the entity a part becomes (`Physics`, a collider, a `Joint`). A part whose pose follows a formula is drawn as an instance and takes none.
- An object that never moves and carries a component becomes an entity named for it, with its parent and local pose; one that never moves and carries none is folded into the object above it. A moving object's leaves are drawn as instances.
## Geometry
| Constructor | Shape |
|-------------|-------|
| `BoxGeometry(width, height, depth)` | box |
| `CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded)` | cylinder; a cone when one radius is 0 |
| `ConeGeometry(radius, height, radialSegments, heightSegments, openEnded)` | cone with its apex up |
| `SphereGeometry(radius, widthSegments, heightSegments)` | UV sphere |
| `TorusGeometry(radius, tube, radialSegments, tubularSegments, arc)` | torus |
| `TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q)` | torus knot |
| `CapsuleGeometry(radius, length, capSegments, radialSegments)` | capsule |
| `PlaneGeometry(width, height, widthSegments, heightSegments)` | flat rectangle |
| `CircleGeometry(radius, segments)` | flat disc |
| `RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength)` | flat annulus |
| `TetrahedronGeometry`, `OctahedronGeometry`, `IcosahedronGeometry`, `DodecahedronGeometry` `(radius, detail)` | regular polyhedra; `detail` above 0 rounds them toward a sphere |
| `LatheGeometry(points, segments)` | a profile of `{ x = radius, y }` points revolved around Y |
| `ExtrudeGeometry(shape, { depth, curveSegments })` | an outline extruded along +Z |
| `ShapeGeometry(shape, curveSegments)` | a flat, filled outline |
| `TubeGeometry(path, tubularSegments, radius, radialSegments, closed)` | a circle swept along a curve |
| `LoftGeometry(sections, { caps })` | a surface through cross-sections along Z |
| `BufferGeometry()` | a mesh from your own arrays |
| `mergeGeometries(list)` | several geometries as one |
Every geometry also takes `translate(x, y, z)`, `rotateX/Y/Z(angle)` and `scale(x, y, z)`, which move it.
### Outlines and curves
`Shape()` records an outline with `moveTo`, `lineTo`, `quadraticCurveTo`, `bezierCurveTo` and `absarc`. `EllipseShape(rx, ry, segments)` and `RoundedRectShape(width, height, radius, segments)` return ready outlines. `CatmullRomCurve3(points, closed)` and `HelixCurve(radius, turns, height)` return curves for `TubeGeometry`.
### Loft
`LoftGeometry` takes sections in order, each `{ shape, z, scale?, offset? }`: an outline, where along Z it stands, a scale (a number or `{ x, y }`) and a move (`{ x, y }`). `caps = false` leaves the ends open. A body, a hull, a fuselage or a bottle is a loft.
### Custom arrays
```luau
local triangle = BufferGeometry()
triangle:setAttribute("position", Float32BufferAttribute({ 0, 0, 0, 1, 0, 0, 0, 1, 0 }, 3))
```
`setAttribute` takes `position`, `normal` and `uv`; `setIndex(list)` gives triangle indices; without normals they are computed and shared across triangles (`computeVertexNormals()`).
## Modifiers
A modifier changes the shape in its own frame, before `translate`/`rotate`/`scale` move it, and modifiers stack in the order called.
| Modifier | Effect |
|----------|--------|
| `:round(radius, segments)` | round every edge with that radius |
| `:bevel(width, segments, angle)` | round only edges sharper than `angle` degrees; `width` is how far it reaches onto each face |
| `:subdivide(levels, mode)` | split every triangle into four, `levels` 1 to 3 times; `"loop"` (default) also smooths, `"linear"` only adds points |
| `:smooth()` | one round of Loop smoothing |
| `:taper(amount, axis)` | scale the cross-section by `1 - amount * d` at distance `d` along `axis` (`"y"` by default) |
| `:twist(angle, axis)` | turn the shape about `axis` by `angle` radians per metre along it |
| `:bend(curvature, axis)` | curve it along `axis`; `curvature` is 1 over the bend's radius in metres |
| `:subtract(other)`, `:union(other)`, `:intersect(other)` | combine with another closed solid, which stands where it was moved to |
`subtract`, `union` and `intersect` take one shape and one shape; merge parts after combining. Both must be closed solids (a box, cylinder, sphere, torus, capsule or polyhedron, or a bevelled or smoothed one).
## Materials
`MeshStandardMaterial({ color, roughness, metalness, emissive, emissiveIntensity, opacity, side })` and `MeshBasicMaterial({ color, opacity, side })`. A colour is a `Color`, a hex string (`"#a3141b"`), a number (`0xa3141b`), a name (`"red"`) or `{ r, g, b }`; hex colours are sRGB. `side = "double"` draws both faces; an `opacity` below 1 blends.
## Math
`Vector3`, `Color` and `MathUtils` come from the same module as the other nouns and are described in the [math](math.module/README.md) module's README: vector methods and operators, colours from hex, names and HSL, and clamp, lerp, smoothstep and a seeded random.
```luau
MathUtils.setSeed(3)
for i = 1, 12 do
local post = Mesh(CylinderGeometry(0.05, 0.05, 1):round(0.01),
MeshStandardMaterial({ color = Color():setHSL(i / 12, 0.5, 0.5) }), "post" .. i)
post.position:set(i * 0.5, 0.5, MathUtils.randFloatSpread(0.2))
end
```
## Motion
Write a pose as a formula of `Time` (seconds) and the `Expr` functions `sin`, `cos`, `sqrt`, `atan2`, `abs`, `min`, `max`, `mod` and `floor`, with `+ - * / ^`:
```luau
local angle = Time * 6.28
piston.position.y = 1.74 * Expr.cos(angle) + Expr.sqrt(32 - 3 * Expr.sin(angle) ^ 2)
crank.rotation.z = -angle
```
The formula is stored with the scene and runs on the device each frame; children follow their parent's motion.
## Lighting
```luau
Lighting({ background = "#0c0f12", environment = 1, sun = { color = "#fff1dc", intensity = 1.6, position = { 18, 30, 22 } } })
PostProcessing({ exposure = 0.9, toneMapping = "aces", bloom = { threshold = 1.05, intensity = 0.55 } })
```
A scene setup places a whole lighting composition as one asset. The V8Dyno scene places `studioLighting`, a studio backdrop, a warm key light and a sky light that lights the model from the backdrop:
```luau
asset.resolve("@builtin::systems.quickGeometry.studioLighting", "sceneSetup"):instantiate(nil, { name = "lighting" })
```
## Where it lives
Each build ends by spawning one entity named `model` with a `Generator` on the `ModelGraph` graph in this package. The tree is the Generator's `objects` and `channels` inputs, stored in `scene.json`; the shapes are made by the nodes of the `shape` nodebox and the modifiers by procgen's `geometry.*` nodes. Names that two parts share get a numeric suffix.
# debug (nodebox)
debug.dump summarizes any graph value into a record; debug.validate checks a Geometry's structure and reports every issue it finds.
# 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.
# geometry.recalculate_normals (procNode)
Every vertex's normal averaged, by area, over the faces meeting it. The node is `geometry.smooth_normals` with a
crease angle of 180 degrees and area weighting, so no vertex splits: a vertex shared by two faces is smooth across
them, and one already split between two copies stays a hard edge.
## Inputs
- `geometry` (`Geometry`): whose surface the normals are read off. Attributes and material carry to the result.
## Outputs
- `geometry`: the geometry with recomputed per-vertex normals.
# material (nodebox)
Materials as records: material.pbrMat is the standard metallic-roughness material made from its PBR maps (base colour, metallic-roughness, normal, occlusion, emissive) and their factors, and material.shader a material of any surface shader, holding every property and slot to what the shader declares. Each answers one element holding the record of the material kind (`records/material.procRecord`), which geometry.set_material, instances.set_material and the other inputs that take a material put on what draws; the output node shows it and the export node saves it as a `.material`.
# instances.cull (procNode)
Keeps the instances a test says to. An instance survives when the value it is judged by is strictly above
`threshold`; `invert` keeps the rest instead. The value is the `mask` field when it is wired, else the named point
`attribute` (`field.attribute`). `elements.keep` on the points carries every attribute onto the instances that stay, so
a culled set realizes as the whole one would have. With nothing to judge by, every instance stays, and inverted, none
does.
## Inputs
- `instances` (`Points`): the set to thin out, points carrying a Mesh.
- `mask` (`Field`): the value each instance is judged by. Wired, it outranks `attribute`.
- `threshold` (`Float`, default 0.5): an instance survives when its value reads strictly above this. Raising it thins
the set, lowering it fills it back in.
- `attribute` (`String`): a point attribute on the set to judge by, read while `mask` is unwired. A name the points do
not carry is refused.
- `invert` (`Bool`, default false): true keeps the complement, every instance the test dropped.
## Outputs
- `instances`: the surviving instances.
# points.box (procNode)
A 3D lattice of points filling a box centred on the origin. Each count is at least 1, and the extent the lattice spans
is the counts times `spacing` (`value.math`). `grid.box` lays out the cells, x fastest, then y, then z, on the device,
and each cell's centre is one point. `attribute.remove` takes the cell layout off the detail so the lattice reads as
Points, and each point carries its own number as `id`.
## Inputs
- `countX` (`Int`, default 3): how many points along X. The lattice holds countX x countY x countZ points and stays
centred on the origin on every axis. Below 1 reads as 1.
- `countY` (`Int`, default 3): how many points along Y, the layers the lattice is stacked in. 1 collapses it to a single
flat sheet at y = 0. Below 1 reads as 1.
- `countZ` (`Int`, default 3): how many points along Z. Below 1 reads as 1.
- `spacing` (`Float`, default 1.0): distance between neighbouring points, the same on all three axes. The lattice spans
(count - 1) x spacing per axis.
## Outputs
- `points`: the lattice, with `id` numbering each point.
# component (nodebox)
component.set gives every element of a class a component with the fields given.
# texture (nodebox)
Textures: images drawn on the device as Texture values, a width, a height and one colour per texel. texture.noise and texture.gradient draw from a formula, texture.from_shader from an author's compute shader and texture.from_raster from the layers of a raster. A material takes a Texture in a slot, and the output node shows one.
texture.cells is the part the first two are built from: one point per texel carrying its column and row.
# geometry
Nodes that move, join, cut, round, thicken and sample meshes. A graph transforms a geometry (`geometry.transform`, `geometry.set_position`, `geometry.merge`), welds and shades it (`geometry.weld`, `geometry.smooth_normals`), models it (`geometry.extrude`, `geometry.solidify`, `geometry.bevel`, `geometry.subdivide`, `geometry.decimate`), builds surfaces from outlines (`geometry.sweep`, `geometry.revolve`, `geometry.loft`, `geometry.ribbon`) and reads it into volumes (`geometry.voxelize`, `geometry.to_sdf`). Each is built from the core nodes and the kernels of the library.
## Nodes
- `geometry.transform`, `geometry.set_position`, `geometry.set_material`, `geometry.merge`, `geometry.triangulate`, `geometry.measure`: the basic edits and the measurement of a geometry. `geometry.merge` also joins pieces into a piece set for `instances.to_points`; a part that lacks an attribute another part carries takes the value an element without it has: an instance attribute's identity, else zero (its README says exactly how).
- `geometry.weld` (with `match = "position+normal"` it keeps hard edges), `geometry.smooth_normals`: merging points and shading normals.
- `geometry.extrude`, `geometry.solidify`, `geometry.bevel`, `geometry.subdivide`, `geometry.decimate`: modelling.
- `geometry.sweep`, `geometry.revolve`, `geometry.loft`, `geometry.ribbon`: surfaces from outlines and paths.
- `geometry.voxelize`, `geometry.to_sdf`: a mesh as cells and as a distance field.
- `geometry.boolean`: union, subtract or intersect of two closed meshes, over the `intersect` kernels.
- `geometry.delete`, `geometry.separate`: the triangles a mask field or primitive attribute selects, taken away or split into two geometries (`elements.keep` on the primitives); `geometry.recalculate_normals`: `geometry.smooth_normals` at 180 degrees, area-weighted.
- `geometry.selected`, `geometry.flip`, `geometry.profile`, `geometry.tangents`, `geometry.sides`, `geometry.shared`, `geometry.bvh`, `geometry.rings`, `geometry.first`: the parts the nodes above are built from, each usable on its own.
- `geometry.unit`, `geometry.perpendicular`, `geometry.rotate`, `geometry.transport`, `geometry.split`: vector arithmetic over sockets that the nodes which orient points and normals share.
- `geometry.offsets`, `geometry.kept`, `geometry.following`, `geometry.trim`, `geometry.blank`: column arithmetic the nodes above share (a prefix sum of counts, the places a mask keeps, a ring read one place on, the primitives of no area dropped, a one-word column to bind).
## Conventions
- Each node's folder name is its call name inside the box: `geometry.<folder>`.
- Inputs and outputs carry the names of the op each node replaces.
- A node that answers a Data table from numbers read back off the device holds the Luau for it in a `readings.module` inside its own folder.
- A node with one output answers that output's value; a node with several answers a record by output name.
- A fold's index runs from 1: the first pass is 1, so a pass that works on level, chunk or step `n` reads `index - 1` when it counts from 0 (`geometry.bvh`, `geometry.to_sdf`, `geometry.sweep`, `geometry.loft`).
- A field bound to a kernel takes the length of that dispatch, so a node writes a value out as a column (a gather with an explicit `count`) before it binds one whose length differs from the dispatch's.
# sdf (nodebox)
Signed distance field nodes: shapes, smooth combines, round and shell, space warps (transform, twist, bend, taper, elongate, mirror, repeat), displacement, grids and fields in and out, and sdf.mesh, which contours a shape into a closed mesh.
# points.grid (procNode)
A flat lattice of points in the XZ plane, centred on the origin. Each count is at least 1, and the extent the lattice
spans is the counts times `spacing` (`value.math`). `grid.box`, one cell thick at height `y`, lays out the cells, x
fastest, then z, on the device, and each cell's centre is one point. `attribute.remove` takes the cell layout off the
detail so the lattice reads as Points, and each point carries its own number as `id`.
## Inputs
- `countX` (`Int`, default 4): how many points along X. The grid holds countX x countZ points and stays centred on the
origin, so each one added widens it by `spacing`, half of that to either side. Below 1 reads as 1.
- `countZ` (`Int`, default 4): how many points along Z. A count of 1 leaves a single row running along X. Below 1 reads
as 1.
- `spacing` (`Float`, default 1.0): distance between neighbouring points, the same on both axes. The grid spans
(countX - 1) x spacing by (countZ - 1) x spacing.
- `y` (`Float`, default 0.0): the height the whole lattice sits at. Every point takes this as its y.
## Outputs
- `points`: the lattice, with `id` numbering each point.
# points.filter (procNode)
Keeps the points a test says to. The value each point is tested by is the `mask` field when it is wired, else the named
`attribute`'s values (`attribute.labels`). The test is a comparison (`field.compare`): above `threshold`, or, when
`equals` is given, equal to the index that value or label names. `elements.keep` on the points carries every attribute
and the detail onto the points that stay, counted on the device. Given neither a mask nor an attribute, the points come
back as they are.
## Inputs
- `points` (`Geometry`): the cloud to thin. Every point attribute and every detail value is carried onto the survivors,
so a colour or an index still belongs to the point it started on.
- `mask` (`Field`): the per-point value tested; a point stays when it is above `threshold`. Wired, it decides, and
`attribute` is read only when this is empty.
- `threshold` (`Float`, default 0.5): a point stays when its value is strictly above this. Raising it keeps fewer
points.
- `attribute` (`String`): a point attribute to test instead of wiring `mask`. A name the points do not carry is refused,
naming the ones they do.
- `equals` (`String | Float`): keeps the points whose `attribute` equals this instead of testing it against
`threshold`. It is a number, or a label: one of the texts a text attribute holds, or one of the names the points'
detail `labels` gives a numeric one (how one solver's particles are split back by the `stream` their source named).
## Outputs
- `points`: the points that stay.
# geometry.delete (procNode)
Deletes the triangles a test selects. A triangle is selected when its value is strictly above `threshold`. The value
each triangle is tested by is the `mask` field when it is wired, else the named primitive `attribute`
(`field.attribute`), else 0. `invert` deletes the triangles the test did not select. `elements.keep` on the primitives
does the removal: every point stays, and the triangles that remain keep their corners and attributes, counted on the
device.
## Inputs
- `geometry` (`Curves | Surface`): whose triangles are thinned. Point and detail attributes carry over as they are;
primitive and vertex attributes stay with the triangles that survive.
- `mask` (`Field`): read once per triangle for whether it goes. Wired, it is what the selection reads, and `attribute`
is read only when this is empty.
- `threshold` (`Float`, default 0.5): a triangle is selected when its value is strictly above this. Raising it deletes
less.
- `attribute` (`String`): a primitive attribute on the geometry to read the selection from, instead of a wired mask. A
name the triangles do not carry is refused.
- `invert` (`Bool`, default false): true deletes every triangle the test did not select, so a mask naming what to keep
cuts away the rest.
## Outputs
- `geometry`: the geometry with the selected triangles removed.
# shader (nodebox)
An author's own compute shaders as nodes. shader.compute runs a .computeShader over the elements of a geometry through the device.kernel op: each buffer binding is a column of the geometry, each param a knob of the node, and what the shader writes comes out as columns.
# scene (nodebox)
scene.query finds entity ids by name, component and hierarchy, scene.fetch brings entities in as points carrying their pose and components, scene.input is the entity the graph stands on, and scene.water is the water the scene holds.
# geometry.separate (procNode)
Splits a geometry's triangles in two by a test. The value each triangle is tested by is the `mask` field when it is
wired, else the named primitive `attribute` (`field.attribute`), else 0. Two comparisons against `threshold` follow
(`field.compare`): strictly above, and at or below. `elements.keep` on the primitives runs once for each, so `a` holds
the triangles above and `b` the rest. Both keep every point, and between them they hold every triangle once.
## Inputs
- `geometry` (`Curves | Surface`): whose triangles are divided. Point and detail attributes carry to both halves as they
are; primitive and vertex attributes stay with each half's own triangles.
- `mask` (`Field`): read once per triangle for which half it joins. Wired, it is what the split reads, and `attribute`
is read only when this is empty.
- `threshold` (`Float`, default 0.5): a triangle goes to `a` when its value is strictly above this, and to `b`
otherwise.
- `attribute` (`String`): a primitive attribute on the geometry to read the split from, instead of a wired mask. A name
the triangles do not carry is refused.
## Outputs
- `a`: the triangles whose value is strictly above `threshold`.
- `b`: the rest. A call answers both as a record by output name.
# sim (nodebox)
Simulation nodes: sim.spawn, sim.force, sim.collider, sim.scene_colliders, sim.particles and sim.shader, built on the runtime's g:state and g:step.
# mesh
The primitive solids and sheets a graph starts from: `mesh.box`, `mesh.sphere`, `mesh.cylinder`, `mesh.cone`, `mesh.capsule`, `mesh.octahedron`, `mesh.torus`, `mesh.rounded_box`, `mesh.plane` and `mesh.grid`. Each is made on the device from lattices and fans of the `make` kernel, with positions, normals and texture coordinates written as formulas over the lattice, and answers triangles centred on the origin that fill the box its parameters name.
## Conventions
- Each node's folder name is its call name inside the box: `mesh.<folder>`.
- Parameters keep the names and defaults of the op each node replaces.
- `mesh.lattice` makes the lattices and fans the presets share, `mesh.spherical` the point of a sphere and `mesh.cube_faces` the faces of a cube; a preset writes its positions, normals and texture coordinates as formulas over the lattice.
# io
The ways in and out of a graph: `import` brings an asset in as the value its type states, `luau` runs a function of a Luau module on the CPU, `output` shows a value in the world and answers a Handle, `export` saves a value as an asset, and `engine` calls the engine bridge that `import`, `export` and the core reading nodes use. `output` holds `show.module` and `engine` holds `engine.module`, the functions they call.
# entity (nodebox)
entity.transform and entity.bounds read one entity's pose and bounds as values, entity.points reads a set of entities as points, and entity.geometry reads the mesh an entity's Model draws as a Geometry.
# 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.