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.…
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.createnever takes anAssetRef— 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 bymeshRef:load()).create(src, guid?) -> MeshHandle— create or fetch a GPU mesh from aMeshCpuHandle, raw geometry{positions, indices, normals?, uvs?, colors?}, compute buffers{vertexBuffer, indexBuffer, vertexCount, indexCount, aabbMin?, aabbMax?}, or aMeshHandle.geometry(mesh) -> MeshGeometry— the mesh's vertex data, the read that pairs withcreate.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.intolands 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 holds | encodeCpu(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 aTextureCpuHandle, raw pixels{rgba, width, height, srgb?}, aTextureHandle, 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-inanimatedTextureshader 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 underkey, sodescribeandliststop 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 runs0 .. laneCount() - 1.set(target, lane, x, y?, z?, w?)— write one lane of an entity's block.targetis an entity proxy or an entity-id string naming a live entity;y/z/wdefault 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-residentrgba16ftexture 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 andfilled, 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 otherconfigureemptied leavesfilledwithout it, which is what separates that from a fill that never landed. What it describes is the array a shader samples: the source texture asetLayercopied from is a GPU resource of its own and keeps the bytes it was written with, sofilledis the reading that answers whether the layer behind acookieLayeris live right now.fillscounts 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 leavesfilledas 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 withobserved = falseandoutcome = "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.nilmeans the renderer holds no material under that key, which is what writes reaching nothing on screen look like.indexis the material index its row is filed under, andtexturesthe texture key each slot of that row names, so asetTexturethe renderer has taken up reads there.materialCost() -> { MaterialObservation }— draws, instances, placeholder draws and material-owned bind groups (bindsset,bindsElidedskipped) 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_materialsserves the same document as files.
renderer.destroy
destroy(handle) -> boolean— free the GPU resource behind aMeshHandle/TextureHandle, routing by the handle'scategory.
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: thesrcshapesrenderer.mesh.create/updateandrenderer.texture.create/updatetake, and the bounds and counts raw geometry implies.renderer.shading: the readingsrenderer.shadingOfbuilds 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/v2global 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.
| arg | type | description |
|---|---|---|
| guid | string | |
| what | string |
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.
| arg | type | description |
|---|---|---|
| t | any | |
| name | string |
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.
| arg | type | description |
|---|---|---|
| value | string | { [string]: any } | AssetRef | |
| what | string |
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.
| arg | type | description |
|---|---|---|
| value | any |
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.
| arg | type | description |
|---|---|---|
| ref | any |
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).
| arg | type | description |
|---|---|---|
| value | any | |
| what | string |
meshKey(mesh: any, what: string) → string
| arg | type | description |
|---|---|---|
| mesh | any | |
| what | string |
textureKey(texture: any, what: string) → string
| arg | type | description |
|---|---|---|
| texture | any | |
| what | string |
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).
| arg | type | description |
|---|---|---|
| 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.
| arg | type | description |
|---|---|---|
| guid | string |
vecToAabb(aabbMin: any, aabbMax: any) → Aabb
| arg | type | description |
|---|---|---|
| aabbMin | any | |
| aabbMax | any |
wrapMeshHandle(guid: string, name: string, bounds: Aabb) → MeshHandle
| arg | type | description |
|---|---|---|
| guid | string | |
| name | string | |
| bounds | Aabb |
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.
| arg | type | description |
|---|---|---|
| width | number | Layer width in pixels. |
| height | number | Layer height in pixels. |
| layers | number | How 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)`.
| arg | type | description |
|---|---|---|
| layer | number | Which layer of the array to write into. |
| textureKey | string | The source texture's name — the one it was created under, as |
| x | number | Left edge of the destination rectangle, in pixels. |
| y | number | Top 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.
| arg | type | description |
|---|---|---|
| geom | MeshGeometry | `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)`.
| arg | type | description |
|---|---|---|
| zmsh | buffer | string | Engine-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.
| arg | type | description |
|---|---|---|
| mesh | string | { [string]: any } | AssetRef | The 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.
| arg | type | description |
|---|---|---|
| mesh | string | { [string]: any } | AssetRef | The 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`.
| arg | type | description |
|---|---|---|
| mesh | string | { [string]: any } | AssetRef | A 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.
| arg | type | description |
|---|---|---|
| mesh | string | { [string]: any } | AssetRef | The mesh the clusters belong to — a `MeshHandle`, a `MeshCpuHandle`, a guid, or a mesh `AssetRef`. |
| clusters | string | Serialized 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.
| arg | type | description |
|---|---|---|
| clusterBytes | buffer | string | Serialized 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.
| arg | type | description |
|---|---|---|
| mesh | string | { [string]: any } | AssetRef | The 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.
| arg | type | description |
|---|---|---|
| mesh | string | { [string]: any } | AssetRef | The 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.
| arg | type | description |
|---|---|---|
| mesh | string | { [string]: any } | AssetRef | The 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.
| arg | type | description |
|---|---|---|
| mesh | string | { [string]: any } | AssetRef | The 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.
| arg | type | description |
|---|---|---|
| mesh | string | { [string]: any } | AssetRef | The 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.
| arg | type | description |
|---|---|---|
| guid | string | |
| vertexCount | number | |
| indexCount | number |
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.
| arg | type | description |
|---|---|---|
| op | string | |
| value | any |
getTriangles(_self: ?) → void
| arg | type | description |
|---|---|---|
| _self | ? |
getVertices(_self: ?) → void
| arg | type | description |
|---|---|---|
| _self | ? |
getBounds(_self: ?) → void
| arg | type | description |
|---|---|---|
| _self | ? |
geometry(_self: ?) → MeshGeometry
| arg | type | description |
|---|---|---|
| _self | ? |
encode(_self: ?) → string
| arg | type | description |
|---|---|---|
| _self | ? |
unload(_self: ?) → void
| arg | type | description |
|---|---|---|
| _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.
| arg | type | description |
|---|---|---|
| ref | string | AssetRef | A 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()`.
| arg | type | description |
|---|---|---|
| handle | MeshHandle | The `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.
| arg | type | description |
|---|---|---|
| mesh | string | { [string]: any } | AssetRef | The 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.
| arg | type | description |
|---|---|---|
| mesh | string | { [string]: any } | AssetRef | The 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
| arg | type | description |
|---|---|---|
| v | any | |
| n | number |
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.
| arg | type | description |
|---|---|---|
| src | any |
take(rec: any, key: string, alt: string?, n: number, into: { number }, index: number) → void
| arg | type | description |
|---|---|---|
| rec | any | |
| key | string | |
| alt | string? | |
| n | number | |
| into | { number } | |
| index | number |
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.
| arg | type | description |
|---|---|---|
| positions | { any } | |
| indices | { any } |
classifyMesh(src: any) → string
| arg | type | description |
|---|---|---|
| src | any |
recordMeshFacts(guid: string, vertexCount: number?, indexCount: number?) → void
| arg | type | description |
|---|---|---|
| guid | string | |
| vertexCount | number? | |
| indexCount | number? |
geometryCounts(src: any) → void
Counts implied by raw geometry: three components per position, one index each.
| arg | type | description |
|---|---|---|
| src | any |
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.
| arg | type | description |
|---|---|---|
| kind | string | |
| 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).
| arg | type | description |
|---|---|---|
| src | any | A MeshCpuHandle, geometry, compute buffers, or a MeshHandle. |
| guid | string? | 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?}`.
| arg | type | description |
|---|---|---|
| handle | MeshHandle | The `MeshHandle` to update. |
| src | any | New geometry `{positions, indices, ...}` or compute buffers |
drawHandleId(draw: any, what: string) → number
| arg | type | description |
|---|---|---|
| draw | any | |
| what | string |
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.
| arg | type | description |
|---|---|---|
| handle | MeshHandle | A `MeshHandle` whose mesh is GPU-resident. |
| opts | any | `{ 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.
| arg | type | description |
|---|---|---|
| draw | InstancedDraw | The `InstancedDraw` to reconfigure. |
| count | number | Instances 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.
| arg | type | description |
|---|---|---|
| draw | InstancedDraw | The `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()`.
| arg | type | description |
|---|---|---|
| draw | InstancedDraw | The `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.
| arg | type | description |
|---|---|---|
| bytes | any | Capture bytes — `.spz` or `.ply`, as a `buffer` or a binary string. |
| convention | string? | 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
| arg | type | description |
|---|---|---|
| guid | string | |
| name | string | |
| width | number | |
| height | number |
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.
| arg | type | description |
|---|---|---|
| op | string | |
| value | any |
readPixel(_self: ?, x: number, y: number) → void
| arg | type | description |
|---|---|---|
| _self | ? | |
| x | number | |
| y | number |
writePixel(_self: ?, x: number, y: number, r: number, g: number, b: number, a: number?) → void
| arg | type | description |
|---|---|---|
| _self | ? | |
| x | number | |
| y | number | |
| r | number | |
| g | number | |
| b | number | |
| a | number? |
rgba(_self: ?) → string
| arg | type | description |
|---|---|---|
| _self | ? |
blit(_self: ?, src: any, x: number, y: number, w: number, h: number, filter: string?) → boolean
| arg | type | description |
|---|---|---|
| _self | ? | |
| src | any | |
| x | number | |
| y | number | |
| w | number | |
| h | number | |
| filter | string? |
getInfo(_self: ?) → void
| arg | type | description |
|---|---|---|
| _self | ? |
encode(_self: ?) → string
| arg | type | description |
|---|---|---|
| _self | ? |
encodePng(_self: ?) → string
| arg | type | description |
|---|---|---|
| _self | ? |
encodeJpeg(_self: ?, quality: number?) → string
| arg | type | description |
|---|---|---|
| _self | ? | |
| quality | number? |
unload(_self: ?) → void
| arg | type | description |
|---|---|---|
| _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`.
| arg | type | description |
|---|---|---|
| rgba | any | Pixel payload at `opts.format`'s native byte width — a `buffer`, a binary string, or a number array. |
| width | number | number |
| height | number | number |
| opts | any | `{ 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`.
| arg | type | description |
|---|---|---|
| bytes | buffer | string | source image bytes. |
| opts | any | `{ 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"`.
| arg | type | description |
|---|---|---|
| ztex | buffer | string | ZTEX 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`.
| arg | type | description |
|---|---|---|
| ztex | buffer | string | ZTEX 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.
| arg | type | description |
|---|---|---|
| texture | string | AssetRef | The 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.
| arg | type | description |
|---|---|---|
| texture | string | { [string]: any } | AssetRef | The 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.
| arg | type | description |
|---|---|---|
| texture | string | { [string]: any } | AssetRef | The 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.
| arg | type | description |
|---|---|---|
| width | number | number Canvas width in pixels. |
| height | number | number Canvas height in pixels. |
| fill | any? | 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
| arg | type | description |
|---|---|---|
| src | any |
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.
| arg | type | description |
|---|---|---|
| src | any | A TextureCpuHandle, raw pixels, a TextureHandle, or render-target dimensions. |
| guid | string? | 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.
| arg | type | description |
|---|---|---|
| handle | TextureHandle | The `TextureHandle` to update. |
| src | any | New 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).
| arg | type | description |
|---|---|---|
| handle | TextureHandle | The `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.
| arg | type | description |
|---|---|---|
| handle | TextureHandle | The `TextureHandle` to read back. |
examples
local key = renderer.texture.capture(cameraTarget)
wrapMaterialHandle(guid: string, name: string) → MaterialHandle
| arg | type | description |
|---|---|---|
| guid | string | |
| name | string |
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.
| arg | type | description |
|---|---|---|
| ref | any | |
| materialName | string | |
| slot | string |
create(content: MaterialContent, key: string) → MaterialHandle
| arg | type | description |
|---|---|---|
| content | MaterialContent | |
| key | string |
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.
| arg | type | description |
|---|---|---|
| guid | string | |
| 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`.
| arg | type | description |
|---|---|---|
| key | string | { [string]: any } | AssetRef | The 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.
| arg | type | description |
|---|---|---|
| key | string |
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`.
| arg | type | description |
|---|---|---|
| key | string | { [string]: any } | AssetRef | The 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`.
| arg | type | description |
|---|---|---|
| key | string | { [string]: any } | AssetRef | The 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`.
| arg | type | description |
|---|---|---|
| entityId | string | The 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`.
| arg | type | description |
|---|---|---|
| key | string | { [string]: any } | AssetRef | The material's registry key, the `MaterialHandle` from |
| name | string | Property name. |
| value | any | New 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.
| arg | type | description |
|---|---|---|
| key | string | { [string]: any } | AssetRef | The material's registry key, the `MaterialHandle` from |
| slot | string | Texture slot name (`"base_color_texture"`, …). |
| ref | string | { [string]: any } | AssetRef | Texture reference — a `.texture` guid / identity / name / path, the |
examples
renderer.material.setTexture("sky", "sky_texture", "panorama.texture")logWarn(msg: string) → void
| arg | type | description |
|---|---|---|
| msg | string |
buildFeatureCtx( ) → any
Build the per-frame `ctx` handed to a feature's setup/render/teardown.
enqueue(spec: ?) → void
| arg | type | description |
|---|---|---|
| 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.
| arg | type | description |
|---|---|---|
| ref | any |
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")`.
| arg | type | description |
|---|---|---|
| ref | any | An `AssetRef<renderFeature>`, or a string identity/guid resolved via |
| guid | string? | 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
| arg | type | description |
|---|---|---|
| s | string |
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.
| arg | type | description |
|---|---|---|
| guid | string |
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.
| arg | type | description |
|---|---|---|
| handleOrGuid | any | A `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.
| arg | type | description |
|---|---|---|
| name | string | The view name, selected via `capture pass=<name>`. |
| config | any | `{ 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).
| arg | type | description |
|---|---|---|
| name | string | The 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`.
| arg | type | description |
|---|---|---|
| name | string | The 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`.
| arg | type | description |
|---|---|---|
| name | string | The 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.
| arg | type | description |
|---|---|---|
| name | string | The 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.
| arg | type | description |
|---|---|---|
| name | string | A debug-pass name (e.g. "normal", "depth", "lightmap"). |
examples
local ch = renderer.debugPass.channel("normal") -- 7name(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.
| arg | type | description |
|---|---|---|
| channel | number | The 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.
| arg | type | description |
|---|---|---|
| enabled | boolean | `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.
| arg | type | description |
|---|---|---|
| enabled | boolean | `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.
| arg | type | description |
|---|---|---|
| enabled | boolean | `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.
| arg | type | description |
|---|---|---|
| enabled | boolean | `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.
| arg | type | description |
|---|---|---|
| scale | number | `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`.
| arg | type | description |
|---|---|---|
| pixels | number | `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.
| arg | type | description |
|---|---|---|
| enabled | boolean | `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.
| arg | type | description |
|---|---|---|
| frames | number | number 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.
| arg | type | description |
|---|---|---|
| mode | string | string 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") endmaterialCost( ) →
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.
| arg | type | description |
|---|---|---|
| name | string | `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.
| arg | type | description |
|---|---|---|
| frames | number | Frames 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.
| arg | type | description |
|---|---|---|
| opts | TextureBudgetOpts | `{ megabytes: number?, bias: number? }` |
examples
renderer.setTextureBudget({ megabytes = 128 })renderer.setTextureBudget({ megabytes = 128, bias = -1 }) -- a tiled material wants finer mipsrenderer.setTextureBudget({ megabytes = 0 }) -- leave residency alonetextureStreaming( ) → 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.
| arg | type | description |
|---|---|---|
| enabled | boolean | `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.
| arg | type | description |
|---|---|---|
| enabled | boolean | `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.
| arg | type | description |
|---|---|---|
| enabled | boolean | `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.
| arg | type | description |
|---|---|---|
| enabled | boolean | `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.
| arg | type | description |
|---|---|---|
| enabled | boolean | `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.
| arg | type | description |
|---|---|---|
| mesh | string | The mesh a caster draws, as a guid or any mesh reference. |
| proxy | string | The 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.
| arg | type | description |
|---|---|---|
| mesh | string? | 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.
| arg | type | description |
|---|---|---|
| entity | string | The entity whose renderables the view is fit around. |
| padding | number? | 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.
| arg | type | description |
|---|---|---|
| program | string | A `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.
| arg | type | description |
|---|---|---|
| handle | any | A `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.
| arg | type | description |
|---|---|---|
| id | string | Entity id. |
| min | any | Local-space minimum corner — a Vec3 table or a 3-element array. |
| max | any | Local-space maximum corner, same shape as `min`. |
examples
renderer.bounds.set(id, cloud.boundsMin, cloud.boundsMax)
axis(v: any, key: string, index: number) → number
| arg | type | description |
|---|---|---|
| v | any | |
| key | string | |
| index | number |
clear(id: string) → boolean
Withdraw the box an entity published, so it stops contributing to the entity's reported extent.
| arg | type | description |
|---|---|---|
| id | string | Entity 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.
| arg | type | description |
|---|---|---|
| level | number | One 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.
| arg | type | description |
|---|---|---|
| x | number | Horizontal offset in NDC. One pixel is `2.0 / width`. |
| y | number | Vertical 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()
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.
Problems
Everything affecting this asset right now: its own problems, anything wrong inside it, and problems on its direct dependencies.
agent_score is exposed.+ 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".
Scoped to this part · feeds back into the world's score.