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

renderer

GPU-resource factory plus CPU codec/store wrappers — the GPU/CPU half of the asset↔resource split. Moves a resource Disk → CPU → GPU in explicit steps and returns inert handles describing each live resource. assetType behaviours, components, and every other module call `renderer.…

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

renderer

GPU-resource factory plus CPU codec/store wrappers — the GPU/CPU half of the asset↔resource split. Moves a resource Disk → CPU → GPU in explicit steps and returns inert handles describing each live resource. assetType behaviours, components, and every other module call renderer.*.

A resource moves through three states, each an explicit call:

  • ref:load() → renderer.<res>.loadCpu(ref) decodes the asset's primary content into the guid-keyed CPU store and returns a CPU handle (holds only a guid plus dims/counts and the read/encode/unload ops).
  • renderer.<res>.create(cpuHandle | rawData, guid?) uploads CPU → GPU, keyed by guid, and returns a GPU handle. create never takes an AssetRef — load the CPU first.
  • renderer.destroy(handle) frees the GPU resource; a CPU handle's :unload() frees the CPU copy.

A MeshHandle / TextureHandle / MaterialHandle is an inert data record ({ kind, category, guid, name, ... }) describing one live GPU resource. Every GPU op lives on renderer.* and takes the handle.

Anywhere a call names a resource it takes any of the forms you already hold — the handle create returned, the CPU handle loadCpu returned, the guid, or the AssetRef asset.resolve returned. Handles compose: what one call hands back, the next call accepts.

Types

  • Aabb — { min = {x,y,z}, max = {x,y,z} }.
  • MeshHandle / MeshCpuHandle / MeshGeometry / MeshBuffers.
  • TextureHandle / TextureCpuHandle / TexturePixels.
  • MaterialHandle / MaterialContent.

renderer.mesh

  • encode(geom) -> string? / decode(zmsh) -> (geom?, errmsg?) — the ZMSH CPU codec.
  • loadCpu(ref) -> MeshCpuHandle — Disk → CPU load (called by meshRef:load()).
  • create(src, guid?) -> MeshHandle — create or fetch a GPU mesh from a MeshCpuHandle, raw geometry {positions, indices, normals?, uvs?, colors?}, compute buffers {vertexBuffer, indexBuffer, vertexCount, indexCount, aabbMin?, aabbMax?}, or a MeshHandle.
  • geometry(mesh) -> MeshGeometry — the mesh's vertex data, the read that pairs with create.
  • update(handle, src) -> MeshHandle — overwrite the GPU resource in place under the same guid.
  • readback(mesh, into?) -> MeshCpuHandle: GPU → CPU recovery of a runtime mesh's geometry. into lands the copy under a CPU-store key of the caller's own, which stays resident until the caller unloads it, whatever re-registers or unloads the mesh itself.
  • isResident(mesh) -> boolean / isCpuResident(mesh) -> boolean.

Geometry moves in four directions, two per axis — DATA the caller holds, and the geometry of a mesh the ENGINE holds:

From→ bytes→ geometry
geometry (data the caller holds)encode(geom)—
ZMSH bytes (data the caller holds)—decode(zmsh)
a mesh the engine holdsencodeCpu(mesh)geometry(mesh)

geometry(mesh) reads the resident CPU copy when there is one and reads the geometry back off the GPU when there isn't (yielding a frame or two), so a mesh straight out of create answers it:

local h = renderer.mesh.create({ positions = P, indices = I, tangents = T })
local geom = renderer.mesh.geometry(h)   -- { positions, indices, tangents, ... }

An optional stream is present only when the mesh carries one. The GPU vertex layout has no "unset" — it holds a zeroed tangent, a zeroed skin binding, and a second UV set copied from the texture UVs for every mesh — so a stream saying only what its absence already says is reported absent. geom.tangents == nil is therefore the answer to whether a mesh has a tangent basis, and geom.uvs1 == nil to whether it has a second UV set.

renderer.texture

  • encode(rgba, width, height, opts) -> (string?, errmsg?) / encodeFromImage(bytes, opts) -> (string?, errmsg?) / decode(ztex) -> (rgba?, width?, height?) — the ZTEX CPU codec.
  • withSampler(ztex, { filter?, wrapU?, wrapV?, anisotropy? }) -> (string?, errmsg?) — the same payload with only its recorded sampler state changed; every level is byte-identical.
  • loadCpu(ref, encodeOpts?) -> TextureCpuHandle — Disk → CPU load with per-pixel access.
  • create(src, guid?) -> TextureHandle — from a TextureCpuHandle, raw pixels {rgba, width, height, srgb?}, a TextureHandle, or render-target dimensions {width, height, name?} (an empty GPU texture a render pass writes into).
  • update(handle, src) -> TextureHandle, destroy(handle), capture(handle) -> string (CPU readback result key), readback(texture) -> TextureCpuHandle, isResident(texture) -> boolean.

renderer.material

  • create(content, key) -> MaterialHandle — register or update a material's GPU record (content = { shader, properties, textures, aliases?, name? }) under its canonical registry key.
  • animatedTexture(texture, opts?) -> MaterialHandle — a material that PLAYS a layered texture: its layers bound as the frames, its timing beside them, the built-in animatedTexture shader turning the clock into the layer showing now. One call from an imported GIF / APNG / animated WebP to a material an entity can wear. guides { path: "topics/animated-images" } is the whole surface.
  • setProperty(key, name, value) — push one changed uniform.
  • setTexture(key, slot, ref) — push one changed texture slot (the texture must already be GPU-resident).
  • destroy(key) -> boolean — drop the definition filed under key, so describe and list stop answering for it. A surface already wearing the handle goes on drawing it.

A MaterialHandle and its guid are two different currencies. What a surface wears is the HANDLE — Model:applySessionMaterial(handle), or a Model's material field. The handle's guid is the material's registry key, which is what setProperty, setTexture, describe and destroy take. A component field resolves an asset, so a bare registry key in one leaves the component waiting for an asset to register under that name.

renderer.instanceData

Four vec4 lanes of generic shader data per entity — the channel that lets ONE material serve many entities that differ in a value, instead of one material per entity. A surface shader reads lane i back as input.shader_data[i], and the engine attaches no meaning to what a lane holds.

  • laneCount() -> number — lanes per entity, so a lane index runs 0 .. laneCount() - 1.
  • set(target, lane, x, y?, z?, w?) — write one lane of an entity's block. target is an entity proxy or an entity-id string naming a live entity; y / z / w default to 0. The lane reaches the block where the call is made, and the draw on the next frame.
  • clear(target) — drop the entity's whole block, so its draws read zero again. Takes an entity that has already gone, and does nothing for one holding no block.

A lane index outside the block, or a target no live entity answers to, is an error at the call rather than a write that lands nowhere. A feature picks the lane indices it owns and names them where it writes them: @builtin::systems.globalIllumination.lightmap holds lane 0 for a receiver's atlas rect and lane 1 for its layer and enable flag, which is the shape to copy.

The same lanes reach a GPU-driven population through renderer.mesh.drawInstanced's instanceDataBuffer, on slots no entity owns.

renderer.featureTexture

The texture analogue: a shared rgba16f 2D array every surface shader can sample as zero_feature_texture(uv, layer), and the array a SpotLight projects a layer of through its cone via cookieLayer.

  • configure(width, height, layers) — size the array. A call for the size it already has is left alone; one that changes the size reallocates, and the replacement is zeroed, so it empties every layer in the array — the layers other features and other cookies own along with your own.
  • setLayer(layer, textureKey, x, y) — copy a GPU-resident rgba16f texture into one layer at that offset, GPU to GPU with no readback. Several small images pack into one layer at different offsets.
  • state() -> { width, height, layers, filled, fills }: the extent the array carries and filled, the ascending 0-based indices of the layers a fill has landed in since it was last sized. One array is shared by every feature and every light cookie, and it has no allocator, so this is what a feature asks to tell whether the array it sized and filled is still the array it is writing into. A layer some other configure emptied leaves filled without it, which is what separates that from a fill that never landed. What it describes is the array a shader samples: the source texture a setLayer copied from is a GPU resource of its own and keeps the bytes it was written with, so filled is the reading that answers whether the layer behind a cookieLayer is live right now. fills counts the fills that have landed in each layer since the array was last sized, fills[layer + 1] for a 0-based layer: a fill of a layer already holding content leaves filled as it was and moves this count, so a feature re-filling its own layer reads its fill arriving here. Measured at the end of the last rendered frame, like every reader below.
renderer.featureTexture.configure(256, 256, 4)
renderer.featureTexture.setLayer(0, "my_gobo", 0, 0)
-- ... elsewhere in the scene, another feature sizes the array ...
local ft = renderer.featureTexture.state()
if ft.width ~= 256 or table.find(ft.filled, 0) == nil then
    -- layer 0 was emptied under us: size it back and re-fill.
end

Reading back what the renderer did

Every call above states an intention. What the renderer made of it is a separate document, published once per frame and read through these:

  • drawDiagnostics() -> { DrawDiagnostic } — every renderable that is NOT drawing what its material says. A surface rendering as the magenta placeholder, one the renderer could bind nothing for, and one drawing a program whose most recent compile failed all land here, each naming the entity, the program asked for, the program bound, and the one cause. It covers every renderable the renderer holds, whether or not a camera reached it — a row with observed = false and outcome = "notDrawn" is the renderer's own resolution for one this frame drew nowhere, so a broken surface off-screen reads the same as one in frame. An empty result means every renderable the renderer holds is drawing the program its material named. Start here when a surface looks wrong.
  • material.renderState(key) -> MaterialObservation? — the blend / cull / topology / queue / depth key the renderer holds a material under, and whether a pipeline exists for it. nil means the renderer holds no material under that key, which is what writes reaching nothing on screen look like. index is the material index its row is filed under, and textures the texture key each slot of that row names, so a setTexture the renderer has taken up reads there.
  • materialCost() -> { MaterialObservation } — draws, instances, placeholder draws and material-owned bind groups (binds set, bindsElided skipped) per material, over the published frame.
  • shaderCost() -> { ShaderCost } — pipeline build time and permutation count per program, summed since engine start, beside the compile gate's word.
  • observe() -> RenderObservation — the whole document the four above read. /zero/runtime/generated_materials serves the same document as files.

renderer.destroy

  • destroy(handle) -> boolean — free the GPU resource behind a MeshHandle / TextureHandle, routing by the handle's category.

Parts

The module is a folder of parts, each a module of its own that init.luau requires:

  • renderer.refs: guid minting and the coercion from whatever names a material, mesh or texture to the key the renderer indexes it by.
  • renderer.sources: the src shapes renderer.mesh.create / update and renderer.texture.create / update take, and the bounds and counts raw geometry implies.
  • renderer.shading: the readings renderer.shadingOf builds out of the document the renderer publishes.

Usage

local renderer = require("@builtin::modules.api.engine.renderer")
local gpu = renderer.mesh.create({ positions = { ... }, indices = { ... } })
renderer.destroy(gpu)

Interface

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

conforms to

zero/source-extract/v2

global renderer global-types module renderer GPU-resource factory + CPU codec/store wrappers — the GPU/CPU half of the asset↔resource split. This module (under `modules/api/`) is the SOLE caller of the internal `__mesh` / `__meshcpu` / `__meshgpu` / `__splat` / `__texture` / `__texturecpu` / `__texturegpu` FFI; assetType behaviours, components, and every other module call `renderer.*`, never the `__` internals. require modules/api/engine/renderer

makeGuid( ) → string

Minted from OS entropy: resource identity must be unique across every VM and every rebuild, and the `math.random` stream cannot provide that — content reseeds it (`math.randomseed`) for deterministic procgen, which replays the stream and hands two resources the same guid.

validateGuid(guid: string, what: string) → string

`guid` names the ASSET IDENTITY a runtime resource is filed under, so a material's texture slot and a saved scene resolve to the same resource across a reload. It is optional on every call that takes it — one is minted when the caller has no identity to preserve — so the message says both what the value has to be and that it can be left out.

argtypedescription
guidstring
whatstring

refField(t: any, name: string) → string

Read one string field off a ref-like table. Plain tables answer to `rawget`; a proxy that serves its fields through `__index` answers to the indexed read, and a proxy that raises on an unknown key is contained by the pcall.

argtypedescription
tany
namestring

materialKey(value: string | { [string]: any } | AssetRef, what: string) → string

One coercion from "whatever identifies a material" to the registry key the renderer indexes by, so a call that takes a key accepts the values a caller already holds: the key itself, the `MaterialHandle` `renderer.material.create` returns, or the `AssetRef` `asset.resolve` returns. `what` names the call in the error, which states the accepted forms rather than the parameter's type.

argtypedescription
valuestring | { [string]: any } | AssetRef
whatstring

resourceGuid(value: any) → void

One coercion from "whatever names a resource" to the guid its CPU and GPU stores are keyed by, so a call that names a resource accepts the values a caller already holds: the guid, the GPU handle `create` returned, the CPU handle `loadCpu` returned, or the `AssetRef` `asset.resolve` returned. The rejection is returned rather than raised so the per-resource wrappers below raise it at their own caller's line.

argtypedescription
valueany

primaryBytes(ref: any) → string

An asset's primary content bytes, waiting for them when they are still on their way. A resource's bytes are content-addressed, and the two reads answer at different moments: the plain read answers from what this engine already holds, the awaiting read answers once the content arrives. Asking in that order is what lets a first load finish on every target. An engine that fetches its content over the network — the browser build — holds nothing the first time it meets a resource, so the plain read alone leaves the asset off the GPU for the rest of the session, and its entity draws nothing. The awaiting read yields, so it runs under a coroutine (a component's `awake`, a task). Asked from a frame where yielding is unavailable, the plain read's answer stands.

argtypedescription
refany

textureRefOf(value: any, what: string) → any

One coercion from "whatever names a texture ASSET" to the ref its content is read through, for the calls that need the payload rather than the guid the GPU keys it by. A ref is taken as it stands; a string is resolved the way `asset.ref` resolves one (guid, identity, name, source path).

argtypedescription
valueany
whatstring

meshKey(mesh: any, what: string) → string

argtypedescription
meshany
whatstring

textureKey(texture: any, what: string) → string

argtypedescription
textureany
whatstring

boundsFromPositions(positions: { number }) → Aabb

Compute a local-space AABB straight from a flat positions array (the geometry path — bounds are free at creation since we already have the verts).

argtypedescription
positions{ number }

cpuBoundsOfGuid(guid: string) → Aabb

Read a mesh's local-space AABB from the guid-keyed CPU store — the bounds computed ONCE when the CPU mesh was decoded/loaded (`renderer.mesh.loadCpu`), carried onto the handle. This is the cheap, correct source: bounds are CPU geometry metadata, never a GPU readback. Returns ZERO_AABB when no CPU mesh is resident under the guid (e.g. a compute-buffer mesh that supplies its own aabbMin/aabbMax) so bounds stay optional metadata, not a hard requirement.

argtypedescription
guidstring

vecToAabb(aabbMin: any, aabbMax: any) → Aabb

argtypedescription
aabbMinany
aabbMaxany

wrapMeshHandle(guid: string, name: string, bounds: Aabb) → MeshHandle

argtypedescription
guidstring
namestring
boundsAabb

configure(width: number, height: number, layers: number) → void

Size the shared feature-texture array — the layers a surface shader reads through `zero_feature_texture(uv, layer)`, and the layers a `SpotLight` projects through its cone via `cookieLayer`. Layers are `rgba16f`. Resizing zeroes every layer, so a feature that owns one re-fills it after.

argtypedescription
widthnumberLayer width in pixels.
heightnumberLayer height in pixels.
layersnumberHow many layers the array holds.

examples

renderer.featureTexture.configure(512, 512, 4)

setLayer(layer: number, textureKey: string, x: number, y: number) → void

Copy a texture already on the GPU into one layer of the shared array, its top-left corner at `(x, y)` — GPU to GPU, with no readback. Several small images pack into one layer by calling this once per image at different offsets. The source must be `rgba16f` and fit at that offset. with `compute.createStorageTexture2D(name, opts)`.

argtypedescription
layernumberWhich layer of the array to write into.
textureKeystringThe source texture's name — the one it was created under, as
xnumberLeft edge of the destination rectangle, in pixels.
ynumberTop edge of the destination rectangle, in pixels.

examples

compute.createStorageTexture2D("gobo", { width = 256, height = 256, format = "rgba16f" })
renderer.featureTexture.setLayer(0, "gobo", 0, 0)

encode(geom: MeshGeometry) →

Encode raw geometry into engine-native `ZMSH` bytes (the on-disk mesh payload). The CPU codec behind the mesh assetType's `onCreate`. Every stream the format carries — including tangents, per-vertex skinning, and the skeleton — round-trips back through `renderer.mesh.decode`. This pair moves DATA the caller is holding; the geometry of a mesh the ENGINE is holding comes from `renderer.mesh.geometry(mesh)`. (nil, errmsg) naming what the geometry could not describe.

argtypedescription
geomMeshGeometry`MeshGeometry` — flat per-vertex float / u32 arrays plus optional `skinning` and `skins`.

examples

local bytes = renderer.mesh.encode({ positions = {...}, indices = {...} })
local bytes = renderer.mesh.encode(renderer.mesh.geometry(meshHandle))

decode(zmsh: buffer | string) →

Decode engine-native `ZMSH` bytes back into a `MeshGeometry`. Inverse of `renderer.mesh.encode`; each optional stream is present only when the blob carries it. Takes the bytes themselves — the geometry of a mesh the engine is holding comes from `renderer.mesh.geometry(mesh)`.

argtypedescription
zmshbuffer | stringEngine-native ZMSH bytes (binary-safe).

examples

local geom = renderer.mesh.decode(meshRef:getBytes())

isResident(mesh: string | { [string]: any } | AssetRef) → boolean

True if a GPU mesh is resident under this mesh's guid.

argtypedescription
meshstring | { [string]: any } | AssetRefThe mesh — a `MeshHandle`, a `MeshCpuHandle`, a guid, or a mesh `AssetRef`.

examples

print(renderer.mesh.isResident(handle))

boundsSource(mesh: string | { [string]: any } | AssetRef) → string

Where this mesh's culling bounds come from. `"compute"` once a compute pass has written its vertices: the engine reduces those vertices to an AABB every frame, so the mesh is culled against the geometry the pass produced wherever it puts it. `"geometry"` otherwise: the AABB of the geometry the mesh was created with.

argtypedescription
meshstring | { [string]: any } | AssetRefThe mesh — a `MeshHandle`, a `MeshCpuHandle`, a guid, or a mesh `AssetRef`.

examples

print(renderer.mesh.boundsSource(mesh))

canBuildClusters( ) → boolean

Whether this engine bakes cluster-LOD hierarchies. It reads the binding the running engine registered: every target the engine ships on carries the builder, so a mesh loaded in a browser bakes its own clusters the same way one loaded natively does, and an engine built without it reports false and answers nil from `renderer.mesh.buildClusters`.

examples

if renderer.mesh.canBuildClusters() then ... end

buildClusters(mesh: string | { [string]: any } | AssetRef) → string

Build a cluster-LOD DAG (Nanite-style virtualized geometry) for the static CPU mesh held under `guid` and return its serialized `data.clusters` bytes. Returns nil when the mesh is degenerate, and on an engine whose `renderer.mesh.canBuildClusters` reports false. Pair with `renderer.mesh.uploadClusters`. `MeshCpuHandle`, a `MeshHandle`, a guid, or a mesh `AssetRef`.

argtypedescription
meshstring | { [string]: any } | AssetRefA mesh loaded into the CPU store (`renderer.mesh.loadCpu`) — the

examples

local cb = renderer.mesh.buildClusters(cpu)

uploadClusters(mesh: string | { [string]: any } | AssetRef, clusters: string) → boolean

Attach a cluster-LOD DAG (bytes from `renderer.mesh.buildClusters`) to the GPU mesh keyed by `guid`, enabling the continuous-cut cluster draw path for that mesh.

argtypedescription
meshstring | { [string]: any } | AssetRefThe mesh the clusters belong to — a `MeshHandle`, a `MeshCpuHandle`, a guid, or a mesh `AssetRef`.
clustersstringSerialized cluster bytes (binary-safe).

examples

renderer.mesh.uploadClusters(gpu, cb)

clusterComponents(clusterBytes: buffer | string) →

Split a cluster blob (from `renderer.mesh.buildClusters`) into its GPU-ready component byte pools — the cluster vertex pool, the geometry-addressing pool (every cluster's local→global vertex map, then every cluster's triangle bytes), and the per-cluster record array — plus their counts. A cluster's triangles address positions inside its own vertex map one byte at a time, and a record's `vertexOffset` indexes the geometry pool in `u32` elements while its `indexOffset` indexes it in bytes, so ONE binding resolves a corner. A pure decode (no GPU work): upload the pools into buffers a compute shader owns (`shaderRef:createBuffer` + `buf:writeBytes`) to drive a cluster draw from Luau.

argtypedescription
clusterBytesbuffer | stringSerialized cluster bytes (binary-safe).

examples

local c = renderer.mesh.clusterComponents(cb)

encodeCpu(mesh: string | { [string]: any } | AssetRef) → string

Encode a mesh's resident CPU copy into `ZMSH` bytes. Reads the ONE guid-keyed CPU store — `meshRef:load()` populates it for assets, and `renderer.mesh.readback(mesh)` populates it for a runtime mesh. Errors loudly when the mesh has no resident CPU copy.

argtypedescription
meshstring | { [string]: any } | AssetRefThe mesh — a `MeshHandle`, a `MeshCpuHandle`, a guid, or a mesh `AssetRef`.

examples

local bytes = renderer.mesh.encodeCpu(handle)

isCpuResident(mesh: string | { [string]: any } | AssetRef) → boolean

True if this mesh has a resident CPU copy in the guid-keyed CPU store.

argtypedescription
meshstring | { [string]: any } | AssetRefThe mesh — a `MeshHandle`, a `MeshCpuHandle`, a guid, or a mesh `AssetRef`.

examples

if renderer.mesh.isCpuResident(handle) then ... end

getVertices(mesh: string | { [string]: any } | AssetRef) →

Read the vertices of a mesh's resident CPU copy — one entry per vertex, `{ pos = {x,y,z}, normal = {x,y,z}, uv = {u,v} }`. Reads the resident CPU store directly (no re-decode). Errors when the mesh has no resident CPU copy — `renderer.mesh.geometry(mesh)` is the read that works wherever the mesh lives, and returns the tangent, colour and skinning streams too. Each record carries `pos`, `normal`, `uv` and `uv1` as named channels (`{ x = , y = , z = }`). Geometry going the other way — into `renderer.mesh.create` — is parallel flat arrays (`positions`, `normals`, `uvs`), and `create` accepts this record list under `vertices` so a mesh read back here can go straight into a new one.

argtypedescription
meshstring | { [string]: any } | AssetRefThe mesh — a `MeshHandle`, a `MeshCpuHandle`, a guid, or a mesh `AssetRef`.

setVertices(mesh: string | { [string]: any } | AssetRef, positions: { number }) → void

Replace a mesh's resident CPU vertex positions (flat `{ x,y,z, ... }`) IN PLACE — indices, normals/uvs, and skinning are preserved, the AABB recomputes, and the GPU re-fetches the new geometry so it shows on screen. The mesh must be CPU-resident (load it, or retain it with keepCpu). Errors with the reason otherwise, or when the vertex count doesn't match.

argtypedescription
meshstring | { [string]: any } | AssetRefThe mesh — a `MeshHandle`, a `MeshCpuHandle`, a guid, or a mesh `AssetRef`.
positions{ number }Flat `{ x,y,z, ... }` — one xyz per vertex; count must match the mesh.

unloadCpu(mesh: string | { [string]: any } | AssetRef) → void

Drop a mesh's resident CPU copy from the guid-keyed CPU store. The explicit release for a runtime geometry mesh's recoverable definition.

argtypedescription
meshstring | { [string]: any } | AssetRefThe mesh — a `MeshHandle`, a `MeshCpuHandle`, a guid, or a mesh `AssetRef`.

wrapMeshCpuHandle(guid: string, vertexCount: number, indexCount: number) → MeshCpuHandle

Build a `MeshCpuHandle` over the guid-keyed CPU store: read (triangles / vertices / bounds) + encode + unload, each reading the Rust-side store. Shared by `loadCpu` (Disk→CPU) and `readback` (GPU→CPU) — both populate the store under `guid`, then hand out this handle.

argtypedescription
guidstring
vertexCountnumber
indexCountnumber

cpuRead(op: string, value: any) → any

Every read goes through the guid-keyed CPU store. A read after the store entry was dropped (`handle:unload()`, or the default drop-after-GPU-upload lifecycle) errors with the remedy instead of returning nil into arithmetic three frames later.

argtypedescription
opstring
valueany

getTriangles(_self: ?) → void

argtypedescription
_self?

getVertices(_self: ?) → void

argtypedescription
_self?

getBounds(_self: ?) → void

argtypedescription
_self?

geometry(_self: ?) → MeshGeometry

argtypedescription
_self?

encode(_self: ?) → string

argtypedescription
_self?

unload(_self: ?) → void

argtypedescription
_self?

loadCpu(ref: string | AssetRef) → MeshCpuHandle

Load a `.mesh` asset's geometry into the ONE guid-keyed CPU store (the Disk→CPU step) and return a CPU handle. The handle holds NO geometry — only the guid plus counts and the per-handle read/encode/unload ops (which read the Rust-side store). Called by `meshRef:load()`. DEFAULT lifecycle: upload to the GPU then `handle:unload()`; the store is populated only by this call. or any string `asset.ref` resolves to one — the guid `encodeCpu` takes, an identity, a name or a source path.

argtypedescription
refstring | AssetRefA mesh `AssetRef` (carries `.guid` and reads its primary via getBytes),

examples

local cpu = meshRef:load(); local gpu = renderer.mesh.create(cpu); cpu:unload()
local cpu = renderer.mesh.loadCpu(gpuMesh.guid)

destroy(handle: MeshHandle) → boolean

Release the GPU mesh behind `handle`, the release that pairs with `renderer.mesh.create`. Routes through `renderer.destroy`, the verb that releases any renderer handle by its category. The CPU copy, if one was loaded, is freed separately by the CPU handle's `:unload()`.

argtypedescription
handleMeshHandleThe `MeshHandle` to release.

examples

local m = renderer.mesh.create(cpu); renderer.mesh.destroy(m)

readback(mesh: string | { [string]: any } | AssetRef) → MeshCpuHandle

Read a runtime GPU mesh's geometry back to CPU and return a `MeshCpuHandle` for it — the GPU→CPU half of the runtime-mesh freeze path. A mesh made with `renderer.mesh.create` keeps no CPU copy, so persisting it (`:encode()` → `asset.create("mesh", …)`) reads it back here first. Yields until the readback completes (a frame or two). After it returns the geometry is resident in the guid-keyed CPU store: `:getTriangles`, `:getVertices`, `:getBounds`, `:geometry`, `:encode`, `:unload` all work. Errors if the mesh never becomes resident in the vertex pool.

argtypedescription
meshstring | { [string]: any } | AssetRefThe mesh — the `MeshHandle` `renderer.mesh.create` returned, a guid, or a mesh `AssetRef`.

examples

local cpu = renderer.mesh.readback(handle); local zmsh = cpu:encode(); cpu:unload()

geometry(mesh: string | { [string]: any } | AssetRef) → MeshGeometry

The complete geometry of a mesh the engine is holding, as a `MeshGeometry` — the same shape `renderer.mesh.create` and `renderer.mesh.encode` take, carrying every stream the mesh has (`positions`, `indices`, and whichever of `normals`, `uvs`, `colors`, `uvs1`, `tangents`, `skinning`, `skins` it was built with). The read that pairs with `create`: hand it the `MeshHandle` `create` returned and get the vertex data back. Reads the resident CPU copy when there is one; for a runtime mesh that lives only on the GPU it reads the geometry back off the GPU first (yielding a frame or two) and leaves CPU residency as it found it. An optional stream is present only when the mesh carries one, so `tangents == nil` is the answer to whether a mesh has a tangent basis, and `uvs1 == nil` to whether it has a second UV set.

argtypedescription
meshstring | { [string]: any } | AssetRefThe mesh — a `MeshHandle`, a `MeshCpuHandle`, a guid, or a mesh `AssetRef`.

examples

local geom = renderer.mesh.geometry(renderer.mesh.create({ positions = P, indices = I }))
local tangents = renderer.mesh.geometry(handle).tangents

vecOf(v: any, n: number) → void

argtypedescription
vany
nnumber

vertexRecordsToArrays(src: any) → any

Geometry input is parallel flat arrays (`positions`, `normals`, `uvs`); `getVertices` answers with one record per vertex (`pos`, `normal`, `uv`, `uv1`). Accepting the record form under `vertices` is what lets geometry read back out of a mesh and go straight into another one without the caller transposing it by hand. A src that already carries `positions` is left alone.

argtypedescription
srcany

take(rec: any, key: string, alt: string?, n: number, into: { number }, index: number) → void

argtypedescription
recany
keystring
altstring?
nnumber
into{ number }
indexnumber

indexRangeFault(positions: { any }, indices: { any }) → string

The fault in an index list that addresses a vertex the position stream does not carry, or nil when every index lands inside it. Indices are 0-based and name a vertex, and `positions` holds three floats per vertex, so the stream describes `#positions // 3` addressable vertices. Every consumer of a runtime mesh reads the stream at those addresses — the GPU draw, the CPU triangle soup, the ray-tracing hit attributes — so the range is settled here, where the geometry enters, and the message names the entry that broke it.

argtypedescription
positions{ any }
indices{ any }

classifyMesh(src: any) → string

argtypedescription
srcany

recordMeshFacts(guid: string, vertexCount: number?, indexCount: number?) → void

argtypedescription
guidstring
vertexCountnumber?
indexCountnumber?

geometryCounts(src: any) → void

Counts implied by raw geometry: three components per position, one index each.

argtypedescription
srcany

listRuntimeResources(kind: string, enrich: ((string, { [string]: any }) → void

Every runtime resource of one kind, from the registry each create path stamps. `enrich` adds the per-kind facts to an entry.

argtypedescription
kindstring
enrich((string, { [string]: any }

create(src: any, guid: string?) → MeshHandle

Create (or fetch) a GPU mesh resource and return its `MeshHandle`. `src`: a `MeshCpuHandle` from `meshRef:load()` (CPU→GPU upload under the asset's guid, idempotent — returns the resident handle if already uploaded); raw geometry `{positions, indices, normals?, uvs?, colors?, uvs1?, unwrapUvs?, tangents?, skinning?, skins?}` (a new runtime mesh — `uvs1` is the lightmap UV set, `unwrapUvs` generates one, `skinning`/`skins` bind a skeleton); GPU compute buffers `{vertexBuffer, indexBuffer, vertexCount, indexCount, aabbMin?, aabbMax?, prevVertexBuffer?}` (size the vertex buffer at `vertexCount * engine.vertexStride` bytes, the engine's standard Vertex layout); or a `MeshHandle` (returned as-is). NEVER takes an AssetRef — load the CPU first. `prevVertexBuffer` is a second buffer of the same size and layout holding those vertices as they stood on the previous frame. Naming it is what makes geometry a compute pass moves report a motion vector: the surface differences the two streams, so every consumer of screen-space velocity — motion blur, temporal reprojection — sees the movement. The engine fills it from the current vertices once per frame, ahead of that frame's compute dispatches, so a frame in which the pass does not run leaves the two streams equal and the geometry reports standing still. `morphTargets` are the shapes the mesh can blend towards: a list of `{ positions, normals? }` records, each holding one offset per vertex from the base geometry, in the mesh's own vertex order. An entity blends them with `ecs.MorphWeights`, weight `i` scaling target `i`. absent). Ignored for the CPU-handle path (the asset's guid is used).

argtypedescription
srcanyA MeshCpuHandle, geometry, compute buffers, or a MeshHandle.
guidstring?Optional v4 guid for a NEW runtime mesh (minted Luau-side when

examples

local gpu = renderer.mesh.create(meshRef:load())
local gpu = renderer.mesh.create({ positions = {...}, indices = {...} })
-- a runtime mesh carrying a lightmap UV set (unwrapped at creation)
local gpu = renderer.mesh.create({ positions = {...}, indices = {...}, unwrapUvs = true })
-- a mesh with one shape to blend towards, driven by ecs.MorphWeights
local gpu = renderer.mesh.create({ positions = P, indices = I, morphTargets = { { positions = D } } })

list( ) →

Every mesh currently registered, ordered by guid — the ones a script created and the ones that reached the device through an asset alike. Answers "which mesh is this?" when all that is known is a size: each entry carries the guid, the vertex/index counts it was created with, where it came from (`origin` is `"asset"` for a mesh the asset path uploaded), whether the GPU still holds it, and where its culling bounds come from (`boundsFrom` is `"compute"` for a mesh a compute pass writes). A resident entry also carries the bytes its buffers cost. `bytes` is the mesh's whole VRAM footprint and is the sum of the THREE buffer columns beside it — `vertexBytes + vertexStorageBytes + indexBytes`, where the storage column is the same vertices bound as a storage buffer for the passes that read them that way. Summing only the vertex and index columns understates a mesh by its vertex size. The `bytes` column is what sums to the `meshes` category of `renderer.gpuMemory()`. boundsFrom, bytes?, vertexBytes?, vertexStorageBytes?, indexBytes?, primitives?, revision? }`.

examples

for _, m in ipairs(renderer.mesh.list()) do print(m.guid, m.bytes) end

update(handle: MeshHandle, src: any) → MeshHandle

Overwrite the GPU resource behind `handle` IN PLACE, under the same guid, from new geometry or compute buffers. Never writes a `.mesh` file — the play-mode mutate path. A Model bound to `handle.guid` reflects the change with no re-bind. Returns the same handle with refreshed bounds. `{vertexBuffer, indexBuffer, vertexCount, indexCount, prevVertexBuffer?}`.

argtypedescription
handleMeshHandleThe `MeshHandle` to update.
srcanyNew geometry `{positions, indices, ...}` or compute buffers

drawHandleId(draw: any, what: string) → number

argtypedescription
drawany
whatstring

drawInstanced(handle: MeshHandle, opts: any) → InstancedDraw

Draw one mesh `instanceCount` times in a single call, each copy placed by a world matrix read from a GPU buffer. The population is a renderable in its own right — it goes through the mesh's ordinary pipeline and the material's ordinary bind groups, so it appears in the deferred pass, the forward passes and the shadow maps exactly as an entity-backed draw of that mesh does. The buffer holds `instanceCount` **column-major** 4x4 matrices, 64 bytes each, tightly packed — the layout a vertex shader reads as `array<mat4x4<f32>>`, which puts each matrix's translation in its LAST four floats (Lua indices 13/14/15 for x/y/z). Packing row-major transposes every instance. The matrices are COPIED into the engine's transform slots once per frame, which is what buys that full-pass parity. Rewrite the buffer between frames and the instances move — no re-registration, no re-upload. `material` is what the population draws with, and it is required: a `MaterialHandle` (`matRef:handle()`), an `AssetRef`, or a registry key. `instanceDataBuffer` names a second buffer, holding 64 bytes per instance — four `vec4` lanes, tightly packed, in instance order. Those lanes arrive in the fragment stage as `zero_object_data(in.instance_id, lane)`, the same read a per-entity `__instancedata` block answers, so the members of one population can differ in whatever their material's shader agrees the lanes carry. Copied every frame like the transforms, from a buffer a compute pass writes: the values never touch the CPU. Omit it and the lanes read zero. `reserveCount` sizes the reservation above `instanceCount` so `renderer.mesh.setInstanceCount` can raise the drawn count later without re-registering; both buffers must back the reservation, not just the count.

argtypedescription
handleMeshHandleA `MeshHandle` whose mesh is GPU-resident.
optsany`{ transformBuffer, instanceCount, material, instanceDataBuffer?, reserveCount?, renderLayer?, castsShadows? }`.

examples

local m = renderer.mesh.create({ positions = ..., indices = ... })
local buf = substrate.createBuffer({
name = "crowd.xf", type = "mat4", len = 64, kind = "gpu",
})
-- Column-major: translation lives at indices 13/14/15.
local xf = {}
for i = 0, 63 do
local m4 = { 1,0,0,0, 0,1,0,0, 0,0,1,0, i * 2, 0, 0, 1 }
for _, v in ipairs(m4) do xf[#xf + 1] = v end
end
buf:write(xf)
local rock = asset.resolve("rock", "material"):handle()
local draw = renderer.mesh.drawInstanced(m, { transformBuffer = "crowd.xf", instanceCount = 64, material = rock })

setInstanceCount(draw: InstancedDraw, count: number) → InstancedDraw

Change how many of a registration's instances draw. Constant time — the reservation, the transform buffer and the pipeline all stay put, so this is the verb for a population whose size changes per frame. The new count must fit the reservation `drawInstanced` was given.

argtypedescription
drawInstancedDrawThe `InstancedDraw` to reconfigure.
countnumberInstances to draw, at least 1 and within the reservation.

examples

renderer.mesh.setInstanceCount(draw, visibleCount)

instanceInfo(draw: InstancedDraw) → InstancedDrawInfo

What a live instanced-draw registration is drawing: which mesh, which transform buffer, which per-instance data buffer if it named one, how many instances, and how many slots it reserved. Returns nil once the registration has been dropped.

argtypedescription
drawInstancedDrawThe `InstancedDraw` to report on.

examples

print(renderer.mesh.instanceInfo(draw).instanceCount)

dropInstanced(draw: InstancedDraw) → boolean

Release an instanced-draw registration and the transform slots it reserved. The mesh and the transform buffer outlive it — destroy those through `renderer.destroy` and the buffer handle's `:destroy()`.

argtypedescription
drawInstancedDrawThe `InstancedDraw` to release.

examples

renderer.mesh.dropInstanced(draw)

components(bytes: any, convention: string?) →

Decode a Gaussian splat capture — a Niantic `.spz` (gzipped or raw) or a 3DGS `.ply` — into the GPU-ready byte pools a render feature uploads. `records` is the packed splat array at `recordBytes` per splat (position, log scale, quaternion, DC colour + opacity); `sh` is the quantized higher-order spherical-harmonics pool at `shStrideWords` u32 words per splat, empty at degree 0. A pure decode (no GPU work): upload the pools with `shaderRef:createBuffer` + `buf:writeBytes` and draw them with a `kind = "splat"`, `channel = "gaussian"` pass. COLMAP-trained captures use) or `"engineNative"` for a capture already in engine space.

argtypedescription
bytesanyCapture bytes — `.spz` or `.ply`, as a `buffer` or a binary string.
conventionstring?Source axis convention: `"rightDownFront"` (the default, what

examples

local c = renderer.splat.components(vfs.readBytes("captures/ceramic.spz"))

wrapTexHandle(guid: string, name: string, width: number, height: number) → TextureHandle

argtypedescription
guidstring
namestring
widthnumber
heightnumber

cpuRead(op: string, value: any) → any

Every read goes through the guid-keyed CPU store. A read after the store entry was dropped (`handle:unload()`, or the default drop-after-GPU-upload lifecycle) errors with the remedy instead of returning nil into arithmetic three frames later.

argtypedescription
opstring
valueany

readPixel(_self: ?, x: number, y: number) → void

argtypedescription
_self?
xnumber
ynumber

writePixel(_self: ?, x: number, y: number, r: number, g: number, b: number, a: number?) → void

argtypedescription
_self?
xnumber
ynumber
rnumber
gnumber
bnumber
anumber?

rgba(_self: ?) → string

argtypedescription
_self?

blit(_self: ?, src: any, x: number, y: number, w: number, h: number, filter: string?) → boolean

argtypedescription
_self?
srcany
xnumber
ynumber
wnumber
hnumber
filterstring?

getInfo(_self: ?) → void

argtypedescription
_self?

encode(_self: ?) → string

argtypedescription
_self?

encodePng(_self: ?) → string

argtypedescription
_self?

encodeJpeg(_self: ?, quality: number?) → string

argtypedescription
_self?
qualitynumber?

unload(_self: ?) → void

argtypedescription
_self?

encode(rgba: any, width: number, height: number, opts: any) →

Encode raw pixels into an engine-native `ZTEX` payload (the on-disk texture content). The CPU codec behind the texture assetType's `onCreate`. `opts.format` selects the on-disk precision: `"rgba8"` / `"srgb"` (default, 8 bits/channel, `rgba` is width*height*4 bytes) or the high-precision data formats `"rgba16"` (16-bit unsigned normalized, width*height*8 bytes) / `"rgba32f"` (32-bit float, width*height*16 bytes) — for height/displacement fields, baked lightmaps, and other data rasters an 8-bit format quantizes visibly. The two high-precision formats store `rgba` verbatim and reject `opts.generateMipmaps` / `opts.maxDimension`.

argtypedescription
rgbaanyPixel payload at `opts.format`'s native byte width — a `buffer`, a binary string, or a number array.
widthnumbernumber
heightnumbernumber
optsany`{ format?, srgb?, generateMipmaps?, maxDimension? }`

encodeFromImage(bytes: buffer | string, opts: any) →

Encode source image bytes (png/jpg/webp/…) into an engine-native `ZTEX` payload. Used by the texture importer / assetType `onChange`.

argtypedescription
bytesbuffer | stringsource image bytes.
optsany`{ format?, srgb?, generateMipmaps?, maxDimension? }`

decode(ztex: buffer | string) →

Decode an engine-native `ZTEX` payload to its pixel buffer, at the texel format the payload was written in. The fourth return names that format — `"rgba8"` (4 bytes/texel, channels 0-255), `"rgba16"` (8 bytes/texel, 16-bit unsigned normalized channels 0-65535) or `"rgba32f"` (16 bytes/texel, float channels) — so a height field read back here keeps every bit it was authored with. An encoded-image payload (png/jpg/webp stored verbatim) decodes to `"rgba8"`.

argtypedescription
ztexbuffer | stringZTEX bytes.

info(ztex: buffer | string) →

Read the header of an engine-native `ZTEX` payload without copying the pixels. Returns its format, dimensions, mip count, `filter` ("nearest" or "linear" — the sampler baked into the blob from the asset's `settings.filter`), and the payload's layer shape. `layers` counts the array layers the payload carries and `isArray` is true past one — the answer to "am I about to sample a `texture_2d_array`?", available before anything samples it. `animated` is true when those layers are a sequence in time; then `frameDelaysMs` lists each layer's display time in milliseconds in display order, and `durationMs` totals one pass. An animated image imports as one layer per frame, so `layers` is its frame count. A still texture reports `layers = 1`, `isArray = false`.

argtypedescription
ztexbuffer | stringZTEX bytes.

examples

local i = renderer.texture.info(bytes); if i.animated then print(i.layers, "frames", i.durationMs, "ms") end

frameSchedule(texture: string | AssetRef) →

The times at which each layer of a timed texture stops being shown, in seconds from the start of the sequence — the running total of the layer display times, so the last entry is the length of one pass. This is the form a sampler reads a sequence through: a time is turned into a layer by finding the first entry it has not passed, whatever the individual layer times are. It is what the `schedule` slot of the builtin `animatedTexture` shader holds, one entry per layer. A texture whose layers carry no timing — a still image, a sprite sheet, a LUT stack — has no schedule and answers nil.

argtypedescription
texturestring | AssetRefThe texture — a guid, an identity, a name, a path, or a texture `AssetRef`.

examples

local ends = renderer.texture.frameSchedule(texRef) -- {0.1, 0.15, 0.35}

isResident(texture: string | { [string]: any } | AssetRef) → boolean

True if a GPU texture is resident under this texture's guid.

argtypedescription
texturestring | { [string]: any } | AssetRefThe texture — a `TextureHandle`, a `TextureCpuHandle`, a guid, or a texture `AssetRef`.

examples

print(renderer.texture.isResident(handle))

readback(texture: string | { [string]: any } | AssetRef) → TextureCpuHandle

Read a runtime GPU texture's pixels back to CPU and return a `TextureCpuHandle` for them — the GPU→CPU half of the runtime-texture freeze path. A texture made with `renderer.texture.create` keeps no CPU copy, so persisting it (`:encode()` → `asset.create("texture", …)`) reads it back here first. Yields until the readback completes (a frame or two). After it `:writePixel`, `:getInfo`, `:encode`, `:unload` all work. Errors if the texture never becomes GPU-resident. A SCENE-space `screen`-sized render target is one resource shared by every render target drawn — the viewport, an offscreen capture, a camera rendering into a texture — resized and re-derived for each of them in turn. The copy is taken ahead of all of them for the frame, so what a readback of its guid answers is the content of the last frame the renderer drew: the presented view's own image at the presented resolution, since the presented view is the sink that draws last. A request made while the renderer is holding frames back is carried to the next frame it draws rather than being answered from a target another sink left standing, so a readback can wait a frame longer than the copy itself takes.

argtypedescription
texturestring | { [string]: any } | AssetRefThe texture — the `TextureHandle` `renderer.texture.create` returned, a guid, or a texture `AssetRef`.

examples

local cpu = renderer.texture.readback(handle); local ztex = cpu:encode(); cpu:unload()

cpuCreate(width: number, height: number, fill: any?) → TextureCpuHandle

Allocate a blank CPU image (RGBA8) filled with a solid colour and return a `TextureCpuHandle`. Compose into it with `canvas:blit(src, x, y, w, h)`, then `canvas:encodeJpeg()` / `:encodePng()` for the bytes; `:unload()` drops it.

argtypedescription
widthnumbernumber Canvas width in pixels.
heightnumbernumber Canvas height in pixels.
fillany?Optional `{ r, g, b, a }` (0-255) solid fill; defaults to opaque white.

examples

local c = renderer.texture.cpuCreate(1024, 576, { 255, 255, 255, 255 })

classifyTex(src: any) → string

argtypedescription
srcany

list( ) →

Every texture currently registered, ordered by guid — the ones a script created and the ones that reached the device through an asset alike. Each entry carries the guid, where it came from (`origin` is `"asset"` for a texture the asset path uploaded), and whether the GPU still holds it. A resident entry also carries the bytes it costs, its dimensions and its texel format, so the listing sums to `renderer.textureMemory()`. format?, compressed?, streamable? }`.

examples

for _, t in ipairs(renderer.texture.list()) do print(t.guid, t.bytes) end

create(src: any, guid: string?) → TextureHandle

Create (or fetch) a GPU texture resource and return its `TextureHandle`. `src`: a `TextureCpuHandle` from `texRef:load()` (CPU→GPU under the asset's guid, idempotent); raw pixels `{rgba, width, height, srgb?, format?}` (a flat width*height*4 byte payload, 0-255, row-major, top-to-bottom, RGBA — a `buffer`, a binary string, or a number array; `format = "rgba16f"` uploads an HDR texture instead, where `rgba` carries float channel values); a `TextureHandle` (returned as-is); or render-target dimensions `{width, height, name?}` with no pixel source — an empty GPU texture a render pass writes into (camera output, UI surface) and that samples like any other texture. A render target also takes `screen` (the engine keeps it the size of the image being drawn), `screenScale` (the fraction of that size it takes) and `screenSpace` (`"scene"`, the default, or `"composite"` — the image the post-scene phases draw into, which is the display's own resolution while the renderer presents the viewport itself and the scene's size while a UI viewport panel owns the presentation). A scene-space target is resized for every render target drawn and cleared before an offscreen one; a composite-space target follows the presented frame alone, which is what lets a pass keep an accumulation in it. One scene-space `screen` target is therefore one resource every render target draws through in turn, so its guid holds the last one's image at the last one's size, and a value read back from it belongs to whichever render target was drawn last. A reading that has to be the viewport's own comes from `screenSpace = "composite"`, or from a target created without `screen`. NEVER takes an AssetRef — load the CPU first. texture is filed under, which a material's texture slot resolves through. Minted when absent. Ignored for the CPU-handle and render-target paths.

argtypedescription
srcanyA TextureCpuHandle, raw pixels, a TextureHandle, or render-target dimensions.
guidstring?Optional v4 guid for a NEW runtime texture — the asset identity the

examples

local gpu = renderer.texture.create(texRef:load())
local gpu = renderer.texture.create({ rgba = pixels, width = 16, height = 16 })
local px = buffer.create(16 * 16 * 4); local gpu = renderer.texture.create({ rgba = px, width = 16, height = 16 })
local rt = renderer.texture.create({ width = 512, height = 256, name = "panel_rt" })

update(handle: TextureHandle, src: any) → TextureHandle

Overwrite the GPU texture behind `handle` IN PLACE, under the same guid, from new raw pixels. Never writes a `.texture` file — the play-mode mutate path. Returns the same handle (refreshed dims). `buffer`, a binary string, or a number array.

argtypedescription
handleTextureHandleThe `TextureHandle` to update.
srcanyNew raw pixels `{rgba, width, height, srgb?, format?}` — `rgba` as a

destroy(handle: TextureHandle) → void

Release the GPU texture behind `handle`. For an empty render-into texture (camera output, UI surface) this also frees its render scratch; for an uploaded runtime texture it drops the GPU resource (and any CPU shadow).

argtypedescription
handleTextureHandleThe `TextureHandle` to release.

examples

renderer.texture.destroy(rt)

capture(handle: TextureHandle) → string

Request a CPU readback of the GPU texture behind `handle` (e.g. a camera's rendered output). Returns a result key to pass to a TextureCpuHandle's `:encode()` once the readback completes.

argtypedescription
handleTextureHandleThe `TextureHandle` to read back.

examples

local key = renderer.texture.capture(cameraTarget)

wrapMaterialHandle(guid: string, name: string) → MaterialHandle

argtypedescription
guidstring
namestring

resolveTextureRef(ref: any, materialName: string, slot: string) → any

The GPU key a texture slot binds by. The renderer looks a slot's texture up by EXACT cache key — the guid an upload landed under — so an identity, a name, a `.texture` path, or the image path a texture was imported from names a real texture the cache has never heard of, and the slot renders the shader's declared fallback instead. Resolving here materialises the texture and returns that key, so every form an author can hold binds the texture they named. A reference that answers to nothing is passed through (the renderer picks up a texture that lands later) and reported, so the fallback is never silent.

argtypedescription
refany
materialNamestring
slotstring

create(content: MaterialContent, key: string) → MaterialHandle

argtypedescription
contentMaterialContent
keystring

frameScheduleTexture(guid: string, ends: { number }) → string

A texture carrying `ends` — the millisecond each layer stops being shown — one texel per layer, the millisecond as a 24-bit integer with its high byte in R. Read with `textureLoad`, so the shader gets the integer back exactly rather than a filtered neighbourhood of it. Returns the guid a material slot binds it by.

argtypedescription
guidstring
ends{ number }

list( ) →

Every runtime material currently registered, ordered by registry key. Each entry carries the key, where it came from, and the shader it binds.

examples

for _, m in ipairs(renderer.material.list()) do print(m.guid, m.shader) end

destroy(key: string | { [string]: any } | AssetRef) → boolean

Drop a runtime material registered via `renderer.material.create`: clears its recoverable definition, unregisters its runtime-resource stamp so it is no longer swept into the material freeze/save flow, and frees the GPU record. Use for transient materials (e.g. a preview swatch) that must not outlive their use. The on-disk asset, if any, is untouched. The reach is the registry: after this, `describe` and `list` stop answering for the key. A surface already wearing the handle goes on drawing what it was given — `Model:restoreSessionMaterial` is what puts a Model back on its authored material. `MaterialHandle` `create` returned, or an `AssetRef` from `asset.resolve`.

argtypedescription
keystring | { [string]: any } | AssetRefThe material's registry key (the one passed to `create`), the

examples

renderer.material.destroy("__preview_swatch_" .. texGuid)

visibilitySurface( ) → any

currentObservation( ) → any

The renderer records a frame's per-renderable resolutions only while something is reading them, so the first read arms recording and the frame after it publishes. This waits that frame out, so every call built on it answers with live data.

publishedMaterial(key: string) → any

What the renderer holds for one material, out of the document it publishes every frame. Reading it neither arms per-draw recording nor waits for a frame, so a caller asking about a material pays what a table lookup costs.

argtypedescription
keystring

describe(key: string | { [string]: any } | AssetRef) → any

The recoverable definition (`{ shader, properties, textures, name }`) this module registered under `key` via `renderer.material.create`, or nil for keys registered elsewhere (e.g. material assets resolved by the assetType). `properties` and `textures` carry the material's current values: each `setProperty` / `setTexture` write lands on this record, a texture slot under the GPU key the slot binds by — these are the WRITES, held here whether or not the renderer took them up. `renderer` beside them is what the renderer holds for the same key: the program its prepared bind group was built against, the render state its draws are looked up under, whether a pipeline exists for that key, and how many draws the observed frame gave it. `renderer` is nil when the renderer holds no material under this key at all, and `resident` states the same fact as a boolean. Writes reach the screen through both halves: `resident = false` says the renderer holds nothing to put them in, and `renderer.draws = 0` on a resident material says it holds them and no renderable is drawing with it. For a material that is resident AND drawn and still looks wrong, `renderer.drawDiagnostics()` names the renderable and the cause. `renderer.material.create`, or an `AssetRef` from `asset.resolve`.

argtypedescription
keystring | { [string]: any } | AssetRefThe material's registry key, the `MaterialHandle` from

renderState(key: string | { [string]: any } | AssetRef) → MaterialObservation

What the renderer holds for a material, which is a different document from the values written to it. `shader` is the program its prepared bind group was built against, `renderState` the blend / cull / topology / queue / depth key its draws are looked up under, `keyBuilt` whether a pipeline exists for that key, and `draws` / `instances` / `placeholderDraws` / `binds` / `bindsElided` what it cost in the frame the renderer last observed — those five read 0 until something arms per-draw recording, which `renderer.materialCost()` and `renderer.drawDiagnostics()` do. `nil` means the renderer holds no material under this key at all — the writes landed on a record nothing is drawing with. `renderer.material.create`, or an `AssetRef` from `asset.resolve`.

argtypedescription
keystring | { [string]: any } | AssetRefThe material's registry key, the `MaterialHandle` from

examples

local r = renderer.material.renderState("water"); print(r.renderState.blend, r.keyBuilt)

sessionKeyFor(entityId: string) → string

The canonical registry key for an entity's SESSION material — the runtime material a system (e.g. GI baking) shows on an entity in place of its authored material for the lifetime of the engine session. One session material per entity: create it under this key, hand the handle to `Model:applySessionMaterial`, and the component re-adopts it across VM reloads by probing this key with `describe`.

argtypedescription
entityIdstringThe entity carrying the material.

examples

local key = renderer.material.sessionKeyFor(entityId)

setProperty(key: string | { [string]: any } | AssetRef, name: string, value: any) → void

Push one changed uniform property to a registered material's GPU record (frame-fast incremental update; no re-register). Keyed by the material's registry key. `renderer.material.create`, or an `AssetRef` from `asset.resolve`.

argtypedescription
keystring | { [string]: any } | AssetRefThe material's registry key, the `MaterialHandle` from
namestringProperty name.
valueanyNew value.

examples

renderer.material.setProperty(asset.resolve("wall", "material"), "roughness", 0.2)

setTexture(key: string | { [string]: any } | AssetRef, slot: string, ref: string | { [string]: any } | AssetRef) → void

Push one changed texture slot to a registered material's GPU record. Keyed by the material's registry key. `renderer.material.create`, or an `AssetRef` from `asset.resolve`. image path it was imported from, a `color:` / `default:` form, a live GPU handle, or a texture `AssetRef` carrying one. An asset reference is materialised (Disk→CPU→GPU) and bound by the key the upload lands under.

argtypedescription
keystring | { [string]: any } | AssetRefThe material's registry key, the `MaterialHandle` from
slotstringTexture slot name (`"base_color_texture"`, …).
refstring | { [string]: any } | AssetRefTexture reference — a `.texture` guid / identity / name / path, the

examples

renderer.material.setTexture("sky", "sky_texture", "panorama.texture")

logWarn(msg: string) → void

argtypedescription
msgstring

buildFeatureCtx( ) → any

Build the per-frame `ctx` handed to a feature's setup/render/teardown.

enqueue(spec: ?) → void

argtypedescription
spec?

frameworkTick( ) → void

The single per-frame tick the engine drives (`__renderfeature.setTick`). Runs every active feature's `render(ctx)`; a feature whose render errors is logged, torn down, and dropped so one bad feature can't wedge the rest.

loadFeatureModule(ref: any) → void

Resolve + load a feature module from its asset ref (or a `{ path = ... }` table). Mirrors testSuite's `loadstring(vfs.read(initPath))`, but captures the returned `{ setup?, render, teardown? }` table.

argtypedescription
refany

create(ref: any, guid: string?) → any

Instantiate a render feature so the engine calls its `render(ctx)` hook every frame. `ref` is an `AssetRef<renderFeature>` whose `init.luau` returns `{ setup?, render, teardown? }`. Returns a live `RenderFeatureHandle` (its `guid` is the stable id, same as mesh/texture handles); tear it down with `renderer:destroy(handle)`. Pass `guid` to assign a specific id. `asset.resolve(ref, "renderFeature")`.

argtypedescription
refanyAn `AssetRef<renderFeature>`, or a string identity/guid resolved via
guidstring?Optional explicit handle guid (minted when omitted).

examples

local h = renderer.feature.create(asset.resolve("acrylic", "renderFeature"))
local h = renderer.feature.create("acrylic")

jstr(s: string) → string

argtypedescription
sstring

destroyFeature(guid: string) → boolean

Tear down a live feature (run `teardown(ctx)`, stop its per-frame render), keyed by the handle's guid. Routed here from `renderer.destroy` / `renderer.feature.destroy`, and from `create` for hot-reload. Assigns the forward-declared local so `create` (defined above) can call it.

argtypedescription
guidstring

list( ) →

List every render feature currently live (running its `render(ctx)` each frame). Each entry is `{ guid, identity }` — the `guid` is the same id a `RenderFeatureHandle` carries, so you can tear a feature down by guid even after losing its handle (e.g. across separate `execute` calls).

examples

for _, f in renderer.feature.list() do print(f.identity, f.guid) end

destroy(handleOrGuid: any) → boolean

Tear down a live render feature by its `RenderFeatureHandle` OR its guid string — the by-id path for when the handle was lost (e.g. across `execute` calls). Same effect as `renderer.destroy(handle)`. Returns true if a feature was live under that id.

argtypedescription
handleOrGuidanyA `RenderFeatureHandle` or its `guid` string.

examples

renderer.feature.destroy("eb623975-d8bd-47a1-a0a4-5c0e56238e2f")

register(name: string, config: any) → number

Register (or update) a content capture view under `name` and return the debug CHANNEL number assigned to it. A render feature gates its pass to this channel (`debugChannel = channel`) so the pass draws only when a capture selects the view. Idempotent: re-registering the same name keeps its channel. called before a capture of this view so the feature that draws it is live (e.g. create it on demand). `warmup` is how many present frames a capture lets the view accumulate before it reads — set it when the feature retains prior-frame state (a temporal diff) so the first capture reads a warm result. `renderLayers` is the layer spec a capture of this view uses when the caller named none — a view that draws its own geometry and wants the scene's kept out of the frame (and out of the depth buffer it tests against) names only its own layer.

argtypedescription
namestringThe view name, selected via `capture pass=<name>`.
configany`{ description?, ensure?, warmup?, renderLayers? }`. `ensure` is

examples

local ch = renderer.captureView.register("lightmap", { description = "...", ensure = fn })

unregister(name: string) → boolean

Withdraw a capture view. A subsequent `capture pass=<name>` no longer resolves to it (falls through to the unknown-view error).

argtypedescription
namestringThe view name.

examples

renderer.captureView.unregister("lightmap")

resolve(name: string) → any

Resolve a capture view by name to its `{ channel, ensure, description, warmup }` record, or nil when no view is registered under `name`.

argtypedescription
namestringThe view name.

examples

local v = renderer.captureView.resolve("lightmap")

channelId(name: string) → number

The debug channel a registered view draws on — what a feature passes as its pass `debugChannel`. Nil when no view is registered under `name`.

argtypedescription
namestringThe view name.

examples

ctx.enqueue { ..., debugChannel = renderer.captureView.channelId("lightmap") }

ready(name: string) → boolean

Whether a registered view can draw yet. A view's passes are enqueued from the moment its render feature first runs, but they are skipped while the materials they name have no pipeline — their shader is still compiling — so for the first frames of a session a camera bound to the view renders the ORDINARY view into its target, and the image gives no sign of it. This reports the difference, and reports it before any camera is on the view, so it is answerable for the first camera bound to one. False for an unregistered name.

argtypedescription
namestringThe view name.

examples

repeat task.wait() until renderer.captureView.ready("zfighting")

list( ) →

Every registered capture view as `{ name, channel, description }` records — what backs the discoverability of `capture pass=<name>` and the unknown-view error's suggestion list.

examples

for _, v in ipairs(renderer.captureView.list()) do ... end

renderingFfi( ) → any

builtins( ) →

The built-in debug-pass names, one per channel in channel order — the engine's built-in pass vocabulary (final, albedo, normal, depth, …).

examples

for _, n in ipairs(renderer.debugPass.builtins()) do ... end

channel(name: string) → number

The channel a debug-pass NAME renders on: a built-in pass, else a content capture view registered via `renderer.captureView`. Nil when the name is neither — the signal a selector uses to reject an unknown pass.

argtypedescription
namestringA debug-pass name (e.g. "normal", "depth", "lightmap").

examples

local ch = renderer.debugPass.channel("normal")   -- 7

name(channel: number) → string

The canonical NAME for a debug channel: a built-in pass name for a built-in channel, else a registered capture view's name. Channel 0 is "final" (the lit image). Nil when no pass owns the channel.

argtypedescription
channelnumberThe channel number.

examples

local name = renderer.debugPass.name(7)   -- "normal"

list( ) →

Every selectable debug-pass name: the built-in passes plus every registered content capture view. What a debug-pass selector offers.

examples

local passes = renderer.debugPass.list()

rtSurface( ) → any

══ renderer ray tracing ══════════════════════════════════════════════ Enable + introspect GPU ray tracing. While enabled the engine builds the scene acceleration structure each frame; a ray-tracing render feature (see renderer.feature) traces against it. The same features run on both backends — hardware ray query and the software/compute path — through one trace surface. This module is the sole caller of the internal `__rendering` FFI (resolved at call time: it is registered on demand and may not exist at module load).

setRaytrace(enabled: boolean) → void

Enable or disable GPU ray tracing. While enabled the engine builds the scene acceleration structure each frame so ray-tracing render features can trace against it; disabling stops the build (so it costs nothing until a ray-traced effect is active). Required before any ray-traced shadows / AO / reflections render.

argtypedescription
enabledboolean`boolean`

examples

renderer.setRaytrace(true); renderer.feature.create("rt_shadows")

getRaytrace( ) → boolean

Whether ray tracing is currently enabled.

raytraceCapability( ) → string

The active ray-tracing backend: `"hardware"` (GPU ray query) or `"compute"` (software traversal — the path on devices without hardware ray query, e.g. the web). The same ray-tracing features work on both.

examples

if renderer.raytraceCapability() == "hardware" then ... end

raytraceStats( ) →

What the ray-tracing acceleration structure holds, and what this session's frames have spent building it. A ray walks a structure built over the scene's geometry, and keeping it current is work a frame pays before it traces anything. On the `"compute"` backend geometry that has stood still long enough is filed under a static partition the frames after it leave alone: `staticTriangles` + `dynamicTriangles` = `triangles`, `nodes` is the hierarchy over them, `fullRebuilds` / `partialRebuilds` / `reusedFrames` count what the session's frames did, and `trianglesRebuilt` is what those rebuilds re-emitted, summed. On the `"hardware"` backend `blas` is the bottom-level structures cached, `blasBuilt` how many the last frame built, and `tlasInstances` what the top-level structure names. The counters are cumulative — sample, run the scene, sample again.

examples

local before = renderer.raytraceStats().trianglesRebuilt

setTransmissionShadows(enabled: boolean) → void

Let translucent casters tint the sunlight they block instead of blocking it outright. A shadow map holds one depth per texel and is compared as a yes-or-no test, so stained glass, water and thin fabric all project the same black silhouette a wall does. With this on, a caster whose material declares opacity (`base_color` alpha under a transparent blend) or `transmission` also draws into a light-space transmittance map, and the colour it lets through multiplies into the directional light reaching whatever stands behind it. Stacked casters compose. Opaque casters are unaffected, and a scene with no translucent caster allocates nothing and records no pass.

argtypedescription
enabledboolean`boolean`

examples

renderer.setTransmissionShadows(true)  -- stained glass tints the floor

transmissionShadows( ) → boolean

Whether translucent casters tint the directional light they block.

mainCameraView( ) →

The main camera's inverse view-projection (column-major, 16 numbers) followed by its world position (3 numbers) — `{m0..m15, px,py,pz}` — for reconstructing world positions from the depth buffer in a ray-tracing pass. Nil before the first render.

setDepthPrepass(enabled: boolean) → void

Enable or disable the opaque depth pre-pass. While enabled the renderer resolves opaque depth in its own pass before shading, so each shaded pixel runs its material once instead of once per surface stacked behind it, and the resolved depth is what occlusion culling reads. Enabled by default.

argtypedescription
enabledboolean`boolean`

examples

renderer.setDepthPrepass(false) -- shade every layer, for comparison

depthPrepass( ) → boolean

Whether the opaque depth pre-pass is currently enabled.

setDepthPrepassOrdering(enabled: boolean) → void

Submit the depth pre-pass nearest-first. Renderables reach the pre-pass in the order they were registered, which stands in no relation to where the camera is: a scene built back-to-front makes every layer write depth and be overwritten by the layer in front of it. Ordered, the nearest surface writes first and the surfaces behind it are rejected by the depth test before they write. The same draws go out either way and the depth that comes out is the same, so `scene.depth_prepass` in `profiler.gpuFrame()` is what moves. Enabled by default.

argtypedescription
enabledboolean`boolean`

examples

renderer.setDepthPrepassOrdering(false) -- submit in registration order

depthPrepassOrdering( ) → boolean

Whether the depth pre-pass is submitted nearest-first.

depthPrepassOrder( ) →

What the last frame's depth pre-passes planned, and how far their sequences were from near-to-far before they ordered. `runs` counts the instanced draws planned; `reordered` counts the adjacent pairs the sort moved past each other, taken before it ran. Both are summed over every pre-pass the frame ran — the window plus each render-target camera, each ordering against its own camera. Both read `0` while the pre-pass or the ordering is off, and `reordered` reads `0` for a frame that already stood in order. The ordering leaves no other trace — the draws, the depth and the image are the same either way.

examples

local o = renderer.depthPrepassOrder()  -- o.reordered > 0 → it sorted

setResolutionScale(scale: number) → number

Render the scene at a fraction of the display's resolution and present it at the display's own size. Shading cost scales with pixel count and with nothing else, so this trades sharpness for frame time without taking anything out of the scene: at `0.5` the scene rasterizes a quarter of the pixels. UI and text are unaffected — they are drawn after the scene is brought back up to size. The scene rows in `profiler.gpuFrame()` are what move.

argtypedescription
scalenumber`number` — fraction of the display resolution, clamped to [0.25, 1].

examples

renderer.setResolutionScale(0.7)

resolutionScale( ) → number

The fraction of the display resolution the scene is currently rendered at. `1` until something sets it.

examples

local s = renderer.resolutionScale()

setMinScreenSize(pixels: number) → void

Stop drawing an object once its on-screen radius falls below this many pixels. A few pixels across, an object carries no detail a viewer can resolve while still costing a full vertex and submission pass, and the cutoff drops it from the camera's draws entirely — `0`, the default, keeps every object however small it lands. Measured from the object's own bounds against the camera's projection, so the same threshold means the same apparent size at any distance or field of view. Shadow casters have their own threshold in `renderer.setShadowCasterCutoff`.

argtypedescription
pixelsnumber`number` — smallest on-screen radius still drawn; 0 disables.

examples

renderer.setMinScreenSize(4) -- drop anything under 4 px of radius
print(renderer.drawStats().compactedDrawn, "instances survived it")

minScreenSize( ) → number

The on-screen radius, in pixels, an object must reach to be drawn. `0` while the cutoff is off.

examples

local px = renderer.minScreenSize()

setOcclusionCulling(enabled: boolean) → void

Enable or disable occlusion culling. While enabled the renderer reduces the pre-pass depth into a pyramid each frame and tests every renderable that cleared the frustum against it, dropping the ones another surface entirely covers before their geometry is submitted. The pyramid describes the frame being drawn, so an object that becomes visible this frame is never held back a frame. Requires the depth pre-pass.

argtypedescription
enabledboolean`boolean`

examples

renderer.setOcclusionCulling(true); print(renderer.cullStats().occlusionCulled)

occlusionCulling( ) → boolean

Whether occlusion culling is currently enabled.

cullStats( ) →

What the last completed frame decided to draw. `total` renderables went into the frustum test, `culled` fell outside it and `visible` survived. Of those, occlusion culling examined `occlusionTested` and proved `occlusionCulled` were entirely behind other geometry — both 0 while `renderer.occlusionCulling()` is false.

examples

local s = renderer.cullStats(); print(s.visible - s.occlusionCulled, "drawn")

drawStats( ) →

What the last completed frame actually submitted. `draws` counts every geometry draw call the frame issued — the camera's passes, each shadow view a shadow-casting light adds, and whatever a render feature draws — and `instances` counts the instances those draws covered. The pair is what separates one draw carrying five hundred instances from five hundred draws carrying one each, so it reads how well the scene batches rather than how many objects are in it. `compacted` is how many of those instances the frame planned through draws whose instance count the GPU decides: the culler's own per-object answers packed into a dense run, so an object it rejects is absent from the draw instead of collapsing to nothing in the vertex stage. `compactedDrawn` is how many of them survived, counted on the GPU as it packed them — a pass that then skips a whole draw over its own layer or visibility answer leaves that draw's instances in both numbers. The plan is made over the populations the frame draws, and the tests answer which of their instances the packing keeps. That packing runs before any pass has resolved the depth occlusion culling is tested against, so on its own it reads the frustum and screen-size answers alone. With `setOcclusionCulling` armed the frame packs the same plan a second time once the test has answered, and `compactedDrawn` then counts what came through occlusion as well. `compactedDrawn` comes back from the buffer the GPU wrote, so it describes a frame that has finished while `compacted` describes the most recent plan, and it holds the last count the GPU wrote until another arrives — a frame that compacts nothing reads `compacted` 0 beside the count from the last frame that did. In a scene standing still the gap between the two is the front-end work culling removed. `materialBinds` is how many times the frame's geometry passes set a material's parameter group, and `materialBindsElided` how many times a pass reached that decision and found the group already bound. Their sum is how many times the decision was reached — once per unit of geometry submitted, which sits at or below `draws`, since a mesh of several primitives draws once per primitive under one set of binds. The ratio inside the pair is what material binding costs the frame: the batched opaque geometry is gathered into runs sharing a material, so a frame of many such draws over few materials binds about once per material rather than once per unit. `materialExtraBinds` and `materialExtraBindsElided` are the same pair for the second group, the storage bindings a shader declares for itself, which only the shaders that have them ever bind.

examples

local d = renderer.drawStats(); print(d.instances / math.max(d.draws, 1), "instances per draw")
print(renderer.drawStats().compactedDrawn, "of", renderer.drawStats().compacted, "survived the cull")
local d = renderer.drawStats(); print(d.materialBinds, "material binds over", d.materialBinds + d.materialBindsElided, "units")

skinningStats( ) →

What the last frame's skinned instances cost. A skinned instance is posed by a compute pass that writes its vertices into a shared pool, and instances holding the same pose read one slice of that pool and the single dispatch that fills it. `instances` is how many were posed, `poses` how many distinct poses they held, and `dispatches` how many dispatches those poses cost this frame — so a crowd whose members move together costs what its poses cost rather than what its head count does, while members at different animation times each hold their own pose and pay for it. `held` is how many of the frame's poses cost no dispatch at all. The pass produces a slice from what the pose is made of, so a slice an earlier frame filled already holds what running it again would write, and a pose still wearing that slice is read as it stands. Skinning is paid for by the poses that CHANGED: a cast standing still reads `dispatches` 0 beside a `held` equal to its `poses`, and the two add up to `poses` in any frame. `reusedSlices` is how many of the frame's poses took a slice the pool already held — one a retired pose gave back, or one a pose nothing has asked for this frame was holding — rather than one cut from pool the engine had never used. A scene whose poses keep changing reads a non-zero count beside a `poolBytes` that stays where it was. `liveBytes` is what the slices holding this frame's poses occupy, against `unsharedBytes` — what the same instances would occupy with a slice each. `poolBytes` is what the pool holds; a previous-position buffer of the same size rides alongside it so skinned deformation reaches motion vectors.

examples

local s = renderer.skinningStats()
print(("%d instances over %d poses"):format(s.instances, s.poses))
print(("%d poses dispatched, %d read as they stood"):format(s.dispatches, s.held))
print(("skinned vertex storage: %d B of an unshared %d B"):format(s.liveBytes, s.unsharedBytes))

morphStats( ) →

The morph state the last frame drew with. A mesh carries the shapes it can blend towards and an entity carries how strongly each is blended (`ecs.MorphWeights`); where both are present, the vertex stage adds the weighted deltas to the base geometry. `instances` is how many render slots that happened at, and `blends` how many single-target blends those slots carry between them: a slot contributes one per target its weights move, or that they moved the frame before, so the number of targets a mesh can be given is bounded by the buffer the blends live in. `meshes` is how many meshes hold a delta block and `targets` how many targets those blocks cover between them; `deltaBytes` is what the shared buffer they are appended into holds. A morph-target mesh whose weights are all zero reads a `meshes` above zero beside an `instances` and `blends` of zero.

examples

local m = renderer.morphStats()
print(("%d instances carrying %d blends over %d meshes"):format(m.instances, m.blends, m.meshes))

uploadStats( ) →

What the last completed frame spent re-describing its renderables to the GPU. Every renderable owns a slot in the per-instance data a draw reads — its world matrix, the bounds the culler tests it by, and the flags that decide which passes and which culling stages see it — and a frame uploads only the slots whose contents changed. `bytes` is what those uploads carried, `fullBytes` what re-sending every slot would have cost, and `writes` how many buffer writes carried it. The three numbers cover that per-renderable data alone, so a scene standing still reads `bytes = 0` against a `fullBytes` that grows with the scene, and the ratio says how much of it the scene's own churn — rather than its size — is paying for.

examples

local u = renderer.uploadStats()
print(("instance upload: %d B of %d B in %d writes"):format(u.bytes, u.fullBytes, u.writes))

framePacing( ) → FramePacing

How far the CPU is allowed to run ahead of the GPU, and what holding it there cost the frame just finished. Submitting work to the GPU returns before the GPU has done it, and everything that submission holds — its staging allocations, its bind groups, its command buffer — stays alive until it completes. A frame that asks for more work than the GPU finishes in a frame's time therefore leaves that behind it, and unbounded that is memory growth rather than a lower frame rate. `framesInFlight` is how many submitted frames have not reported done through the queue's completion signal, held under `maxFramesInFlight`: a device that keeps up reads under the bound, one that is behind reads at it. It counts submissions, which is its own quantity — how many presented images the swapchain permits in flight is a separate setting. `mechanism` names how that bound is enforced here: `submission-wait` waits for the frame that many frames back and reports the wait in `waitMs`, so a paced frame costs latency and still draws; `submitted-work-done` counts outstanding frames off the queue's completion signal and declines to start a frame while the bound is met, counting those in `pacedFrames` and leaving the last presented image up. `submittedFrames` counts the frames that were admitted and submitted, so it rises for as long as the renderer is producing frames — which is what tells a renderer running slowly under a tight bound from one that has stopped. `stalled` reads true while that completion signal has stopped arriving and the pacer stood down rather than hold the image indefinitely; it clears on the first frame that finds the count back under the bound. `presentMode` is what the surface presents with and `presentModes` what it offers; both are empty of meaning on a headless renderer, which never presents.

examples

local p = renderer.framePacing()
print(("%d of %d frames in flight, paced by %s"):format(p.framesInFlight, p.maxFramesInFlight, p.mechanism))

setMaxFramesInFlight(frames: number) → number

Set how many frames of GPU work may be outstanding before the renderer stops running ahead. One is the least overlap this can express — a frame's work is waited for as soon as the next frame has been submitted — which is the lowest latency and the lowest throughput; higher values let a slow frame build a longer backlog, and that backlog is memory. Takes effect on the next frame. Answers the bound after clamping to [1, 8], so asking for more than the renderer honours reports what you actually got.

argtypedescription
framesnumbernumber Frames of GPU work that may be outstanding, 1 through 8.

examples

renderer.setMaxFramesInFlight(1) -- lowest latency
print(renderer.setMaxFramesInFlight(99), "was clamped")

setPresentMode(mode: string) → string

Set how a presented frame reaches the display. `fifo` queues every frame and shows it on a vertical blank, which never tears and never drops one; `mailbox` replaces the queued frame with the newest, which does not tear and does not hold the renderer to the refresh rate; `immediate` presents as soon as a frame is ready and can tear; `fifo_relaxed` is `fifo` that tears rather than stall when a frame misses its blank; `auto_vsync` and `auto_no_vsync` leave the choice to the backend. A surface that does not offer the mode presents `fifo` instead, so read `renderer.framePacing().presentMode` for what took effect and `.presentModes` for what this surface offers. Takes effect on the next frame.

argtypedescription
modestringstring One of "fifo", "fifo_relaxed", "mailbox", "immediate", "auto_vsync", "auto_no_vsync".

examples

renderer.setPresentMode("mailbox")
print(renderer.framePacing().presentMode, "is what the surface took")

pipelineCache( ) → PipelineCache

What the driver's compiled-pipeline store held, built, and wrote back. A pipeline is machine code the GPU driver compiles from the shader bound into it, and that compile is what a launch pays before the first frame drawing with each pipeline can appear. The store keeps that compiled code across runs, so a launch whose shaders have not changed reads back what the previous one compiled. `restoredBytes` is what a previous run left for this GPU and this launch read; `pipelinesBuilt` counts the pipelines built since startup and `buildMs` is what they cost together, which is the number the store lowers. `saves` and `savedBytes` describe writing it back — deferred until a burst of builds settles, so one launch is one write — and `dirty` is true while pipelines have been built that the file does not hold, including after a write that failed, which `lastError` then names. `path` is the file, named after the GPU it belongs to. `supported` is false where the platform holds no store a program can carry: a browser keeps its own and hands none out, and an adapter can lack the capability. `reason` says which, and the build count and timing still read true there. `lastError` names a read or write failure; a failed store costs the saved compile and never the frame, since every pipeline is built from its source either way. `pipelinesBuilt` and `buildMs` are engine-wide totals; `renderer.shaderCost()` is the same cost broken down per program, with each one's permutation count.

examples

local c = renderer.pipelineCache()
print(("%d pipelines in %.1f ms, %d bytes restored"):format(c.pipelinesBuilt, c.buildMs, c.restoredBytes))

observe( ) → RenderObservation

Everything the renderer knows about the frame it last drew: what program it bound for each renderable, the render state it holds each material under, and what each program has cost in pipeline builds. `renderables` is one row per renderable in the renderer's draw list, carrying the program its material named (`requestedProgram`) beside the one that was bound (`boundProgram`) — `__error__` wherever the lookup missed and the draw went ahead on the magenta placeholder — plus `substituted`, the `outcome` (`drew` / `drewPlaceholder` / `skipped` / `notDrawn`), the `reason` that forced it and the compiler's own `detail` for a failed compile. `observed` says which of two answers a row is: `true` for a resolution a geometry pass took as it drew, `false` for the renderer's own resolution of a renderable this frame drew nowhere, which is what a renderable outside every camera's frustum or layer mask reports. `materials` is one row per material the renderer holds a prepared bind group for; `shaders` is one row per program pipelines have been built for. `frame` names the frame every per-frame count covers; `retainedFrames` how many frames a resolution a pass took is kept for after the last frame that drew it; `window` and `costWindow` state both in the document itself. Recording is armed by the first read, so this waits for the frame that first records rather than answering empty.

examples

local o = renderer.observe(); print(o.placeholderDraws, "renderables drew the placeholder in frame", o.frame)

drawDiagnostics( ) →

Every renderable that is NOT drawing what its material says — the one call for "why does this surface look wrong". Three states land here: a surface rendering as the magenta placeholder (`substituted`), one the renderer could bind nothing for at all (`outcome = "skipped"`), and one drawing a program whose most recent compile FAILED (`stale`), which is what a shader edited into brokenness looks like — the pipeline its last good compile built keeps drawing, so the picture is intact and answers to none of the edits since. Each row names the entity, the program asked for, the program bound, `programStatus` — the compile gate's word about the program the material NAMED — and the one cause from `shaderCompileFailed` / `shaderNotRegistered` / `shaderNotCompiledYet` / `noGbufferEntry` / `renderStateKeyNotBuilt` / `noPipelineForTarget` / `unshaded`, with the compiler's own message in `detail` or `programError`. Covers every renderable the renderer holds, whether or not a camera reached it: a row with `observed = false` and `outcome = "notDrawn"` carries the renderer's own resolution for one this frame drew nowhere, so a broken surface off-screen is reported the same as one in frame. An empty result means every renderable the renderer holds is drawing the program its material named and that program compiles. Answers on the deferred path as well as forward, and in edit mode as well as play.

examples

for _, d in renderer.drawDiagnostics() do print(d.entity, d.reason, d.detail) end
if #renderer.drawDiagnostics() == 0 then print("every surface is drawing what it says") end

materialCost( ) →

What each material cost the frame the renderer last drew, and the state it holds each one under. One row per material the renderer holds a prepared bind group for — a material an author wrote and the renderer never prepared is absent, which is itself the answer to "why is nothing I set reaching the screen". `draws` and `instances` cover that one frame; `placeholderDraws` is how many of those draws bound the magenta placeholder instead of this material's own program; `binds` is how many material-owned bind groups the frame's passes SET for it and `bindsElided` how many of its draws wanted a group the pass already held, which is what draw-key sorting buys; a draw that fell back to the placeholder bound the placeholder's group, so it counts in `placeholderDraws` and in neither bind count. `uniformBytes` is the GPU uniform buffer's own size, which is the reflected property block raised to the 16-byte floor and rounded up to the copy alignment. `renderer.drawDiagnostics()` names WHICH renderable is not drawing what its material says, and why.

examples

for _, m in renderer.materialCost() do print(m.material, m.draws, m.binds, m.bindsElided) end

shaderCost( ) →

What each program has cost in pipeline builds, beside the compile gate's most recent word about it. `variants` is how many pipelines this engine has built for it — one per (target format, vertex layout, render-state key) permutation reached — and `buildMs` what those builds cost, both summed since engine start. A pipeline the driver's own store restored is not built and so is not counted, so a second launch on the same adapter reports less than the first. `status` is `compiled`, `failed` or `pending`, and `error` carries the compiler's message for a failure. Ordered by cost, most expensive first.

examples

local top = renderer.shaderCost()[1]; print(top.shader, top.variants, top.buildMs)

materialIdentity( ) → MaterialIdentity

Which material each renderable draws with, as a number a shader can carry. A material is authored and bound by name, and no shader can read a string — so every renderable's per-instance record holds a material index instead. `slots` is the name → index table those indices are drawn from: an index is assigned the first time the renderer draws with that material and does not move afterwards, so two renderables that differ only in material read different indices, and one renderable reads the same index frame after frame. It follows that the table keeps a row for every material name drawn this session, whether or not anything still draws with it. `renderables` is a row per renderable that owns a GPU slot — the entity it belongs to, that slot, and the index the record at it carries; `populations` is the same for an instanced draw, whose whole reserved run of slots carries the one material its registration named. That index is what a shader reads as `instance_data[slot].material_index`, and the row a ray hit resolves through `zeroMaterial()`. A renderable draws with the material its entity references, so one whose entity names none carries index 0.

examples

local id = renderer.materialIdentity()
for _, r in id.renderables do print(r.entity, r.slot, r.index, r.material) end

materialIndex(name: string) → number

The index standing for a material, or `nil` for one the renderer has not drawn with yet. Pass it to a shader (or compare it against what a shader read out of `instance_data[slot].material_index`) to tell which material a drawing instance carries.

argtypedescription
namestring`string` Material name, as `renderer.material.create` filed it.

examples

local red = renderer.materialIndex("brick_red")

gpuMemory( ) → GpuMemory

Where the renderer's GPU memory went at the last completed frame — the call to reach for when something is holding memory and you do not know what. The category figures cover what the renderer asked for on purpose and are always there. `allocator` is the device's own ledger with a row per creation label, largest first, which is what names an allocation no category claims; arm it with `renderer.setGpuMemoryTracking`. The gap between `allocator.allocatedBytes` and `categorised` is the per-frame render targets and scratch. `compute` is what the compute subsystem holds; `compute.observe()` names each of those resources and what it costs. published its first frame.

examples

local m = renderer.gpuMemory()
print(("shadows %.1f MiB"):format(m.shadow.total / 1024 / 1024))
renderer.setGpuMemoryTracking(60)
-- a second later, the biggest allocation in the engine:
local top = renderer.gpuMemory().allocator.byLabel[1]
print(top.label, top.bytes)

setGpuMemoryTracking(frames: number) → number

Arm the GPU allocator sampler at one reading every `frames` frames, or disarm it with 0. Building the ledger walks every live allocation, so it is off by default; the category figures in `renderer.gpuMemory()` cost nothing either way. A reader between samples sees the most recent ledger, so a slow interval still answers — 60 is a reading a second at 60 Hz.

argtypedescription
framesnumberFrames between readings. 0 disarms the sampler.

examples

renderer.setGpuMemoryTracking(60)
renderer.setGpuMemoryTracking(0)

shadowMemory( ) →

How much GPU memory the shadow maps hold right now, in bytes, by the light kind that owns them. The spot atlas and the point pool are sized to the casters in the scene rather than to the budget, so `spot` and `point` move as lights that cast shadows appear and leave, and a scene with one shadowed light holds far less than one that fills every slot. A budget is the ceiling they grow within — `renderer.spotShadowBudget().layers` and `renderer.pointShadowBudget().slots` report that ceiling, unmoved by how many casters exist. Raising shadow resolution costs the square of the change across every cascade.

examples

local m = renderer.shadowMemory()
print(("shadows: %.1f MiB"):format(m.total / 1024 / 1024))

shadowCacheStats( ) →

What the last frame did with the shadow maps it already had. A shadow view — one directional cascade, one atlas layer of spot tiles, one point light's cube — is drawn again only when something it draws from changed: its light moved, a caster it can see moved or appeared or vanished, a caster's geometry or material changed, a caster changed pose or moved the nodes its parts are placed by, or the map it writes into was reallocated. Anything else keeps the depth already in the texture, so a scene that stops moving reads `rendered` 0 while `cached` keeps climbing. A mesh whose vertices a compute pass writes — a population, or a mesh built from a compute buffer — re-renders the views it stands in every frame. Counted per light kind, plus the totals across all three.

examples

local s = renderer.shadowCacheStats()
print(("shadow views: %d drawn, %d cached"):format(s.rendered, s.cached))

reflectionEnvironment( ) →

What a reflective surface is reflecting. `probes` is how many reflection probes the shading blends; they are gathered highest `priority` first, each rank taking the coverage the ranks above it left, so a small interior probe ranked above the large exterior one it sits inside wins outright wherever it reaches full weight. `ranks` is the priority each of those probe slots was published with, in slot order. `sky` is whether the sky fallback is armed: with it, coverage no probe claims reflects the captured sky, and without it a surface outside every probe's radius falls back to the nearest probe alone. `skyCaptured` is whether the sky slot holds a capture — arming is refused until it does, since an uncaptured slot reflects black. `slots` is how many cube slots the environment array holds right now: one until something is captured into it, then one per probe plus the sky's, at index `skySlot`. `maxProbes` is how many of them probes may take, and `resident` whether the array has grown past that single slot. Capture the sky with `environment.captureSky()`.

examples

local env = renderer.reflectionEnvironment()
print(("%d probes, sky fallback %s"):format(env.probes, tostring(env.sky)))

renderTargets( ) →

Every render target the renderer owns and what each one costs, measured from the texture that is allocated. One row per target, each carrying its `name`, whether it is `resident`, the `bytes` it holds while it is, its `width`/`height`/`layers`/`mipLevels`, and `onDemand`. An `onDemand` target exists only while something needs it: a target nothing writes into reads `resident = false` and `bytes = 0` and appears again the frame something writes it, and one sized by content — the reflection-probe cube array — holds the slots content asked for. A camera rendering into a texture carries its own depth, motion vectors, occlusion and G-buffer, reported as `camera[<handle>].*` rows for as long as that camera renders; the colour image it draws into belongs to the texture cache instead. `totalBytes` is what the resident targets hold together. Measured at the end of the last rendered frame.

examples

local rt = renderer.renderTargets()
print(("render targets: %.1f MiB over %d resident"):format(rt.totalBytes / 1048576, rt.residentCount))
for _, t in rt.targets do
if t.onDemand then print(t.name, t.resident, t.bytes) end
end

passSchedule( ) →

The schedule check over this frame's enqueued render passes. Passes declare what they read (`inputs`) and what they write (`output` / `outputs` / `storage`), and the frame runs them in phase order and, inside a phase, in `order` order. `violations` holds every input bound to a render target the frame produces LATER: that read samples the target as the frame found it, which is the previous frame's contents for a target that persists and an empty target for one just created, and the pass renders either way. A pass reading a target one frame late on purpose declares that slot in its enqueue's `readsPrevious` and drops out of the list; `unboundPrevious` holds declared slots the pass binds no render target to, which cover nothing. A target no queued pass writes is not reported — a camera rendering to texture and `compute.dispatch` both fill targets outside the pass queue. `unreachable` holds passes at a phase that does not run their kind: every phase drains its fragment and compute passes, while `afterLighting` is the one that draws geometry, draw and splat passes, so one of those enqueued elsewhere sits in the queue and never runs. Each finding is also stated in the engine log the first time it appears.

examples

local s = renderer.passSchedule()
for _, v in s.violations do print(v.message) end

textureMemory( ) →

What the GPU texture cache holds, split by whether the texture is block-compressed. `compressedBytes` and `uncompressedBytes` are what those textures cost in VRAM, measured from each texture's own format and mip chain — so a `.texture` whose settings name `format = "bc7"` appears in the compressed columns at a quarter of what the same image costs as RGBA8. `blockCompressionSupported` is whether this adapter can hold block-compressed textures at all; where it is false a BC7 payload is uploaded decoded and lands in the uncompressed columns instead, so the texture is present everywhere and compressed where the hardware allows it. Measured at the end of the last rendered frame. `streamableTextures` is how many of them retain the payload a texture budget re-uploads them from, and `streamSourceBytes` what those payloads occupy in system memory — bytes that are not VRAM.

examples

local tm = renderer.textureMemory()
print(("%d compressed textures hold %.1f MiB"):format(tm.compressedTextures, tm.compressedBytes / 1048576))

setTextureBudget(opts: TextureBudgetOpts) → TextureBudget

Bound the VRAM a world's textures occupy, by keeping only the mip levels the frame is actually sampling. Pass `{ megabytes = 256 }`; `0` — the default — leaves texture residency alone and every texture stays fully resident the way it uploaded. With a budget armed, each frame measures how many pixels the largest surface wearing a texture covers and asks for the mip level that serves it one texel per pixel. The textures whose surfaces cover the fewest pixels give up levels until the set fits. Detail climbs one level per frame, from the image already on screen, so a surface the camera approaches sharpens rather than popping, and no texture is taken below the level whose longest side is 64 texels. `bias` shifts every measurement by whole mip levels — negative asks for finer detail than the surface's screen footprint implies, which is what a material that tiles its texture across a surface needs. The plan moves a texture whose demand the frame can measure: one at least 256 texels on its narrowest side, worn by a surface an entity draws. A texture a UI image, a post-process property or a render feature holds a view of stays whole, because nothing measures how much of the screen those cover. A texture already resident when the budget is armed keeps no payload to be re-uploaded from and stays where it is: setting `render.texture_budget_mb` in the world settings, which is read before content loads, is what puts a whole world's textures under streaming. Disarming returns every texture to the level it uploaded at and keeps those payloads, so arming the budget again governs the same set.

argtypedescription
optsTextureBudgetOpts`{ megabytes: number?, bias: number? }`

examples

renderer.setTextureBudget({ megabytes = 128 })
renderer.setTextureBudget({ megabytes = 128, bias = -1 })  -- a tiled material wants finer mips
renderer.setTextureBudget({ megabytes = 0 })               -- leave residency alone

textureStreaming( ) → TextureStreaming

What the last frame's texture-residency plan decided. `budgetBytes` is the armed budget, and `0` means residency is left alone. `streamable` is how many textures the plan can move. `residentBytes` is what those textures occupy now, measured from the textures that are allocated; `demandedBytes` is what the frame's demand alone would have cost, so the two part exactly where the budget is doing something. `starved` counts the textures left coarser than the frame asked for, `promoted` the ones that climbed a level this frame, and `changed` the ones whose GPU texture was replaced. A camera approaching a surface reads `promoted` above zero for a few frames and then zero once it settles. With `budgetBytes` at 0 nothing holds a level back, so `residentBytes`, `plannedBytes` and `demandedBytes` all read the whole chain of every texture still carrying a payload — which is how a session that armed a budget and dropped it reads back that the levels came home.

examples

local ts = renderer.textureStreaming()
print(("textures: %.1f MiB resident of %.1f MiB demanded, %d starved"):format(
ts.residentBytes / 1048576, ts.demandedBytes / 1048576, ts.starved))

setShadowCaching(enabled: boolean) → void

Whether a shadow map that nothing changed is kept rather than drawn again. On by default: a shadow view — one directional cascade, one atlas layer of spot tiles, one point light's cube — is rasterized on the frames its own inputs change and holds the depth it drew on the ones they do not. Off, every view is drawn on every pass, which is what a shadow suspected of holding a stale image is compared against.

argtypedescription
enabledboolean`boolean`

examples

renderer.setShadowCaching(false)  -- draw every shadow view, every frame

shadowCaching( ) → boolean

Whether a shadow view may keep the depth it already holds.

setShadowCasterBatching(enabled: boolean) → void

Whether a shadow view draws every caster of one mesh together. On by default: a view — one directional cascade, one atlas layer of spot tiles, one point light's cube — submits one draw per geometry over every caster of it the view admits, wherever those casters sit in render order and whatever transform slots they hold. Off, a view draws the runs of render-order neighbours that share a mesh AND hold consecutive slots, so a scene that has spawned and despawned anything fragments into many more draws. The image is the same either way, which is what makes this the comparison a shadow suspected of being placed by the batching is made against.

argtypedescription
enabledboolean`boolean`

examples

renderer.setShadowCasterBatching(false)  -- draw the runs the scene presents

shadowCasterBatching( ) → boolean

Whether a shadow view draws every caster of one mesh together.

setSkinnedBatching(enabled: boolean) → void

Whether skinned instances holding one pose draw together. On by default: instances of one mesh wearing one material and posed alike read the same post-skinned vertices, so the camera's colour passes submit them as a single instanced draw, and so does each shadow view and the velocity pass while `renderer.shadowCasterBatching()` is on — that switch is what makes a depth view form its draws by geometry at all. The camera depth pre-pass submits its casters nearest-first, which is a run per span of neighbours rather than a draw per geometry, so a crowd costs a draw per member there. Off, each skinned instance draws on its own at its own slot in every pass that rasterizes it. The image is the same either way, which is what makes this the comparison a frame suspected of being formed by the batching is made against — `renderer.drawStats().draws` counts the difference and `renderer.skinningStats().poses` says how many distinct poses it holds.

argtypedescription
enabledboolean`boolean`

examples

renderer.setSkinnedBatching(false)  -- a draw per skinned instance

skinnedBatching( ) → boolean

Whether skinned instances holding one pose draw together.

setBlendedBatching(enabled: boolean) → void

Whether neighbours in a view's back-to-front blended order draw together. On by default: alpha-blended geometry is submitted farthest-first, and a stretch of neighbours in that order sharing a mesh, a material, a shader and a pose is submitted as one instanced draw over those neighbours, which puts the same members on screen in the same order out of a single submission. A run stops wherever a differently-drawn renderable sorts between two of its members, and a mesh of several primitives keeps a draw per renderable — both would otherwise move fragments through each other. Off, every blended renderable draws on its own at its own slot, so a transparent crowd costs a draw per member. The image is the same either way, which is what makes this the comparison a frame suspected of being formed by the batching is made against; `renderer.drawStats().draws` counts the difference.

argtypedescription
enabledboolean`boolean`

examples

renderer.setBlendedBatching(false)  -- a draw per blended renderable

blendedBatching( ) → boolean

Whether blended neighbours sharing a draw key draw together.

setSkinningPoseHold(enabled: boolean) → void

Whether a pose the skinning pass already wrote is read as it stands. On by default: the pass produces an instance's vertices from its joint matrices, its node transforms, its blend weight and its blend model, so the slice holding a pose already holds what running the pass over those same inputs would write. A frame binding a pose whose slice still holds it reads the slice and dispatches nothing, and skinning costs what the frame's poses CHANGED — a paused clip, a skeleton nothing drives, a cast standing in one pose, each cost compute the frame the pose arrived and nothing after it. Off, every pose a frame binds is dispatched again, which is the comparison a frame suspected of reading a slice that no longer holds its pose is made against; the image is the same either way and `renderer.skinningStats()` counts the difference as `dispatches` against `held`. A mesh whose vertices a compute pass writes is dispatched every frame however this stands.

argtypedescription
enabledboolean`boolean`

examples

renderer.setSkinningPoseHold(false)  -- dispatch every pose, every frame

skinningPoseHold( ) → boolean

Whether a pose already written into its slice skips its dispatch.

shadowConfig( ) → ShadowConfig

The directional shadow quality now in force. `resolution` and `cascades` size the cascade depth array; `distance` and `splitLambda` place the splits along the view; `fadeFraction` and `softness` shape how the result is sampled.

examples

print(renderer.shadowConfig().cascades)

pointShadowBudget( ) → PointShadowBudget

The point-light shadow pool now in force. A point light with `castsShadows` renders an omnidirectional cube map, six faces of depth, and `slots` is how many of them fit — a further caster is lit but throws no shadow, and the engine log names how many were turned away. The slot count is bought rather than authored: `megabytes` of VRAM at `resolution` texels per face is what decides it.

examples

local p = renderer.pointShadowBudget()
print(("%d shadowed point lights, %.1f MiB"):format(p.slots, p.bytes / 1024 / 1024))

spotShadowBudget( ) → SpotShadowBudget

The spot and area-light shadow atlas now in force. Each shadow-casting spot is given a tile of it every frame, sized to what the camera can resolve: a light filling the view gets a whole layer at `resolution`, one far away gets a `minResolution` tile, and the atlas holds `tiles` of the smallest kind. That is what lets one budget serve a close hero light and a street of distant ones without either the memory or the sharpness being set for the worst case.

examples

local s = renderer.spotShadowBudget()
print(("%d layers of %d, %.1f MiB"):format(s.layers, s.resolution, s.bytes / 1024 / 1024))

shadowCasterCutoff( ) → ShadowCasterCutoff

How small, and how far away, a caster may get before it stops writing depth into any shadow view. A shadow view rasterizes a caster's whole triangle count whatever the shadow it produces ends up covering, so an object the viewer resolves a fraction of a pixel of, and one past the range the scene cares about, each cost a full depth pass per shadowed light for detail nothing reads. Both thresholds are 0 — released — until something sets them.

examples

local c = renderer.shadowCasterCutoff(); print(c.minRadiusPx, c.maxDistance)

setShadowProxy(mesh: string, proxy: string) → void

Rasterize `proxy` in place of `mesh` in every shadow view. A shadow is a silhouette resolved at the resolution of a shadow map, so the triangles that carry a mesh's close-up detail write depth no reader can resolve — a decimated version of the shape, a level of its own LOD chain, or a hand-built hull casts the same shadow for a fraction of the geometry. The registration is keyed by MESH, so one call covers every instance of it — entities and GPU-driven populations alike — and a crowd sharing that mesh stays one draw. The proxy is placed by whatever places the caster, its instance's own transforms, so it stands where the caster stands, at the caster's scale. An entity caster keeps its own geometry where a stand-in could not be placed or deformed correctly: it is skinned (it rasterizes the post-skinned vertices written for its own mesh), it blends morph targets (whose deltas describe its own mesh and are read by vertex id), or its proxy would be placed by a different node of its model than the source mesh is. Either caster keeps it where the renderer holds no geometry under the proxy's guid. Each of those is counted in `renderer.shadowProxies()`. Nothing else in the scene draws a proxy, so this call is what brings it onto the GPU, and it raises where it cannot. A proxy already resident there is registered as it stands.

argtypedescription
meshstringThe mesh a caster draws, as a guid or any mesh reference.
proxystringThe mesh it rasterizes into shadow views instead.

examples

renderer.setShadowProxy(statueMesh, statueHullMesh)
print(renderer.shadowProxies().triangles, "vs", renderer.shadowProxies().sourceTriangles)

clearShadowProxy(mesh: string?) → number

Stop proxying `mesh`, so it rasterizes its own geometry into shadow views again. Called with no argument, drops every registration.

argtypedescription
meshstring?The mesh to stop proxying. Omit to clear all of them.

examples

renderer.clearShadowProxy(statueMesh)
print(renderer.clearShadowProxy(), "proxies dropped")

shadowProxies( ) → ShadowProxyReport

The shadow proxies in force and what the last frame's shadow passes did with them. `triangles` and `sourceTriangles` are what those passes submitted and what they would have submitted from the source meshes — the before/after of every registration, equal while nothing is proxied.

examples

local p = renderer.shadowProxies()
print(("shadow triangles: %d of %d"):format(p.triangles, p.sourceTriangles))

setShadowHero(entity: string, padding: number?) → void

Give one caster a directional shadow view of its own, fit to its world bounds. A cascade covers the slab of world the camera sees, so its texels are spread over tens of metres and one character standing in the middle of it is resolved by a handful of them. The hero view is the same light and the same depth range zoomed onto that entity's bounds, so the whole map goes into the shadow it and the ground under it carry — `renderer.shadowHero().zoom` is the factor its texel density gains. It renders beside the cascades, into a layer of the same texture allocated while a hero is registered, and every surface inside it reads it in place of the cascade, crossing back at its edge. Nothing else about the shadow changes: the same casters reach it, at the same depth range, through the same filter. leaves the bind-pose box and for the filter that samples outside a silhouette. 1.0 fits them exactly.

argtypedescription
entitystringThe entity whose renderables the view is fit around.
paddingnumber?How much room the fit leaves around those bounds — for a pose that

examples

renderer.setShadowHero(player.id)
print(("hero shadow: %.1f texels/unit vs %.1f"):format(
renderer.shadowHero().texelsPerUnit, renderer.shadowHero().cascadeTexelsPerUnit))

clearShadowHero( ) → boolean

Release the hero caster, so the directional shadow is the cascades' alone again and the layer the hero view rendered into is given back.

examples

renderer.clearShadowHero()

shadowHero( ) → ShadowHeroReport

The registered hero caster and what the last frame's fit produced. A frame that fit nothing says why in `decline`.

examples

local h = renderer.shadowHero()
print(h.active, h.zoom, h.decline)

shaderVariants( ) →

Every shader that declares optional features, and the programs its materials have made it compile. Each row carries the features the shader declares, the base program it ships as, and one entry per variant with the features that variant holds — so the permutation count a scene's materials are spending is a number to read rather than something to infer from compile time. A shader whose variants reach `budget` compiles no more; the materials asking for further feature sets draw with the base program.

examples

for _, s in renderer.shaderVariants() do print(s.shader, #s.variants, s.budget) end

variantSource(program: string) → string

The WGSL one of the programs `renderer.shaderVariants()` lists holds, exactly as the shader compiler received it. `program` is the `program` field of a row's `base` or of one of its `variants`. Reading a base alongside a variant shows what a feature set selected: each program's text holds the code its own features guard.

argtypedescription
programstringA `program` name from `renderer.shaderVariants()`.

examples

local row = renderer.shaderVariants()[1]
local base = renderer.variantSource(row.base.program)

destroy(handle: any) → boolean

Free the GPU resource behind a renderer handle (the GPU-destroy verb). Routes by the handle's `category`, so one call releases a mixed set of handles. The on-disk asset, if any, is untouched. A CPU handle's `:unload()` frees the CPU copy separately.

argtypedescription
handleanyA `MeshHandle`, `TextureHandle`, `MaterialHandle` or feature handle.

examples

renderer.destroy(meshHandle); renderer.destroy(materialHandle)

set(id: string, min: any, max: any) → boolean

Publish the local-space box an entity's content-drawn geometry occupies. `entity:bounds()` and `entity:hierarchyBounds()` union it with whatever mesh geometry the entity has, each carried out of its own local space, so framing a camera on the entity frames what a feature actually draws.

argtypedescription
idstringEntity id.
minanyLocal-space minimum corner — a Vec3 table or a 3-element array.
maxanyLocal-space maximum corner, same shape as `min`.

examples

renderer.bounds.set(id, cloud.boundsMin, cloud.boundsMax)

axis(v: any, key: string, index: number) → number

argtypedescription
vany
keystring
indexnumber

clear(id: string) → boolean

Withdraw the box an entity published, so it stops contributing to the entity's reported extent.

argtypedescription
idstringEntity id.

examples

renderer.bounds.clear(id)

filteringSurface( ) → any

══ renderer texture filtering ════════════════════════════════════════ How many samples a material texture may take along the axis of greatest compression. Isotropic filtering picks one mip from the larger of the two screen-space derivatives, which is why a surface at a grazing angle — a road, a floor, a wall seen edge-on — blurs to a flat average well before the horizon. Anisotropy spends extra samples along that axis and keeps the detail that is in the texture. The scene-wide level is seeded from the `render.anisotropy` world setting; these are the runtime controls a quality slider drives.

setAnisotropy(level: number) → number

Set the maximum anisotropy material textures are sampled with. Takes effect on the next frame for content already on screen — no reload, no texture re-upload. 1 is plain trilinear. asking for more than the device offers reports what was actually applied.

argtypedescription
levelnumberOne of 1, 2, 4, 8, 16. Any other value is an error.

examples

renderer.setAnisotropy(16)

anisotropy( ) → number

The maximum anisotropy material textures are sampled with right now — the requested level clamped to what this device honours.

examples

if renderer.anisotropy() < 4 then ... end

maxAnisotropy( ) → number

The highest anisotropy this device honours: 16 on hardware that filters anisotropically, 1 on hardware that does not, where a higher request would be downgraded to trilinear regardless. Read it to report quality honestly — `renderer.setAnisotropy` clamps for you, so a request never needs guarding.

examples

local best = renderer.maxAnisotropy()

setProjectionOffset(x: number, y: number) → void

Offset the main camera's projection by a sub-pixel amount, in NDC, for the frames until it is set again. The offset is in NDC because that is the space it is constant in: one pixel is `2.0 / width` across, so half a pixel is `1.0 / width`. Velocity (`@scene.motion`) is measured against the offset-free projection, so a still scene reports no motion however the samples are placed — and picking resolves a click to the same ray either way. `(0, 0)` samples pixel centres.

argtypedescription
xnumberHorizontal offset in NDC. One pixel is `2.0 / width`.
ynumberVertical offset in NDC. One pixel is `2.0 / height`.

examples

renderer.setProjectionOffset(0.5 * 2 / w, -0.25 * 2 / h)

projectionOffset( ) →

The sub-pixel projection offset in force for the main camera, in NDC.

examples

local ox, oy = renderer.projectionOffset()
⌬ Types
Aabb = {MeshHandle = {InstancedDraw = {InstancedDrawInfo = {MeshCpuHandle = {MeshSkin = {MeshGeometry = {MeshBuffers = {ClusterComponents = {SplatComponents = {TextureHandle = {TextureCpuHandle = {TexturePixels = {MaterialHandle = {MaterialContent = {FramePacing = {PipelineCache = {RenderStateReport = {MaterialObservation = {DrawDiagnostic = {ShaderCost = {RenderObservation = {MaterialIdentity = {GpuMemoryLabel = {GpuMemoryAllocator = {GpuMemory = {ShadowConfig = {RenderTargetInfo = {PassScheduleViolation = {PassScheduleUnbound = {PassScheduleUnreachable = {PointShadowBudget = {TextureBudgetOpts = {TextureBudget = {TextureStreaming = {SpotShadowBudget = {ShadowCasterCutoff = {ShadowProxyEntry = {ShadowProxyReport = {ShadowHeroReport = {ShaderProgramInfo = {ShaderVariants = {

Sub-parts

Everything contained inside this part. Assets are composite children (clickable cards). Files are leaf payloads. Expand any row to view its source.

Showing up to 3 levels deep. Open a part to see what it holds further down.

84+items
▣
module · born here
❒asset
# renderer.holds The reads every renderer cell a hold pins answers the same way. A hold on a cell such as `renderer.temporal` (the per-frame clock) or `renderer.atmospherics` (the share of the air that reaches the image) names who took it and the key it was taken under, so a caller reads who holds the cell, an exclusive hold is refused for every other key, and a hold whose task ended is handed back. - `statedOwner(options)` answers the key `options.owner` states, or nil. - `actor()` answers the id and display name of the caller the call is attributed to. - `ownerLabel(owner, ownerName)` answers how a refusal names the holder. - `holderIsGone(holder)` answers whether the task that took a hold was cancelled or died; `holdingTask()` answers the task taking a hold now. ```luau local Holds = require("modules.api.engine.renderer.holds") assert(Holds.statedOwner({ owner = "shot" }) == "shot") assert(Holds.ownerLabel("abc", "Ada") == "Ada (abc)") assert(Holds.holderIsGone(nil) == false) ```
▲ 0↑ born
▣
module · born here
❒asset
# renderer.letGo The watch that releases a runtime texture, material, mesh or render feature mid-session once no script reaches a handle to it and nothing else holds it. It reads the renderer's handle sets every few dozen frames: a resource whose last handle the garbage collector took joins the watch and is judged against the runtime resource census, by the holders `renderer.collect` reads, and released once nothing holds it. A resource kept only by the component or scene load that created it stays while that owner does, and the log names an owner once it holds 64 of one kind that way, and again each time that count doubles. A render feature holds what it created through the handles it keeps and the passes it queues, which the census names as references, so a target whose handle the feature dropped and that none of its passes names any more is released while the feature stands. A texture or mesh the asset path uploaded under its asset's guid waits on the watch while that asset stands, and is judged from its holders once the asset index changes and the asset no longer answers. A texture a released material record named goes on the watch with it, the one the device holds for an asset included: that asset is the path the texture is read back by, so it is released once nothing else names it, the way a collection releases it. - `new(host)` makes the watch over the handle sets, census and release the renderer hands it in `host`, and answers `{ start, rejudge, letGo }`: `start()` starts the task that reads the sets unless it is running, `rejudge(kind, guid)` marks a watched resource due a judgement at the next reading, and `letGo(kind, guid)` puts a resource a holder other than a handle let go of on the watch.
▲ 0↑ born
▣
module · born here
❒asset
▲ 0↑ born
▣
module · born here
❒asset
# renderer.refs How `renderer.*` names a live resource. A runtime resource is filed under a v4 guid, minted from OS entropy or given by the caller; and each call that names a resource takes whatever the caller already holds (the key or guid, the handle `create` returned, the CPU handle `load` returned, or an `AssetRef`) and coerces it to the key the renderer's stores index it by. - `makeGuid()` mints a guid; `validateGuid(guid, what)` answers `guid` when it is a v4 guid and raises at the caller's line when it is not. - `materialKey(value, what)`, `meshKey(value, what)` and `textureKey(value, what)` answer the registry key or guid a value names, and raise a rejection that lists the accepted forms. - `refField(t, name)`, `declaredCategory(value)` and `shapeName(value)` read a ref-like table the way the coercions do. - `primaryBytes(ref)` answers an asset's primary content bytes, waiting for them under a coroutine when they are still on their way; `textureRefOf(value, what)` answers the ref a texture asset's content is read through. ```luau local Refs = require("modules.api.engine.renderer.refs") local guid = Refs.makeGuid() assert(Refs.validateGuid(guid, "example") == guid) assert(Refs.meshKey({ kind = "MeshHandle", category = "mesh", guid = guid }, "example") == guid) ```
▲ 0↑ born
▣
module · born here
❒asset
# renderer.shading The readings `renderer.shadingOf` builds out of the document the renderer publishes every frame. - `shadingSubject(value, what)` answers the id a shading question names: an entity proxy's id, an entity-id string, or the registry key of a material in any form a material answers to. - `publishedRenderable(doc, id)` answers the row that answers for a subject: the entity's own row, or a row drawing with the material, a fault wherever there is one. - `materialRow(doc, id)` answers the renderer's record for one material. - `shadingFault(state, means, row)` builds the fault reading a row carries. ```luau local Shading = require("modules.api.engine.renderer.shading") local doc = { renderables = { { entity = "e1", material = "m1", substituted = false } }, materials = {} } local row = Shading.publishedRenderable(doc, Shading.shadingSubject("e1", "example")) assert(row.material == "m1") ```
▲ 0↑ born
▣
module · born here
❒asset
# renderer.sources The `src` shapes `renderer.mesh.create` / `update` and `renderer.texture.create` / `update` take. - `classifyMesh(src)` answers which mesh src it is (`SRC_GPU`, `SRC_CPU`, `SRC_GEOMETRY` or `SRC_BUFFERS`), and raises for a src that is none of them or a geometry src whose indices address a vertex its positions do not carry. - `vertexRecordsToArrays(src)` turns geometry written as per-vertex records (`vertices = { { pos, normal?, uv?, uv1? }, ... }`) into the parallel flat arrays the upload takes. - `boundsFromPositions(positions)`, `vecToAabb(min, max)` and `ZERO_AABB` are the bounds a mesh is created with; `geometryCounts(src)` answers the vertex and index counts raw geometry implies. - `classifyTex(src)` answers which texture src it is (`TSRC_GPU`, `TSRC_CPU`, `TSRC_PIXELS` or `TSRC_TARGET`). ```luau local Sources = require("modules.api.engine.renderer.sources") local src = { positions = { 0, 0, 0, 1, 0, 0, 0, 1, 0 }, indices = { 0, 1, 2 } } assert(Sources.classifyMesh(src) == Sources.SRC_GEOMETRY) print(Sources.boundsFromPositions(src.positions).max.x) -- 1 ```
▲ 0↑ born
·
assettype · born here
❒asset
# Module (asset type) A module is a reusable, stateless (or globally-stateful) Luau library that other code pulls in with `require()`. Modules are the unit of factored-out logic in a world: helpers, math libraries, format parsers, registries, shared algorithms. ## When to use one - You have logic you want to share across multiple components, services, scenes, or tools. - You have a registry, lookup table, or shared cache that callers all read from / write to. - You want a stable API surface (`M.fn`) other code can depend on. If the logic is bound to one entity, use a `.component`. If you want a named UI of fields rather than functions, use a `.preset`. ## Where it lives - Source: `/zero/source/.../<name>.module/` - Identity: the source path with `/` written as `.` and each segment's type suffix dropped — `/zero/source/demo/beats.module` is `demo.beats`, and `/zero/source/kit.package/beats.module` is `kit.beats`, the container's name kept and its `.package` suffix gone. `asset.create` returns this string, `asset.resolve(...).identity` reads it back, and the `require` forms below write it as `<identity>`. - Folder shape: - `init.luau` (or `init.lua`) — module body. **Required.** Returns a table (conventionally named `M`). - `README.md` — instance-level documentation. **Required.** - `.metadata` — agent-editable tags + free-form fields. **Required.** ## How to create one ```luau asset.create("module", "<name>") -- Creates: /zero/source/<name>.module/ -- init.luau (canonical `local M = {} … return M`) -- README.md (instance README template) -- `folder` places it in a subfolder of /source, and that subfolder -- leads the identity: `{ folder = "lib" }` produces `lib.<name>`. -- `into` authors it inside a resolved container (a package, a toolbox), -- whose own identity leads the same way: asset.create("module", "<name>", { folder = "lib" }) asset.create("module", "<name>", { into = asset.resolve("myPkg.package") }) ``` ## How it operates 1. **Registration.** Writing `init.luau` into a `.module/` folder indexes the asset and registers the module path with the resolver. 2. **Loading.** The first `require("<identity>")` runs the file's body and caches the returned table. Subsequent requires from anywhere return the **same table** — this is the shared-state lever for "module-local" registries. The body runs in an environment of the module's own: a name it declares without `local` is readable by the module's own functions and by no other script, so an export reaches its callers through the returned table and nothing else. Requiring a component's folder runs its chunk the same way, once, and its `update`, `start` and `public` stay in that environment; a component runs on an entity through `entity(id).component.add(name)`. 3. **Hot reload.** Editing the file re-runs the module body and folds what it returns into the table already loaded, so that table keeps its identity: a caller that captured it with `require` reads the new source's functions and values through the reference it already holds, and a later `require` returns that same table. A key the new source drops goes away; a key something set at runtime stays. The body's own `local`s start again from their initial values, so state that must outlive an edit lives in `modules.state()` (`guides { path: "core/scripting-and-tasks" }`). 4. **Identity resolution.** A module is reached by its `<identity>`, and where the caller lives decides which spelling of it resolves. For a module in a **world**, from a caller in that same world — another module, a component, a scene entrypoint, or an `execute` chunk: - `require("<identity>")` — the identity on its own, resolved against the caller's own root. It carries every folder segment, so a module created with `{ folder = "demo" }` is `require("demo.beats")`. - `require("@root::<identity>")` — the same root-relative resolution, written out. - `require(".sibling")` — a module in the same folder, by its bare name; `..name` steps up one folder, `...name` two. Logs, stack traces and hot-reload notices name that same module `@local.source.<identity>` — its key under the world source root. The `<identity>` tail of that key is the form above, so a trace reading `@local.source.demo.beats` is `require("demo.beats")`. For a module in a **library** — content under `/zero/source/libs/@<lib>/` — `@<lib>::` addresses that library's root from anywhere: `require("@builtin::modules.transform")`. Mounting a world as a library moves its files under such a root and flips the caller root to `@<lib>::`, which is what keeps the root-relative forms above resolving across the move. ## Discovery - `asset.list("module")` — every registered module. - `asset.inspect("<name>")` — public functions, source path, this type README. - `ls /zero/source/<name>.module` lists the files the folder holds. ## Authoring conventions - Return a single `M` table from `init.luau`. Top-level statements with side effects run on first require — useful for one-time initialization, dangerous if they touch the engine before it's ready. - Write exported functions as `typed function`, not `function`: the argument types are enforced at the call and the checker knows the signature, so a caller's mistake is reported where they made it. - Annotate exported functions with `--!desc` / `--!arg` / `--!return` / `--!example` so the LSP, `tools.list`, and `asset.inspect` surface them. A function with no `--!desc` is reachable only by someone already reading this file. - Declare a VALUE with `Field.<kind>(default, mode, description)`, and a table whose members are reached through a metatable with `--!members <TypeName>` — the latter gives the surface its accepted member set, its type, and its documentation from one table. See `guides { path: "core/authoring" }` for all four rules and `modules/api/engine/entity.module/members.module` for a worked member table. - Keep module state in module-local upvalues or in `modules.state()`. A name the body declares without `local` lives in the module's environment, which every run of the module shares: a function the previous run left in place reads what the reload assigned. Module-locals start again from their initial values with each hot reload; the table `modules.state()` returns is the same table on both sides of every reload. - Prefer focused modules over kitchen-sink modules. If two halves of a module have no shared state, split them. ## Common pitfalls - **Cyclic requires.** A `require` chain that loops will return the partial table (the half built before the cycle was detected). Design for one-way dependencies. - **Engine-time side effects.** Don't `entity.spawn` at module top-level — the engine may not be ready. Expose an `M.init` and call it from a scene entrypoint. - **Hot-reload + module-local cache.** A module that caches expensive computation in upvalues loses that cache on reload — fine for dev, but be aware in performance work. - **`init.lua` vs `init.luau`.** Either works, `.luau` is canonical. - **Writing one while play runs.** A `/source` write made while play is running lands on the play shadow, and a guarded play-exit discards it unless it is kept. One `.module` write shadows `init.luau`, the `README.md` and the `.metadata` together. `vfs.write(path, bytes, { durable = true })` skips the shadow, and `vfs.promotePlayShadow` keeps what is already on it — the `core/vfs` guide has the model and what each route costs. ## Related types - `.component` — for entity-bound state + lifecycle hooks. - `.service` — generates content you don't have yet (a mesh, sound, texture, …) via a metered provider. - `.tool` — for a single agent-callable function with a YAML schema. - `.package` — to group several modules + components + scenes into one shippable folder. ## In the Inspector Exports: what the module exports (name, kind, signature), parsed from its source without running it, with **Check** (the LSP's diagnostics for its entry file) and **Open**.
▲ 0↑ born
▣
module · born here
❒asset
# material_records The material GPU records this session has released and nothing has filed again. A `.material` asset files its GPU record at its point of use — `matRef:handle()` — and memoises the handle it filed on the ref's runtime, so a second bind of the same material costs a table read where the first cost a parse and an upload. That memo names a record the renderer's registry holds, and `renderer.material.destroy` takes the record away while the asset and its memo stand. The asset is what files the next record, so it has to know which names that applies to. This set is that knowledge: a release puts the key in, filing a record under the key takes it out, and the point of use reads it for the cost of one table index. Written by `renderer.material.destroy` and `renderer.material.create`; read by the `.material` assetType's `handle()`. ## API ```luau local MaterialRecords = require("modules.material_records") -- A point of use holding a memo asks whether the record it names still stands. if MaterialRecords.released[identity] ~= nil then -- The record is gone: file another one, which takes the mark off. end MaterialRecords.noteReleased(key) -- the record under `key` has been released MaterialRecords.noteFiled(key) -- a record stands under `key` again ``` ## Lifetime The set lives in the session store, so it holds for as long as the GPU records it answers for: a VM reload leaves those records standing and leaves this standing with them, and both die with the engine process.
▲ 0↑ born
▣
module · born here
❒asset
# material_schema A shader's declared property vocabulary, and the routing of an authored key onto it. A material's properties belong to its **shader**. The uniform buffer is packed by reflected field name, so a key the shader does not declare is never read by anything: it sits in the material's property table, reads back as though it applied, and contributes nothing to the render. This module is the single place that answers "is this key real, is it a texture slot, or is it neither" — so every path that accepts material properties gives the same answer. Consumed by `material.assetType` (the `.material` asset path) and by `renderer.material.create` (the runtime GPU path). ## API ```luau local schema = require("modules.material_schema") local s = schema.forShader("pbr") -- nil when the shader can't resolve schema.route(s, "base_color", {1,0,0,1}) -- "property", "base_color" schema.route(s, "color", {1,0,0,1}) -- "property", "base_color" (alias) schema.route(s, "base_color_texture", tex) -- "texture", "base_color_texture" schema.route(s, "baseColor", {1,0,0,1}) -- "unknown", "baseColor" schema.declaredNamesList(s) -- "alpha_cutoff, anisotropy, …" schema.undeclaredMessage(name, key, "pbr", s) schema.acceptsSlot(s, "base_color_texture") -- true: the shader declares the slot schema.acceptsSlot(s, "base_color") -- false: a property, not a texture slot schema.declaredSlotsList(s) -- "base_color_texture, emissive_texture, …" schema.undeclaredSlotMessage(name, slot, "pbr", s) schema.isTextureSlotType("texture") -- true schema.isTextureSlotType("texture_array") -- true schema.isTextureSlotType("color") -- false ``` A `properties.yaml` entry of type `texture` or `texture_array` declares a texture slot; every other type except `buffer` declares a property. A texture reaches the bind group only through a slot the shader declares, since the material interface is generated from those slots. `renderer.material.create`, `renderer.material.setTexture` and a material asset's `setTexture` / `writeTexture` refuse any other slot through `acceptsSlot` and report it with `undeclaredSlotMessage`. A schema that holds no names at all (a shader whose vocabulary has not been read yet) accepts every slot. ## Routing order `route` applies the alias table first, then decides by surface: 1. **Alias** — `color` → `base_color`, but only when the shader declares the canonical name and *not* the alias, so a shader that genuinely exposes `color` keeps its own meaning. 2. **Texture** — the schema declares the name as a texture slot, *or* the value is itself a texture (handle / `AssetRef<texture>`). A texture stored as a uniform property reads back via `getProperty` but never reaches the bind group, so the value's own shape decides regardless of the key. 3. **Property** — the schema declares the name as a uniform property. 4. **Unknown** — neither. Nothing reads it; the caller warns with `undeclaredMessage` and drops it. ## When the shader can't be resolved `forShader` returns `nil` for a shader that is not registered yet (a runtime shader still compiling, a name that resolves later). Callers stay permissive in that case rather than reject every key against an empty vocabulary — the check applies where the vocabulary is actually known.
▲ 0↑ born
▣
module · born here
❒asset
# asset Module Public Luau surface over the `__asset` Internal FFI namespace — asset resolver, ref envelope builder, sidecar metadata. ## Purpose Wrap the raw `__asset.*` FFI namespace in a typed Luau table that gets auto-injected as `_G.asset` via the prelude. Three families: - **Lookup** — `resolve`, `ref`, `typeRef`, `inspect`, `source`, `identity`, `guid`, `meta`, `deps`. Every op accepts any name an asset has (handle, guid, identity, path, bare name) and returns the requested view. - **Discovery** — `categories`, `list`, `containing`. - **Generic `.metadata` sidecar** — `metadata`, `set_metadata`, field-level `get_field` / `set_field` / `remove_field` / `has_field`, tag helpers (`tags`, `has_tag`, `add_tag`, `remove_tag`), and `validate`. The previously-FFI `bundle.*` namespace was dissolved into the bundle assetType (see `src/lua/lib/assetTypes/bundle.assetType/`); that's not exposed here. The prelude mints `bundle` separately as a thin Luau table grafted from `bundle_update`. ## Usage ```luau -- Lookup local cam = asset.resolve("@builtin::components.Camera") local ref = asset.ref("animations.idle", "animation") print(asset.identity(cam), asset.guid(cam), asset.source(cam)) -- Discovery for _, c in ipairs(asset.categories()) do print(c) end for _, sceneRef in ipairs(asset.list("scene")) do print(sceneRef.identity) end local s = asset.containing("/zero/source/scenes/main.scene/scene.json") -- Metadata sidecar (agent-editable) asset.set_field(ref, "category", "movement") asset.add_tag(ref, "looping") print(asset.has_tag(ref, "looping")) -- Structural validation local v = asset.validate(cam) for _, p in ipairs(v.problems) do print(p.severity, p.message) end ``` ## Exports - Lookup: `resolve`, `ref`, `typeRef`, `inspect`, `source`, `identity`, `guid`, `meta`, `deps`. - Discovery: `categories`, `list`, `containing`. - `.metadata` sidecar: `metadata`, `set_metadata`, `get_field`, `set_field`, `remove_field`, `has_field`, `tags`, `has_tag`, `add_tag`, `remove_tag`, `list_fields`, `list_field_values`. - Validation: `validate`.
▲ 0↑ born
▣
module · born here
❒asset
# session Session-scoped key-value state. The store lives in the module's environment, which loads once per engine process, so values survive VM reloads (play flips, hot reloads) and die with the process. Use it for state whose lifetime must equal the session's runtime artifacts (GPU resources, runtime materials, bake outputs), which outlive a world save and would leave stale claims otherwise. ```lua local Session = require("modules.session") Session.set("my_system_" .. entityId, handle) local handle = Session.get("my_system_" .. entityId) ```
▲ 0↑ born
▣
module · born here
❒asset
# field Single-field component schema builder. Every `public.X` on a component declares its type, default value, and Sync/NoSync replication mode in one place via the `Field.<kind>(default, mode)` constructor that produces a `FieldDesc<T>` descriptor. The engine walks `public` at component registration, extracts each descriptor into the per-component asset-fields + sync registries, runs each asset default through the category-aware resolver, and replaces the descriptor with its unwrapped default so user code reads `public.X` as the value (not the descriptor). This module is exposed as the `Field`, `Sync`, and `NoSync` Luau globals via `--!global` directives. Component authors call `Field.<kind>` and `Sync` / `NoSync` directly without a `require`. `--!global-types` exports `SyncMode`, `FieldDesc<T>`, `AssetRef<C>`, `EntityRef`, and `ComponentRef<T>` to every typed source. ## Exports - `Field.number(default, mode, marker?) -> FieldDesc<number>` - `Field.range(min, max, default, mode, marker?) -> FieldDesc<number>` - `Field.integer(min, max, default, mode, marker?) -> FieldDesc<number>` - `Field.string(default, mode, marker?) -> FieldDesc<string>` - `Field.enum(values, default, mode, marker?) -> FieldDesc<string>` - `Field.bool(default, mode, marker?) -> FieldDesc<boolean>` - `Field.vec2(default, mode, marker?) -> FieldDesc<vec2>` - `Field.vec3(default, mode, marker?) -> FieldDesc<vec3>` - `Field.quat(default, mode, marker?) -> FieldDesc<quat>` - `Field.color(default, mode, marker?) -> FieldDesc<color>` - `Field.entityRef(default, mode, marker?) -> FieldDesc<EntityRef>` - `Field.assetRef<C>(category, default, mode, marker?) -> FieldDesc<AssetRef<C>>` - `Field.dataRef<C>(contract, default, mode, marker?) -> FieldDesc<AssetRef<"data">>` - `Field.componentRef<T>(componentType, default, mode, marker?) -> FieldDesc<ComponentRef<T>>` - `Field.table<T>(default, mode, marker?) -> FieldDesc<T>` - `Field.alias(target, description?) -> FieldDesc<any>` - `Sync` / `NoSync` — string singletons used as the replication-mode argument. Every constructor's trailing `marker` argument accepts the bare `Serialized` marker (unchanged meaning), a plain string read as the field's description, or a `FieldOptions` table carrying `serialized` and/or `description`. Types (global via `--!global-types`): - `SyncMode = "Sync" | "NoSync"` - `FieldOptions = { serialized: SerializedMode?, description: string? }` - `FieldDesc<T> = { __zero_field: boolean, kind: string, default: T?, sync: boolean, serialized: boolean?, description: string?, enforced: boolean, category: string?, componentType: string? }` - `AssetRef<C> = { __ref: string, type: C, name: string, guid: string, identity: string, path: string, primary: string? }` — the envelope `asset.resolve` / `asset.ref` / `asset.list` hand back. The category is in `type`; `primary` is the single content file the resolver found, which `getSource` reads, falling back to `path`. - `EntityRef` — the live entity proxy (`entity(id)` / `entity.spawn()` / `bundle:instantiate()` return it; carries `id`, `name`, `position`, `component`, …). An `entityRef` field accepts a proxy OR a raw id string on write and reads back a live proxy (`.id` for the string, `nil` if unset); the stored/serialised form is the plain id. - `ComponentRef<T> = { __ref: string, entity: string, componentType: T }` ## Usage ```luau -- Inside a `public` block on a component public = { positionX = Field.number(0, Sync), speed = Field.number(5, Sync, "Metres per second at full throttle."), enabled = Field.bool(true, Sync), material = Field.assetRef("material", "@my-library::materials.gold", Sync), source = Field.assetRef("bundle", nil, Sync), target = Field.entityRef(nil, Sync), aimCam = Field.componentRef("Camera", nil, NoSync), idMap = Field.table({} :: { [string]: string }, NoSync), } ``` ## Notes - `Sync` / `NoSync` is REQUIRED on every constructor. Passing `nil`, `true`, `false`, or anything else raises a load-time error so a multiplayer-by-default engine can't silently ship single-player components. - `Field.assetRef`'s `category` argument is inferred as a singleton string type (`C`). Cross-category assignment is therefore a type error: `AssetRef<"mesh">` does not unify with `AssetRef<"material">`. - `Field.componentRef`'s `componentType` argument works the same way — the engine validates the referent's component type at every write. - `Field.table<T>`: pin the shape by ascribing the default, `Field.table({} :: MyShape, NoSync)`. - A live component proxy held in a `Field.table` value, at any depth, is saved in the scene record as its reference: the `{ __ref, entity, componentType }` envelope `Field.componentRef` stores, so a component holding itself saves one envelope naming itself. - `Field.range` and `Field.enum` carry a `constraint` the engine checks on the field's default and on every write, through `field_constraints.module`. A value outside the declared interval or member set is refused with the interval or the whole set named, so what the field reads back is a value its consumer can use. - `Field.integer` carries the same `range` constraint with `whole = true`: a fraction is refused as well as a value outside the interval, for a count, a level or a group number, where a fraction would be read as some other whole number. - The engine resolves any string default for `assetRef` through `asset.resolve(identity, category)` at component registration, so the first read of `public.<field>` returns a resolved envelope, not a raw string. - `Field.dataRef` rides the same `assetRef` machinery (category `"data"`) plus a contract gate: every write (and the registration-time default) must resolve to a `.data` instance whose dataType contract chain includes `contract`, checked through the generic field-constraint hook. A rejected write raises and leaves the field's previous value unchanged. - Constrained fields (`Field.dataRef`) are top-level only — declaring one inside `Field.struct` / `Field.list` aborts component registration with an error. - `FieldDesc.enforced` is true exactly for the kinds that carry a `constraint` (`enum`, `range`, `bitmask`, `dataRef`, `taggedRef`, `instantiableRef`) — the field the `field_constraints` hook checks on every write and default. Every other kind reads `enforced = false`.
▲ 0↑ born
✦
shader · born here
❒asset
# pbr The engine's standard physically-based material — the full glTF metallic-roughness workflow lit by the shared `@builtin::shaderModules.pbr_shading` model. This is the default surface shader a model uses when its material doesn't specify another, and it is also registered under the legacy alias **`standard`** (the name many materials reference). It is a `surface()` shader: it fills a `PbrSurface` and the engine generates every pipeline entry point and lights it. Every parameter defaults to a neutral value, so a material that sets nothing renders as a clean dielectric; the advanced lobes only cost anything when a material opts into them. ## Properties | Property | Type | Default | Meaning | |---|---|---|---| | `base_color` | color | `[1,1,1,1]` | Albedo tint, multiplied by `base_color_texture` and vertex colour. | | `emissive` | color | `[0,0,0,1]` | Emissive tint, multiplied by `emissive_texture` and `emissive_intensity`. | | `emissive_intensity` | float | `1.0` | HDR multiplier on the emissive output. | | `roughness` | range | `0.5` | Perceptual roughness, multiplied by the green channel of `roughness_metallic_texture`. | | `metallic` | range | `0.0` | Metalness, multiplied by the blue channel of `roughness_metallic_texture`. | | `reflectance` | range | `0.5` | Dielectric reflectance knob (neutral 0.5 → 4% F0). | | `ior` | float | `1.5` | Index of refraction → dielectric F0 and the refraction direction. | | `normal_scale` | float | `1.0` | Strength of the tangent-space `normal_texture`. | | `occlusion_strength` | range | `1.0` | Blend of the `occlusion_texture` (R) into the ambient term. | | `clearcoat` | range | `0.0` | Strength of a second dielectric clearcoat specular lobe. | | `clearcoat_roughness` | range | `0.0` | Roughness of the clearcoat lobe. | | `anisotropy` | float | `0.0` | Anisotropic highlight stretch along the tangent ([-1,1]). | | `sheen_color` | color | `[0,0,0,1]` | Tint of the sheen lobe — the retroreflective rim of velvet, satin and brushed fabric. Black leaves the base untouched. | | `sheen_roughness` | range | `0.3` | Width of the sheen lobe. | | `iridescence` | range | `0.0` | Blend toward the thin-film response, the hue that shifts with view angle. | | `iridescence_thickness` | float | `400.0` | Film thickness in nanometres — which wavelengths cancel and which reinforce. | | `iridescence_ior` | float | `1.3` | Index of refraction of the film. | | `subsurface_color` | color | `[0,0,0,1]` | Tint of the light that entered the surface, scattered beneath it and left again. Black leaves the base untouched. | | `subsurface_radius` | float | `0.5` | How far the diffuse falloff wraps past the terminator, taken per channel against `subsurface_color`. | | `fibre_color` | color | `[0,0,0,1]` | Tint of the second of the two highlights a hair or fur strand gives. Black leaves the base untouched. | | `fibre_specular` | range | `0.35` | Strength of the first strand highlight, in the light's own colour. | | `fibre_shift` | float | `0.06` | How far apart the two strand highlights sit along the fibre. | | `fibre_roughness` | range | `0.1` | Width of the first strand highlight. | | `transmission` | range | `0.0` | Specular transmission — refracts the environment through the surface. | | `thickness` | float | `0.0` | Volume thickness for Beer–Lambert transmission absorption. | | `attenuation_color` | color | `[1,1,1,1]` | Transmission absorption tint. | | `attenuation_distance` | float | large | Beer–Lambert absorption distance. | | `uv_scale` | float2 | `[1,1]` | UV tiling applied before every texture sample. | | `uv_offset` | float2 | `[0,0]` | UV offset applied before every texture sample. | | `alpha_cutoff` | range | `0.0` | Mask threshold — fragments with `alpha <` this are discarded (0 = no cutoff). | | `double_sided` | bool | `false` | Flip the shading normal on back faces. | | `receives_fog` | bool | `true` | Whether the screen-space fog passes (height fog, aerial perspective) reach this surface. `false` leaves an opaque deferred draw at the colour it shaded to, however deep in the medium it stands — see below. | | `instance_color_lane` | float | `-1` | Which of the instance's four shader-data lanes colours it (rgb colour, a coverage). `-1` reads none. See below. | | `instance_emission` | float | `0` | How brightly the lane colour glows where it covers. | ### Emissive authoring The glow output is `emissive × emissive_intensity` (× the `emissive_texture`). The glow **colour** is `emissive`, a vec; the **intensity** over it is `emissive_intensity`, a scalar. So `{ emissive = {0.1, 0.9, 1, 1}, emissive_intensity = 5 }` is a cyan glow at 5×, and it is these two names that `getProperties()` lists and `setProperty` writes. A spelling another engine's convention uses for the same role — `emissive_color`, `emission`, `emissive_tint` — is resolved onto `emissive` when the material is authored, so content carried in from glTF, Unity or Godot reaches the property under the name this shader declares. Where two such spellings meet on one of the two names, the shape of each value says which of them it is: a vec is the colour and a number is the intensity, so `{ emissive_color = {0.2, 0.8, 1, 1}, emissive = 5 }` is the same cyan glow at 5x. Two values of one shape are one property's, and the one written under the name the shader declares applies while the other is named in a warning. A bare positive scalar `emissive` with no colour beside it is the "turn emission on" shorthand and means a white glow at that intensity, so `emissive = 20` on a white material lights up. ### The lobes over the base layer Beyond metallic-roughness, the shading model carries six layers this material declares. Each is gated on its own neutral value, so a material that sets none of them shades as a plain dielectric and each one costs only where it is asked for. | Layer | Turned on by | What it looks like | |---|---|---| | Clearcoat | `clearcoat > 0` | A second dielectric specular lobe on top — car paint, lacquer, a varnished surface. | | Anisotropy | `anisotropy ~= 0` | The highlight stretches along the tangent — brushed metal, a vinyl record. | | Sheen | `sheen_color` above black | A retroreflective rim that brightens toward grazing angles — velvet, satin, dusty cloth. | | Iridescence | `iridescence > 0` | The specular hue shifts with view angle — an oil slick, a soap film, anodised metal, a beetle shell. Thickness picks the colours. | | Subsurface | `subsurface_color` above black | Light wraps past the terminator and glows through thin geometry lit from behind — skin, wax, marble, a leaf. `thickness` gates how much reaches the far side. | | Fibre | `fibre_color` above black | The two offset highlights a strand gives instead of the one a surface gives — hair, fur. Taken around the world tangent as the fibre axis. | All six are evaluated inside the engine's own light loop, once for every light that reaches the surface, so each one is shadowed, attenuated and cone-masked with the base layer it sits over. Each layer, and specular transmission beside them, is a shader feature its gating property switches on (`features:` in `properties.yaml`: `PBR_CLEARCOAT`, `PBR_ANISOTROPY`, `PBR_SHEEN`, `PBR_IRIDESCENCE`, `PBR_SUBSURFACE`, `PBR_FIBRE`, `PBR_TRANSMISSION`; the per-instance colour below is `PBR_INSTANCE_COLOR`). A material that sets the property away from its neutral value draws a program holding that layer; one that leaves every layer at rest draws a program holding none of them, so the default material pays only for the metallic-roughness model it shades as. Setting a property with `renderer.material.setProperty` moves the material between the two programs, and `renderer.shaderVariants()` lists the ones a scene has asked for. An oil-slicked wet surface is `iridescence = 1`, an `iridescence_thickness` around 300-500 nm and a low `roughness` over a dark `base_color`. Skin is a warm `subsurface_color` with a `subsurface_radius` near 0.5. Velvet is a `sheen_color` at the fabric's own hue over a dark base. ### Standing outside the fog `receives_fog = 0` declares that the screen-space fog passes — `heightFog` and `aerialPerspective` in `@builtin::systems.atmosphere` — leave this surface at the colour it shaded to. The declaration travels to those passes as a per-pixel surface flag written into the alpha of the G-buffer normal (`@builtin::shaderModules.surface_flags`). Only the deferred G-buffer fragment entry writes that channel, so the declaration reaches the fog from an **opaque** draw on the **deferred** path. A draw the renderer sends through the forward fragment entry — every draw on the forward path, and the transparent phase on either path — writes no G-buffer channel to carry it, and its pixels take the fog like any other. ### Per-instance colour `instance_color_lane` names one of the four shader-data lanes every drawn instance carries (`renderer.instanceData.set` for an entity, the `instanceDataBuffer` of `renderer.mesh.drawInstanced` for a population). The lane's `rgb` is this instance's colour and its `a` is how much of it covers the material's own base colour and emission, 0 none through 1 all, so one material draws every member of a structure, a crowd or a population in a colour of its own: a stress map, a heat map, damage tints, team colours, a selection highlight. A lane never written reads zero and leaves the material's own look. ```luau local mat = renderer.material.create({ shader = "@builtin::shaders.pbr", properties = { instance_color_lane = 2, roughness = 0.6 } }, "beams") beam.component.add("Model", { model = "cube", material = mat }) -- the handle renderer.instanceData.set(beam, 2, 1, 0.2, 0, 1) -- this beam orange-red ``` The colour replaces the base colour before lighting, so the surface still shades and the `albedo` capture pass reads the lane colour. `instance_emission` adds the lane colour as emission where it covers. Lanes 0 and 1 carry a baked lightmap's rect and layer, so a lit material takes lane 2 or 3. The read is the `PBR_INSTANCE_COLOR` feature, so a material that leaves `instance_color_lane` at `-1` draws a program without it. `@builtin::materials.instance_color` is this material ready made, reading lane 2. A write is local to the engine that makes it and replicates nothing, which is what makes it cheap enough to recolour hundreds of members every frame; `Model.tint` is the synced tint every participant sees. ## Textures (glTF metallic-roughness set) | Slot | Default | Channels | |---|---|---| | `base_color_texture` | white | RGBA albedo (sRGB). | | `roughness_metallic_texture` | white | G = roughness, B = metallic (glTF packing). | | `emissive_texture` | white | RGB emissive (sRGB). | | `normal_texture` | flat-normal | Tangent-space normal map. | | `occlusion_texture` | white | R = ambient occlusion. | A program samples the maps its material binds and no other. Each slot is a shader feature switched on by the material binding a texture there (`PBR_BASE_COLOR_MAP`, `PBR_ROUGHNESS_METALLIC_MAP`, `PBR_NORMAL_MAP`, `PBR_EMISSIVE_MAP`, `PBR_OCCLUSION_MAP`): a slot left unbound, or bound to its own default (`default:white`, `default:normal`), reads as the value that default stands for, times the slot's factor, with no texture sample, and an unbound normal map leaves the geometric normal exactly as it is. A solid-colour material takes no texture sample at all. A material binding one image as both `roughness_metallic_texture` and `occlusion_texture` (glTF's packed occlusion-roughness-metallic image) draws `PBR_OCCLUSION_IN_ROUGHNESS_METALLIC`, which reads occlusion from the R of the metallic-roughness texel and samples the image once. Because the engine holds the full `PbrSurface`, the capture tool's debug passes (albedo / roughness / metallic / AO / emissive / world-normal / shadow / depth / motion) all read real material data.
▲ 0↑ born
▣
module · born here
❒asset
# vfs_async_read Pure-Luau wrapper that grafts a yielding `vfs.read` over the engine's sync `vfs.read` binding. The `vfs` API module (`modules/api/engine/vfs`) calls `M.installInto(vfs)` on itself as it loads, so every VM holding `vfs` (user VMs and the trusted VM alike) reads through it; user code never requires this module directly: it just calls `vfs.read(path)` and the wrapper handles cache misses by yielding the running coroutine until the bytes resolve. ## Exports - `M.installInto(vfs: VfsNamespace)`: replace `vfs.read` (and `vfs.readBounded` and `vfs.list`) with the yielding wrapper. No-op when the target lacks `read` and `readAsync` as functions. - `M.CANNOT_WAIT`: `"VFS_READ_CANNOT_WAIT"`, the code a read raises when it names a known file whose bytes have not arrived and the reading code cannot yield. Types: - `VfsNamespace = { read?, readAsync?, readBounded?, list? }`: the engine's `vfs` global shape. ## Usage ```luau -- The `vfs` API module installs the wrapper onto itself as it loads: require("@builtin::modules.vfs_async_read").installInto(vfs) -- After install, every `vfs.read` call yields on cache miss, and a read -- that finds no bytes answers nil and the reason: local bytes, why = vfs.read("/zero/source/some.asset") ``` ## Where a read can wait - On a miss the wrapper schedules `vfs.readAsync(path, opts)`, which fires `BlobProvider::fetch` under the hood, and `task.await`s the promise. A wait that resolves without bytes answers nil and the reason: the sentence the engine's read gave beside its nil, or, for bytes that were on their way, the one it gives once the wait ends. - Waiting takes a yield, so it happens where `coroutine.isyieldable()` is true: a task, the component hooks the engine runs on a coroutine (`awake`, `start`, `update`, `fixedUpdate`, `onEnable`, `onOwnerChanged`, `onSyncReceived`), a replicated event's handlers, and a world or scene entrypoint's hooks. - Where it is false (`onDisable`, `onDestroy`, `onPropertyChanged`, a received synced-function call, a `vfs.watch` callback, a module's top level while `require` runs it, a metamethod, a `table.sort` comparator, a VM's main thread) a miss the engine's read answers `nil, "pending"` for (a file `vfs.exists` knows that is no directory and whose bytes can still arrive, a render surface being captured, a `/runtime/sync` node whose current reading the next frame assembles) raises `VFS_READ_CANNOT_WAIT: vfs.read("<path>") ...`, naming the path and the places it can be read from. Every other miss answers nil and the reason there as everywhere else. - `vfs.list` answers a directory whose current listing the next frame assembles (a `/runtime/sync` directory nothing has read lately) after waiting that frame where the code can yield, and raises `VFS_READ_CANNOT_WAIT: vfs.list("<path>") ...` where it cannot. - `installInto` is idempotent in the trivial sense: calling it twice re-wraps `vfs.read` around the already-wrapped function, which is fine but pointless.
▲ 0↑ born
▣
module · born here
❒asset
# texture_ref The GPU key a material's texture slot binds by, resolved from whatever form the author wrote it in. The renderer binds a texture slot by **exact GPU-cache key**, and that key is the guid an upload lands under. A reference in any other form — an asset identity (`wall.texture`), a bare name, a `.texture` path, the image path a texture was imported from — names a real texture the cache has never heard of. Bound as written it leaves the slot on the shader's declared fallback: white for a `base_color_texture`, black for a sky panorama. The material then renders as though nothing was bound, and nothing distinguishes that from a texture the author meant to be dark. This module is the single place that answers "what key does this reference bind by", so the same string binds the same texture wherever it is written. Consumed by `material.assetType` (the `.material` asset path), `renderer.material.create`, and `renderer.material.setTexture`. ## API ```luau local TextureRef = require("modules.texture_ref") TextureRef.resolve("wall.texture") -- "9f2c…", "asset" TextureRef.resolve("9f2c…") -- "9f2c…", "asset" (idempotent) TextureRef.resolve("/source/sky/pano.png") -- "f181…", "asset" (→ pano.texture) TextureRef.resolve("color:1,0,0,1") -- unchanged, "procedural" TextureRef.resolve("video_0") -- unchanged, "live" TextureRef.resolve("nothing_here") -- unchanged, "unresolved" TextureRef.isProcedural("default:white") -- true TextureRef.unresolvedMessage(ref, "renderer.material.setTexture") ``` `resolve` also **materialises** the texture (Disk→CPU→GPU via `texRef:handle()`) — the guid only becomes a cache key once the upload has landed. ## Resolution order 1. **Procedural** — `color:` / `default:` / `runtime:`. The GPU texture cache produces these itself, so they pass through untouched. 2. **The reference itself** — a guid, an asset identity, a bare name, or a `.texture` path, resolved through `asset.resolve(ref, "texture")`. 3. **The imported container** — when the reference is a loose raster path (`png` / `jpg` / `jpeg` / `webp`), the sibling `<stem>.texture` the texture importer promotes it into. The importer *removes* the loose original, so the path an author copied out of an import log names a file that no longer exists; this step follows the image to where its texture actually went. 4. **The alternate identity** — a slot's stable identity, passed by the `.material` path so a binding whose guid was orphaned by a delete + recreate still finds the texture the author named. 5. **A resident GPU key** — a live texture with no asset behind it: a video frame (`video_0`), a rasterised text texture, a render target. Binds exactly as written. Anything left is `"unresolved"`. The reference is still returned unchanged — a texture that lands later is picked up by the renderer's own pending retry — but the caller has the outcome and reports it with `unresolvedMessage` instead of letting the slot fall back in silence.
▲ 0↑ born
✦
shader · born here
❒asset
▲ 0↑ born
·
assettype · born here
❒asset
# assetType (asset type) An asset type says what a kind of asset is: the files an asset of the kind is made of, the code that gives it behaviour, the interface a person uses to work with it, and how it is found, pictured and checked. A `<typename>.assetType/` folder declares a type called `<typename>`, and every `<name>.<typename>/` folder is an asset of it. `assetType` is itself a type, so a type is an asset like any other: it is created, versioned, installed and contributed the same way. ## Making a type `asset.create("assetType", "<typename>")` scaffolds a type. The type registers the moment its folder is written, anywhere under `/zero/source/`, and from then on `<name>.<typename>/` folders are its assets. An asset of a type that is not registered yet is not an asset, so make the type first. A type folder is a root: `~.x` in any file inside it names the type's own `x`, wherever the type is installed. Keep the type's whole implementation inside its folder and reach it that way. What a type folder must hold is set by this type's own `type.yaml`, the same way every type's `type.yaml` sets what its assets hold. `asset.validate` on a type reports anything missing, and the scaffold produces a folder that passes. ## What sets your type's schema (`type.yaml`) `type.yaml` is the structural contract every asset of the type is checked against. The keys below are the ones the engine reads; a key not listed here is ignored. | Key | What it controls | |---|---| | `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. | | `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. | | `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. | | `is_container` | Whether the suffix stays in the identities of what the asset holds. | | `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. | | `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. | | `is_text_default` | Whether the asset's files are text unless stated otherwise. | | `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. | | `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. | | `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. | | `files: { required, optional }` | The files an asset holds (below). | | `allow_unlisted` | `false` reports every file the type does not declare. | | `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. | | `settings:` | Typed per-asset settings (below). | | `inspector:` | The interface people use for the type and its assets (below). | | `preview:` | How an asset is pictured (below). | | `references:` | Names of other assets the type's files carry (below). | | `indexing:` | What search reads for each asset (below). | | `describe:` | How a missing description is generated (below). | ### The files an asset holds Each entry under `files.required` or `files.optional` is `{ path, kind: file | folder, one_of_group?, content? }`. `*` in a path matches within one segment. Entries that share a `one_of_group` are satisfied by any one of them. `content` lists checks on the file's bytes: | Check | Passes when | |---|---| | `non_empty` | the file has content | | `json_field { key, type?, non_empty?, accept? }` | the JSON holds the key (a dotted path) with that shape | | `yaml_field { key, type?, non_empty?, accept? }` | the same for YAML | | `described { keys?, headings?, message? }` | the file says what the asset is (see "Ask your assets to say what they are") | Each check takes a `message`, which is what the author is told when it fails. ### Settings `settings: { values, schema: { type | instance, export? } }` gives every asset typed settings. `values` names the file an asset's values live in; `schema.type` declares one schema for the whole type, and `schema.instance` names a file each asset declares its own in. `asset.create` writes the resolved values, and a write to the values file reaches `onChange` with what changed. ## The human side (`inspector.luau`) A type is used by people through its Inspector, and without one the type is usable only from code. The Inspector is the type's interface for a person: for a procedural graph it is the graph editor, for a kit it is the tracking view of what the kit holds and what is still missing. Writing it is part of writing the type. `inspector: { type, instance? }` in `type.yaml` names the files. `type` is the interface for the type itself and for its assets; `instance` names a file an asset may ship to add its own. Each returns: ```luau return { sections = { { id = "graph", title = "Graph", build = function(ctx) ... end } }, replace = { contents = { ... } }, -- replace a default section by id order = { "graph", "contents" }, -- section order } ``` `build(ctx)` receives the asset and builds the section. A section's `title`, and the text its rows carry, is a string or an `i18n.text` value read from a catalog (`i18n.text("inspectors.mesh.title")`), which follows the editor's language. `asset.create("assetType", ...)` scaffolds a working `inspector.luau` to start from. `asset.validate` on a type that names no inspector, or names one that does not load, reports it. ## Say what your type is for (`about.yaml`) Every type carries an `about.yaml` that says what the type is for, in three plain-language texts: ```yaml intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering." function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text." usage: "You choose it by name for your UI or your text, and the text appears in that typeface." ``` - **`intent`** is what the type is for in someone's game, in the words a game maker uses. Up to 800 bytes. - **`function`** is how it works today: what an asset of it is made of and what the engine does with it. Up to 1500 bytes. - **`usage`** is what a person or an agent does with one. Up to 1200 bytes. Write about the type as a whole, not one asset of it, and say what it does now. Agents read these texts to learn when to reach for the type and how; people searching find the type by them. The scaffold starts each text with `[[describe]]` and a note on what to write; a text that still starts that way counts as not written. `services describe` can write them. They show up in `asset.inspect` as `detail.about`, in `assetTypeRef:getAbout()`, at the end of the type's `types/<typename>` guide, and at the top of the type's Inspector. ## Ask your assets to say what they are A type can require each asset to carry a description: a file, written by the author or generated, saying what the asset is and what it is for. Declare it with a `described` check: ```yaml files: required: - path: "README.md" kind: "file" content: - { check: "described", message: "Say what this widget is for and where it goes." } ``` A file that is missing, empty or still has a line starting with `[[describe]]` fails the check, and so does a YAML file whose named `keys` are missing or over their `max_bytes`, or a Markdown file missing a named heading. `asset.validate` names the asset, and a push that carries it is refused with `message`. `services describe` finds such assets and writes their descriptions. `describe:` steers what is generated: ```yaml describe: guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI." examples: - "<identity of an asset of this type whose description reads well>" ``` An example is an asset of your type whose description is a true, written one, never a placeholder and never the asset being described; with none, leave `examples` empty. A type whose assets the model cannot perceive (a sound, a motion) says so in `guidance`, and the description is drawn only from what the asset's own files state. Start the file unwritten in your `template/`: a heading and one line starting with `[[describe]]`, never example content, which every new asset would carry verbatim. A type whose assets say what they are through their own content (a mesh, a texture) declares no check. ## The type's code (`behavior.luau`) `behavior.luau` returns one table. These are the keys the engine reads from it; anything else on the table is the type's own. ### What the type's assets can do | Key | Shape | What the engine does with it | |---|---|---| | `ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every asset of the type: `ref:name(...)`. | | `modules` | `{ [name] = require(".x") }` | Code the type's assets reach with `asset.containing(__FILE__).modules.<name>`. | | `events` | an events schema | Events an asset fires. Readers subscribe through `ref.events.<name>:connect(...)`; the type fires them. | | `refShapes` | `{ [method] = function(self) -> (typeExpr, source?) }` | The result type of a `ref` method for one particular asset (below). | | `namePattern` | a Lua pattern | The names `asset.create` accepts for the type's assets. Default `^[A-Za-z][A-Za-z0-9_]*$`. | | `derive` | `{ output, module, compute, fingerprint, matches?, required?, timeout? }` | A file computed from the asset when it is committed; a `required` one holds the commit until it lands. | Some `ref` names mean the same for every type, and the engine calls them: - **`instantiate(self, target?, opts?) -> (root, idMap)`**: puts the asset in a scene. Defining it is what makes the type scene-instantiable. Its return is a contract (below). - **`inspect(self) -> detail`**: what `asset.inspect` reports for the asset beyond the common record (below). - **`preview(self, opts)`**: renders the asset's picture; it wins over the type's `preview:` recipe. - **`previewMaterial(self) -> { material }`**: the material a `surface` preview paints. - **`saveDefinition(self)`**: writes the asset's in-memory edits back to its files in edit mode. Some names are answered for every asset before the type is asked, so a `ref` entry of the same name is never reached: `getSource`, `getBytes`, `getText`, `exists`, `deps`, `canInstantiate`, `canPreview`, `preview` (which calls yours when you define one), `meta`, `runtime`, `events`, `typeRef`, `modules`, and the residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`, `gpu_resident`. ### When the engine calls the type | Hook | Signature | When it runs | |---|---|---| | `onCreate` | `(name, opts) -> { [path] = contents }` | On `asset.create`. Returns the files of the new asset, laid over the type's `template/`. Annotate `opts`: its type is the schema `asset.create` checks the caller's arguments against. A `""` key writes a single loose file. | | `onReplace` | `(dest, files) -> files` | On an `asset.create` over an asset already at `dest`, after `onCreate`, so what the author added can be carried into the replacement. | | `onRegister` | `(self)` | Once per asset, when it first registers: when the world loads, on a live `asset.create`, and when an asset arrives later (installed, pulled, synced). This is what makes an asset take effect the moment it is written. | | `onChange` | `(ref, change)` | On every write to a file inside an asset of the type. `change` is `{ path, asset, type, kind, origin }`, plus `settings` and `settingsChanged` for a write to the settings values file; `kind` is `edited` or `seeded`, `origin` is `local` or `remote`. Filter on `change.path`. Writes to one asset arrive in order, each after the hook for the one before has finished, and the hook may wait on what it reads. A write the hook makes inside its own asset arrives later like any other, so keep the hook convergent. | | `onDependencyChange` | `(ref, change)` | When a module the asset's code requires is re-run, or a name the asset carries starts resolving. `change.kind` is `dependency`. | | `onDelete` | `(ref)` | When an asset of the type leaves the world: deleted, or the world it is in is swapped away. | | `validate` | `(ref) -> { { code, message, severity?, path? } }` | On `asset.validate`, after the `type.yaml` checks, for the type's own rules. `severity` defaults to `error`. Runs on every push, so a type's rules hold at publish. A hook that fails reports `validate.hook_failed`. | ### Settings hooks | Hook | When it runs | |---|---| | `settingsDefaults(name, opts, asked) -> table` | Once per `asset.create`, for values the schema's defaults do not give. | | `settingsCorrections(values, name, opts) -> (corrections?, reasons?)` | On every settings write. A correction to a field the writer named refuses the write, giving the reason. | | `settingsDerivedDefaults(values, explicit, changed)` | On a settings write, for fields derived from others. | | `normalizeSettings(values, stored?)` | On every read and write, to map an earlier spelling of a field to the current one. | | `settingsHealed(values, stored)` | On a read, to repair stored values. | | `settingsSchemaProblem(schema, ref) -> string?` | When an asset's own schema is read; a returned string refuses the schema. | `creationInputs` (`{ [opt] = true | selectorOpt }`) names `asset.create` options that are inputs to the type rather than settings. ### Reloading An edit to `behavior.luau` reaches existing assets with no restart. ## How an asset is pictured (`preview:`) | `kind` | The picture is | The type provides | |---|---|---| | `instantiate` | the asset placed in the preview studio through its `instantiate` | `ref.instantiate` | | `image` | a file the asset holds, fitted to the frame | `source: { files }`, the candidate files in order | | `surface` | the asset painted on a mesh | `mesh`, and `ref.previewMaterial` | | `custom` | whatever `ref.preview` returns | `ref.preview` | ```yaml preview: kind: surface mesh: sphere ``` `angle: [yaw, pitch]` turns the camera. The studio owns the light, the backdrop and the framing, so an asset pictures the same in every world. A type with no `preview:` that defines `instantiate` still answers `ref:preview()`. A picture is rendered when something asks to view it (the editor showing the asset, `ref:preview()`), when previews are generated on request (`assets.generatePreviews`), and when the asset is staged. An edit alone renders nothing. The picture records what it was made from, so a stale one is told from a current one. ## The names your type's assets hold (`references:`) Where your type's own format or API carries the name of another asset, declare it here: ```yaml references: keys: # a top-level key of the type's files that holds a name, or a table of them - { key: "shader", type: "shader" } args: # an argument of a call, counting from 1 - { call: "g:node", position: 2, type: "procNode" } fields: # a field of the options table a call takes - { call: "fx.beam", field: "material", type: "material" } ``` `type` is the category the name resolves in. `asset.declareReferenceKey`, `asset.declareReferenceArg` and `asset.declareReferenceField` declare the same from a script. ## What search reads (`indexing:`) `indexing:` is how assets are found. Search reaches an asset only through what its type's `indexing:` names, and adds nothing of its own. That includes you: an asset indexed badly is one you cannot find later, when you are making something else and need it. A type whose assets are never looked for says `indexing: none`. ```yaml indexing: data: # text, read from the asset's files - role: identity extractor: verbatim source: { file: "README.md" } - role: interface extractor: symbols source: { files: ["init.luau"] } - role: implementation extractor: verbatim source: { files: ["init.luau"] } content: # the picture - role: identity modality: image source: { file: "preview.png" } facets: # what a query filters and re-ranks by file: ".metadata" rigged: { type: bool, from: { components: { contains: SkinnedModel } } } roughness: { type: number, filter: range, from: { file: "mat.yaml", field: "floats.roughness" } } ``` **Roles.** Each `data` and `content` entry has a `role`, and a query matches in two slots: - **`identity`**: what an asset is. For anything you look at, the picture; for anything else, the text that says what it is. - **`capability`**: what it does and how it is made. `interface` (the signatures or shape a caller uses) and `implementation` (the body) both count as capability, and a type with code usually declares both. Ask what a person would recognise an asset of the type by, and what it does, and point each role at the file that says it. For text, that is the asset's description: the file your template starts with a `[[describe]]` block, which the author writes or `services describe` fills in (see "Ask your assets to say what they are"). **`data`.** `extractor: verbatim` embeds a file's text as it is; `symbols` embeds the declared signatures of code. `source` is `{ file }` or `{ files: [...] }`. Never index a file name (`source: { field: name }`): one or two words carry nothing to match. **`content`.** `modality: image` embeds the picture itself, so a text query matches what the asset looks like. A type whose assets are looked at makes the picture its identity. **`facets`.** What a query narrows and re-ranks the matches by. `file` is embedded whole, so keys nobody declared in it are still found. Each further key is computed for every asset and states a value for every one, including `false`: a file can imply "not rigged" but never say it, and a query separates rigged from unrigged only because the unrigged ones say `rigged: false`. A key is `{ type: bool | number | enum, filter?: range, from }`, where `from` is `{ file, field }` (a field of one of the asset's files, dotted for nesting), `{ metadata: key }`, or `{ components: { contains | any_outside } }` (what the asset's entities carry). ## What blocks a push A push checks every asset it carries against its type. These refuse it: - a required file that is missing, a `content` check that fails, a `described` file not written yet; - an error from the type's `validate`. Unlisted files and warnings do not. A `described` file blocks only a push that changes the asset. When a push is refused, the message names each asset and what it lacks. `world.publishBlockers()` and `zm status` read the same list without pushing. ## Typing a result from the asset (`refShapes`) A `ref` method whose result depends on the asset (one entry per child folder, per row of a config, per control a map declares) can only be annotated as `{ [string]: Thing }`, which accepts any key. `refShapes` states the result for each asset instead: a function returning a Luau type expression for that asset, and the module whose types the expression uses. Read the asset; never run it. ```lua -- inputMap.assetType/behavior.luau M.refShapes = { activate = function(self): (string, string) local names = {} for _, control in ipairs(M.ref.controls(self)) do table.insert(names, control.name .. ": Handle") end if #names == 0 then return "", "" end return "{ " .. table.concat(names, ", ") .. " }", "@builtin::modules.zinput.scheme" end, } ``` With it, `map.jump:onPressed(fn)` is checked and `map.noexisting` is reported. A per-asset type applies where the call site names which asset: a component field whose default names it, or an annotation `AssetRef<"inputMap", "<identity>">`. `asset.resolve(name, category)` carries only the category, and a name computed at runtime carries nothing, so calls on those keep the declared return. The type belongs to the call's result: index it there, or bind what you need from it there, and the names stay checked. `require("@builtin::assetTypes.assetType.shared.refShapes").published()` shows what was published: `categories` (each type's method surface) and `returns` (per-asset results by identity, then method). An identity missing from `returns` was never published. Results are recomputed when an asset is written; at most 64 assets of one type are read. ## Putting an asset in a scene (`ref.instantiate`) A caller writes one piece of code against every instantiable type, so what `instantiate` returns is fixed: ```lua local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable") M.ref = { instantiate = function(self, target, opts) local root = Instantiable.root(self, target, opts) -- compose the asset under `root`, now return Instantiable.result(self, root, idMap) end, } ``` **In.** `target` is the entity the asset lands under, or onto for a hierarchy type; with none, the type spawns a new root. `position`, `rotation` (three numbers in degrees, or a quaternion), `scale`, `name` and `temporary` mean the same for every type: `Instantiable.root` applies them to a root you make, `Instantiable.place` to one you adopt. Document any options of your own in the hook's `--!arg` docs. **Out.** `(root, idMap)`. `root` is the composed root, live when you return: build synchronously, never defer to a component's `awake`. `idMap` maps each original id to the spawned one, so a component that composes the asset again on every load can pass it back in and keep references into the composition. Every call goes through `Instantiable.result`, which refuses a root that is not live and turns a missing `idMap` into `{}`. ## Inspecting an asset (`ref.inspect`) `asset.inspect(ref)` builds a record every asset shares (`identity`, `name`, `guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`, `description`, `tags`), then calls `ref.inspect(self)` for the type's own `detail`: ```lua M.ref = { inspect = function(self) -- read the asset's own files, never runtime state: inspect works on an asset -- that has not been compiled, uploaded or registered return { --[[ what makes this asset what it is ]] } end, } ``` Without it, the record is the shared part alone, and an agent inspecting the asset learns nothing of what it is. A hook that raises leaves `detail` empty and sets `record.warning`. ## Discovery - `asset.list("assetType")`: every registered type. - `asset.inspect("<typename>")`: the type, its README and its `about.yaml` texts. - `asset.resolve("<typename>", "assetType")`: the type itself.
▲ 0↑ born
▣
module · born here
❒asset
# result The handle `asset.list` returns. A query result **is** the array of matched `AssetRef` handles. Entry `1` is the first match, `#rows` is the count, `ipairs(rows)` walks it, and anything that accepts a list of refs accepts it unchanged. The handle adds methods on top of that array through a metatable, so reading the result stays one expression. ```lua local hero = asset.list({ type = "mesh", fields = { tags = "hero" } }):first() local prop = asset.list({ type = "mesh", path = "/zero/source/props" }):random() asset.list("material") :filter(function(m) return m.name:find("rust") ~= nil end) :each(function(m) print(m.identity) end) ``` ## Methods | Method | Returns | |---|---| | `:first()` / `:last()` | One entry, or nil when the query matched nothing. | | `:random()` | One entry chosen at random, or nil. | | `:count()` | How many entries matched. | | `:isEmpty()` | Whether nothing matched. | | `:each(fn)` | The same result, after calling `fn(entry, index)` in order. | | `:map(fn)` | A new result holding `fn(entry, index)` per entry. | | `:filter(predicate)` | A new result holding the entries kept. | | `:searchable()` | A new result without the deprecated assets, the ones a search or a picker offers. | | `:sort(comparator?)` | A new, ordered result; ordered by identity when the comparator is omitted. | | `:toArray()` | The entries as a plain table, without the handle. | `:map`, `:filter`, and `:sort` return new results carrying the same methods, so they chain. `:sort` leaves the result it was called on as it is. ## Ordering `asset.list` already returns its matches ordered — by identity unless the query asks for another field with `order` — so `:first()` names the same asset on every call. `:sort` is for orders the query cannot express, such as one computed from an entry's fields. ## What the handle does not change The metatable carries `__index` alone. Length, `ipairs`, `pairs`, `next`, `table.*`, and serialisation all read the array part, so a result behaves exactly as a plain array everywhere those are used.
▲ 0↑ born
▣
module · born here
❒asset
# asset_warmup `asset.warmup` — a **read-only closure inspector**. Returns the transitive set of assets that the CPU-residency system *would* load when the given asset enters `/runtime/` — i.e. the asset plus everything reachable through its declared content references. It does **not** itself change residency or touch bytes: ```lua local closure = asset.warmup("@builtin::meshes.cube") -- → the asset + every texture/material/mesh it transitively references ``` Residency is owned by the engine's reference-counted CPU-residency system, which acquires the closure on a `/runtime/` enter (usage 0→1) and releases it on the last drop (→0), loading/unloading bytes at the per-node 0↔1 boundaries so a texture shared by two materials stays resident until BOTH are gone. This helper just lets scripts/agents **inspect** that closure (debugging, "what would loading X pull in?") without any side effect — it avoids `asset.resolve` (which fires the BlobStore prefetch) and uses the side-effect-free `asset.guid` / `asset.deps` / `asset.identity`. The closure is the generic `.refs` graph, so this is fully type-agnostic — material/mesh/user-types all resolve the same way with zero per-type knowledge. By default it follows `asset_ref` / `component` (content) edges and skips `asset_type` (structural) / `require` (code); `opts.vias` overrides. Deduped by guid via an explicit work-stack so diamonds appear once and cycles terminate. Installed onto the FFI `asset` namespace by the prelude.
▲ 0↑ born
▣
module · born here
❒asset
# luau_introspect (module) Parses Luau/asset source TEXT into structured declarations. Pure string/pattern parsing (`string.find` / `string.match` / `string.gmatch`) over the literal source — no compiling, no VM spawn, no runtime state, no engine FFI. Given source text, it extracts what is written in the file. This is the shared parser every per-assetType `M.ref.inspect` hook uses to turn a component/module/tool's own source into the structured record `asset.inspect` returns. ## Exports - `docstrings(src) -> DocMap` — scans `--!desc` / `--!arg` / `--!return` / `--!example` comment runs and binds each run to the name of the declaration on the next non-comment line (the identifier after `function`, `public:`, `local function`, or `M.`). - `publicFields(src) -> { FieldEntry }` — parses `public = { name = Field.<kind>(default, mode), ... }` table-literal entries and module-scope `public.<name> = Field.<kind>(...)` assignments. - `events(src) -> { EventEntry }` — parses `events = { name = Event(payloadSchema?, syncMode?), ... }` table-literal entries. - `methods(src) -> { MethodEntry }` — parses `function public:<name>(...)` / `typed function public:<name>(...)` declarations (params + optional return type). - `lifecycleHooks(src, catalog) -> { string }` — top-level `function <name>(` declarations whose name is in the caller-supplied `catalog` array. - `moduleExports(src) -> { ExportEntry }` — parses `M.<name> = function` assignments, `function M.<name>(...)` declarations, and a trailing `return { foo = foo, ... }` export table. - `forSource(src, computeFn) -> any` — memoises `computeFn(src)` keyed on `src` itself in a module-local table. The same source text returns the cached result without re-running `computeFn`; different source text recomputes. Keyed on the source content (not an asset checksum) because composite/container assets (component folders, scene folders, etc.) all hash to the empty-string checksum — a checksum-keyed cache collapses every such asset's detail onto whichever one was inspected first. ## Usage ```luau local Introspect = require("modules.luau_introspect") local src = self:getInitScript() local detail = Introspect.forSource(src, function(s) return { fields = Introspect.publicFields(s), events = Introspect.events(s), methods = Introspect.methods(s), hooks = Introspect.lifecycleHooks(s, lifecycleCatalog), } end) ``` ## Notes - Every function is a pure string→table transform: same source text in, same structured table out, every time. No reads of live component state, no entity/world queries. - Structural scanning runs over a comment- and string-aware **mask** of the source (a same-length copy where comment bodies and string-literal contents are blanked to spaces, delimiters and newlines preserved). Pattern matches and brace/paren balancing run on the mask — so a brace, `Field.`, `Event(`, or a whole entry that appears inside a comment or a string literal never registers — while captured values are sliced from the original source at the same (aligned) indices. This makes the parser robust to apostrophes in comments, commented-out entries, string defaults containing `}` / `Field.` / `Event(`, and `[[ ]]` long strings. - `default` / `category` are raw trimmed source-text slices (with any trailing comment stripped), not evaluated values. - For a **ref constructor** (`Field.assetRef` / `dataRef` / `resource` / `componentRef`) the FIRST positional argument is the category / contract / componentType selector, captured under `category`; the SECOND argument is captured under `default`. - For every **other** Field kind the first argument is the `default` and `category` is nil. - A trailing `Sync` / `NoSync` identifier is captured as `sync`, tolerating a trailing comma or a trailing comment after the last argument. - Field/Event entries whose key is a computed or indirect expression (`[expr] = Field.number(...)`) are omitted — only literal identifier keys are recognised. - `methods` captures a `...` variadic parameter (as `name = "..."`), with its `: <type>` annotation when present. - A `--!desc` written above a field/event declaration (`<name> = Field.<kind>(...)` / `<name> = Event(...)`) or a `public.<name> =` assignment binds to that name in `docstrings`, and is folded into the corresponding `publicFields` / `events` entry's `desc`. - `lifecycleHooks` never hardcodes the lifecycle-callback catalog; the caller passes the list of names to match against. - `forSource`'s memo is bounded (oldest-key eviction) so a long session touching many distinct asset versions can't grow it without limit.
▲ 0↑ born
▣
module · born here
❒asset
# assetType.shared.ref Builds the metatable every `AssetRef` (the `{ __ref, type, name, guid, identity, path }` envelope returned by `asset.resolve` / `asset.ref`) carries. Replaces the per-call C metatable that used to live in `crates/zero_scripting/src/ffi/bindings/asset.rs::attach_asset_ref_metatable`. ## Public API ```lua local assetRef = require("@builtin::assetTypes.assetType.shared.ref") -- Called by the Rust factory (push_asset_ref_handle) via -- _G.__build_asset_ref_proxy after the envelope fields are set. assetRef.build(envelope) -- attaches AssetRefMT, returns the table ``` The module exposes no invalidation surface — discovery is registry-driven and hot-reload is transparent (see "Discovery and hot-reload" below). ## Method dispatch order `ref.foo` is resolved in this order: 1. **Default methods** — `getSource` / `getBytes` / `getText` / `exists` / `inspect` and the lazy `meta` property. Per-type definitions cannot override these (engine contract from gh#1889). 2. **Per-type `ref` table** — discovered through `asset.resolve(<typename>, "assetType")` + `require(<identity>.behavior)`. The lookup resolves to whichever `<typename>.assetType/` folder is currently registered for the typename (built-in, user, or library-vendored) and pulls its `ref` methods. 3. **Nil** — unknown key, same shape as the original C metatable. ## Adding methods for a new asset type Drop a `behavior.luau` into the type folder: ``` src/lua/lib/assetTypes/<typename>.assetType/ ├── type.yaml -- structural spec (existing) ├── behavior.luau -- ref + global behaviour (new) └── template/ -- placeholder body (existing) ``` `behavior.luau` returns: ```lua return { ref = { --!desc Per-instance method on every `<typename>` AssetRef. myMethod = function(self, ...) ... end, }, global = { -- Reserved for the asset.<typename>.* surface — not consumed -- yet; included so the contract from gh#1889 lands cleanly. }, } ``` Within `ref` methods, `self` is the AssetRef envelope: `self.path`, `self.identity`, `self.guid`, `self.type`, `self.name` are available. Engine-required fields (`guid`, `path`, `identity`, `type`) must not be redefined. ## Discovery and hot-reload Type discovery uses the asset registry, so it doesn't matter where a `<typename>.assetType/` folder lives — engine built-ins under `@builtin::assetTypes.<X>`, user types dropped under `/zero/source/<X>.assetType/`, or types vendored inside an imported library all resolve identically. The dispatcher walks `asset.resolve(<typename>, "assetType")` → canonical identity → `require <identity>.behavior` on every miss; the asset registry is the cache for the resolve half and Luau's `_LOADED` is the cache for the require half. Hot-reload is transparent. When a `<typename>.assetType/behavior.luau` is rewritten through VFS, the engine's `invalidate_require_cache_for_state` re-runs the module and mutates the cached `_LOADED[<identity>.behavior]` table in place. Dispatch reads `mod.ref` on every access (rather than caching a sub-pointer), so existing AssetRefs see the new methods on the very next access — no Rust-side hook into this module is needed, and no invalidation API is exposed for callers to call. The same registry-driven path also handles type **registration** correctness: dropping a new `<typename>.assetType/behavior.luau` updates the asset registry, the next `asset.resolve(<typename>, "assetType")` returns the new ref, and AssetRefs of that type immediately gain the new methods. ## Why Luau, not Rust The asset surface needed per-category behaviour (`material:getProperties()`, `bundle:instantiate(entityId)`, `tool:run(args)`) and the old shape couldn't grow without an FFI change per method. Owning the proxy in Luau means: - Type-specific methods ship as content (the `<typename>.assetType/` folder), not engine code. - Adding a new asset type drops in a new folder; no Rust rebuild. - Methods can call any other Luau global (`vfs`, `asset`, `Material`, `entity`, etc.) directly, instead of going through narrow FFI primitives. ## Consumers - `crates/zero_scripting/src/ffi/bindings/asset.rs::attach_asset_ref_metatable` — the Rust factory that pushes envelopes invokes `_G.__build_asset_ref_proxy` once per push. - Every Luau call site of `asset.resolve` / `asset.ref` / `entity(id).component.X.material` / any binding declared `AssetRef<...>` — they all receive envelopes built through this module.
▲ 0↑ born
▣
module · born here
❒asset
# yaml.module YAML decode + encode for authored engine content. Pure Luau, no engine dependencies — a general parsing library, not data-system plumbing. ```luau local Yaml = require("@builtin::modules.yaml") local doc = Yaml.decode(vfs.read(path)) vfs.write(path, Yaml.encode(doc)) ``` ## Supported subset - Block mappings (`key: value`) and block sequences (`- item`), nested to any depth. - Compact sequence-of-mapping entries (`- path: x` / ` kind: y`). - Flow collections — `{ a: 1, b: 2 }` and `[1, 2, 3]` — single line. - Plain scalars with type inference: `~` / `null` → nil, `true` / `false` → boolean, numeric literals → number, everything else → string. - Single- and double-quoted strings (`''` escapes a literal quote inside a single-quoted string; `\n` `\t` `\r` `\\` `\"` inside a double-quoted one). A quote opens a quoted scalar where a scalar begins — after `key:`, after a `- ` entry marker, or inside a flow collection — so a plain scalar carries an apostrophe as data (`note: the world's rules`). Quoted keys are read in flow mappings. - `#` comments — honored outside quotes, so a `#` inside a quoted string is kept as data. - Literal (`|`) and folded (`>`) block scalars, with a chomping indicator (`-` strips the final newline, `+` keeps every trailing blank line, none keeps one newline) and an indentation indicator (`1`-`9`: the content's indent past the parent's), in either order (`|-`, `>+`, `|2`, `>1-`). A block scalar's content is literal text: quotes (balanced or not), `#`, `key: value` and `---` inside it are data. - An optional leading `---` document marker. ## Loud-error contract Constructs outside the subset above raise instead of misparsing: anchors/aliases (`&`, `*`), tags (`!`), directives (`%`), multi-document streams (a second `---`), a block-scalar header it cannot read (`|x`, `|-+`, `|0`), tab indentation, and inconsistent indentation (both block structure and block-scalar bodies). Every error carries the offending line number (`yaml: line N: ...`), so a bad config points straight at the line to fix. Tab indentation is rejected everywhere — including block-scalar body lines whose leading whitespace contains a tab. A tab after the first non-space character of a line is content and passes through. ## API - `Yaml.decode(text: string): any` — decode a YAML document into a Luau value (table, scalar, or nil for an empty document). Raises on malformed input or an unsupported construct. - `Yaml.decodeWithComments(text: string): (any, boolean)` — decode as `decode` does, and report whether the text carries a comment by the decoder's own rule: a `#` at a line's start or after whitespace, outside a quoted scalar and outside a block scalar. Re-encoding the value drops such comments, so an editor that writes a document back reads this first. - `Yaml.encode(value: table): string` — encode a Luau table as YAML (block style, two-space indent, alphabetically sorted keys). Raises on values YAML can't represent (functions, userdata, non-string mapping keys). A top-level empty table encodes to an empty document, which decodes back to `nil` (the YAML empty-document ambiguity).
▲ 0↑ born
▣
module · born here
❒asset
# json JSON encode/decode library for Luau. Encodes Lua values to JSON strings and decodes JSON strings back to Lua values. Used for communication with the Rust side of the engine, the VFS read/write bridge, and any wire-format that needs JSON. Pure Luau, no engine dependencies. Compact and pretty-printed encoders, plus a hand-rolled decoder that streams the input by position so it works under WASM as well as native. ## Exports - `Json.encode(value: any, indent?: string, currentIndent?: string) -> string` — compact encode. Functions / unknown types and NaN/Inf encode as `null`. - `Json.encodePretty(value: any, indentStr?: string) -> string` — pretty-printed encode with sorted object keys (diff-friendly). - `Json.encodeArgs(...: any) -> string` — encode varargs as a JSON array. - `Json.decode(str: string) -> any` — decode a JSON string. Returns the decoded value, or `nil` + error message on failure. ## Usage ```luau local Json = require("@builtin::modules.json") local widget = { type = "button", text = "Click Me" } local compact = Json.encode(widget) -- '{"text":"Click Me","type":"button"}' local pretty = Json.encodePretty(widget, " ") local decoded = Json.decode(compact) local v, err = Json.decode("oops") -- v = nil, err = error message ``` ## Notes - Object keys are sorted alphabetically in both encoders for consistent output across runs. - Numeric keys on objects are stringified at encode time (JSON has no numeric keys). Pure-integer key sets get detected as arrays via `isArray` and encoded with brackets. - NaN, +Inf, -Inf encode as `null` — JSON has no representation. Round trips through `decode` recover `null` (Lua `nil`), so they don't preserve. - Unicode `\uXXXX` escapes decode to UTF-8 by hand to stay WASM-safe. Only the BMP is covered; supplementary planes via surrogate pairs are not. - Functions encode as `null`. - Decode is character-streamed — no regex, no `string.match` patterns on the whole input — so the line-and-column information needs to be reconstructed from the position offset.
▲ 0↑ born
▣
module · born here
❒asset
# assetType runtime The machinery that reads a `<typename>.assetType/behavior.luau` and turns its declarations into live behaviour. A `behavior.luau` is a table of declarations — `ref` methods, `modules` shared code, an `events` schema, a `namePattern`, `refShapes`, and the `onCreate` / `onRegister` / `onChange` / `onDelete` / `validate` / `settingsDefaults` / `settingsCorrections` hooks. None of it runs itself. This is the code that runs it, and it lives here because reading a type's declarations is the **assetType type's own behaviour** — the same way `material.assetType` owns what a `.material` does. ## Sub-modules | Module | Reads | Responsibility | |---|---|---| | `ref.module` | `ref`, `modules` | Builds every `AssetRef` envelope, attaches the shared metatable, and dispatches per-type methods and shared modules onto it. Also owns edit-mode write-behind persistence. | | `create.module` | `onCreate`, `namePattern`, `validate` | Backs `asset.create`: resolves the type, checks the name against its pattern, runs `onCreate` (or clones `template/`), and writes the instance. `validate.module` beside it checks a creation `opts` table against the type's `createSchema`. Before running `onCreate`, resolves the type's settings chain (below) and hands the result to the hook as `opts.settings`. | | `settings.module` | `settings`, `settingsDefaults`, `settingsCorrections` | A type's declared settings schema and where its values live (`type.yaml`'s `settings:` block). `Settings.resolveForCreate` layers the schema's own defaults, the type's own `settingsDefaults(name, opts, asked)` hook (a DEFAULT the schema can't express — a name-derived convention, a fact read off a payload the caller handed it, a value following a field `asked` shows a higher layer naming; any later layer overrides it), the Preset Manager, an importer's settings, the caller's `settings` table, then the type's own `settingsCorrections(values, name, opts)` hook (a CROSS-FIELD CONSTRAINT the schema can't express, applied last over the fully merged values). A correction over a default/preset/importer value lands silently; a correction that would override what the caller's own `settings` table explicitly asked for refuses the creation instead, naming the field and why. Neither hook is ever handed a table to mutate; each returns what it wants changed (`settingsCorrections` may also return a `{ [field]: reason }` table for that refusal message). `Settings.cloneValues` deep-copies a values table — `create.module` hands `onCreate` a copy, never the table it stamps. `Settings.valuesOf` / `writeValues` read and write an asset's own values file. | | `typeYaml.module` | `type.yaml` | The folder a type lives in and its parsed `type.yaml`, decoded once per content version of the file. `settings.module` and `inspector.module` read their blocks through it. `about` / `aboutAt` read a type's `about.yaml` (`intent`, `function`, `usage`), leaving out any key that is empty or still starts with `[[describe]]`; `aboutRows` and `aboutMarkdown` lay the texts out for the Inspector and the `types/<name>` guide. | | `inspector.module` | `type.yaml`'s `inspector:` block | Which inspector a type declares for its assets (`inspector: { type: ... }` or `{ instance: ... }`), and the declaration that file returns — the sections it adds, the generic ones it replaces, and their order — or the problem that kept it from loading. | | `onRegister.module` | `onRegister` | Fires an instance's once-only registration hook — on arrival, on world load, and for `@builtin` library instances. | | `changeDispatch.module` | `onChange`, `onDelete`, `refShapes` | Routes a VFS source write or a folder delete to the enclosing typed asset's type hooks. | | `refShapes.module` | `refShapes`, `ref` | Publishes what every `AssetRef<category>` answers to, so a member read on an asset-typed value is checked against that category's real surface. | | `events.module` | `events` | The per-asset event runtime behind `ref.events`. | | `instantiable.module` | `ref.instantiate` | The instantiation contract an asset type opts into: `root` stands the root entity, `place` applies the base placement opts to one the type adopted, and `result` shapes the `(root, idMap)` every `instantiate` returns. Also registers the `sceneInstantiable` field-constraint validator. | | `declaration.module` | `type.yaml` | The type's decoded declaration, read once and held until a write inside an `.assetType` folder; what every question about a type as a whole reads. | | `previewRecipe.module` | `type.yaml` `preview:` | How an instance's `preview.png` is produced: which of the four recipes (`instantiate`, `image`, `surface`, `custom`) the type declares, and what that recipe needs. | ## Reaching it ```luau local rt = require("@builtin::assetTypes.assetType.shared") rt.ref.loadTypeBehavior("material") ``` Fields resolve lazily. The prelude requires the sub-modules directly, in dependency order (`ref`, then `changeDispatch`, `onRegister.install()`, `refShapes.install()`) — a table that required all six on load would take that ordering away from it.
▲ 0↑ born
·
assettype · born here
❒asset
# Shader (asset type) A shader is a WGSL program that runs on the GPU. Materials reference shaders and supply property values; renderable entities reference materials, not shaders directly. This README is the canonical reference for writing **every** kind of shader — it covers all domains, the surface authoring contract, the material property schema, the engine library functions you can call, and how a shader registers and compiles. > New to how shaders, materials, meshes, and textures relate as assets and live > GPU resources? Read `core/resource-model` first. ## Folder shape A `.shader` is a folder asset: ``` <name>.shader/ shader.wgsl # the WGSL body (required) properties.yaml # the material property schema (optional; surface shaders) README.md # a one-paragraph description of THIS shader (required) .metadata # asset metadata ``` Each file carries a committed `.meta` sidecar pinning its stable guid. The identity is `<name>` (the `.shader` suffix strips). A shader's material properties are exactly the ones its `properties.yaml` declares: a shader with no `properties.yaml` declares none, and the engine reads no property from the WGSL body. A `.wgsl` file standing on its own, outside a `.shader` folder, is WGSL source rather than a shader: a material draws with the `.shader` folder that holds it as `shader.wgsl`. Materials and other assets reference a shader by **AssetRef** (a typed, guid-backed handle), never by a raw string. ## Domains The first line of `shader.wgsl` declares the domain: ```wgsl // @domain: surface ``` | Domain | What it is | You write | |---|---|---| | `surface` | A material on a mesh (the common case). | `fragment()` (+ optional `vertex()`/`vertex_clip()`). The engine generates everything else. | | `post-process` | A full-screen pass over the rendered frame, in the space it declares (bloom, vignette, grade). | `fragment(in: PostInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. | | `screen` | A standalone full-screen visual (UI background, procedural). | `fragment(in: ScreenInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. | | `sky` | The sky background (a fullscreen material). | `fragment(in: SkyInput) -> vec4` only. The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) interface from `properties.yaml`. | | `compute` | GPU data processing, no rasterization. | An `@compute @workgroup_size(...)` entry over storage buffers; you write the `@group/@binding` lines yourself. For compute work, the `.computeShader` assetType (see below) generates them for you. | `// @domain:` resolves the names above and `postprocess` / `screenspace` / `ui` as further spellings of `post-process` and `screen`. A body carrying no `@domain:` line is `surface`. `shaderRef:domain()` answers the domain a body declares, a further spelling as the domain it names. Any other name is refused where the shader registers, with an error naming the spellings that resolve, so a shader reaches the renderer only under a domain the compiler scaffolds. Particles are drawn and simulated through these domains like anything else: the particle package's `particle_sprite` and `particle_mesh` are `surface` shaders, and its simulation, culling and sorting steps are `.computeShader` assets. ## Texture coordinate space A shader that samples a texture through a coordinate it builds itself declares which space that coordinate lives in, on a line beside `@domain:`: ```wgsl // @domain: surface // @uv_space: world ``` | Value | The coordinate | A material's `uv_scale` means | |---|---|---| | `mesh` (the default) | The mesh's own UV attribute, `input.uv`. | How many times the texture repeats across a surface. | | `world` | The fragment's world position, as a triplanar projection samples. | How many times the texture repeats per world unit, so a larger surface carries more. | Texture residency reads the declaration to work out how finely a frame samples each texture: a material laying eight copies of its texture across a surface samples each copy at an eighth of the surface's size, and the mip level that serves it is three levels coarser than the surface's own footprint implies. Leaving the line out puts the shader in mesh space, which is what sampling `input.uv` is. `renderer.textureStreaming().textures` reads back the span each texture was measured at and the level that span asked for. **Compute shaders have their own assetType.** A `.computeShader/` folder gives compute the same zero-scaffolding contract surface/sky/post/screen get: you write only `@compute fn main` (+ helper fns/structs, **no `@group/@binding` lines**) and declare bindings in a sibling `bindings.yaml` (storage buffers, textures, samplers, storage textures, plus a `params:` uniform); the engine generates the `@group(0)/@binding(N)` declarations. Dispatch it through a resolved reference (`asset.resolve("name", "computeShader"):dispatch(...)`). See the `.computeShader` assetType README and `man compute`. **Surface**, **sky**, **post-process**, and **screen** shaders all get engine-generated scaffolding — you write only `fragment()` and declare properties in `properties.yaml`; the engine generates the entry points and the group(1) material interface. (Each domain's `fragment` takes a domain-specific input instead of `FragmentData`: `SkyInput`, `PostInput`, or `ScreenInput` — see "Sky shaders" and "Post-process & screen shaders" below.) Compute shaders get the same treatment via the separate `.computeShader` assetType (write only `@compute fn main`, declare bindings in `bindings.yaml`). The `compute` domain here writes its own entry points directly — see `man compute`. ## Surface shaders A surface shader writes **only** the parts that are unique to it. The engine owns all the scaffolding — the vertex stage, every render-mode entry point (`vs_main` / `fs_forward` / `fs_gbuffer`), group(0) (camera, transforms, lights, shadows, and the material rows), and the material interface generated from `properties.yaml` (`material` and your texture slots). Adding a render path never touches your shader. Inside `fragment()` you have access to exactly four things — nothing is hidden: 1. **`input: FragmentData`** — the interpolated per-fragment surface data the engine hands you: world position, world normal, uv, view direction, vertex colour, and more. Every field is in the `FragmentData` table below. 2. **`material.*` and your textures** — the material inputs **you** declare in `properties.yaml`. The mapping is mechanical: a scalar property named `foo` becomes `material.foo`; a texture property named `bar` becomes `bar` (the texture) and `bar_sampler` (its sampler). `material` has **exactly** the fields your `properties.yaml` declares and no others — to add an input, add a property. List what a shader exposes with `shaderRef:getProperties()` or `asset.inspect("<name>")`. 3. **Engine state** — the scene's camera, lights, time, and shadows that the renderer binds for every surface shader. `uniforms.*` (sun direction/colour, ambient, `camera_pos`, `time`) and the punctual lights (`zero_point_light(i)`) are always in scope; the shadow functions come from `#include "@builtin::shaderModules.shadows"`. This is how you light a surface **without** the prebuilt PBR — see "Engine state" and "Writing your own shading" below. 4. **Library functions** you `#include` (see "Library includes"). A shader and its property schema go together. The two files below are a complete surface shader: `properties.yaml` — declares the material inputs: ```yaml properties: - { name: base_color, type: color, default: [1, 1, 1, 1] } - { name: roughness, type: float, default: 0.5, min: 0, max: 1 } - { name: metallic, type: float, default: 0.0, min: 0, max: 1 } - { name: base_color_texture, type: texture, default: white } ``` `shader.wgsl`; those declarations are read as `material.base_color`, `material.roughness`, `material.metallic`, and the `base_color_texture` / `base_color_texture_sampler` pair: ```wgsl // @domain: surface #include "@builtin::shaderModules.pbr_shading" // the PBR helpers — see "Library includes" fn fragment(input: FragmentData) -> vec4<f32> { var s = zero_pbr_default_surface(input); s.albedo = material.base_color.rgb * textureSample(base_color_texture, base_color_texture_sampler, input.uv).rgb; s.perceptual_roughness = material.roughness; s.metallic = material.metallic; return vec4<f32>(zero_pbr_shade(input, s), material.base_color.a); } ``` `fragment()` returns the final colour. The engine forces no lighting model on you — flat, toon, PS1, dithered, or PBR are all just different `fragment()` bodies. Calling `zero_pbr_shade` is opt-in. ### The two surface bodies, and what each gives up A surface shader exposes one of two entry points, and which one decides how much of the shader the engine can see: | Body | The engine gets | PBR debug passes read | |---|---|---| | `fn fragment(input: FragmentData) -> vec4<f32>` | the finished pixel, and the `PbrSurface` too when the body hands one to `zero_pbr_shade` | the real channel where a surface was handed over; magenta, the "no data here" marker, where the body shades by its own math | | `fn surface(input: FragmentData) -> PbrSurface` | the surface (albedo, roughness, metallic, emissive, normal, occlusion), which the engine then lights | the real channel | Both are first-class: `fragment()` is what you want when the shader owns its own look, `surface()` when you want engine lighting. `capture { pass = "albedo" }` (and `roughness` / `metallic` / `ao` / `emissive`) answers about your material for either body wherever the engine has the surface — writing the same `PbrSurface` behind `surface()` or behind `fragment()` + `zero_pbr_shade` gives one answer per channel. A body that lights itself by its own math draws those channels magenta. `pbr.shader` exposes `surface()`. `capture { pass = "normal" }` is a geometry read rather than a material one, so it answers for every shader: the normal of the surface where one was handed over, and the interpolated normal of the triangle where none was. It is the same normal the frame's normal buffer carries, which is what a screen-space pass reading `@scene.normal` sees. `shaderRef:shadingModel()` reports which one a shader ended up with — `"engine-lit"` for `surface()`, `"self-shading"` for `fragment()`. ### Optional vertex hooks ```wgsl // Displace geometry in OBJECT space. Runs on skinned meshes too (it sees the // already-skinned, morph-applied local position). Return the modified vertex. // The `v` parameter is immutable (WGSL function params are), so copy it into a // `var` first and modify that. fn vertex(v: VertexData) -> VertexData { var out = v; out.position += out.normal * sin(out.time) * 0.1; return out; } // Post-transform vertex hook (runs AFTER the engine's world/skin/projection). Two // things you can do here, separately or together: // * move `clip_position` — vertex jitter, PS1 snapping, render-resolution lowering; // * write `color` — PER-VERTEX (Gouraud) shading: light the vertex from its // world_normal + the light context and the engine forwards the result into the // interpolated `vertex_color` the fragment reads. fn vertex_clip(v: ClipVertex) -> ClipVertex { var out = v; // Gouraud: Lambert sun + ambient, evaluated once per vertex (flat-banded shading). let n_dot_l = max(dot(v.world_normal, -normalize(v.light_direction)), 0.0); let lit = v.ambient_color * v.ambient_intensity + v.light_color * v.light_intensity * n_dot_l; out.color = vec4<f32>(v.color.rgb * lit, v.color.a); out.clip_position = round(out.clip_position * 80.0) / 80.0; // PS1 snap return out; } ``` #### Geometry built per instance: grass, kelp, hair cards, debris `vertex()` knows which vertex of which instance it places: `VertexData.vertex_index` is the vertex's index in its mesh and `VertexData.instance_id` the instance's slot, whose lanes `zero_object_data(v.instance_id, lane)` reads. A hook can therefore build its geometry rather than displace it: a strip mesh drawn thousands of times by `renderer.mesh.drawInstanced`, each copy shaped, sized and bent from the lanes of its `instanceDataBuffer`, becomes a field of grass blades, kelp fronds or hair cards that sway with `v.time`. Being a surface shader, it is lit, shadowed (it casts the shape the hook built), motion-vectored and fogged like the rest of the scene. The rendering-instance-data guide (`guides { path = "topics/rendering-instance-data" }`) has a worked blade field; a render feature's raster pass (`types/rasterShader`) is the hand-written alternative, a vertex and fragment program with its own pipeline. #### Declaring how far a hook moves geometry: `vertexBoundsDilation` Static geometry is culled per cluster against its bounds as authored. A hook that moves vertices — wind sway, an outline hull, a vertex wave — can move them outside those bounds, and the cull then drops clusters whose displaced triangles are still on screen. Declare the farthest the hook moves any vertex, in world units, as a `vertexBoundsDilation` float property, with a default that covers the shader's own properties across their ranges: ```yaml properties: - { name: sway, type: float, default: 0.5, min: 0, max: 4 } # 0.4 x sway, at sway's largest value. - { name: vertexBoundsDilation, type: float, default: 1.6, min: 0, max: 100 } ``` Each material sets its own value — a material that sways less can set less, one moved farther sets more — and a material that sets none takes the default. The cull adds the material's value to every bound in its frustum and occlusion tests (not to the level-of-detail cut). A shader with a hook and no `vertexBoundsDilation` property is named once in the engine log when it compiles; its geometry is culled against its undisplaced bounds. ### Structs the engine passes you `FragmentData` (input to `fragment()`): | Field | Type | Meaning | |---|---|---| | `world_position` | `vec3<f32>` | fragment world-space position | | `world_normal` | `vec3<f32>` | interpolated geometric normal (normalized) | | `world_tangent` | `vec4<f32>` | xyz = world tangent, w = handedness (mikktspace) | | `uv` | `vec2<f32>` | primary texture coordinates (perspective-correct) | | `affine_uv` | `vec2<f32>` | the same UVs interpolated **without** perspective correction — the PS1 texture "swim". Always available; sample with it instead of `uv` for affine texture mapping | | `vertex_color` | `vec4<f32>` | interpolated per-vertex colour (white if unset; carries per-vertex lighting if `vertex_clip()` wrote it — see Gouraud below) | | `view_position` | `vec3<f32>` | camera world position | | `view_direction` | `vec3<f32>` | normalized world-space direction the camera sees this point from: toward the camera's position under a perspective projection, against its forward axis (the same for every point) under an orthographic one | | `light_direction` | `vec3<f32>` | directional (sun) travel direction, unit length; surface→sun is `-light_direction`. Where no sun reaches the camera it points straight down | | `light_color` | `vec3<f32>` | sun colour | | `light_intensity` | `f32` | sun intensity; 0 where no sun reaches the camera | | `ambient_color` | `vec3<f32>` | ambient colour | | `ambient_intensity` | `f32` | ambient intensity as it reaches this pixel: the scene's ambient occlusion is already in it (times `ambient_visibility`), so a crease darkens under the ambient with no work in the shader | | `ambient_visibility` | `f32` | the share of the light of its surroundings that reaches this pixel: 1 minus the scene's ambient occlusion here, 1 where nothing occludes it. Multiply it into any light of the surroundings you gather yourself (a sky colour, a reflection-probe or environment sample); `ambient_intensity` already carries it. `zero_scene_bent_normal(input.frag_coord.xy, n)` names the direction the open part of the hemisphere faces, `n` where no pass wrote one | | `frag_coord` | `vec4<f32>` | framebuffer pixel coords (xy) + depth (z) — for screen-space dither | | `receives_shadows` | `f32` | per-instance: > 0.5 if this surface receives shadows | | `material_index` | `u32` | per-instance: the index standing for the material this surface draws with — the number `renderer.materialIdentity()` maps to a name | | `shader_data` | `array<vec4<f32>, 4>` | per-instance: this entity's own four `vec4` lanes — its `ecs.ShaderData` component's `lane0`..`lane3`, or what `renderer.instanceData.set` put in them (zero until something does). A procedural graph's elements set them through the `data0`..`data3` attributes | | `front_facing` | `bool` | true for front faces (double-sided shading) | | `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world | `shader_data` is the per-instance channel, and it is what lets ONE material serve many entities that differ in a value — a dissolve at its own progress per subject, a hit flash at its own age, a fill level per instance. The alternative is a material per entity, which is a separate pipeline binding and a separate row in the material table for every one of them. ```wgsl const DISSOLVE_LANE: u32 = 0u; fn fragment(input: FragmentData) -> vec4<f32> { let progress = input.shader_data[DISSOLVE_LANE].x; ... } ``` ```lua -- one material on twenty entities, each at its own progress renderer.instanceData.set(subject, 0, progress) renderer.instanceData.clear(subject) -- back to zero lanes ``` The engine attaches no meaning to a lane: a shader and whatever writes it agree what each one carries. Name the indices in the module that writes them. `renderer.instanceData.laneCount()` is how many there are. The same lanes reach a hardware-instanced population through `renderer.mesh.drawInstanced`'s `instanceDataBuffer`, on slots no entity owns. `VertexData` (in/out of `vertex()`): `position` (object-local, model-scale + morph applied), `normal`, `uv`, `color`, `time`, and which vertex of which instance it is: `instance_id` (`u32`, the instance's slot — `zero_object_data(v.instance_id, lane)` reads the lanes the fragment gets as `shader_data`) and `vertex_index` (`u32`, the vertex's index in its mesh). Both hold the same values in the colour pass, the depth views, every shadow page and the previous-frame evaluation, so geometry a hook builds from them — a blade placed and bent by its instance's lanes, a strip shaped by its vertex's index — lands in the same place in each. The rendering-instance-data guide has a worked blade field. `ClipVertex` (in/out of `vertex_clip()`) — the post-transform vertex. Read context: `clip_position`, `world_position`, `world_normal`, `uv`, `view_position`, `view_direction`, `light_direction`, `light_color`, `light_intensity`, `ambient_color`, `ambient_intensity`, `time`, `view_proj` (the view-projection of the frame being evaluated), and where the vertex stands on its instance: `local_position` (its position in the mesh, after `vertex()` and before the instance's world transform), `object_origin` (the world position of the instance's origin), `object_scale` (the world length of the instance's x, y and z axes) and `object_axes` (`mat3x3<f32>`, the world direction of those axes, unit length) — what a camera-facing card, a shard grown about its own base, or anything placed per instance is built from. **Writable:** `clip_position` (snap / jitter) and `color` (write a lit colour here for per-vertex Gouraud shading; the engine forwards it to the interpolated `vertex_color` — left untouched, the mesh's own vertex colour passes through). `vertex()` and `vertex_clip()` run in the vertex stage, which reads the frame uniforms (`uniforms.*`, and the `ClipVertex` members built from them), the scene buffer (`zero_object_data`, `zero_object_visuals`, the node transforms), the material interface and a `read` buffer property. The point, spot and area lights (`zero_point_light`, `zero_punctual_projection`), the shadow maps, the environment and light probes, the feature textures, the scene depth, colour and reflection copies and a `@group(2)` buffer the shader declares `read_write` are visible to the fragment stage alone: read them in `fragment()` or `surface()`. A shader whose vertex hook reaches one fails to compile, and the error names the stage, the binding and the calls that reach it. ### Each hook runs twice: this frame and the one before it A vertex hook decides where the surface IS, so it also decides where the surface WAS. The engine runs every hook a shader declares a second time, over the same vertex standing one frame back — the previous-frame position stream, with `time` = the clock that frame was drawn at and (for `vertex_clip()`) `view_proj` = the view-projection it was drawn with. The motion vector the renderer publishes is taken between the two results, so a displacement that moves with time reports the velocity of the displaced surface, and a displacement that does not move reports the motion of the transform alone because the identical offset appears on both evaluations and cancels. What that asks of a hook: - **Take the frame from the argument.** `v.time` is the clock of the evaluation being run; `uniforms.time` is always this frame's. A displacement built on `uniforms.time` is identical on both evaluations, so its motion vector cancels to exactly zero. The same holds for `v.view_proj` against `uniforms.view_proj`: a clip hook that rebuilds its position from world space through `uniforms.view_proj` reprojects the previous frame with this frame's camera, and reports no camera motion at all. The wind helpers come in both shapes for this reason — `zero_wind_sway_at_time(world_pos, stiffness, v.time)` inside a hook, `zero_wind_sway(world_pos, stiffness)` outside one. - **Anchor a wrap to `uniforms.time`.** A displacement that jumps discontinuously — a falling drop that restarts at the top, a looping offset — differences its jump as velocity on whichever frame it wraps. Compute the wrap COUNT from `uniforms.time` and the position within the cycle from `v.time`, and both evaluations share the same cycle, so the surface reports the speed it fell at. `@builtin::shaders.rain_material` and `snow_material` do exactly that. The per-vertex attributes (`world_normal`, `uv`, `color`) and the lighting and camera-position context are this frame's on both evaluations, so a hook that displaces along its normal reports the motion of the transform plus this frame's displacement. ## Engine state — point lights & shadows The common lighting state — the sun (`input.light_direction` / `light_color` / `light_intensity`), the ambient (`input.ambient_color` / `ambient_intensity`), the camera (`input.view_position` / `view_direction`), and `input.time` — is already on `FragmentData`, so most shaders never touch the raw engine state. The one thing not on `FragmentData` is the punctual-light array (its length varies), which is always in scope. A scene can hold up to 1024 lights, so a fragment walks the ones the light grid lists where it stands, which hold every light that can reach it: | Expression | Type | Meaning | |---|---|---| | `zero_lights_near(world_pos)` | `ZeroLightsNear` | the lights that can reach a fragment at `world_pos`; `.count` of them | | `zero_light_near(near, k)` | `u32` | the index of the `k`th of them, for `zero_point_light` | | `uniforms.point_light_count` | `u32` | number of lights the frame shades under, every one of them | | `zero_point_light(i)` | `PointLightData` | one point or spot light (fields below) | | `zero_punctual_projection(i)` | `PunctualProjection` | a spot or area light's projection: `view_proj`, the frustum its cookie and shadow are placed by, and `cookie_layer` | `PointLightData`: `position`, `radius`, `color`, `intensity`, `direction`, `cone_outer_cos`, `cone_inner_cos`, `kind` (0 = point, 1 = spot). Shadows come from `#include "@builtin::shaderModules.shadows"`: - `compute_directional_shadow_factor(world_pos, normal, light_dir) -> f32` — 1.0 lit, 0.0 fully shadowed. - `compute_spot_shadow_factor(...)` / `compute_point_shadow_factor(...)` / `compute_area_shadow_factor(...)` — one shadow shape each. - `compute_punctual_shadow_factor(light_index, world_pos, normal) -> f32` — the row's own shape, read off its `kind`, for a loop that walks the punctual lights and does not want the switch. - `zshadow_light_reach(light_index, world_pos, normal, object_channels) -> f32` — how much direct light that row puts on a surface on those light channels: the channel mask, falloff, cone or rect orientation, and the cosine, times intensity. Zero exactly where the light contributes nothing. ## Writing your own shading The engine forces no lighting model — `zero_pbr_shade` is just one option. You can light a surface yourself from the state above. Here is a complete custom-lit (Lambert diffuse) surface with no PBR: ```wgsl // @domain: surface #include "@builtin::shaderModules.shadows" // exposes compute_directional_shadow_factor fn fragment(input: FragmentData) -> vec4<f32> { let n = normalize(input.world_normal); let albedo = material.base_color.rgb; // Directional (sun) light: Lambert N·L, attenuated by its shadow. let sun = normalize(-input.light_direction); // surface -> sun let sun_shadow = compute_directional_shadow_factor(input.world_position, n, input.light_direction); var lit = input.light_color * input.light_intensity * max(dot(n, sun), 0.0) * sun_shadow; // Point + spot lights: the ones that can reach this fragment. let near = zero_lights_near(input.world_position); for (var k = 0u; k < near.count; k = k + 1u) { let pl = zero_point_light(zero_light_near(near, k)); let to_light = pl.position - input.world_position; let dist = length(to_light); let l = to_light / max(dist, 1e-4); let atten = max(1.0 - dist / max(pl.radius, 1e-4), 0.0); lit += pl.color * pl.intensity * max(dot(n, l), 0.0) * atten; } // Ambient fill, with the scene's ambient occlusion already in it. lit += input.ambient_color * input.ambient_intensity; return vec4<f32>(albedo * lit, material.base_color.a); } ``` - **Unlit:** skip the lights and return your colour directly. - **Toon / PS1 / custom:** start from the loop above and band, quantize, or warp it however you like. - **PBR:** build a `PbrSurface` and call `zero_pbr_shade` (see "Library includes") instead of writing the BRDF by hand. ## Material properties — `properties.yaml` A surface shader declares its material properties in a sibling `properties.yaml`. The engine GENERATES the entire group(1) interface from it — the uniform struct (`material.<name>`) plus a texture/sampler pair per declared texture. You write no `@group`/`@binding` lines. ```yaml properties: - { name: base_color, type: color, default: [1, 1, 1, 1] } - { name: roughness, type: float, default: 0.5, min: 0, max: 1 } - { name: metallic, type: float, default: 0.0, min: 0, max: 1 } - { name: emissive, type: color, default: [0, 0, 0, 1] } - { name: base_color_texture, type: texture, default: white } - { name: normal_texture, type: texture, default: flat_normal } ``` | `type` | WGSL field type | Notes | |---|---|---| | `float` | `f32` | optional `min`/`max` for editor sliders | | `float2`/`float3`/`float4` | `vec2/3/4<f32>` | | | `color` | `vec4<f32>` | linear RGB colour and alpha, default is `[r,g,b,a]`; the shader reads it as written | | `int` | `i32` | | | `bool` | `u32` | | | `texture` | `texture_2d<f32>` + `sampler` | `default:` is a built-in texture name (`white`, `black`, `flat_normal`) | A `color` holds linear RGB, the space lighting is computed in, the way `base_color` multiplies a colour texture's linear sample. A colour picked from a picture or written as a hex code is sRGB, and written as it is it reads paler and less saturated than picked: convert it first, `color.toLinear(assert(color.hex("#ff8800")))` (`{ r, g, b, a }`: `#ff8800` is `{ r = 1, g = 0.246, b = 0, a = 1 }`), and write that. In the shader you read scalars as `material.<name>` and sample textures as `textureSample(<name>, <name>_sampler, uv)`. A texture slot with no bound texture samples its default, so a shader can always sample — no presence flag needed. `vertex()` reads the same material interface, so a height or deformation map drives displacement from the slot it was bound to. A vertex stage has no implicit derivatives, so sample it at an explicit mip there: `textureSampleLevel(<name>, <name>_sampler, uv, 0.0)`. ## Sky shaders A `// @domain: sky` shader draws the sky as a fullscreen pass. You write **only** `fn fragment(in: SkyInput) -> vec4<f32>` — the colour along the view ray for each pixel — and declare tunables in `properties.yaml` exactly like a surface shader (read as `material.<name>`, textures via `textureSample(<name>, <name>_sampler, uv)`). The engine generates the fullscreen `vs_main`/`fs_main`, the group(1) interface, and reconstructs the world-space ray; there is no separate sky renderer — a sky material runs through the same material pipeline, just on a fullscreen triangle. A sky pipeline binds group(0) and the group(1) interface alone, so a sky that reads a `buffer` property or any other `@group(2)` binding fails to compile, and the error names the binding and the calls that reach it. `SkyInput` (the only argument) carries: | Field | Type | Meaning | |---|---|---| | `ray_dir` | `vec3<f32>` | normalized world-space ray through this pixel | | `ndc` | `vec2<f32>` | screen position in NDC `[-1, 1]` | | `sun_direction` | `vec3<f32>` | unit vector TOWARD the sun (from the directional light) | | `camera_pos` | `vec3<f32>` | world-space camera position | | `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world | | `constants` | `SkyConstants` | what the shader's `sky_constants()` returned for this draw (zeros when it declares none) | ```wgsl // @domain: sky fn fragment(in: SkyInput) -> vec4<f32> { let up = max(in.ray_dir.y, 0.0); let col = mix(material.horizon_color.rgb, material.zenith_color.rgb, up); return vec4<f32>(col * material.exposure, 1.0); } ``` Day/night comes from `sun_direction.y` (the directional light's elevation), so a sky shader never needs a time-of-day uniform — orient the light and the sky follows. The builtin sky shaders (`procedural_sky`, `solid_sky`, `cubemap_sky`, `equirect_sky`) are all authored this way; author a custom sky material and point a `Skybox` component at it. `fragment()` runs once for every pixel of the view and every texel of each environment-capture face. A value that holds for the whole draw (a colour mixed from the material and the sun's elevation, a `cos` of an angular size, an exponent derived from a property) goes in an optional `fn sky_constants(in: SkyConstantsInput) -> SkyConstants`, which the generated vertex stage evaluates once per draw. `fragment()` reads its result as `in.constants`. `SkyConstantsInput` carries `sun_direction`, `camera_pos` and `time` (the same values `SkyInput` holds), `sky_constants()` reads the material as `material.<name>` like `fragment()`, and `SkyConstants` is eight `vec4<f32>` slots, `v0` to `v7`, packed however the sky likes: ```wgsl // @domain: sky fn sky_constants(in: SkyConstantsInput) -> SkyConstants { let day = clamp(in.sun_direction.y * 2.0, 0.0, 1.0); var c: SkyConstants; c.v0 = vec4<f32>(mix(vec3<f32>(0.02), material.zenith_color.rgb, day), day); c.v1 = vec4<f32>(mix(vec3<f32>(0.01), material.horizon_color.rgb, day), 0.0); return c; } fn fragment(in: SkyInput) -> vec4<f32> { let up = max(in.ray_dir.y, 0.0); return vec4<f32>(mix(in.constants.v1.rgb, in.constants.v0.rgb, up), 1.0); } ``` A branch on an `in.constants` value is taken or skipped by every pixel of the draw together, so a term that only contributes some of the time (stars at night) costs nothing while it is off. The vertex stage has no implicit derivatives, so a texture read in `sky_constants()` is `textureSampleLevel`. ## Post-process & screen shaders `// @domain: post-process` and `// @domain: screen` shaders are authored exactly like surface and sky — you write **only** `fn fragment(in: PostInput) -> vec4<f32>` (post) or `fn fragment(in: ScreenInput) -> vec4<f32>` (screen) and declare tunables in `properties.yaml` (read as `material.<name>`, textures via `textureSample(<name>, <name>_sampler, uv)`). The engine generates the fullscreen `vs_main`/`fs_main` and the group(1) material interface. **There are no `uniforms.params[i]` slots** — that convention is retired; every input is a named property. A **post-process** shader's `properties.yaml` carries one further, top-level key beside `properties:` — `space`, either `light` (the default) or `display`: ```yaml space: display properties: - { name: amount, type: float, default: 1.0, min: 0, max: 1 } ``` `light` is the scene's linear radiance — what every surface, the sky and every `afterLighting` feature write, unbounded above 1.0. `display` is the code values the `__display__` pass leaves behind after applying exposure and its tone curve — the 0-1 range a colourist's tool and a dithered or quantized effect expect. `postprocess.add`'s `opts.space` overrides what the asset declares for one registration. The chain converts at both ends of an effect that runs on a segment in the other space, so a light-space vignette still darkens a frame graded after `__display__`, and a lookup table built from a `.cube` export always sees the code values it was authored against, wherever the chain runs it. `space` also decides which layer a registration that names none lands on: a `light` shader grades `scene`, the segment holding the scene's own light, and a `display` shader grades `display`, the picture after `__display__` and before the UI lands on it. So `postprocess.add("glow", asset.resolve("~.shaders.bloom", "shader"))` thresholds highlights that still stand above 1.0, and a lookup table registered the same way reads the code values it was built for and leaves every screen in the colours it declares. `opts.layer` names one explicitly — `"all"`, after the UI, is what an effect that must grade the interface says. A post-process shader may also declare the post stage of the frame it runs in, `stage:` — `optics` (the `scene` layer), `display` (the `display` layer) or `ui` (the `all` layer); `renderer.post.stages()` lists every stage with the colour space and resolution its picture is held in. A registration takes the declared stage unless `opts.stage` or `opts.layer` names another seam, and a stage the frame does not have, or one only render features run in, is refused naming the stages there are: ```yaml space: display stage: display properties: - { name: amount, type: float, default: 1.0, min: 0, max: 1 } ``` A **post-process** shader's `properties.yaml` carries a further, optional top-level key — `passes:`, the pass list the frame draws through, in order: ```yaml space: light passes: - { name: bright, entry: bright, scale: 0.5, inputs: [scene] } - { name: down1, entry: downsample, scale: 0.25, inputs: [bright] } - { name: up0, entry: upsample, scale: 0.5, inputs: [down1, bright] } - { name: composite, entry: composite, inputs: [scene, up0] } ``` Every pass's entry — `fn <entry>(in: PostInput) -> vec4<f32>` — lives in the one `shader.wgsl` the assetType recompiles on. `scale` is the fraction of the view a pass draws at; the LAST pass takes none, since it draws at the view's size and writes the chain's output. `inputs` names what a pass reads — `"scene"`, the chain's input for this effect, or the name of an EARLIER pass — and `inputs[0]` is what `zero_sample_scene(uv)` reads inside that pass's body; every input, `inputs[0]` included, is also reachable by index through `zero_pass_input(i, uv)` and `zero_pass_input_size(i)`, below. The one place the two reads of `inputs[0]` disagree: in an effect whose declared space differs from the segment it draws on, `zero_sample_scene` converts a `scene` input into that space while `zero_pass_input(0, uv)` hands back the segment's own, unconverted value. A shader declaring no `passes:` is one pass whose entry is `fragment`, and its generated WGSL is byte-identical to what it is without the key. A pass that is not the last writes a scratch target the effect owns — in the space the shader declared, view-sized times its own `scale` — allocated on the first draw and replaced whenever the size changes. `engine.params`, below, carries the drawing pass's own index, its scale, and its first input's texel size, so one shader body serves every level of a chain built this way. The worked example is the bloom: `@builtin::shaders.post.bloom` declares twelve passes — a threshold pass, five downsamples, five tent upsamples and a composite — out of four entries, since the five downsamples share one and the five upsamples share another, each level reading the one below it through `zero_pass_input` and telling itself apart by `engine.params`. Its own README walks the declaration. A declaration is refused at compile time — reported through `compileStatus()`, `postprocess.add`'s second return value, or a live effect's `status()[i].error` — for: an entry `passes:` names that `shader.wgsl` does not define; an input naming a later pass, or naming neither `scene` nor an earlier pass; a `scale` outside `(0, 1]`; a `scale` declared on the last pass; a `buffer` property (group(2) carries the pass inputs); or a shader whose group(0) plus declared texture slots plus widest pass's inputs ask for more than the 16 FRAGMENT sampled textures one shader stage has. A **post-process** shader runs as a full-screen pass over the already-rendered frame. Its `fragment` argument and framework helpers: `PostInput`: | Field | Type | Meaning | |---|---|---| | `frag_coord` | `vec4<f32>` | framebuffer pixel coords (`@builtin(position)`) | | `uv` | `vec2<f32>` | screen UV, `(0,0)` top-left … `(1,1)` bottom-right | Framework helpers (always in scope — no include needed): | Call | Returns | Meaning | |---|---|---| | `zero_sample_scene(uv)` | `vec4<f32>` | the rendered scene colour at `uv`, converted into the space this effect declared (`zero_scene_light` is the same call, for content that reads it by that name) | | `zero_scene_depth(uv: vec2<f32>)` | `f32` | scene depth at `uv` — a screen UV here, where the surface domain's `zero::scene_depth` module takes a pixel coordinate under the same name (exact texel — an R32Float copy). Reversed: 1.0 is the near plane, 0.0 the far plane and empty sky, so a nearer surface reads GREATER and `d > 0.0` means "a surface was drawn here" | | `zero_linear_depth_through(d, near, far, engine.view_proj)` | `f32` | that sample as a distance in metres along the camera's view axis, under a perspective or an orthographic camera — the one inversion of the reversed range (`zero_linear_depth(d, near, far)` is its perspective case alone) | | `zero_scene_motion(uv)` | `vec2<f32>` | per-pixel screen-space motion vector at `uv` | | `zero_pass_input(i, uv)` | `vec4<f32>` | the pass's declared input `i`, at `uv`. Input 0 is what `zero_sample_scene` reads | | `zero_pass_input_size(i)` | `vec2<f32>` | that input's size in texels, so one entry serves every level of a chain | | `zero_display_exposure()` | `f32` | the exposure in force: the gain `__display__` multiplies the scene's light by before its curve, the value this frame's display pass draws with (1 where the chain carries none). Light times it is light in the units the picture shows it at, so a threshold judged against `light * zero_display_exposure()` picks the same highlights at every exposure | Engine data uniform `engine` (a `PostEngineData`): | Field | Type | Meaning | |---|---|---| | `resolution` | `vec4<f32>` | `x`=width, `y`=height, `z`=1/width, `w`=1/height | | `time` | `vec4<f32>` | `x`=elapsed seconds, `y`=dt, `z`=frame index | | `view_proj` | `mat4x4<f32>` | this frame's view-projection | | `prev_view_proj` | `mat4x4<f32>` | last frame's view-projection (motion) | | `inv_view_proj` | `mat4x4<f32>` | inverse view-projection (world-space reconstruction) | | `params` | `vec4<f32>` | `x`=this pass's own index, `y`=the scale it draws at, `zw`=1/size of its first input — for a pass the post-process chain draws. A pass a `renderFeature` fragment pass draws carries that feature's `spec.params` here instead; a shader declaring `passes:` is always drawn by the chain, so the two never meet in one shader. | | `exposure` | `vec4<f32>` | `x`=the exposure in force (what `zero_display_exposure()` reads) | The engine fills all of it **per render target**. A registered effect runs over the live viewport's frame AND over every offscreen one — a `capture` from a world-space station or orbiting an entity, a capture of a named camera, a render-to-texture camera — and in each of those, `view_proj`, `prev_view_proj` and `inv_view_proj` are the camera THAT render was drawn from, while `resolution` is that target's own pixel size. So a pass reconstructing world space from `zero_scene_depth(uv)` reconstructs against the station and lens the capture asked for, and an offscreen frame is a picture of the effect as it stands at that station. (A render feature's passes reach an offscreen render the same way, against the same camera — the `renderFeature` assetType README carries that half, including `@frame.camera`, its own per-target camera input.) An offscreen render keeps no view history of its own, so `prev_view_proj` there holds that same matrix rather than the frame before it, and a pass taking camera motion from the two reads none. On the viewport the pair is a frame apart, so camera motion is the one reading a capture answers differently from the screen. `postProcessing = false` on a capture is the one control that takes the chain off the frame it returns; it names the camera property the ephemeral capture camera is built with, so it scopes to that one capture. What a capture opts out of is the registered effects; `__display__` still runs on it, so the exposure and tone curve that turn the scene's light into a picture are on what a capture returns. A diagnostic capture (`albedo`, `normal`, `motion_vectors`, …) bypasses `__display__` itself, since a channel like that is a reading of the scene rather than a graded picture of it. The environment-cube capture bypasses it too, and for the same reason: a probe face carries radiance into the cube array, and `__display__` would fit that radiance to a display's code values — a picture of it rather than the value the PBR indirect term multiplies into its lighting. A complete post-process effect — a vignette via `fragment()` + `properties.yaml`: `properties.yaml`: ```yaml properties: - { name: intensity, type: float, default: 0.5, min: 0, max: 1 } - { name: radius, type: float, default: 0.75, min: 0, max: 1 } - { name: softness, type: float, default: 0.45, min: 0, max: 1 } ``` `shader.wgsl`: ```wgsl // @domain: post-process fn fragment(in: PostInput) -> vec4<f32> { let color = zero_sample_scene(in.uv); let intensity = max(material.intensity, 0.01); let radius = max(material.radius, 0.01); let softness = max(material.softness, 0.01); let center = in.uv - vec2<f32>(0.5); let dist = length(center); let vignette = smoothstep(radius, radius - softness, dist); let darkened = color.rgb * mix(vec3<f32>(1.0), vec3<f32>(vignette), intensity); return vec4<f32>(darkened, color.a); } ``` The asset above **defines** the effect. It enters the frame when something registers it: ```luau postprocess.add("vignette", asset.resolve("~.shaders.vignette", "shader"), { priority = 200 }) ``` The registration names no layer, so the effect grades the layer its `space` belongs to: this vignette reads light, so it runs on `scene`, over the picture before the UI reaches it. Registering it is the one step that makes it render, so a world's chain holds exactly the passes its content asked for. Editing the shader body afterwards recompiles every effect registered from it, in place — the pass keeps its enabled state, priority, layer, tuned property values and bound textures, and draws the new pixels on the next frame. `postprocess.remove(name)` takes it back out of the chain and leaves the asset alone. Drive the named properties at runtime with `postprocess.setProperty(name, prop, value)` and bind texture properties with `postprocess.setTexture(name, prop, path)` (both keyed by the **property name**, never a slot index — see the post-process section of `man shaders` / the `postprocess.*` API). Read them back with `postprocess.describe(name)`: it carries the chain state `postprocess.status()` lists for that effect, the `properties` schema it was registered with, and the `values` each of those properties currently holds. Before the effect exists, `shaderRef:getProperties()` on the asset names the same schema, so what a pass takes is answerable either side of the registration. A **screen** shader is a standalone full-screen visual (UI background, procedural pattern). `ScreenInput` mirrors `PostInput` (`frag_coord` + `uv`); there is no scene to sample, so it has no `zero_sample_scene` helpers. Its `engine` uniform is a `ScreenEngineData`: | Field | Type | Meaning | |---|---|---| | `time` | `f32` | gameplay seconds: advances with the world at `engine.timeScale` and stands still while gameplay is paused (edit mode starts paused), so an effect slows and stops with the world | | `scroll` | `f32` | UI scroll offset | | `resolution` | `vec2<f32>` | render-target size in pixels | | `mouse` | `vec2<f32>` | mouse position | | `velocity` | `f32` | scroll velocity | ```wgsl // @domain: screen fn fragment(in: ScreenInput) -> vec4<f32> { let t = engine.time * 0.5; let col = vec3<f32>( sin(in.uv.x * 3.14159 + t) * 0.5 + 0.5, sin(in.uv.y * 3.14159 + t * 0.7) * 0.5 + 0.5, material.brightness ); return vec4<f32>(col, 1.0); } ``` ## Library includes A library module is a **`.shaderModule` asset**: it only EXPOSES functions and structs and does nothing on its own (exactly like a Unity `.cginc`). You must call what you include. Include one by its identity, the same string you would hand `asset.resolve`: | Include | Exposes | |---|---| | `@builtin::shaderModules.pbr_shading` | `struct PbrSurface { albedo, normal (world), metallic, perceptual_roughness, emissive, occlusion }`; `zero_pbr_default_surface(FragmentData) -> PbrSurface`; `zero_pbr_shade(FragmentData, PbrSurface) -> vec3<f32>` (the full forward PBR lighting); `zero_pbr_indirect_visibility(FragmentData, PbrSurface) -> ZpbrIndirectVisibility` (the share of the surroundings' light each indirect lobe takes from the scene's ambient occlusion: `diffuse` with the light a crease bounces back, `specular` from the open cone around the bent normal); `zero_pbr_shade_with_visibility(FragmentData, PbrSurface, ZpbrIndirectVisibility) -> vec3<f32>` (the same lighting with that share stated by the caller) | | `@builtin::shaderModules.shadows` | `compute_directional_shadow_factor(...)`, `compute_spot_shadow_factor(...)`, `compute_point_shadow_factor(...)`, `compute_area_shadow_factor(...)`, `compute_punctual_shadow_factor(...)`, `zshadow_light_reach(...)`; each light's `_with_kernel` form takes a shared `ZShadowKernel` (`zshadow_kernel()`) so several lookups of one fragment derive its filter rotation once | | `@builtin::shaderModules.engine_bindings` | the group(0) declarations (camera, transforms, lights, shadow maps) — surface shaders get this implicitly; include it directly only for advanced raw access | | `@builtin::shaderModules.shadow_bias` | `zshadow_offset_receiver(...)`, `zshadow_directional_depth_bias(...)` and the rest of the bias math, as pure functions | | `@builtin::shaderModules.texturing` | `ztex_stochastic(...)` (tile without a visible repeat grid), `ztex_blend_normals(...)` (reoriented normal blending) | | `@builtin::shaderModules.depth` | `zero_linear_depth_through(depth, near, far, view_proj)` — the one reading of a stored depth, for the projection the view-projection states; `zero_linear_depth` and `zero_linear_depth_orthographic` are its two cases | | `@builtin::shaderModules.ambient_light` (`zero::ambient_light`) | `zpbr_surroundings_irradiance(world_pos, n, flat_ambient)` (the diffuse light the surroundings hand a surface with normal `n`: the flat ambient, the captured sky and reflection probes, and the baked light-probe volumes, as the PBR model reads it) and `zpbr_surroundings_in_scatter(world_pos, flat_ambient)` (that light averaged over every direction: what a participating medium scatters). A compute pass binds `environment_map`, `environment_sampler` and `zero_environment` to `@scene.environment`, `@scene.environmentSampler` and `@scene.reflectionProbes` | | `@builtin::shaderModules.gbuffer_material` (`zero::gbuffer_material`) | `struct ZeroGbufferMaterial { base_color, metallic, perceptual_roughness }`; `zero_gbuffer_unpack_material(texel: vec4<u32>) -> ZeroGbufferMaterial`; `zero_gbuffer_material(t: texture_2d<u32>, coord: vec2<i32>) -> ZeroGbufferMaterial`, `zero_gbuffer_base_color`/`zero_gbuffer_metallic`/`zero_gbuffer_roughness(t, coord)` — the one unpacking of `@scene.material`'s `Rgba8Uint` texel into what a surface reflects | | `zero::scene_depth` | `zero_scene_depth(px: vec2<f32>)`, `zero_scene_depth_uv(uv: vec2<f32>)`, `zero_scene_depth_texel(px: vec2<i32>)`, `zero_scene_depth_size()`, `zero_scene_depth_is_sky(d: f32)`, `zero_scene_world_position(px: vec2<f32>)`, `zero_scene_world_normal(px: vec2<f32>)`, `zero_scene_depth_fade(px: vec2<f32>, world_position: vec3<f32>, fade_distance: f32)` — every `px` is a pixel coordinate in two components, so a surface fragment passes `input.frag_coord.xy`, not the `vec4<f32>` `FragmentData.frag_coord` holds. The depth already drawn UNDER a surface fragment, and the world position and geometric normal of the surface standing there. What a decal projector box, a soft particle, a forcefield or water intersection foam shades against. Surface domain; the depth belongs to the view being drawn | | `zero::scene_color` | `zero_scene_color(px: vec2<f32>)`, `zero_scene_color_uv(uv: vec2<f32>)`, `zero_scene_color_texel(px: vec2<i32>)`, `zero_scene_color_size()`, `zero_scene_color_refract(px: vec2<f32>, offset_px: vec2<f32>)`, `zero_scene_color_refract_uv(px: vec2<f32>, offset_fraction: vec2<f32>)` — every `px` is a pixel coordinate in two components, so a surface fragment passes `input.frag_coord.xy`, not the `vec4<f32>` `FragmentData.frag_coord` holds. The scene colour already composed BEHIND a surface fragment, and the displaced read that bends it. What heat haze, a refraction shockwave, a cloaking or shield warp, glass and ice shade with. Surface domain; the colour belongs to the view being drawn, and is the lit opaque scene as it stood immediately before the transparent pass — so a `blend`-queue surface reads this frame's, an opaque one reads the previous frame's, and two overlapping blended surfaces both read the same picture and do not bend each other | | `zero::projection` | `zero_projection_is_orthographic(view_proj: mat4x4<f32>) -> bool`, `zero_projection_parallel_ray(view_proj: mat4x4<f32>) -> vec3<f32>`, `zero_projection_view_direction(view_proj: mat4x4<f32>, camera_position: vec3<f32>, world_position: vec3<f32>) -> vec3<f32>`: what a view-projection states about how it projects: whether it is orthographic, the direction an orthographic one sees along (pointing back toward the camera), and the direction a camera sees a world point from under either projection, the value `FragmentData.view_direction` holds. Pure math with no bindings, so a surface, post-process or compute shader passes the view-projection it holds (`uniforms.view_proj`, `engine.view_proj`, or a uniform of its own) | `asset.list("shaderModule")` enumerates the `.shaderModule` assets in this engine, builtin and world-authored alike, and each one's README says what it exposes. Those are the `@builtin::shaderModules.*` rows above; a module you write is included exactly the same way, by its own identity or by the `~.name` form. The `zero::`-named rows come from the renderer itself. Their WGSL is baked into the engine binary and registered under those names before any asset exists, so they answer an `#include` in every engine and appear in no asset index. A shader that includes one records no dependency on it: the engine reading the shader is the engine that already holds the module. Two spellings reach the same `.shaderModule`: a module's declared alias answers as well as its identity, so a shader written against `zero::pbr` compiles and pins the asset that name resolves to. Prefer the identity: it says which asset travels with the content. Whichever punctuation an include is written with — `#include "name"`, `#include 'name'` or `#include <name>` — names the same module and records the same dependency. The engine's own scaffolding — `zero::surface`, `zero::sky`, `zero::post`, `zero::screen` — is injected by the compiler around the matching domain and is never written by hand. The surface framework puts `safe_normalize`, `mat3_from_mat4` and `apply_normal_map(FragmentData, tangent_normal)` in scope for every surface shader. ## Shader features — compile-time variants A **property** is runtime uniform data (a colour, a float, a texture): set per material, read as `material.<name>`, no recompile. A **feature** decides which code is in the program at all. Use a property when the value changes at runtime, a feature when it changes what the shader is. Declare features in `properties.yaml`, alongside the properties: ```yaml properties: - { name: base_color, type: color, default: [1, 1, 1, 1] } features: - { name: PARALLAX, default: false, description: silhouette parallax march } - { name: DETAIL, default: true, description: detail-normal overlay } ``` Guard the code each feature owns with `#ifdef`: ```wgsl fn surface(input: FragmentData) -> PbrSurface { var s = zero_pbr_default_surface(input); #ifdef PARALLAX s.normal = parallax_normal(input); // absent when PARALLAX is off #else s.normal = input.world_normal; #endif return s; } ``` `#ifdef` / `#ifndef` / `#else` / `#endif`, one per line, and they nest. The directives resolve before the WGSL reaches the compiler, so the program holds exactly the lines its feature set selected and every other line is an empty one, which keeps a compiler message on the line number the file shows. An unbalanced block is a compile error naming its line. A material is what chooses a feature set, so `features:` shapes the shaders a material draws with — the surface, sky and screen-space domains. A material names the features it wants in its `mat.yaml`: ```yaml name: worn_rock shader: "@builtin::shaders.pbr_layered" features: PARALLAX: true # on, over the shader's default DETAIL: false # off, against the shader's default ``` or through `asset.create`: ```lua asset.create("material", "worn_rock", { shader = "@builtin::shaders.pbr_layered", features = { PARALLAX = true, DETAIL = false }, }) ``` ### A property that switches a feature on A feature can also be switched on by a material's property values. List the properties under the feature's `properties:`, and the feature is on for every material whose value for one of them stands away from that property's declared default: ```yaml properties: - { name: clearcoat, type: range, default: 0.0, min: 0, max: 1 } features: - { name: CLEARCOAT, properties: [clearcoat], description: the coat lobe } ``` ```wgsl #ifdef CLEARCOAT s.clearcoat = material.clearcoat; #endif ``` A material at `clearcoat: 0` draws a program holding none of the coat's code; one that sets `clearcoat: 0.6`, in its `mat.yaml`, through `asset.create` or with `renderer.material.setProperty`, draws the `CLEARCOAT` variant, and setting it back to 0 returns it to the base program. The property stays a runtime value the program reads; the feature decides only whether the code reading it is there. This is how a shader with costly optional parts keeps every material that leaves them at rest on the cheap program without each material having to name a feature. A material naming the feature off under `features:` keeps it off whatever the property holds. Write the guarded code so that, with the feature off, the shader computes what it would with the property at its default: the material sees one look either way, and pays for the part only where it shows. Each distinct set of switched-on features is a program to compile the first time a material reaches it. A material keeps the programs its values switched it onto compiled while it lives, so a property crossing back and forth reuses them; when the shader's variant budget is spent, the ones no material draws with are given back first. A `properties:` entry is a value property (`float`, `range`, `int`, `bool`, `color`, `float2` to `float4`) the shader declares; one naming no declared property, or a texture or buffer, is refused by name. ### A texture that switches a feature A feature can be switched by the textures a material binds. `textures:` lists texture slots, and the feature is on for every material binding a texture in one of them other than the slot's declared default; `shared_texture:` lists two or more slots, and the feature is on for every material binding one and the same texture in all of them. This is how a shader samples only the maps a material binds: ```yaml properties: - { name: base_color_texture, type: texture, default: white } - { name: rm_texture, type: texture, default: white } - { name: ao_texture, type: texture, default: white } features: - { name: BASE_MAP, default: true, textures: [base_color_texture], description: the base colour map } - { name: AO_MAP, default: true, textures: [ao_texture], description: the occlusion map } - { name: PACKED_AO, shared_texture: [rm_texture, ao_texture], description: occlusion read from the rm map } ``` ```wgsl var base_texel = vec4<f32>(1.0); // what the white default stands for #ifdef BASE_MAP base_texel = textureSample(base_color_texture, base_color_texture_sampler, uv); #endif ``` A switched feature, by value or by texture, is decided by what the material holds: on where one of its switches holds, off where none does, and a material naming the feature under `features:` decides it over the switch. A map feature declared `default: true` keeps the shader's own default configuration sampling every map, so a material whose feature set the variant budget has no room for still draws its maps. A `textures:` or `shared_texture:` entry naming no declared texture slot, and a `shared_texture:` listing one slot, are refused by name. The engine compiles one program per feature set its materials ask for, named `<shader>#<features>`. Materials sharing a set share that program. A feature the shader does not declare selects nothing, so a stray name cannot make the engine compile anything, and the compile names both halves of a mismatch: a guard on a name `features:` does not declare, and a declared name no guard tests. **Permutations are the cost.** A shader with n features can express 2^n programs, each its own compile and pipeline. One shader holds at most 32 variants; a material asking for a set past that draws with the shader's default features and the engine logs which shader ran out. Read what a scene is spending: ```lua for _, s in renderer.shaderVariants() do print(s.shader, #s.variants, "of", s.budget) print(renderer.variantSource(s.base.program)) -- what it ships as for _, v in s.variants do print(v.program, renderer.variantSource(v.program)) -- what one asked for end end ``` A shader registers under every key it answers to — its identity, its guid, each alias — and each key is a row. A variant lands on the row for the key the material named, which for authored content is the guid, so take a program name from the report rather than composing one. ## Materials reference shaders A `.material` applies a shader to entities. Its `mat.yaml` references the shader by its identity string and supplies property values: ```yaml name: my_material shader: "@builtin::shaders.pbr" render: blend: alphaBlend cull: back depth_write: false properties: roughness: 0.5 base_color: [1.0, 1.0, 1.0, 1.0] textures: base_color_texture: { ref: "default:white" } ``` `shader:` is a plain identity string, and a colour is an array. A key's value is the rest of its line, so every value above stands alone on one. ### The render block Render behaviour (the blend equation, alpha cutout, which faces are drawn) lives in the `render:` block and drives the pipeline, not the fragment. These are the keys that reach the pipeline from both authoring routes, and the values each one takes: | Key | Values | Sets | |-----|--------|------| | `blend` | `opaque` `transparent` `alpha` `alphaBlend` `additive` `add` `cutout` `alphaCutout` `premultiplied` `premultipliedAlpha` `multiply` | the equation the fragment composites with | | `cull` | `back` `front` `none` `off` `disabled` | which faces the rasterizer keeps | | `depth_write` | `true` `false` | whether the draw writes depth | | `depth_compare` | `less` `lessEqual` `lequal` `equal` `greater` `greaterEqual` `gequal` `always` `never` | the test a fragment's depth passes | | `topology` | `triangleList` `lineList` `lines` `line` | what consecutive vertices assemble into | | `queue` | a whole number: `2000` opaque, `3000` transparent, `4000` overlay | the draw order of the material; a number inside a queue orders within it | `blend` is also spelled `type`, and the two name one key. Its equations, over the fragment the shader returned (`src`) and the value already in the target (`dst`): `opaque` is `src`; `transparent`, `alpha` and `alphaBlend` are `src * src.a + dst * (1 - src.a)`; `additive` and `add` are `src + dst`, the mode a glow, a light shaft or a spark card is written for; `premultiplied` and `premultipliedAlpha` are `src + dst * (1 - src.a)`, taking a source that already carries its own coverage; `multiply` is `src * dst`, which is how a soot, grime or shadow card darkens what stands behind it. `cutout` and `alphaCutout` keep the fragment or discard it on its alpha and go on writing depth. The same block is what `asset.create`'s `render` argument takes, key for key and value for value, so one material named in Luau and the same material standing on disk ask for their pipeline with the same words. `depth_write` is the one key whose value takes the shape of its route: the word `false` on a `mat.yaml` line, the boolean `false` in the Luau table. ```lua asset.create("material", "heat_plume", { shader = "@builtin::shaders.pbr", render = { blend = "alphaBlend", cull = "none", depth_write = false }, }) ``` Where a value outside a key's set is reported is what the two routes differ on. `asset.create` refuses the call on any of these keys and names the set it measured the value against, or for `queue`, that it takes a number. A `mat.yaml` standing on disk registers either way, each key falling back to a value of its own: `blend` to `opaque`, `cull` to `back`, `depth_write` to `true`, `depth_compare` to `less`, `topology` to `triangleList` and `queue` to `2000`. The engine log carries the blend fallback, naming the value and the set it was measured against, so a `mat.yaml` value is worth putting through `asset.create` once — that is where every key answers with its set. ## Registration & hot reload A `.shader` is compiled by the asset system, not by the renderer: writing `shader.wgsl` or `properties.yaml` fires the `.shader` assetType's `onChange`, which compiles it: the body + the property schema are read, the group(1) interface and (for surface) every render-mode entry point are generated, `#include`s are expanded, the result is **validated**, and the shader is registered. Validation happens at this compile step — the whole point of "compile". A shader with invalid WGSL (an unknown field, a type mismatch, an undefined function) **fails to compile** with the real reason — readable directly from Luau via `shaderRef:compileStatus()` (`{ status = "compiled" | "failed" | "pending", error?, pending? }`), and also in the author log and `asset.inspect`; it is **not** registered. This fires on create and on every edit, so saving a `.wgsl` recompiles with no world reload; the change is visible on the next frame. Compilation is async, so a `compileStatus()` of `"pending"` immediatel
▲ -1↑ born
backing path · modules/api/engine/renderer.module

Problems

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

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

Usability ratings

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

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

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

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